UNPKG

590 kBJavaScriptView Raw
1// PouchDB localStorage plugin 7.2.1
2// Based on localstorage-down: https://github.com/No9/localstorage-down
3//
4// (c) 2012-2020 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 (process){
10/* Copyright (c) 2013 Rod Vagg, MIT License */
11
12function AbstractChainedBatch (db) {
13 this._db = db
14 this._operations = []
15 this._written = false
16}
17
18AbstractChainedBatch.prototype._checkWritten = function () {
19 if (this._written)
20 throw new Error('write() already called on this batch')
21}
22
23AbstractChainedBatch.prototype.put = function (key, value) {
24 this._checkWritten()
25
26 var err = this._db._checkKeyValue(key, 'key', this._db._isBuffer)
27 if (err) throw err
28 err = this._db._checkKeyValue(value, 'value', this._db._isBuffer)
29 if (err) throw err
30
31 if (!this._db._isBuffer(key)) key = String(key)
32 if (!this._db._isBuffer(value)) value = String(value)
33
34 if (typeof this._put == 'function' )
35 this._put(key, value)
36 else
37 this._operations.push({ type: 'put', key: key, value: value })
38
39 return this
40}
41
42AbstractChainedBatch.prototype.del = function (key) {
43 this._checkWritten()
44
45 var err = this._db._checkKeyValue(key, 'key', this._db._isBuffer)
46 if (err) throw err
47
48 if (!this._db._isBuffer(key)) key = String(key)
49
50 if (typeof this._del == 'function' )
51 this._del(key)
52 else
53 this._operations.push({ type: 'del', key: key })
54
55 return this
56}
57
58AbstractChainedBatch.prototype.clear = function () {
59 this._checkWritten()
60
61 this._operations = []
62
63 if (typeof this._clear == 'function' )
64 this._clear()
65
66 return this
67}
68
69AbstractChainedBatch.prototype.write = function (options, callback) {
70 this._checkWritten()
71
72 if (typeof options == 'function')
73 callback = options
74 if (typeof callback != 'function')
75 throw new Error('write() requires a callback argument')
76 if (typeof options != 'object')
77 options = {}
78
79 this._written = true
80
81 if (typeof this._write == 'function' )
82 return this._write(callback)
83
84 if (typeof this._db._batch == 'function')
85 return this._db._batch(this._operations, options, callback)
86
87 process.nextTick(callback)
88}
89
90module.exports = AbstractChainedBatch
91}).call(this,_dereq_(68))
92},{"68":68}],2:[function(_dereq_,module,exports){
93(function (process){
94/* Copyright (c) 2013 Rod Vagg, MIT License */
95
96function AbstractIterator (db) {
97 this.db = db
98 this._ended = false
99 this._nexting = false
100}
101
102AbstractIterator.prototype.next = function (callback) {
103 var self = this
104
105 if (typeof callback != 'function')
106 throw new Error('next() requires a callback argument')
107
108 if (self._ended)
109 return callback(new Error('cannot call next() after end()'))
110 if (self._nexting)
111 return callback(new Error('cannot call next() before previous next() has completed'))
112
113 self._nexting = true
114 if (typeof self._next == 'function') {
115 return self._next(function () {
116 self._nexting = false
117 callback.apply(null, arguments)
118 })
119 }
120
121 process.nextTick(function () {
122 self._nexting = false
123 callback()
124 })
125}
126
127AbstractIterator.prototype.end = function (callback) {
128 if (typeof callback != 'function')
129 throw new Error('end() requires a callback argument')
130
131 if (this._ended)
132 return callback(new Error('end() already called on iterator'))
133
134 this._ended = true
135
136 if (typeof this._end == 'function')
137 return this._end(callback)
138
139 process.nextTick(callback)
140}
141
142module.exports = AbstractIterator
143
144}).call(this,_dereq_(68))
145},{"68":68}],3:[function(_dereq_,module,exports){
146(function (Buffer,process){
147/* Copyright (c) 2013 Rod Vagg, MIT License */
148
149var xtend = _dereq_(125)
150 , AbstractIterator = _dereq_(2)
151 , AbstractChainedBatch = _dereq_(1)
152
153function AbstractLevelDOWN (location) {
154 if (!arguments.length || location === undefined)
155 throw new Error('constructor requires at least a location argument')
156
157 if (typeof location != 'string')
158 throw new Error('constructor requires a location string argument')
159
160 this.location = location
161}
162
163AbstractLevelDOWN.prototype.open = function (options, callback) {
164 if (typeof options == 'function')
165 callback = options
166
167 if (typeof callback != 'function')
168 throw new Error('open() requires a callback argument')
169
170 if (typeof options != 'object')
171 options = {}
172
173 if (typeof this._open == 'function')
174 return this._open(options, callback)
175
176 process.nextTick(callback)
177}
178
179AbstractLevelDOWN.prototype.close = function (callback) {
180 if (typeof callback != 'function')
181 throw new Error('close() requires a callback argument')
182
183 if (typeof this._close == 'function')
184 return this._close(callback)
185
186 process.nextTick(callback)
187}
188
189AbstractLevelDOWN.prototype.get = function (key, options, callback) {
190 var err
191
192 if (typeof options == 'function')
193 callback = options
194
195 if (typeof callback != 'function')
196 throw new Error('get() requires a callback argument')
197
198 if (err = this._checkKeyValue(key, 'key', this._isBuffer))
199 return callback(err)
200
201 if (!this._isBuffer(key))
202 key = String(key)
203
204 if (typeof options != 'object')
205 options = {}
206
207 if (typeof this._get == 'function')
208 return this._get(key, options, callback)
209
210 process.nextTick(function () { callback(new Error('NotFound')) })
211}
212
213AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
214 var err
215
216 if (typeof options == 'function')
217 callback = options
218
219 if (typeof callback != 'function')
220 throw new Error('put() requires a callback argument')
221
222 if (err = this._checkKeyValue(key, 'key', this._isBuffer))
223 return callback(err)
224
225 if (err = this._checkKeyValue(value, 'value', this._isBuffer))
226 return callback(err)
227
228 if (!this._isBuffer(key))
229 key = String(key)
230
231 // coerce value to string in node, don't touch it in browser
232 // (indexeddb can store any JS type)
233 if (!this._isBuffer(value) && !process.browser)
234 value = String(value)
235
236 if (typeof options != 'object')
237 options = {}
238
239 if (typeof this._put == 'function')
240 return this._put(key, value, options, callback)
241
242 process.nextTick(callback)
243}
244
245AbstractLevelDOWN.prototype.del = function (key, options, callback) {
246 var err
247
248 if (typeof options == 'function')
249 callback = options
250
251 if (typeof callback != 'function')
252 throw new Error('del() requires a callback argument')
253
254 if (err = this._checkKeyValue(key, 'key', this._isBuffer))
255 return callback(err)
256
257 if (!this._isBuffer(key))
258 key = String(key)
259
260 if (typeof options != 'object')
261 options = {}
262
263 if (typeof this._del == 'function')
264 return this._del(key, options, callback)
265
266 process.nextTick(callback)
267}
268
269AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
270 if (!arguments.length)
271 return this._chainedBatch()
272
273 if (typeof options == 'function')
274 callback = options
275
276 if (typeof callback != 'function')
277 throw new Error('batch(array) requires a callback argument')
278
279 if (!Array.isArray(array))
280 return callback(new Error('batch(array) requires an array argument'))
281
282 if (typeof options != 'object')
283 options = {}
284
285 var i = 0
286 , l = array.length
287 , e
288 , err
289
290 for (; i < l; i++) {
291 e = array[i]
292 if (typeof e != 'object')
293 continue
294
295 if (err = this._checkKeyValue(e.type, 'type', this._isBuffer))
296 return callback(err)
297
298 if (err = this._checkKeyValue(e.key, 'key', this._isBuffer))
299 return callback(err)
300
301 if (e.type == 'put') {
302 if (err = this._checkKeyValue(e.value, 'value', this._isBuffer))
303 return callback(err)
304 }
305 }
306
307 if (typeof this._batch == 'function')
308 return this._batch(array, options, callback)
309
310 process.nextTick(callback)
311}
312
313//TODO: remove from here, not a necessary primitive
314AbstractLevelDOWN.prototype.approximateSize = function (start, end, callback) {
315 if ( start == null
316 || end == null
317 || typeof start == 'function'
318 || typeof end == 'function') {
319 throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments')
320 }
321
322 if (typeof callback != 'function')
323 throw new Error('approximateSize() requires a callback argument')
324
325 if (!this._isBuffer(start))
326 start = String(start)
327
328 if (!this._isBuffer(end))
329 end = String(end)
330
331 if (typeof this._approximateSize == 'function')
332 return this._approximateSize(start, end, callback)
333
334 process.nextTick(function () {
335 callback(null, 0)
336 })
337}
338
339AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
340 var self = this
341
342 options = xtend(options)
343
344 ;[ 'start', 'end', 'gt', 'gte', 'lt', 'lte' ].forEach(function (o) {
345 if (options[o] && self._isBuffer(options[o]) && options[o].length === 0)
346 delete options[o]
347 })
348
349 options.reverse = !!options.reverse
350
351 // fix `start` so it takes into account gt, gte, lt, lte as appropriate
352 if (options.reverse && options.lt)
353 options.start = options.lt
354 if (options.reverse && options.lte)
355 options.start = options.lte
356 if (!options.reverse && options.gt)
357 options.start = options.gt
358 if (!options.reverse && options.gte)
359 options.start = options.gte
360
361 if ((options.reverse && options.lt && !options.lte)
362 || (!options.reverse && options.gt && !options.gte))
363 options.exclusiveStart = true // start should *not* include matching key
364
365 return options
366}
367
368AbstractLevelDOWN.prototype.iterator = function (options) {
369 if (typeof options != 'object')
370 options = {}
371
372 options = this._setupIteratorOptions(options)
373
374 if (typeof this._iterator == 'function')
375 return this._iterator(options)
376
377 return new AbstractIterator(this)
378}
379
380AbstractLevelDOWN.prototype._chainedBatch = function () {
381 return new AbstractChainedBatch(this)
382}
383
384AbstractLevelDOWN.prototype._isBuffer = function (obj) {
385 return Buffer.isBuffer(obj)
386}
387
388AbstractLevelDOWN.prototype._checkKeyValue = function (obj, type) {
389 if (obj === null || obj === undefined)
390 return new Error(type + ' cannot be `null` or `undefined`')
391
392 if (obj === null || obj === undefined)
393 return new Error(type + ' cannot be `null` or `undefined`')
394
395 if (this._isBuffer(obj)) {
396 if (obj.length === 0)
397 return new Error(type + ' cannot be an empty Buffer')
398 } else if (String(obj) === '')
399 return new Error(type + ' cannot be an empty String')
400}
401
402module.exports.AbstractLevelDOWN = AbstractLevelDOWN
403module.exports.AbstractIterator = AbstractIterator
404module.exports.AbstractChainedBatch = AbstractChainedBatch
405
406}).call(this,{"isBuffer":_dereq_(25)},_dereq_(68))
407},{"1":1,"125":125,"2":2,"25":25,"68":68}],4:[function(_dereq_,module,exports){
408'use strict';
409
410module.exports = argsArray;
411
412function argsArray(fun) {
413 return function () {
414 var len = arguments.length;
415 if (len) {
416 var args = [];
417 var i = -1;
418 while (++i < len) {
419 args[i] = arguments[i];
420 }
421 return fun.call(this, args);
422 } else {
423 return fun.call(this, []);
424 }
425 };
426}
427},{}],5:[function(_dereq_,module,exports){
428(function (global){
429'use strict';
430
431var objectAssign = _dereq_(66);
432
433// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
434// original notice:
435
436/*!
437 * The buffer module from node.js, for the browser.
438 *
439 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
440 * @license MIT
441 */
442function compare(a, b) {
443 if (a === b) {
444 return 0;
445 }
446
447 var x = a.length;
448 var y = b.length;
449
450 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
451 if (a[i] !== b[i]) {
452 x = a[i];
453 y = b[i];
454 break;
455 }
456 }
457
458 if (x < y) {
459 return -1;
460 }
461 if (y < x) {
462 return 1;
463 }
464 return 0;
465}
466function isBuffer(b) {
467 if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
468 return global.Buffer.isBuffer(b);
469 }
470 return !!(b != null && b._isBuffer);
471}
472
473// based on node assert, original notice:
474// NB: The URL to the CommonJS spec is kept just for tradition.
475// node-assert has evolved a lot since then, both in API and behavior.
476
477// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
478//
479// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
480//
481// Originally from narwhal.js (http://narwhaljs.org)
482// Copyright (c) 2009 Thomas Robinson <280north.com>
483//
484// Permission is hereby granted, free of charge, to any person obtaining a copy
485// of this software and associated documentation files (the 'Software'), to
486// deal in the Software without restriction, including without limitation the
487// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
488// sell copies of the Software, and to permit persons to whom the Software is
489// furnished to do so, subject to the following conditions:
490//
491// The above copyright notice and this permission notice shall be included in
492// all copies or substantial portions of the Software.
493//
494// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
495// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
496// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
497// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
498// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
499// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
500
501var util = _dereq_(8);
502var hasOwn = Object.prototype.hasOwnProperty;
503var pSlice = Array.prototype.slice;
504var functionsHaveNames = (function () {
505 return function foo() {}.name === 'foo';
506}());
507function pToString (obj) {
508 return Object.prototype.toString.call(obj);
509}
510function isView(arrbuf) {
511 if (isBuffer(arrbuf)) {
512 return false;
513 }
514 if (typeof global.ArrayBuffer !== 'function') {
515 return false;
516 }
517 if (typeof ArrayBuffer.isView === 'function') {
518 return ArrayBuffer.isView(arrbuf);
519 }
520 if (!arrbuf) {
521 return false;
522 }
523 if (arrbuf instanceof DataView) {
524 return true;
525 }
526 if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
527 return true;
528 }
529 return false;
530}
531// 1. The assert module provides functions that throw
532// AssertionError's when particular conditions are not met. The
533// assert module must conform to the following interface.
534
535var assert = module.exports = ok;
536
537// 2. The AssertionError is defined in assert.
538// new assert.AssertionError({ message: message,
539// actual: actual,
540// expected: expected })
541
542var regex = /\s*function\s+([^\(\s]*)\s*/;
543// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
544function getName(func) {
545 if (!util.isFunction(func)) {
546 return;
547 }
548 if (functionsHaveNames) {
549 return func.name;
550 }
551 var str = func.toString();
552 var match = str.match(regex);
553 return match && match[1];
554}
555assert.AssertionError = function AssertionError(options) {
556 this.name = 'AssertionError';
557 this.actual = options.actual;
558 this.expected = options.expected;
559 this.operator = options.operator;
560 if (options.message) {
561 this.message = options.message;
562 this.generatedMessage = false;
563 } else {
564 this.message = getMessage(this);
565 this.generatedMessage = true;
566 }
567 var stackStartFunction = options.stackStartFunction || fail;
568 if (Error.captureStackTrace) {
569 Error.captureStackTrace(this, stackStartFunction);
570 } else {
571 // non v8 browsers so we can have a stacktrace
572 var err = new Error();
573 if (err.stack) {
574 var out = err.stack;
575
576 // try to strip useless frames
577 var fn_name = getName(stackStartFunction);
578 var idx = out.indexOf('\n' + fn_name);
579 if (idx >= 0) {
580 // once we have located the function frame
581 // we need to strip out everything before it (and its line)
582 var next_line = out.indexOf('\n', idx + 1);
583 out = out.substring(next_line + 1);
584 }
585
586 this.stack = out;
587 }
588 }
589};
590
591// assert.AssertionError instanceof Error
592util.inherits(assert.AssertionError, Error);
593
594function truncate(s, n) {
595 if (typeof s === 'string') {
596 return s.length < n ? s : s.slice(0, n);
597 } else {
598 return s;
599 }
600}
601function inspect(something) {
602 if (functionsHaveNames || !util.isFunction(something)) {
603 return util.inspect(something);
604 }
605 var rawname = getName(something);
606 var name = rawname ? ': ' + rawname : '';
607 return '[Function' + name + ']';
608}
609function getMessage(self) {
610 return truncate(inspect(self.actual), 128) + ' ' +
611 self.operator + ' ' +
612 truncate(inspect(self.expected), 128);
613}
614
615// At present only the three keys mentioned above are used and
616// understood by the spec. Implementations or sub modules can pass
617// other keys to the AssertionError's constructor - they will be
618// ignored.
619
620// 3. All of the following functions must throw an AssertionError
621// when a corresponding condition is not met, with a message that
622// may be undefined if not provided. All assertion methods provide
623// both the actual and expected values to the assertion error for
624// display purposes.
625
626function fail(actual, expected, message, operator, stackStartFunction) {
627 throw new assert.AssertionError({
628 message: message,
629 actual: actual,
630 expected: expected,
631 operator: operator,
632 stackStartFunction: stackStartFunction
633 });
634}
635
636// EXTENSION! allows for well behaved errors defined elsewhere.
637assert.fail = fail;
638
639// 4. Pure assertion tests whether a value is truthy, as determined
640// by !!guard.
641// assert.ok(guard, message_opt);
642// This statement is equivalent to assert.equal(true, !!guard,
643// message_opt);. To test strictly for the value true, use
644// assert.strictEqual(true, guard, message_opt);.
645
646function ok(value, message) {
647 if (!value) fail(value, true, message, '==', assert.ok);
648}
649assert.ok = ok;
650
651// 5. The equality assertion tests shallow, coercive equality with
652// ==.
653// assert.equal(actual, expected, message_opt);
654
655assert.equal = function equal(actual, expected, message) {
656 if (actual != expected) fail(actual, expected, message, '==', assert.equal);
657};
658
659// 6. The non-equality assertion tests for whether two objects are not equal
660// with != assert.notEqual(actual, expected, message_opt);
661
662assert.notEqual = function notEqual(actual, expected, message) {
663 if (actual == expected) {
664 fail(actual, expected, message, '!=', assert.notEqual);
665 }
666};
667
668// 7. The equivalence assertion tests a deep equality relation.
669// assert.deepEqual(actual, expected, message_opt);
670
671assert.deepEqual = function deepEqual(actual, expected, message) {
672 if (!_deepEqual(actual, expected, false)) {
673 fail(actual, expected, message, 'deepEqual', assert.deepEqual);
674 }
675};
676
677assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
678 if (!_deepEqual(actual, expected, true)) {
679 fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
680 }
681};
682
683function _deepEqual(actual, expected, strict, memos) {
684 // 7.1. All identical values are equivalent, as determined by ===.
685 if (actual === expected) {
686 return true;
687 } else if (isBuffer(actual) && isBuffer(expected)) {
688 return compare(actual, expected) === 0;
689
690 // 7.2. If the expected value is a Date object, the actual value is
691 // equivalent if it is also a Date object that refers to the same time.
692 } else if (util.isDate(actual) && util.isDate(expected)) {
693 return actual.getTime() === expected.getTime();
694
695 // 7.3 If the expected value is a RegExp object, the actual value is
696 // equivalent if it is also a RegExp object with the same source and
697 // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
698 } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
699 return actual.source === expected.source &&
700 actual.global === expected.global &&
701 actual.multiline === expected.multiline &&
702 actual.lastIndex === expected.lastIndex &&
703 actual.ignoreCase === expected.ignoreCase;
704
705 // 7.4. Other pairs that do not both pass typeof value == 'object',
706 // equivalence is determined by ==.
707 } else if ((actual === null || typeof actual !== 'object') &&
708 (expected === null || typeof expected !== 'object')) {
709 return strict ? actual === expected : actual == expected;
710
711 // If both values are instances of typed arrays, wrap their underlying
712 // ArrayBuffers in a Buffer each to increase performance
713 // This optimization requires the arrays to have the same type as checked by
714 // Object.prototype.toString (aka pToString). Never perform binary
715 // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
716 // bit patterns are not identical.
717 } else if (isView(actual) && isView(expected) &&
718 pToString(actual) === pToString(expected) &&
719 !(actual instanceof Float32Array ||
720 actual instanceof Float64Array)) {
721 return compare(new Uint8Array(actual.buffer),
722 new Uint8Array(expected.buffer)) === 0;
723
724 // 7.5 For all other Object pairs, including Array objects, equivalence is
725 // determined by having the same number of owned properties (as verified
726 // with Object.prototype.hasOwnProperty.call), the same set of keys
727 // (although not necessarily the same order), equivalent values for every
728 // corresponding key, and an identical 'prototype' property. Note: this
729 // accounts for both named and indexed properties on Arrays.
730 } else if (isBuffer(actual) !== isBuffer(expected)) {
731 return false;
732 } else {
733 memos = memos || {actual: [], expected: []};
734
735 var actualIndex = memos.actual.indexOf(actual);
736 if (actualIndex !== -1) {
737 if (actualIndex === memos.expected.indexOf(expected)) {
738 return true;
739 }
740 }
741
742 memos.actual.push(actual);
743 memos.expected.push(expected);
744
745 return objEquiv(actual, expected, strict, memos);
746 }
747}
748
749function isArguments(object) {
750 return Object.prototype.toString.call(object) == '[object Arguments]';
751}
752
753function objEquiv(a, b, strict, actualVisitedObjects) {
754 if (a === null || a === undefined || b === null || b === undefined)
755 return false;
756 // if one is a primitive, the other must be same
757 if (util.isPrimitive(a) || util.isPrimitive(b))
758 return a === b;
759 if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
760 return false;
761 var aIsArgs = isArguments(a);
762 var bIsArgs = isArguments(b);
763 if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
764 return false;
765 if (aIsArgs) {
766 a = pSlice.call(a);
767 b = pSlice.call(b);
768 return _deepEqual(a, b, strict);
769 }
770 var ka = objectKeys(a);
771 var kb = objectKeys(b);
772 var key, i;
773 // having the same number of owned properties (keys incorporates
774 // hasOwnProperty)
775 if (ka.length !== kb.length)
776 return false;
777 //the same set of keys (although not necessarily the same order),
778 ka.sort();
779 kb.sort();
780 //~~~cheap key test
781 for (i = ka.length - 1; i >= 0; i--) {
782 if (ka[i] !== kb[i])
783 return false;
784 }
785 //equivalent values for every corresponding key, and
786 //~~~possibly expensive deep test
787 for (i = ka.length - 1; i >= 0; i--) {
788 key = ka[i];
789 if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
790 return false;
791 }
792 return true;
793}
794
795// 8. The non-equivalence assertion tests for any deep inequality.
796// assert.notDeepEqual(actual, expected, message_opt);
797
798assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
799 if (_deepEqual(actual, expected, false)) {
800 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
801 }
802};
803
804assert.notDeepStrictEqual = notDeepStrictEqual;
805function notDeepStrictEqual(actual, expected, message) {
806 if (_deepEqual(actual, expected, true)) {
807 fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
808 }
809}
810
811
812// 9. The strict equality assertion tests strict equality, as determined by ===.
813// assert.strictEqual(actual, expected, message_opt);
814
815assert.strictEqual = function strictEqual(actual, expected, message) {
816 if (actual !== expected) {
817 fail(actual, expected, message, '===', assert.strictEqual);
818 }
819};
820
821// 10. The strict non-equality assertion tests for strict inequality, as
822// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
823
824assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
825 if (actual === expected) {
826 fail(actual, expected, message, '!==', assert.notStrictEqual);
827 }
828};
829
830function expectedException(actual, expected) {
831 if (!actual || !expected) {
832 return false;
833 }
834
835 if (Object.prototype.toString.call(expected) == '[object RegExp]') {
836 return expected.test(actual);
837 }
838
839 try {
840 if (actual instanceof expected) {
841 return true;
842 }
843 } catch (e) {
844 // Ignore. The instanceof check doesn't work for arrow functions.
845 }
846
847 if (Error.isPrototypeOf(expected)) {
848 return false;
849 }
850
851 return expected.call({}, actual) === true;
852}
853
854function _tryBlock(block) {
855 var error;
856 try {
857 block();
858 } catch (e) {
859 error = e;
860 }
861 return error;
862}
863
864function _throws(shouldThrow, block, expected, message) {
865 var actual;
866
867 if (typeof block !== 'function') {
868 throw new TypeError('"block" argument must be a function');
869 }
870
871 if (typeof expected === 'string') {
872 message = expected;
873 expected = null;
874 }
875
876 actual = _tryBlock(block);
877
878 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
879 (message ? ' ' + message : '.');
880
881 if (shouldThrow && !actual) {
882 fail(actual, expected, 'Missing expected exception' + message);
883 }
884
885 var userProvidedMessage = typeof message === 'string';
886 var isUnwantedException = !shouldThrow && util.isError(actual);
887 var isUnexpectedException = !shouldThrow && actual && !expected;
888
889 if ((isUnwantedException &&
890 userProvidedMessage &&
891 expectedException(actual, expected)) ||
892 isUnexpectedException) {
893 fail(actual, expected, 'Got unwanted exception' + message);
894 }
895
896 if ((shouldThrow && actual && expected &&
897 !expectedException(actual, expected)) || (!shouldThrow && actual)) {
898 throw actual;
899 }
900}
901
902// 11. Expected to throw an error:
903// assert.throws(block, Error_opt, message_opt);
904
905assert.throws = function(block, /*optional*/error, /*optional*/message) {
906 _throws(true, block, error, message);
907};
908
909// EXTENSION! This is annoying to write outside this module.
910assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
911 _throws(false, block, error, message);
912};
913
914assert.ifError = function(err) { if (err) throw err; };
915
916// Expose a strict only variant of assert
917function strict(value, message) {
918 if (!value) fail(value, true, message, '==', strict);
919}
920assert.strict = objectAssign(strict, assert, {
921 equal: assert.strictEqual,
922 deepEqual: assert.deepStrictEqual,
923 notEqual: assert.notStrictEqual,
924 notDeepEqual: assert.notDeepStrictEqual
925});
926assert.strict.strict = assert.strict;
927
928var objectKeys = Object.keys || function (obj) {
929 var keys = [];
930 for (var key in obj) {
931 if (hasOwn.call(obj, key)) keys.push(key);
932 }
933 return keys;
934};
935
936}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
937},{"66":66,"8":8}],6:[function(_dereq_,module,exports){
938if (typeof Object.create === 'function') {
939 // implementation from standard node.js 'util' module
940 module.exports = function inherits(ctor, superCtor) {
941 ctor.super_ = superCtor
942 ctor.prototype = Object.create(superCtor.prototype, {
943 constructor: {
944 value: ctor,
945 enumerable: false,
946 writable: true,
947 configurable: true
948 }
949 });
950 };
951} else {
952 // old school shim for old browsers
953 module.exports = function inherits(ctor, superCtor) {
954 ctor.super_ = superCtor
955 var TempCtor = function () {}
956 TempCtor.prototype = superCtor.prototype
957 ctor.prototype = new TempCtor()
958 ctor.prototype.constructor = ctor
959 }
960}
961
962},{}],7:[function(_dereq_,module,exports){
963module.exports = function isBuffer(arg) {
964 return arg && typeof arg === 'object'
965 && typeof arg.copy === 'function'
966 && typeof arg.fill === 'function'
967 && typeof arg.readUInt8 === 'function';
968}
969},{}],8:[function(_dereq_,module,exports){
970(function (process,global){
971// Copyright Joyent, Inc. and other Node contributors.
972//
973// Permission is hereby granted, free of charge, to any person obtaining a
974// copy of this software and associated documentation files (the
975// "Software"), to deal in the Software without restriction, including
976// without limitation the rights to use, copy, modify, merge, publish,
977// distribute, sublicense, and/or sell copies of the Software, and to permit
978// persons to whom the Software is furnished to do so, subject to the
979// following conditions:
980//
981// The above copyright notice and this permission notice shall be included
982// in all copies or substantial portions of the Software.
983//
984// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
985// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
986// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
987// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
988// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
989// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
990// USE OR OTHER DEALINGS IN THE SOFTWARE.
991
992var formatRegExp = /%[sdj%]/g;
993exports.format = function(f) {
994 if (!isString(f)) {
995 var objects = [];
996 for (var i = 0; i < arguments.length; i++) {
997 objects.push(inspect(arguments[i]));
998 }
999 return objects.join(' ');
1000 }
1001
1002 var i = 1;
1003 var args = arguments;
1004 var len = args.length;
1005 var str = String(f).replace(formatRegExp, function(x) {
1006 if (x === '%%') return '%';
1007 if (i >= len) return x;
1008 switch (x) {
1009 case '%s': return String(args[i++]);
1010 case '%d': return Number(args[i++]);
1011 case '%j':
1012 try {
1013 return JSON.stringify(args[i++]);
1014 } catch (_) {
1015 return '[Circular]';
1016 }
1017 default:
1018 return x;
1019 }
1020 });
1021 for (var x = args[i]; i < len; x = args[++i]) {
1022 if (isNull(x) || !isObject(x)) {
1023 str += ' ' + x;
1024 } else {
1025 str += ' ' + inspect(x);
1026 }
1027 }
1028 return str;
1029};
1030
1031
1032// Mark that a method should not be used.
1033// Returns a modified function which warns once by default.
1034// If --no-deprecation is set, then it is a no-op.
1035exports.deprecate = function(fn, msg) {
1036 // Allow for deprecating things in the process of starting up.
1037 if (isUndefined(global.process)) {
1038 return function() {
1039 return exports.deprecate(fn, msg).apply(this, arguments);
1040 };
1041 }
1042
1043 if (process.noDeprecation === true) {
1044 return fn;
1045 }
1046
1047 var warned = false;
1048 function deprecated() {
1049 if (!warned) {
1050 if (process.throwDeprecation) {
1051 throw new Error(msg);
1052 } else if (process.traceDeprecation) {
1053 console.trace(msg);
1054 } else {
1055 console.error(msg);
1056 }
1057 warned = true;
1058 }
1059 return fn.apply(this, arguments);
1060 }
1061
1062 return deprecated;
1063};
1064
1065
1066var debugs = {};
1067var debugEnviron;
1068exports.debuglog = function(set) {
1069 if (isUndefined(debugEnviron))
1070 debugEnviron = process.env.NODE_DEBUG || '';
1071 set = set.toUpperCase();
1072 if (!debugs[set]) {
1073 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
1074 var pid = process.pid;
1075 debugs[set] = function() {
1076 var msg = exports.format.apply(exports, arguments);
1077 console.error('%s %d: %s', set, pid, msg);
1078 };
1079 } else {
1080 debugs[set] = function() {};
1081 }
1082 }
1083 return debugs[set];
1084};
1085
1086
1087/**
1088 * Echos the value of a value. Trys to print the value out
1089 * in the best way possible given the different types.
1090 *
1091 * @param {Object} obj The object to print out.
1092 * @param {Object} opts Optional options object that alters the output.
1093 */
1094/* legacy: obj, showHidden, depth, colors*/
1095function inspect(obj, opts) {
1096 // default options
1097 var ctx = {
1098 seen: [],
1099 stylize: stylizeNoColor
1100 };
1101 // legacy...
1102 if (arguments.length >= 3) ctx.depth = arguments[2];
1103 if (arguments.length >= 4) ctx.colors = arguments[3];
1104 if (isBoolean(opts)) {
1105 // legacy...
1106 ctx.showHidden = opts;
1107 } else if (opts) {
1108 // got an "options" object
1109 exports._extend(ctx, opts);
1110 }
1111 // set default options
1112 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
1113 if (isUndefined(ctx.depth)) ctx.depth = 2;
1114 if (isUndefined(ctx.colors)) ctx.colors = false;
1115 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
1116 if (ctx.colors) ctx.stylize = stylizeWithColor;
1117 return formatValue(ctx, obj, ctx.depth);
1118}
1119exports.inspect = inspect;
1120
1121
1122// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
1123inspect.colors = {
1124 'bold' : [1, 22],
1125 'italic' : [3, 23],
1126 'underline' : [4, 24],
1127 'inverse' : [7, 27],
1128 'white' : [37, 39],
1129 'grey' : [90, 39],
1130 'black' : [30, 39],
1131 'blue' : [34, 39],
1132 'cyan' : [36, 39],
1133 'green' : [32, 39],
1134 'magenta' : [35, 39],
1135 'red' : [31, 39],
1136 'yellow' : [33, 39]
1137};
1138
1139// Don't use 'blue' not visible on cmd.exe
1140inspect.styles = {
1141 'special': 'cyan',
1142 'number': 'yellow',
1143 'boolean': 'yellow',
1144 'undefined': 'grey',
1145 'null': 'bold',
1146 'string': 'green',
1147 'date': 'magenta',
1148 // "name": intentionally not styling
1149 'regexp': 'red'
1150};
1151
1152
1153function stylizeWithColor(str, styleType) {
1154 var style = inspect.styles[styleType];
1155
1156 if (style) {
1157 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
1158 '\u001b[' + inspect.colors[style][1] + 'm';
1159 } else {
1160 return str;
1161 }
1162}
1163
1164
1165function stylizeNoColor(str, styleType) {
1166 return str;
1167}
1168
1169
1170function arrayToHash(array) {
1171 var hash = {};
1172
1173 array.forEach(function(val, idx) {
1174 hash[val] = true;
1175 });
1176
1177 return hash;
1178}
1179
1180
1181function formatValue(ctx, value, recurseTimes) {
1182 // Provide a hook for user-specified inspect functions.
1183 // Check that value is an object with an inspect function on it
1184 if (ctx.customInspect &&
1185 value &&
1186 isFunction(value.inspect) &&
1187 // Filter out the util module, it's inspect function is special
1188 value.inspect !== exports.inspect &&
1189 // Also filter out any prototype objects using the circular check.
1190 !(value.constructor && value.constructor.prototype === value)) {
1191 var ret = value.inspect(recurseTimes, ctx);
1192 if (!isString(ret)) {
1193 ret = formatValue(ctx, ret, recurseTimes);
1194 }
1195 return ret;
1196 }
1197
1198 // Primitive types cannot have properties
1199 var primitive = formatPrimitive(ctx, value);
1200 if (primitive) {
1201 return primitive;
1202 }
1203
1204 // Look up the keys of the object.
1205 var keys = Object.keys(value);
1206 var visibleKeys = arrayToHash(keys);
1207
1208 if (ctx.showHidden) {
1209 keys = Object.getOwnPropertyNames(value);
1210 }
1211
1212 // IE doesn't make error fields non-enumerable
1213 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
1214 if (isError(value)
1215 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
1216 return formatError(value);
1217 }
1218
1219 // Some type of object without properties can be shortcutted.
1220 if (keys.length === 0) {
1221 if (isFunction(value)) {
1222 var name = value.name ? ': ' + value.name : '';
1223 return ctx.stylize('[Function' + name + ']', 'special');
1224 }
1225 if (isRegExp(value)) {
1226 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
1227 }
1228 if (isDate(value)) {
1229 return ctx.stylize(Date.prototype.toString.call(value), 'date');
1230 }
1231 if (isError(value)) {
1232 return formatError(value);
1233 }
1234 }
1235
1236 var base = '', array = false, braces = ['{', '}'];
1237
1238 // Make Array say that they are Array
1239 if (isArray(value)) {
1240 array = true;
1241 braces = ['[', ']'];
1242 }
1243
1244 // Make functions say that they are functions
1245 if (isFunction(value)) {
1246 var n = value.name ? ': ' + value.name : '';
1247 base = ' [Function' + n + ']';
1248 }
1249
1250 // Make RegExps say that they are RegExps
1251 if (isRegExp(value)) {
1252 base = ' ' + RegExp.prototype.toString.call(value);
1253 }
1254
1255 // Make dates with properties first say the date
1256 if (isDate(value)) {
1257 base = ' ' + Date.prototype.toUTCString.call(value);
1258 }
1259
1260 // Make error with message first say the error
1261 if (isError(value)) {
1262 base = ' ' + formatError(value);
1263 }
1264
1265 if (keys.length === 0 && (!array || value.length == 0)) {
1266 return braces[0] + base + braces[1];
1267 }
1268
1269 if (recurseTimes < 0) {
1270 if (isRegExp(value)) {
1271 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
1272 } else {
1273 return ctx.stylize('[Object]', 'special');
1274 }
1275 }
1276
1277 ctx.seen.push(value);
1278
1279 var output;
1280 if (array) {
1281 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
1282 } else {
1283 output = keys.map(function(key) {
1284 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
1285 });
1286 }
1287
1288 ctx.seen.pop();
1289
1290 return reduceToSingleString(output, base, braces);
1291}
1292
1293
1294function formatPrimitive(ctx, value) {
1295 if (isUndefined(value))
1296 return ctx.stylize('undefined', 'undefined');
1297 if (isString(value)) {
1298 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
1299 .replace(/'/g, "\\'")
1300 .replace(/\\"/g, '"') + '\'';
1301 return ctx.stylize(simple, 'string');
1302 }
1303 if (isNumber(value))
1304 return ctx.stylize('' + value, 'number');
1305 if (isBoolean(value))
1306 return ctx.stylize('' + value, 'boolean');
1307 // For some reason typeof null is "object", so special case here.
1308 if (isNull(value))
1309 return ctx.stylize('null', 'null');
1310}
1311
1312
1313function formatError(value) {
1314 return '[' + Error.prototype.toString.call(value) + ']';
1315}
1316
1317
1318function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
1319 var output = [];
1320 for (var i = 0, l = value.length; i < l; ++i) {
1321 if (hasOwnProperty(value, String(i))) {
1322 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
1323 String(i), true));
1324 } else {
1325 output.push('');
1326 }
1327 }
1328 keys.forEach(function(key) {
1329 if (!key.match(/^\d+$/)) {
1330 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
1331 key, true));
1332 }
1333 });
1334 return output;
1335}
1336
1337
1338function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
1339 var name, str, desc;
1340 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
1341 if (desc.get) {
1342 if (desc.set) {
1343 str = ctx.stylize('[Getter/Setter]', 'special');
1344 } else {
1345 str = ctx.stylize('[Getter]', 'special');
1346 }
1347 } else {
1348 if (desc.set) {
1349 str = ctx.stylize('[Setter]', 'special');
1350 }
1351 }
1352 if (!hasOwnProperty(visibleKeys, key)) {
1353 name = '[' + key + ']';
1354 }
1355 if (!str) {
1356 if (ctx.seen.indexOf(desc.value) < 0) {
1357 if (isNull(recurseTimes)) {
1358 str = formatValue(ctx, desc.value, null);
1359 } else {
1360 str = formatValue(ctx, desc.value, recurseTimes - 1);
1361 }
1362 if (str.indexOf('\n') > -1) {
1363 if (array) {
1364 str = str.split('\n').map(function(line) {
1365 return ' ' + line;
1366 }).join('\n').substr(2);
1367 } else {
1368 str = '\n' + str.split('\n').map(function(line) {
1369 return ' ' + line;
1370 }).join('\n');
1371 }
1372 }
1373 } else {
1374 str = ctx.stylize('[Circular]', 'special');
1375 }
1376 }
1377 if (isUndefined(name)) {
1378 if (array && key.match(/^\d+$/)) {
1379 return str;
1380 }
1381 name = JSON.stringify('' + key);
1382 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
1383 name = name.substr(1, name.length - 2);
1384 name = ctx.stylize(name, 'name');
1385 } else {
1386 name = name.replace(/'/g, "\\'")
1387 .replace(/\\"/g, '"')
1388 .replace(/(^"|"$)/g, "'");
1389 name = ctx.stylize(name, 'string');
1390 }
1391 }
1392
1393 return name + ': ' + str;
1394}
1395
1396
1397function reduceToSingleString(output, base, braces) {
1398 var numLinesEst = 0;
1399 var length = output.reduce(function(prev, cur) {
1400 numLinesEst++;
1401 if (cur.indexOf('\n') >= 0) numLinesEst++;
1402 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
1403 }, 0);
1404
1405 if (length > 60) {
1406 return braces[0] +
1407 (base === '' ? '' : base + '\n ') +
1408 ' ' +
1409 output.join(',\n ') +
1410 ' ' +
1411 braces[1];
1412 }
1413
1414 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
1415}
1416
1417
1418// NOTE: These type checking functions intentionally don't use `instanceof`
1419// because it is fragile and can be easily faked with `Object.create()`.
1420function isArray(ar) {
1421 return Array.isArray(ar);
1422}
1423exports.isArray = isArray;
1424
1425function isBoolean(arg) {
1426 return typeof arg === 'boolean';
1427}
1428exports.isBoolean = isBoolean;
1429
1430function isNull(arg) {
1431 return arg === null;
1432}
1433exports.isNull = isNull;
1434
1435function isNullOrUndefined(arg) {
1436 return arg == null;
1437}
1438exports.isNullOrUndefined = isNullOrUndefined;
1439
1440function isNumber(arg) {
1441 return typeof arg === 'number';
1442}
1443exports.isNumber = isNumber;
1444
1445function isString(arg) {
1446 return typeof arg === 'string';
1447}
1448exports.isString = isString;
1449
1450function isSymbol(arg) {
1451 return typeof arg === 'symbol';
1452}
1453exports.isSymbol = isSymbol;
1454
1455function isUndefined(arg) {
1456 return arg === void 0;
1457}
1458exports.isUndefined = isUndefined;
1459
1460function isRegExp(re) {
1461 return isObject(re) && objectToString(re) === '[object RegExp]';
1462}
1463exports.isRegExp = isRegExp;
1464
1465function isObject(arg) {
1466 return typeof arg === 'object' && arg !== null;
1467}
1468exports.isObject = isObject;
1469
1470function isDate(d) {
1471 return isObject(d) && objectToString(d) === '[object Date]';
1472}
1473exports.isDate = isDate;
1474
1475function isError(e) {
1476 return isObject(e) &&
1477 (objectToString(e) === '[object Error]' || e instanceof Error);
1478}
1479exports.isError = isError;
1480
1481function isFunction(arg) {
1482 return typeof arg === 'function';
1483}
1484exports.isFunction = isFunction;
1485
1486function isPrimitive(arg) {
1487 return arg === null ||
1488 typeof arg === 'boolean' ||
1489 typeof arg === 'number' ||
1490 typeof arg === 'string' ||
1491 typeof arg === 'symbol' || // ES6 symbol
1492 typeof arg === 'undefined';
1493}
1494exports.isPrimitive = isPrimitive;
1495
1496exports.isBuffer = _dereq_(7);
1497
1498function objectToString(o) {
1499 return Object.prototype.toString.call(o);
1500}
1501
1502
1503function pad(n) {
1504 return n < 10 ? '0' + n.toString(10) : n.toString(10);
1505}
1506
1507
1508var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
1509 'Oct', 'Nov', 'Dec'];
1510
1511// 26 Feb 16:19:34
1512function timestamp() {
1513 var d = new Date();
1514 var time = [pad(d.getHours()),
1515 pad(d.getMinutes()),
1516 pad(d.getSeconds())].join(':');
1517 return [d.getDate(), months[d.getMonth()], time].join(' ');
1518}
1519
1520
1521// log is just a thin wrapper to console.log that prepends a timestamp
1522exports.log = function() {
1523 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
1524};
1525
1526
1527/**
1528 * Inherit the prototype methods from one constructor into another.
1529 *
1530 * The Function.prototype.inherits from lang.js rewritten as a standalone
1531 * function (not on Function.prototype). NOTE: If this file is to be loaded
1532 * during bootstrapping this function needs to be rewritten using some native
1533 * functions as prototype setup using normal JavaScript does not work as
1534 * expected during bootstrapping (see mirror.js in r114903).
1535 *
1536 * @param {function} ctor Constructor function which needs to inherit the
1537 * prototype.
1538 * @param {function} superCtor Constructor function to inherit prototype from.
1539 */
1540exports.inherits = _dereq_(6);
1541
1542exports._extend = function(origin, add) {
1543 // Don't do anything if add isn't an object
1544 if (!add || !isObject(add)) return origin;
1545
1546 var keys = Object.keys(add);
1547 var i = keys.length;
1548 while (i--) {
1549 origin[keys[i]] = add[keys[i]];
1550 }
1551 return origin;
1552};
1553
1554function hasOwnProperty(obj, prop) {
1555 return Object.prototype.hasOwnProperty.call(obj, prop);
1556}
1557
1558}).call(this,_dereq_(68),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
1559},{"6":6,"68":68,"7":7}],9:[function(_dereq_,module,exports){
1560'use strict'
1561
1562exports.byteLength = byteLength
1563exports.toByteArray = toByteArray
1564exports.fromByteArray = fromByteArray
1565
1566var lookup = []
1567var revLookup = []
1568var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
1569
1570var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
1571for (var i = 0, len = code.length; i < len; ++i) {
1572 lookup[i] = code[i]
1573 revLookup[code.charCodeAt(i)] = i
1574}
1575
1576// Support decoding URL-safe base64 strings, as Node.js does.
1577// See: https://en.wikipedia.org/wiki/Base64#URL_applications
1578revLookup['-'.charCodeAt(0)] = 62
1579revLookup['_'.charCodeAt(0)] = 63
1580
1581function getLens (b64) {
1582 var len = b64.length
1583
1584 if (len % 4 > 0) {
1585 throw new Error('Invalid string. Length must be a multiple of 4')
1586 }
1587
1588 // Trim off extra bytes after placeholder bytes are found
1589 // See: https://github.com/beatgammit/base64-js/issues/42
1590 var validLen = b64.indexOf('=')
1591 if (validLen === -1) validLen = len
1592
1593 var placeHoldersLen = validLen === len
1594 ? 0
1595 : 4 - (validLen % 4)
1596
1597 return [validLen, placeHoldersLen]
1598}
1599
1600// base64 is 4/3 + up to two characters of the original data
1601function byteLength (b64) {
1602 var lens = getLens(b64)
1603 var validLen = lens[0]
1604 var placeHoldersLen = lens[1]
1605 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
1606}
1607
1608function _byteLength (b64, validLen, placeHoldersLen) {
1609 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
1610}
1611
1612function toByteArray (b64) {
1613 var tmp
1614 var lens = getLens(b64)
1615 var validLen = lens[0]
1616 var placeHoldersLen = lens[1]
1617
1618 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
1619
1620 var curByte = 0
1621
1622 // if there are placeholders, only get up to the last complete 4 chars
1623 var len = placeHoldersLen > 0
1624 ? validLen - 4
1625 : validLen
1626
1627 var i
1628 for (i = 0; i < len; i += 4) {
1629 tmp =
1630 (revLookup[b64.charCodeAt(i)] << 18) |
1631 (revLookup[b64.charCodeAt(i + 1)] << 12) |
1632 (revLookup[b64.charCodeAt(i + 2)] << 6) |
1633 revLookup[b64.charCodeAt(i + 3)]
1634 arr[curByte++] = (tmp >> 16) & 0xFF
1635 arr[curByte++] = (tmp >> 8) & 0xFF
1636 arr[curByte++] = tmp & 0xFF
1637 }
1638
1639 if (placeHoldersLen === 2) {
1640 tmp =
1641 (revLookup[b64.charCodeAt(i)] << 2) |
1642 (revLookup[b64.charCodeAt(i + 1)] >> 4)
1643 arr[curByte++] = tmp & 0xFF
1644 }
1645
1646 if (placeHoldersLen === 1) {
1647 tmp =
1648 (revLookup[b64.charCodeAt(i)] << 10) |
1649 (revLookup[b64.charCodeAt(i + 1)] << 4) |
1650 (revLookup[b64.charCodeAt(i + 2)] >> 2)
1651 arr[curByte++] = (tmp >> 8) & 0xFF
1652 arr[curByte++] = tmp & 0xFF
1653 }
1654
1655 return arr
1656}
1657
1658function tripletToBase64 (num) {
1659 return lookup[num >> 18 & 0x3F] +
1660 lookup[num >> 12 & 0x3F] +
1661 lookup[num >> 6 & 0x3F] +
1662 lookup[num & 0x3F]
1663}
1664
1665function encodeChunk (uint8, start, end) {
1666 var tmp
1667 var output = []
1668 for (var i = start; i < end; i += 3) {
1669 tmp =
1670 ((uint8[i] << 16) & 0xFF0000) +
1671 ((uint8[i + 1] << 8) & 0xFF00) +
1672 (uint8[i + 2] & 0xFF)
1673 output.push(tripletToBase64(tmp))
1674 }
1675 return output.join('')
1676}
1677
1678function fromByteArray (uint8) {
1679 var tmp
1680 var len = uint8.length
1681 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
1682 var parts = []
1683 var maxChunkLength = 16383 // must be multiple of 3
1684
1685 // go through the array every three bytes, we'll deal with trailing stuff later
1686 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
1687 parts.push(encodeChunk(
1688 uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
1689 ))
1690 }
1691
1692 // pad the end with zeros, but make sure to not forget the extra bytes
1693 if (extraBytes === 1) {
1694 tmp = uint8[len - 1]
1695 parts.push(
1696 lookup[tmp >> 2] +
1697 lookup[(tmp << 4) & 0x3F] +
1698 '=='
1699 )
1700 } else if (extraBytes === 2) {
1701 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
1702 parts.push(
1703 lookup[tmp >> 10] +
1704 lookup[(tmp >> 4) & 0x3F] +
1705 lookup[(tmp << 2) & 0x3F] +
1706 '='
1707 )
1708 }
1709
1710 return parts.join('')
1711}
1712
1713},{}],10:[function(_dereq_,module,exports){
1714
1715},{}],11:[function(_dereq_,module,exports){
1716(function (Buffer){
1717var toString = Object.prototype.toString
1718
1719var isModern = (
1720 typeof Buffer.alloc === 'function' &&
1721 typeof Buffer.allocUnsafe === 'function' &&
1722 typeof Buffer.from === 'function'
1723)
1724
1725function isArrayBuffer (input) {
1726 return toString.call(input).slice(8, -1) === 'ArrayBuffer'
1727}
1728
1729function fromArrayBuffer (obj, byteOffset, length) {
1730 byteOffset >>>= 0
1731
1732 var maxLength = obj.byteLength - byteOffset
1733
1734 if (maxLength < 0) {
1735 throw new RangeError("'offset' is out of bounds")
1736 }
1737
1738 if (length === undefined) {
1739 length = maxLength
1740 } else {
1741 length >>>= 0
1742
1743 if (length > maxLength) {
1744 throw new RangeError("'length' is out of bounds")
1745 }
1746 }
1747
1748 return isModern
1749 ? Buffer.from(obj.slice(byteOffset, byteOffset + length))
1750 : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
1751}
1752
1753function fromString (string, encoding) {
1754 if (typeof encoding !== 'string' || encoding === '') {
1755 encoding = 'utf8'
1756 }
1757
1758 if (!Buffer.isEncoding(encoding)) {
1759 throw new TypeError('"encoding" must be a valid string encoding')
1760 }
1761
1762 return isModern
1763 ? Buffer.from(string, encoding)
1764 : new Buffer(string, encoding)
1765}
1766
1767function bufferFrom (value, encodingOrOffset, length) {
1768 if (typeof value === 'number') {
1769 throw new TypeError('"value" argument must not be a number')
1770 }
1771
1772 if (isArrayBuffer(value)) {
1773 return fromArrayBuffer(value, encodingOrOffset, length)
1774 }
1775
1776 if (typeof value === 'string') {
1777 return fromString(value, encodingOrOffset)
1778 }
1779
1780 return isModern
1781 ? Buffer.from(value)
1782 : new Buffer(value)
1783}
1784
1785module.exports = bufferFrom
1786
1787}).call(this,_dereq_(12).Buffer)
1788},{"12":12}],12:[function(_dereq_,module,exports){
1789(function (Buffer){
1790/*!
1791 * The buffer module from node.js, for the browser.
1792 *
1793 * @author Feross Aboukhadijeh <https://feross.org>
1794 * @license MIT
1795 */
1796/* eslint-disable no-proto */
1797
1798'use strict'
1799
1800var base64 = _dereq_(9)
1801var ieee754 = _dereq_(22)
1802var customInspectSymbol =
1803 (typeof Symbol === 'function' && typeof Symbol.for === 'function')
1804 ? Symbol.for('nodejs.util.inspect.custom')
1805 : null
1806
1807exports.Buffer = Buffer
1808exports.SlowBuffer = SlowBuffer
1809exports.INSPECT_MAX_BYTES = 50
1810
1811var K_MAX_LENGTH = 0x7fffffff
1812exports.kMaxLength = K_MAX_LENGTH
1813
1814/**
1815 * If `Buffer.TYPED_ARRAY_SUPPORT`:
1816 * === true Use Uint8Array implementation (fastest)
1817 * === false Print warning and recommend using `buffer` v4.x which has an Object
1818 * implementation (most compatible, even IE6)
1819 *
1820 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
1821 * Opera 11.6+, iOS 4.2+.
1822 *
1823 * We report that the browser does not support typed arrays if the are not subclassable
1824 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
1825 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
1826 * for __proto__ and has a buggy typed array implementation.
1827 */
1828Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
1829
1830if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
1831 typeof console.error === 'function') {
1832 console.error(
1833 'This browser lacks typed array (Uint8Array) support which is required by ' +
1834 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
1835 )
1836}
1837
1838function typedArraySupport () {
1839 // Can typed array instances can be augmented?
1840 try {
1841 var arr = new Uint8Array(1)
1842 var proto = { foo: function () { return 42 } }
1843 Object.setPrototypeOf(proto, Uint8Array.prototype)
1844 Object.setPrototypeOf(arr, proto)
1845 return arr.foo() === 42
1846 } catch (e) {
1847 return false
1848 }
1849}
1850
1851Object.defineProperty(Buffer.prototype, 'parent', {
1852 enumerable: true,
1853 get: function () {
1854 if (!Buffer.isBuffer(this)) return undefined
1855 return this.buffer
1856 }
1857})
1858
1859Object.defineProperty(Buffer.prototype, 'offset', {
1860 enumerable: true,
1861 get: function () {
1862 if (!Buffer.isBuffer(this)) return undefined
1863 return this.byteOffset
1864 }
1865})
1866
1867function createBuffer (length) {
1868 if (length > K_MAX_LENGTH) {
1869 throw new RangeError('The value "' + length + '" is invalid for option "size"')
1870 }
1871 // Return an augmented `Uint8Array` instance
1872 var buf = new Uint8Array(length)
1873 Object.setPrototypeOf(buf, Buffer.prototype)
1874 return buf
1875}
1876
1877/**
1878 * The Buffer constructor returns instances of `Uint8Array` that have their
1879 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
1880 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
1881 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
1882 * returns a single octet.
1883 *
1884 * The `Uint8Array` prototype remains unmodified.
1885 */
1886
1887function Buffer (arg, encodingOrOffset, length) {
1888 // Common case.
1889 if (typeof arg === 'number') {
1890 if (typeof encodingOrOffset === 'string') {
1891 throw new TypeError(
1892 'The "string" argument must be of type string. Received type number'
1893 )
1894 }
1895 return allocUnsafe(arg)
1896 }
1897 return from(arg, encodingOrOffset, length)
1898}
1899
1900// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
1901if (typeof Symbol !== 'undefined' && Symbol.species != null &&
1902 Buffer[Symbol.species] === Buffer) {
1903 Object.defineProperty(Buffer, Symbol.species, {
1904 value: null,
1905 configurable: true,
1906 enumerable: false,
1907 writable: false
1908 })
1909}
1910
1911Buffer.poolSize = 8192 // not used by this implementation
1912
1913function from (value, encodingOrOffset, length) {
1914 if (typeof value === 'string') {
1915 return fromString(value, encodingOrOffset)
1916 }
1917
1918 if (ArrayBuffer.isView(value)) {
1919 return fromArrayLike(value)
1920 }
1921
1922 if (value == null) {
1923 throw new TypeError(
1924 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
1925 'or Array-like Object. Received type ' + (typeof value)
1926 )
1927 }
1928
1929 if (isInstance(value, ArrayBuffer) ||
1930 (value && isInstance(value.buffer, ArrayBuffer))) {
1931 return fromArrayBuffer(value, encodingOrOffset, length)
1932 }
1933
1934 if (typeof value === 'number') {
1935 throw new TypeError(
1936 'The "value" argument must not be of type number. Received type number'
1937 )
1938 }
1939
1940 var valueOf = value.valueOf && value.valueOf()
1941 if (valueOf != null && valueOf !== value) {
1942 return Buffer.from(valueOf, encodingOrOffset, length)
1943 }
1944
1945 var b = fromObject(value)
1946 if (b) return b
1947
1948 if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
1949 typeof value[Symbol.toPrimitive] === 'function') {
1950 return Buffer.from(
1951 value[Symbol.toPrimitive]('string'), encodingOrOffset, length
1952 )
1953 }
1954
1955 throw new TypeError(
1956 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
1957 'or Array-like Object. Received type ' + (typeof value)
1958 )
1959}
1960
1961/**
1962 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
1963 * if value is a number.
1964 * Buffer.from(str[, encoding])
1965 * Buffer.from(array)
1966 * Buffer.from(buffer)
1967 * Buffer.from(arrayBuffer[, byteOffset[, length]])
1968 **/
1969Buffer.from = function (value, encodingOrOffset, length) {
1970 return from(value, encodingOrOffset, length)
1971}
1972
1973// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
1974// https://github.com/feross/buffer/pull/148
1975Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)
1976Object.setPrototypeOf(Buffer, Uint8Array)
1977
1978function assertSize (size) {
1979 if (typeof size !== 'number') {
1980 throw new TypeError('"size" argument must be of type number')
1981 } else if (size < 0) {
1982 throw new RangeError('The value "' + size + '" is invalid for option "size"')
1983 }
1984}
1985
1986function alloc (size, fill, encoding) {
1987 assertSize(size)
1988 if (size <= 0) {
1989 return createBuffer(size)
1990 }
1991 if (fill !== undefined) {
1992 // Only pay attention to encoding if it's a string. This
1993 // prevents accidentally sending in a number that would
1994 // be interpretted as a start offset.
1995 return typeof encoding === 'string'
1996 ? createBuffer(size).fill(fill, encoding)
1997 : createBuffer(size).fill(fill)
1998 }
1999 return createBuffer(size)
2000}
2001
2002/**
2003 * Creates a new filled Buffer instance.
2004 * alloc(size[, fill[, encoding]])
2005 **/
2006Buffer.alloc = function (size, fill, encoding) {
2007 return alloc(size, fill, encoding)
2008}
2009
2010function allocUnsafe (size) {
2011 assertSize(size)
2012 return createBuffer(size < 0 ? 0 : checked(size) | 0)
2013}
2014
2015/**
2016 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
2017 * */
2018Buffer.allocUnsafe = function (size) {
2019 return allocUnsafe(size)
2020}
2021/**
2022 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
2023 */
2024Buffer.allocUnsafeSlow = function (size) {
2025 return allocUnsafe(size)
2026}
2027
2028function fromString (string, encoding) {
2029 if (typeof encoding !== 'string' || encoding === '') {
2030 encoding = 'utf8'
2031 }
2032
2033 if (!Buffer.isEncoding(encoding)) {
2034 throw new TypeError('Unknown encoding: ' + encoding)
2035 }
2036
2037 var length = byteLength(string, encoding) | 0
2038 var buf = createBuffer(length)
2039
2040 var actual = buf.write(string, encoding)
2041
2042 if (actual !== length) {
2043 // Writing a hex string, for example, that contains invalid characters will
2044 // cause everything after the first invalid character to be ignored. (e.g.
2045 // 'abxxcd' will be treated as 'ab')
2046 buf = buf.slice(0, actual)
2047 }
2048
2049 return buf
2050}
2051
2052function fromArrayLike (array) {
2053 var length = array.length < 0 ? 0 : checked(array.length) | 0
2054 var buf = createBuffer(length)
2055 for (var i = 0; i < length; i += 1) {
2056 buf[i] = array[i] & 255
2057 }
2058 return buf
2059}
2060
2061function fromArrayBuffer (array, byteOffset, length) {
2062 if (byteOffset < 0 || array.byteLength < byteOffset) {
2063 throw new RangeError('"offset" is outside of buffer bounds')
2064 }
2065
2066 if (array.byteLength < byteOffset + (length || 0)) {
2067 throw new RangeError('"length" is outside of buffer bounds')
2068 }
2069
2070 var buf
2071 if (byteOffset === undefined && length === undefined) {
2072 buf = new Uint8Array(array)
2073 } else if (length === undefined) {
2074 buf = new Uint8Array(array, byteOffset)
2075 } else {
2076 buf = new Uint8Array(array, byteOffset, length)
2077 }
2078
2079 // Return an augmented `Uint8Array` instance
2080 Object.setPrototypeOf(buf, Buffer.prototype)
2081
2082 return buf
2083}
2084
2085function fromObject (obj) {
2086 if (Buffer.isBuffer(obj)) {
2087 var len = checked(obj.length) | 0
2088 var buf = createBuffer(len)
2089
2090 if (buf.length === 0) {
2091 return buf
2092 }
2093
2094 obj.copy(buf, 0, 0, len)
2095 return buf
2096 }
2097
2098 if (obj.length !== undefined) {
2099 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
2100 return createBuffer(0)
2101 }
2102 return fromArrayLike(obj)
2103 }
2104
2105 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
2106 return fromArrayLike(obj.data)
2107 }
2108}
2109
2110function checked (length) {
2111 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
2112 // length is NaN (which is otherwise coerced to zero.)
2113 if (length >= K_MAX_LENGTH) {
2114 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
2115 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
2116 }
2117 return length | 0
2118}
2119
2120function SlowBuffer (length) {
2121 if (+length != length) { // eslint-disable-line eqeqeq
2122 length = 0
2123 }
2124 return Buffer.alloc(+length)
2125}
2126
2127Buffer.isBuffer = function isBuffer (b) {
2128 return b != null && b._isBuffer === true &&
2129 b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
2130}
2131
2132Buffer.compare = function compare (a, b) {
2133 if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
2134 if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
2135 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
2136 throw new TypeError(
2137 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
2138 )
2139 }
2140
2141 if (a === b) return 0
2142
2143 var x = a.length
2144 var y = b.length
2145
2146 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
2147 if (a[i] !== b[i]) {
2148 x = a[i]
2149 y = b[i]
2150 break
2151 }
2152 }
2153
2154 if (x < y) return -1
2155 if (y < x) return 1
2156 return 0
2157}
2158
2159Buffer.isEncoding = function isEncoding (encoding) {
2160 switch (String(encoding).toLowerCase()) {
2161 case 'hex':
2162 case 'utf8':
2163 case 'utf-8':
2164 case 'ascii':
2165 case 'latin1':
2166 case 'binary':
2167 case 'base64':
2168 case 'ucs2':
2169 case 'ucs-2':
2170 case 'utf16le':
2171 case 'utf-16le':
2172 return true
2173 default:
2174 return false
2175 }
2176}
2177
2178Buffer.concat = function concat (list, length) {
2179 if (!Array.isArray(list)) {
2180 throw new TypeError('"list" argument must be an Array of Buffers')
2181 }
2182
2183 if (list.length === 0) {
2184 return Buffer.alloc(0)
2185 }
2186
2187 var i
2188 if (length === undefined) {
2189 length = 0
2190 for (i = 0; i < list.length; ++i) {
2191 length += list[i].length
2192 }
2193 }
2194
2195 var buffer = Buffer.allocUnsafe(length)
2196 var pos = 0
2197 for (i = 0; i < list.length; ++i) {
2198 var buf = list[i]
2199 if (isInstance(buf, Uint8Array)) {
2200 buf = Buffer.from(buf)
2201 }
2202 if (!Buffer.isBuffer(buf)) {
2203 throw new TypeError('"list" argument must be an Array of Buffers')
2204 }
2205 buf.copy(buffer, pos)
2206 pos += buf.length
2207 }
2208 return buffer
2209}
2210
2211function byteLength (string, encoding) {
2212 if (Buffer.isBuffer(string)) {
2213 return string.length
2214 }
2215 if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
2216 return string.byteLength
2217 }
2218 if (typeof string !== 'string') {
2219 throw new TypeError(
2220 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
2221 'Received type ' + typeof string
2222 )
2223 }
2224
2225 var len = string.length
2226 var mustMatch = (arguments.length > 2 && arguments[2] === true)
2227 if (!mustMatch && len === 0) return 0
2228
2229 // Use a for loop to avoid recursion
2230 var loweredCase = false
2231 for (;;) {
2232 switch (encoding) {
2233 case 'ascii':
2234 case 'latin1':
2235 case 'binary':
2236 return len
2237 case 'utf8':
2238 case 'utf-8':
2239 return utf8ToBytes(string).length
2240 case 'ucs2':
2241 case 'ucs-2':
2242 case 'utf16le':
2243 case 'utf-16le':
2244 return len * 2
2245 case 'hex':
2246 return len >>> 1
2247 case 'base64':
2248 return base64ToBytes(string).length
2249 default:
2250 if (loweredCase) {
2251 return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
2252 }
2253 encoding = ('' + encoding).toLowerCase()
2254 loweredCase = true
2255 }
2256 }
2257}
2258Buffer.byteLength = byteLength
2259
2260function slowToString (encoding, start, end) {
2261 var loweredCase = false
2262
2263 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
2264 // property of a typed array.
2265
2266 // This behaves neither like String nor Uint8Array in that we set start/end
2267 // to their upper/lower bounds if the value passed is out of range.
2268 // undefined is handled specially as per ECMA-262 6th Edition,
2269 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
2270 if (start === undefined || start < 0) {
2271 start = 0
2272 }
2273 // Return early if start > this.length. Done here to prevent potential uint32
2274 // coercion fail below.
2275 if (start > this.length) {
2276 return ''
2277 }
2278
2279 if (end === undefined || end > this.length) {
2280 end = this.length
2281 }
2282
2283 if (end <= 0) {
2284 return ''
2285 }
2286
2287 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
2288 end >>>= 0
2289 start >>>= 0
2290
2291 if (end <= start) {
2292 return ''
2293 }
2294
2295 if (!encoding) encoding = 'utf8'
2296
2297 while (true) {
2298 switch (encoding) {
2299 case 'hex':
2300 return hexSlice(this, start, end)
2301
2302 case 'utf8':
2303 case 'utf-8':
2304 return utf8Slice(this, start, end)
2305
2306 case 'ascii':
2307 return asciiSlice(this, start, end)
2308
2309 case 'latin1':
2310 case 'binary':
2311 return latin1Slice(this, start, end)
2312
2313 case 'base64':
2314 return base64Slice(this, start, end)
2315
2316 case 'ucs2':
2317 case 'ucs-2':
2318 case 'utf16le':
2319 case 'utf-16le':
2320 return utf16leSlice(this, start, end)
2321
2322 default:
2323 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
2324 encoding = (encoding + '').toLowerCase()
2325 loweredCase = true
2326 }
2327 }
2328}
2329
2330// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
2331// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
2332// reliably in a browserify context because there could be multiple different
2333// copies of the 'buffer' package in use. This method works even for Buffer
2334// instances that were created from another copy of the `buffer` package.
2335// See: https://github.com/feross/buffer/issues/154
2336Buffer.prototype._isBuffer = true
2337
2338function swap (b, n, m) {
2339 var i = b[n]
2340 b[n] = b[m]
2341 b[m] = i
2342}
2343
2344Buffer.prototype.swap16 = function swap16 () {
2345 var len = this.length
2346 if (len % 2 !== 0) {
2347 throw new RangeError('Buffer size must be a multiple of 16-bits')
2348 }
2349 for (var i = 0; i < len; i += 2) {
2350 swap(this, i, i + 1)
2351 }
2352 return this
2353}
2354
2355Buffer.prototype.swap32 = function swap32 () {
2356 var len = this.length
2357 if (len % 4 !== 0) {
2358 throw new RangeError('Buffer size must be a multiple of 32-bits')
2359 }
2360 for (var i = 0; i < len; i += 4) {
2361 swap(this, i, i + 3)
2362 swap(this, i + 1, i + 2)
2363 }
2364 return this
2365}
2366
2367Buffer.prototype.swap64 = function swap64 () {
2368 var len = this.length
2369 if (len % 8 !== 0) {
2370 throw new RangeError('Buffer size must be a multiple of 64-bits')
2371 }
2372 for (var i = 0; i < len; i += 8) {
2373 swap(this, i, i + 7)
2374 swap(this, i + 1, i + 6)
2375 swap(this, i + 2, i + 5)
2376 swap(this, i + 3, i + 4)
2377 }
2378 return this
2379}
2380
2381Buffer.prototype.toString = function toString () {
2382 var length = this.length
2383 if (length === 0) return ''
2384 if (arguments.length === 0) return utf8Slice(this, 0, length)
2385 return slowToString.apply(this, arguments)
2386}
2387
2388Buffer.prototype.toLocaleString = Buffer.prototype.toString
2389
2390Buffer.prototype.equals = function equals (b) {
2391 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
2392 if (this === b) return true
2393 return Buffer.compare(this, b) === 0
2394}
2395
2396Buffer.prototype.inspect = function inspect () {
2397 var str = ''
2398 var max = exports.INSPECT_MAX_BYTES
2399 str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
2400 if (this.length > max) str += ' ... '
2401 return '<Buffer ' + str + '>'
2402}
2403if (customInspectSymbol) {
2404 Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect
2405}
2406
2407Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
2408 if (isInstance(target, Uint8Array)) {
2409 target = Buffer.from(target, target.offset, target.byteLength)
2410 }
2411 if (!Buffer.isBuffer(target)) {
2412 throw new TypeError(
2413 'The "target" argument must be one of type Buffer or Uint8Array. ' +
2414 'Received type ' + (typeof target)
2415 )
2416 }
2417
2418 if (start === undefined) {
2419 start = 0
2420 }
2421 if (end === undefined) {
2422 end = target ? target.length : 0
2423 }
2424 if (thisStart === undefined) {
2425 thisStart = 0
2426 }
2427 if (thisEnd === undefined) {
2428 thisEnd = this.length
2429 }
2430
2431 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
2432 throw new RangeError('out of range index')
2433 }
2434
2435 if (thisStart >= thisEnd && start >= end) {
2436 return 0
2437 }
2438 if (thisStart >= thisEnd) {
2439 return -1
2440 }
2441 if (start >= end) {
2442 return 1
2443 }
2444
2445 start >>>= 0
2446 end >>>= 0
2447 thisStart >>>= 0
2448 thisEnd >>>= 0
2449
2450 if (this === target) return 0
2451
2452 var x = thisEnd - thisStart
2453 var y = end - start
2454 var len = Math.min(x, y)
2455
2456 var thisCopy = this.slice(thisStart, thisEnd)
2457 var targetCopy = target.slice(start, end)
2458
2459 for (var i = 0; i < len; ++i) {
2460 if (thisCopy[i] !== targetCopy[i]) {
2461 x = thisCopy[i]
2462 y = targetCopy[i]
2463 break
2464 }
2465 }
2466
2467 if (x < y) return -1
2468 if (y < x) return 1
2469 return 0
2470}
2471
2472// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
2473// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
2474//
2475// Arguments:
2476// - buffer - a Buffer to search
2477// - val - a string, Buffer, or number
2478// - byteOffset - an index into `buffer`; will be clamped to an int32
2479// - encoding - an optional encoding, relevant is val is a string
2480// - dir - true for indexOf, false for lastIndexOf
2481function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
2482 // Empty buffer means no match
2483 if (buffer.length === 0) return -1
2484
2485 // Normalize byteOffset
2486 if (typeof byteOffset === 'string') {
2487 encoding = byteOffset
2488 byteOffset = 0
2489 } else if (byteOffset > 0x7fffffff) {
2490 byteOffset = 0x7fffffff
2491 } else if (byteOffset < -0x80000000) {
2492 byteOffset = -0x80000000
2493 }
2494 byteOffset = +byteOffset // Coerce to Number.
2495 if (numberIsNaN(byteOffset)) {
2496 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
2497 byteOffset = dir ? 0 : (buffer.length - 1)
2498 }
2499
2500 // Normalize byteOffset: negative offsets start from the end of the buffer
2501 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
2502 if (byteOffset >= buffer.length) {
2503 if (dir) return -1
2504 else byteOffset = buffer.length - 1
2505 } else if (byteOffset < 0) {
2506 if (dir) byteOffset = 0
2507 else return -1
2508 }
2509
2510 // Normalize val
2511 if (typeof val === 'string') {
2512 val = Buffer.from(val, encoding)
2513 }
2514
2515 // Finally, search either indexOf (if dir is true) or lastIndexOf
2516 if (Buffer.isBuffer(val)) {
2517 // Special case: looking for empty string/buffer always fails
2518 if (val.length === 0) {
2519 return -1
2520 }
2521 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
2522 } else if (typeof val === 'number') {
2523 val = val & 0xFF // Search for a byte value [0-255]
2524 if (typeof Uint8Array.prototype.indexOf === 'function') {
2525 if (dir) {
2526 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
2527 } else {
2528 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
2529 }
2530 }
2531 return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
2532 }
2533
2534 throw new TypeError('val must be string, number or Buffer')
2535}
2536
2537function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
2538 var indexSize = 1
2539 var arrLength = arr.length
2540 var valLength = val.length
2541
2542 if (encoding !== undefined) {
2543 encoding = String(encoding).toLowerCase()
2544 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
2545 encoding === 'utf16le' || encoding === 'utf-16le') {
2546 if (arr.length < 2 || val.length < 2) {
2547 return -1
2548 }
2549 indexSize = 2
2550 arrLength /= 2
2551 valLength /= 2
2552 byteOffset /= 2
2553 }
2554 }
2555
2556 function read (buf, i) {
2557 if (indexSize === 1) {
2558 return buf[i]
2559 } else {
2560 return buf.readUInt16BE(i * indexSize)
2561 }
2562 }
2563
2564 var i
2565 if (dir) {
2566 var foundIndex = -1
2567 for (i = byteOffset; i < arrLength; i++) {
2568 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
2569 if (foundIndex === -1) foundIndex = i
2570 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
2571 } else {
2572 if (foundIndex !== -1) i -= i - foundIndex
2573 foundIndex = -1
2574 }
2575 }
2576 } else {
2577 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
2578 for (i = byteOffset; i >= 0; i--) {
2579 var found = true
2580 for (var j = 0; j < valLength; j++) {
2581 if (read(arr, i + j) !== read(val, j)) {
2582 found = false
2583 break
2584 }
2585 }
2586 if (found) return i
2587 }
2588 }
2589
2590 return -1
2591}
2592
2593Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
2594 return this.indexOf(val, byteOffset, encoding) !== -1
2595}
2596
2597Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
2598 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
2599}
2600
2601Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
2602 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
2603}
2604
2605function hexWrite (buf, string, offset, length) {
2606 offset = Number(offset) || 0
2607 var remaining = buf.length - offset
2608 if (!length) {
2609 length = remaining
2610 } else {
2611 length = Number(length)
2612 if (length > remaining) {
2613 length = remaining
2614 }
2615 }
2616
2617 var strLen = string.length
2618
2619 if (length > strLen / 2) {
2620 length = strLen / 2
2621 }
2622 for (var i = 0; i < length; ++i) {
2623 var parsed = parseInt(string.substr(i * 2, 2), 16)
2624 if (numberIsNaN(parsed)) return i
2625 buf[offset + i] = parsed
2626 }
2627 return i
2628}
2629
2630function utf8Write (buf, string, offset, length) {
2631 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
2632}
2633
2634function asciiWrite (buf, string, offset, length) {
2635 return blitBuffer(asciiToBytes(string), buf, offset, length)
2636}
2637
2638function latin1Write (buf, string, offset, length) {
2639 return asciiWrite(buf, string, offset, length)
2640}
2641
2642function base64Write (buf, string, offset, length) {
2643 return blitBuffer(base64ToBytes(string), buf, offset, length)
2644}
2645
2646function ucs2Write (buf, string, offset, length) {
2647 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
2648}
2649
2650Buffer.prototype.write = function write (string, offset, length, encoding) {
2651 // Buffer#write(string)
2652 if (offset === undefined) {
2653 encoding = 'utf8'
2654 length = this.length
2655 offset = 0
2656 // Buffer#write(string, encoding)
2657 } else if (length === undefined && typeof offset === 'string') {
2658 encoding = offset
2659 length = this.length
2660 offset = 0
2661 // Buffer#write(string, offset[, length][, encoding])
2662 } else if (isFinite(offset)) {
2663 offset = offset >>> 0
2664 if (isFinite(length)) {
2665 length = length >>> 0
2666 if (encoding === undefined) encoding = 'utf8'
2667 } else {
2668 encoding = length
2669 length = undefined
2670 }
2671 } else {
2672 throw new Error(
2673 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
2674 )
2675 }
2676
2677 var remaining = this.length - offset
2678 if (length === undefined || length > remaining) length = remaining
2679
2680 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
2681 throw new RangeError('Attempt to write outside buffer bounds')
2682 }
2683
2684 if (!encoding) encoding = 'utf8'
2685
2686 var loweredCase = false
2687 for (;;) {
2688 switch (encoding) {
2689 case 'hex':
2690 return hexWrite(this, string, offset, length)
2691
2692 case 'utf8':
2693 case 'utf-8':
2694 return utf8Write(this, string, offset, length)
2695
2696 case 'ascii':
2697 return asciiWrite(this, string, offset, length)
2698
2699 case 'latin1':
2700 case 'binary':
2701 return latin1Write(this, string, offset, length)
2702
2703 case 'base64':
2704 // Warning: maxLength not taken into account in base64Write
2705 return base64Write(this, string, offset, length)
2706
2707 case 'ucs2':
2708 case 'ucs-2':
2709 case 'utf16le':
2710 case 'utf-16le':
2711 return ucs2Write(this, string, offset, length)
2712
2713 default:
2714 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
2715 encoding = ('' + encoding).toLowerCase()
2716 loweredCase = true
2717 }
2718 }
2719}
2720
2721Buffer.prototype.toJSON = function toJSON () {
2722 return {
2723 type: 'Buffer',
2724 data: Array.prototype.slice.call(this._arr || this, 0)
2725 }
2726}
2727
2728function base64Slice (buf, start, end) {
2729 if (start === 0 && end === buf.length) {
2730 return base64.fromByteArray(buf)
2731 } else {
2732 return base64.fromByteArray(buf.slice(start, end))
2733 }
2734}
2735
2736function utf8Slice (buf, start, end) {
2737 end = Math.min(buf.length, end)
2738 var res = []
2739
2740 var i = start
2741 while (i < end) {
2742 var firstByte = buf[i]
2743 var codePoint = null
2744 var bytesPerSequence = (firstByte > 0xEF) ? 4
2745 : (firstByte > 0xDF) ? 3
2746 : (firstByte > 0xBF) ? 2
2747 : 1
2748
2749 if (i + bytesPerSequence <= end) {
2750 var secondByte, thirdByte, fourthByte, tempCodePoint
2751
2752 switch (bytesPerSequence) {
2753 case 1:
2754 if (firstByte < 0x80) {
2755 codePoint = firstByte
2756 }
2757 break
2758 case 2:
2759 secondByte = buf[i + 1]
2760 if ((secondByte & 0xC0) === 0x80) {
2761 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
2762 if (tempCodePoint > 0x7F) {
2763 codePoint = tempCodePoint
2764 }
2765 }
2766 break
2767 case 3:
2768 secondByte = buf[i + 1]
2769 thirdByte = buf[i + 2]
2770 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
2771 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
2772 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
2773 codePoint = tempCodePoint
2774 }
2775 }
2776 break
2777 case 4:
2778 secondByte = buf[i + 1]
2779 thirdByte = buf[i + 2]
2780 fourthByte = buf[i + 3]
2781 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
2782 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
2783 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
2784 codePoint = tempCodePoint
2785 }
2786 }
2787 }
2788 }
2789
2790 if (codePoint === null) {
2791 // we did not generate a valid codePoint so insert a
2792 // replacement char (U+FFFD) and advance only 1 byte
2793 codePoint = 0xFFFD
2794 bytesPerSequence = 1
2795 } else if (codePoint > 0xFFFF) {
2796 // encode to utf16 (surrogate pair dance)
2797 codePoint -= 0x10000
2798 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
2799 codePoint = 0xDC00 | codePoint & 0x3FF
2800 }
2801
2802 res.push(codePoint)
2803 i += bytesPerSequence
2804 }
2805
2806 return decodeCodePointsArray(res)
2807}
2808
2809// Based on http://stackoverflow.com/a/22747272/680742, the browser with
2810// the lowest limit is Chrome, with 0x10000 args.
2811// We go 1 magnitude less, for safety
2812var MAX_ARGUMENTS_LENGTH = 0x1000
2813
2814function decodeCodePointsArray (codePoints) {
2815 var len = codePoints.length
2816 if (len <= MAX_ARGUMENTS_LENGTH) {
2817 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
2818 }
2819
2820 // Decode in chunks to avoid "call stack size exceeded".
2821 var res = ''
2822 var i = 0
2823 while (i < len) {
2824 res += String.fromCharCode.apply(
2825 String,
2826 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
2827 )
2828 }
2829 return res
2830}
2831
2832function asciiSlice (buf, start, end) {
2833 var ret = ''
2834 end = Math.min(buf.length, end)
2835
2836 for (var i = start; i < end; ++i) {
2837 ret += String.fromCharCode(buf[i] & 0x7F)
2838 }
2839 return ret
2840}
2841
2842function latin1Slice (buf, start, end) {
2843 var ret = ''
2844 end = Math.min(buf.length, end)
2845
2846 for (var i = start; i < end; ++i) {
2847 ret += String.fromCharCode(buf[i])
2848 }
2849 return ret
2850}
2851
2852function hexSlice (buf, start, end) {
2853 var len = buf.length
2854
2855 if (!start || start < 0) start = 0
2856 if (!end || end < 0 || end > len) end = len
2857
2858 var out = ''
2859 for (var i = start; i < end; ++i) {
2860 out += hexSliceLookupTable[buf[i]]
2861 }
2862 return out
2863}
2864
2865function utf16leSlice (buf, start, end) {
2866 var bytes = buf.slice(start, end)
2867 var res = ''
2868 for (var i = 0; i < bytes.length; i += 2) {
2869 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
2870 }
2871 return res
2872}
2873
2874Buffer.prototype.slice = function slice (start, end) {
2875 var len = this.length
2876 start = ~~start
2877 end = end === undefined ? len : ~~end
2878
2879 if (start < 0) {
2880 start += len
2881 if (start < 0) start = 0
2882 } else if (start > len) {
2883 start = len
2884 }
2885
2886 if (end < 0) {
2887 end += len
2888 if (end < 0) end = 0
2889 } else if (end > len) {
2890 end = len
2891 }
2892
2893 if (end < start) end = start
2894
2895 var newBuf = this.subarray(start, end)
2896 // Return an augmented `Uint8Array` instance
2897 Object.setPrototypeOf(newBuf, Buffer.prototype)
2898
2899 return newBuf
2900}
2901
2902/*
2903 * Need to make sure that buffer isn't trying to write out of bounds.
2904 */
2905function checkOffset (offset, ext, length) {
2906 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
2907 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
2908}
2909
2910Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
2911 offset = offset >>> 0
2912 byteLength = byteLength >>> 0
2913 if (!noAssert) checkOffset(offset, byteLength, this.length)
2914
2915 var val = this[offset]
2916 var mul = 1
2917 var i = 0
2918 while (++i < byteLength && (mul *= 0x100)) {
2919 val += this[offset + i] * mul
2920 }
2921
2922 return val
2923}
2924
2925Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
2926 offset = offset >>> 0
2927 byteLength = byteLength >>> 0
2928 if (!noAssert) {
2929 checkOffset(offset, byteLength, this.length)
2930 }
2931
2932 var val = this[offset + --byteLength]
2933 var mul = 1
2934 while (byteLength > 0 && (mul *= 0x100)) {
2935 val += this[offset + --byteLength] * mul
2936 }
2937
2938 return val
2939}
2940
2941Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
2942 offset = offset >>> 0
2943 if (!noAssert) checkOffset(offset, 1, this.length)
2944 return this[offset]
2945}
2946
2947Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
2948 offset = offset >>> 0
2949 if (!noAssert) checkOffset(offset, 2, this.length)
2950 return this[offset] | (this[offset + 1] << 8)
2951}
2952
2953Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
2954 offset = offset >>> 0
2955 if (!noAssert) checkOffset(offset, 2, this.length)
2956 return (this[offset] << 8) | this[offset + 1]
2957}
2958
2959Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
2960 offset = offset >>> 0
2961 if (!noAssert) checkOffset(offset, 4, this.length)
2962
2963 return ((this[offset]) |
2964 (this[offset + 1] << 8) |
2965 (this[offset + 2] << 16)) +
2966 (this[offset + 3] * 0x1000000)
2967}
2968
2969Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
2970 offset = offset >>> 0
2971 if (!noAssert) checkOffset(offset, 4, this.length)
2972
2973 return (this[offset] * 0x1000000) +
2974 ((this[offset + 1] << 16) |
2975 (this[offset + 2] << 8) |
2976 this[offset + 3])
2977}
2978
2979Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
2980 offset = offset >>> 0
2981 byteLength = byteLength >>> 0
2982 if (!noAssert) checkOffset(offset, byteLength, this.length)
2983
2984 var val = this[offset]
2985 var mul = 1
2986 var i = 0
2987 while (++i < byteLength && (mul *= 0x100)) {
2988 val += this[offset + i] * mul
2989 }
2990 mul *= 0x80
2991
2992 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
2993
2994 return val
2995}
2996
2997Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
2998 offset = offset >>> 0
2999 byteLength = byteLength >>> 0
3000 if (!noAssert) checkOffset(offset, byteLength, this.length)
3001
3002 var i = byteLength
3003 var mul = 1
3004 var val = this[offset + --i]
3005 while (i > 0 && (mul *= 0x100)) {
3006 val += this[offset + --i] * mul
3007 }
3008 mul *= 0x80
3009
3010 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
3011
3012 return val
3013}
3014
3015Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
3016 offset = offset >>> 0
3017 if (!noAssert) checkOffset(offset, 1, this.length)
3018 if (!(this[offset] & 0x80)) return (this[offset])
3019 return ((0xff - this[offset] + 1) * -1)
3020}
3021
3022Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
3023 offset = offset >>> 0
3024 if (!noAssert) checkOffset(offset, 2, this.length)
3025 var val = this[offset] | (this[offset + 1] << 8)
3026 return (val & 0x8000) ? val | 0xFFFF0000 : val
3027}
3028
3029Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
3030 offset = offset >>> 0
3031 if (!noAssert) checkOffset(offset, 2, this.length)
3032 var val = this[offset + 1] | (this[offset] << 8)
3033 return (val & 0x8000) ? val | 0xFFFF0000 : val
3034}
3035
3036Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
3037 offset = offset >>> 0
3038 if (!noAssert) checkOffset(offset, 4, this.length)
3039
3040 return (this[offset]) |
3041 (this[offset + 1] << 8) |
3042 (this[offset + 2] << 16) |
3043 (this[offset + 3] << 24)
3044}
3045
3046Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
3047 offset = offset >>> 0
3048 if (!noAssert) checkOffset(offset, 4, this.length)
3049
3050 return (this[offset] << 24) |
3051 (this[offset + 1] << 16) |
3052 (this[offset + 2] << 8) |
3053 (this[offset + 3])
3054}
3055
3056Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
3057 offset = offset >>> 0
3058 if (!noAssert) checkOffset(offset, 4, this.length)
3059 return ieee754.read(this, offset, true, 23, 4)
3060}
3061
3062Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
3063 offset = offset >>> 0
3064 if (!noAssert) checkOffset(offset, 4, this.length)
3065 return ieee754.read(this, offset, false, 23, 4)
3066}
3067
3068Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
3069 offset = offset >>> 0
3070 if (!noAssert) checkOffset(offset, 8, this.length)
3071 return ieee754.read(this, offset, true, 52, 8)
3072}
3073
3074Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
3075 offset = offset >>> 0
3076 if (!noAssert) checkOffset(offset, 8, this.length)
3077 return ieee754.read(this, offset, false, 52, 8)
3078}
3079
3080function checkInt (buf, value, offset, ext, max, min) {
3081 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
3082 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
3083 if (offset + ext > buf.length) throw new RangeError('Index out of range')
3084}
3085
3086Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
3087 value = +value
3088 offset = offset >>> 0
3089 byteLength = byteLength >>> 0
3090 if (!noAssert) {
3091 var maxBytes = Math.pow(2, 8 * byteLength) - 1
3092 checkInt(this, value, offset, byteLength, maxBytes, 0)
3093 }
3094
3095 var mul = 1
3096 var i = 0
3097 this[offset] = value & 0xFF
3098 while (++i < byteLength && (mul *= 0x100)) {
3099 this[offset + i] = (value / mul) & 0xFF
3100 }
3101
3102 return offset + byteLength
3103}
3104
3105Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
3106 value = +value
3107 offset = offset >>> 0
3108 byteLength = byteLength >>> 0
3109 if (!noAssert) {
3110 var maxBytes = Math.pow(2, 8 * byteLength) - 1
3111 checkInt(this, value, offset, byteLength, maxBytes, 0)
3112 }
3113
3114 var i = byteLength - 1
3115 var mul = 1
3116 this[offset + i] = value & 0xFF
3117 while (--i >= 0 && (mul *= 0x100)) {
3118 this[offset + i] = (value / mul) & 0xFF
3119 }
3120
3121 return offset + byteLength
3122}
3123
3124Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
3125 value = +value
3126 offset = offset >>> 0
3127 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
3128 this[offset] = (value & 0xff)
3129 return offset + 1
3130}
3131
3132Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
3133 value = +value
3134 offset = offset >>> 0
3135 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
3136 this[offset] = (value & 0xff)
3137 this[offset + 1] = (value >>> 8)
3138 return offset + 2
3139}
3140
3141Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
3142 value = +value
3143 offset = offset >>> 0
3144 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
3145 this[offset] = (value >>> 8)
3146 this[offset + 1] = (value & 0xff)
3147 return offset + 2
3148}
3149
3150Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
3151 value = +value
3152 offset = offset >>> 0
3153 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
3154 this[offset + 3] = (value >>> 24)
3155 this[offset + 2] = (value >>> 16)
3156 this[offset + 1] = (value >>> 8)
3157 this[offset] = (value & 0xff)
3158 return offset + 4
3159}
3160
3161Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
3162 value = +value
3163 offset = offset >>> 0
3164 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
3165 this[offset] = (value >>> 24)
3166 this[offset + 1] = (value >>> 16)
3167 this[offset + 2] = (value >>> 8)
3168 this[offset + 3] = (value & 0xff)
3169 return offset + 4
3170}
3171
3172Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
3173 value = +value
3174 offset = offset >>> 0
3175 if (!noAssert) {
3176 var limit = Math.pow(2, (8 * byteLength) - 1)
3177
3178 checkInt(this, value, offset, byteLength, limit - 1, -limit)
3179 }
3180
3181 var i = 0
3182 var mul = 1
3183 var sub = 0
3184 this[offset] = value & 0xFF
3185 while (++i < byteLength && (mul *= 0x100)) {
3186 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
3187 sub = 1
3188 }
3189 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
3190 }
3191
3192 return offset + byteLength
3193}
3194
3195Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
3196 value = +value
3197 offset = offset >>> 0
3198 if (!noAssert) {
3199 var limit = Math.pow(2, (8 * byteLength) - 1)
3200
3201 checkInt(this, value, offset, byteLength, limit - 1, -limit)
3202 }
3203
3204 var i = byteLength - 1
3205 var mul = 1
3206 var sub = 0
3207 this[offset + i] = value & 0xFF
3208 while (--i >= 0 && (mul *= 0x100)) {
3209 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
3210 sub = 1
3211 }
3212 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
3213 }
3214
3215 return offset + byteLength
3216}
3217
3218Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
3219 value = +value
3220 offset = offset >>> 0
3221 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
3222 if (value < 0) value = 0xff + value + 1
3223 this[offset] = (value & 0xff)
3224 return offset + 1
3225}
3226
3227Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
3228 value = +value
3229 offset = offset >>> 0
3230 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
3231 this[offset] = (value & 0xff)
3232 this[offset + 1] = (value >>> 8)
3233 return offset + 2
3234}
3235
3236Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
3237 value = +value
3238 offset = offset >>> 0
3239 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
3240 this[offset] = (value >>> 8)
3241 this[offset + 1] = (value & 0xff)
3242 return offset + 2
3243}
3244
3245Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
3246 value = +value
3247 offset = offset >>> 0
3248 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
3249 this[offset] = (value & 0xff)
3250 this[offset + 1] = (value >>> 8)
3251 this[offset + 2] = (value >>> 16)
3252 this[offset + 3] = (value >>> 24)
3253 return offset + 4
3254}
3255
3256Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
3257 value = +value
3258 offset = offset >>> 0
3259 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
3260 if (value < 0) value = 0xffffffff + value + 1
3261 this[offset] = (value >>> 24)
3262 this[offset + 1] = (value >>> 16)
3263 this[offset + 2] = (value >>> 8)
3264 this[offset + 3] = (value & 0xff)
3265 return offset + 4
3266}
3267
3268function checkIEEE754 (buf, value, offset, ext, max, min) {
3269 if (offset + ext > buf.length) throw new RangeError('Index out of range')
3270 if (offset < 0) throw new RangeError('Index out of range')
3271}
3272
3273function writeFloat (buf, value, offset, littleEndian, noAssert) {
3274 value = +value
3275 offset = offset >>> 0
3276 if (!noAssert) {
3277 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
3278 }
3279 ieee754.write(buf, value, offset, littleEndian, 23, 4)
3280 return offset + 4
3281}
3282
3283Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
3284 return writeFloat(this, value, offset, true, noAssert)
3285}
3286
3287Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
3288 return writeFloat(this, value, offset, false, noAssert)
3289}
3290
3291function writeDouble (buf, value, offset, littleEndian, noAssert) {
3292 value = +value
3293 offset = offset >>> 0
3294 if (!noAssert) {
3295 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
3296 }
3297 ieee754.write(buf, value, offset, littleEndian, 52, 8)
3298 return offset + 8
3299}
3300
3301Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
3302 return writeDouble(this, value, offset, true, noAssert)
3303}
3304
3305Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
3306 return writeDouble(this, value, offset, false, noAssert)
3307}
3308
3309// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
3310Buffer.prototype.copy = function copy (target, targetStart, start, end) {
3311 if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
3312 if (!start) start = 0
3313 if (!end && end !== 0) end = this.length
3314 if (targetStart >= target.length) targetStart = target.length
3315 if (!targetStart) targetStart = 0
3316 if (end > 0 && end < start) end = start
3317
3318 // Copy 0 bytes; we're done
3319 if (end === start) return 0
3320 if (target.length === 0 || this.length === 0) return 0
3321
3322 // Fatal error conditions
3323 if (targetStart < 0) {
3324 throw new RangeError('targetStart out of bounds')
3325 }
3326 if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
3327 if (end < 0) throw new RangeError('sourceEnd out of bounds')
3328
3329 // Are we oob?
3330 if (end > this.length) end = this.length
3331 if (target.length - targetStart < end - start) {
3332 end = target.length - targetStart + start
3333 }
3334
3335 var len = end - start
3336
3337 if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
3338 // Use built-in when available, missing from IE11
3339 this.copyWithin(targetStart, start, end)
3340 } else if (this === target && start < targetStart && targetStart < end) {
3341 // descending copy from end
3342 for (var i = len - 1; i >= 0; --i) {
3343 target[i + targetStart] = this[i + start]
3344 }
3345 } else {
3346 Uint8Array.prototype.set.call(
3347 target,
3348 this.subarray(start, end),
3349 targetStart
3350 )
3351 }
3352
3353 return len
3354}
3355
3356// Usage:
3357// buffer.fill(number[, offset[, end]])
3358// buffer.fill(buffer[, offset[, end]])
3359// buffer.fill(string[, offset[, end]][, encoding])
3360Buffer.prototype.fill = function fill (val, start, end, encoding) {
3361 // Handle string cases:
3362 if (typeof val === 'string') {
3363 if (typeof start === 'string') {
3364 encoding = start
3365 start = 0
3366 end = this.length
3367 } else if (typeof end === 'string') {
3368 encoding = end
3369 end = this.length
3370 }
3371 if (encoding !== undefined && typeof encoding !== 'string') {
3372 throw new TypeError('encoding must be a string')
3373 }
3374 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
3375 throw new TypeError('Unknown encoding: ' + encoding)
3376 }
3377 if (val.length === 1) {
3378 var code = val.charCodeAt(0)
3379 if ((encoding === 'utf8' && code < 128) ||
3380 encoding === 'latin1') {
3381 // Fast path: If `val` fits into a single byte, use that numeric value.
3382 val = code
3383 }
3384 }
3385 } else if (typeof val === 'number') {
3386 val = val & 255
3387 } else if (typeof val === 'boolean') {
3388 val = Number(val)
3389 }
3390
3391 // Invalid ranges are not set to a default, so can range check early.
3392 if (start < 0 || this.length < start || this.length < end) {
3393 throw new RangeError('Out of range index')
3394 }
3395
3396 if (end <= start) {
3397 return this
3398 }
3399
3400 start = start >>> 0
3401 end = end === undefined ? this.length : end >>> 0
3402
3403 if (!val) val = 0
3404
3405 var i
3406 if (typeof val === 'number') {
3407 for (i = start; i < end; ++i) {
3408 this[i] = val
3409 }
3410 } else {
3411 var bytes = Buffer.isBuffer(val)
3412 ? val
3413 : Buffer.from(val, encoding)
3414 var len = bytes.length
3415 if (len === 0) {
3416 throw new TypeError('The value "' + val +
3417 '" is invalid for argument "value"')
3418 }
3419 for (i = 0; i < end - start; ++i) {
3420 this[i + start] = bytes[i % len]
3421 }
3422 }
3423
3424 return this
3425}
3426
3427// HELPER FUNCTIONS
3428// ================
3429
3430var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
3431
3432function base64clean (str) {
3433 // Node takes equal signs as end of the Base64 encoding
3434 str = str.split('=')[0]
3435 // Node strips out invalid characters like \n and \t from the string, base64-js does not
3436 str = str.trim().replace(INVALID_BASE64_RE, '')
3437 // Node converts strings with length < 2 to ''
3438 if (str.length < 2) return ''
3439 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
3440 while (str.length % 4 !== 0) {
3441 str = str + '='
3442 }
3443 return str
3444}
3445
3446function utf8ToBytes (string, units) {
3447 units = units || Infinity
3448 var codePoint
3449 var length = string.length
3450 var leadSurrogate = null
3451 var bytes = []
3452
3453 for (var i = 0; i < length; ++i) {
3454 codePoint = string.charCodeAt(i)
3455
3456 // is surrogate component
3457 if (codePoint > 0xD7FF && codePoint < 0xE000) {
3458 // last char was a lead
3459 if (!leadSurrogate) {
3460 // no lead yet
3461 if (codePoint > 0xDBFF) {
3462 // unexpected trail
3463 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3464 continue
3465 } else if (i + 1 === length) {
3466 // unpaired lead
3467 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3468 continue
3469 }
3470
3471 // valid lead
3472 leadSurrogate = codePoint
3473
3474 continue
3475 }
3476
3477 // 2 leads in a row
3478 if (codePoint < 0xDC00) {
3479 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3480 leadSurrogate = codePoint
3481 continue
3482 }
3483
3484 // valid surrogate pair
3485 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
3486 } else if (leadSurrogate) {
3487 // valid bmp char, but last char was a lead
3488 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3489 }
3490
3491 leadSurrogate = null
3492
3493 // encode utf8
3494 if (codePoint < 0x80) {
3495 if ((units -= 1) < 0) break
3496 bytes.push(codePoint)
3497 } else if (codePoint < 0x800) {
3498 if ((units -= 2) < 0) break
3499 bytes.push(
3500 codePoint >> 0x6 | 0xC0,
3501 codePoint & 0x3F | 0x80
3502 )
3503 } else if (codePoint < 0x10000) {
3504 if ((units -= 3) < 0) break
3505 bytes.push(
3506 codePoint >> 0xC | 0xE0,
3507 codePoint >> 0x6 & 0x3F | 0x80,
3508 codePoint & 0x3F | 0x80
3509 )
3510 } else if (codePoint < 0x110000) {
3511 if ((units -= 4) < 0) break
3512 bytes.push(
3513 codePoint >> 0x12 | 0xF0,
3514 codePoint >> 0xC & 0x3F | 0x80,
3515 codePoint >> 0x6 & 0x3F | 0x80,
3516 codePoint & 0x3F | 0x80
3517 )
3518 } else {
3519 throw new Error('Invalid code point')
3520 }
3521 }
3522
3523 return bytes
3524}
3525
3526function asciiToBytes (str) {
3527 var byteArray = []
3528 for (var i = 0; i < str.length; ++i) {
3529 // Node's code seems to be doing this and not & 0x7F..
3530 byteArray.push(str.charCodeAt(i) & 0xFF)
3531 }
3532 return byteArray
3533}
3534
3535function utf16leToBytes (str, units) {
3536 var c, hi, lo
3537 var byteArray = []
3538 for (var i = 0; i < str.length; ++i) {
3539 if ((units -= 2) < 0) break
3540
3541 c = str.charCodeAt(i)
3542 hi = c >> 8
3543 lo = c % 256
3544 byteArray.push(lo)
3545 byteArray.push(hi)
3546 }
3547
3548 return byteArray
3549}
3550
3551function base64ToBytes (str) {
3552 return base64.toByteArray(base64clean(str))
3553}
3554
3555function blitBuffer (src, dst, offset, length) {
3556 for (var i = 0; i < length; ++i) {
3557 if ((i + offset >= dst.length) || (i >= src.length)) break
3558 dst[i + offset] = src[i]
3559 }
3560 return i
3561}
3562
3563// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
3564// the `instanceof` check but they should be treated as of that type.
3565// See: https://github.com/feross/buffer/issues/166
3566function isInstance (obj, type) {
3567 return obj instanceof type ||
3568 (obj != null && obj.constructor != null && obj.constructor.name != null &&
3569 obj.constructor.name === type.name)
3570}
3571function numberIsNaN (obj) {
3572 // For IE11 support
3573 return obj !== obj // eslint-disable-line no-self-compare
3574}
3575
3576// Create lookup table for `toString('hex')`
3577// See: https://github.com/feross/buffer/issues/219
3578var hexSliceLookupTable = (function () {
3579 var alphabet = '0123456789abcdef'
3580 var table = new Array(256)
3581 for (var i = 0; i < 16; ++i) {
3582 var i16 = i * 16
3583 for (var j = 0; j < 16; ++j) {
3584 table[i16 + j] = alphabet[i] + alphabet[j]
3585 }
3586 }
3587 return table
3588})()
3589
3590}).call(this,_dereq_(12).Buffer)
3591},{"12":12,"22":22,"9":9}],13:[function(_dereq_,module,exports){
3592(function (Buffer){
3593// Copyright Joyent, Inc. and other Node contributors.
3594//
3595// Permission is hereby granted, free of charge, to any person obtaining a
3596// copy of this software and associated documentation files (the
3597// "Software"), to deal in the Software without restriction, including
3598// without limitation the rights to use, copy, modify, merge, publish,
3599// distribute, sublicense, and/or sell copies of the Software, and to permit
3600// persons to whom the Software is furnished to do so, subject to the
3601// following conditions:
3602//
3603// The above copyright notice and this permission notice shall be included
3604// in all copies or substantial portions of the Software.
3605//
3606// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3607// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3608// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3609// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3610// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3611// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3612// USE OR OTHER DEALINGS IN THE SOFTWARE.
3613
3614// NOTE: These type checking functions intentionally don't use `instanceof`
3615// because it is fragile and can be easily faked with `Object.create()`.
3616
3617function isArray(arg) {
3618 if (Array.isArray) {
3619 return Array.isArray(arg);
3620 }
3621 return objectToString(arg) === '[object Array]';
3622}
3623exports.isArray = isArray;
3624
3625function isBoolean(arg) {
3626 return typeof arg === 'boolean';
3627}
3628exports.isBoolean = isBoolean;
3629
3630function isNull(arg) {
3631 return arg === null;
3632}
3633exports.isNull = isNull;
3634
3635function isNullOrUndefined(arg) {
3636 return arg == null;
3637}
3638exports.isNullOrUndefined = isNullOrUndefined;
3639
3640function isNumber(arg) {
3641 return typeof arg === 'number';
3642}
3643exports.isNumber = isNumber;
3644
3645function isString(arg) {
3646 return typeof arg === 'string';
3647}
3648exports.isString = isString;
3649
3650function isSymbol(arg) {
3651 return typeof arg === 'symbol';
3652}
3653exports.isSymbol = isSymbol;
3654
3655function isUndefined(arg) {
3656 return arg === void 0;
3657}
3658exports.isUndefined = isUndefined;
3659
3660function isRegExp(re) {
3661 return objectToString(re) === '[object RegExp]';
3662}
3663exports.isRegExp = isRegExp;
3664
3665function isObject(arg) {
3666 return typeof arg === 'object' && arg !== null;
3667}
3668exports.isObject = isObject;
3669
3670function isDate(d) {
3671 return objectToString(d) === '[object Date]';
3672}
3673exports.isDate = isDate;
3674
3675function isError(e) {
3676 return (objectToString(e) === '[object Error]' || e instanceof Error);
3677}
3678exports.isError = isError;
3679
3680function isFunction(arg) {
3681 return typeof arg === 'function';
3682}
3683exports.isFunction = isFunction;
3684
3685function isPrimitive(arg) {
3686 return arg === null ||
3687 typeof arg === 'boolean' ||
3688 typeof arg === 'number' ||
3689 typeof arg === 'string' ||
3690 typeof arg === 'symbol' || // ES6 symbol
3691 typeof arg === 'undefined';
3692}
3693exports.isPrimitive = isPrimitive;
3694
3695exports.isBuffer = Buffer.isBuffer;
3696
3697function objectToString(o) {
3698 return Object.prototype.toString.call(o);
3699}
3700
3701}).call(this,{"isBuffer":_dereq_(25)})
3702},{"25":25}],14:[function(_dereq_,module,exports){
3703var Buffer = _dereq_(12).Buffer
3704
3705var CHARS = '.PYFGCRLAOEUIDHTNSQJKXBMWVZ_pyfgcrlaoeuidhtnsqjkxbmwvz1234567890'
3706 .split('').sort().join('')
3707
3708module.exports = function (chars, exports) {
3709 chars = chars || CHARS
3710 exports = exports || {}
3711 if(chars.length !== 64) throw new Error('a base 64 encoding requires 64 chars')
3712
3713 var codeToIndex = new Buffer(128)
3714 codeToIndex.fill()
3715
3716 for(var i = 0; i < 64; i++) {
3717 var code = chars.charCodeAt(i)
3718 codeToIndex[code] = i
3719 }
3720
3721 exports.encode = function (data) {
3722 var s = '', l = data.length, hang = 0
3723 for(var i = 0; i < l; i++) {
3724 var v = data[i]
3725
3726 switch (i % 3) {
3727 case 0:
3728 s += chars[v >> 2]
3729 hang = (v & 3) << 4
3730 break;
3731 case 1:
3732 s += chars[hang | v >> 4]
3733 hang = (v & 0xf) << 2
3734 break;
3735 case 2:
3736 s += chars[hang | v >> 6]
3737 s += chars[v & 0x3f]
3738 hang = 0
3739 break;
3740 }
3741
3742 }
3743 if(l%3) s += chars[hang]
3744 return s
3745 }
3746 exports.decode = function (str) {
3747 var l = str.length, j = 0
3748 var b = new Buffer(~~((l/4)*3)), hang = 0
3749
3750 for(var i = 0; i < l; i++) {
3751 var v = codeToIndex[str.charCodeAt(i)]
3752
3753 switch (i % 4) {
3754 case 0:
3755 hang = v << 2;
3756 break;
3757 case 1:
3758 b[j++] = hang | v >> 4
3759 hang = (v << 4) & 0xff
3760 break;
3761 case 2:
3762 b[j++] = hang | v >> 2
3763 hang = (v << 6) & 0xff
3764 break;
3765 case 3:
3766 b[j++] = hang | v
3767 break;
3768 }
3769
3770 }
3771 return b
3772 }
3773 return exports
3774}
3775
3776module.exports(CHARS, module.exports)
3777
3778
3779},{"12":12}],15:[function(_dereq_,module,exports){
3780/**
3781 * Copyright (c) 2013 Petka Antonov
3782 *
3783 * Permission is hereby granted, free of charge, to any person obtaining a copy
3784 * of this software and associated documentation files (the "Software"), to deal
3785 * in the Software without restriction, including without limitation the rights
3786 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
3787 * copies of the Software, and to permit persons to whom the Software is
3788 * furnished to do so, subject to the following conditions:</p>
3789 *
3790 * The above copyright notice and this permission notice shall be included in
3791 * all copies or substantial portions of the Software.
3792 *
3793 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
3794 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
3795 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
3796 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
3797 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
3798 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
3799 * THE SOFTWARE.
3800 */
3801"use strict";
3802function Deque(capacity) {
3803 this._capacity = getCapacity(capacity);
3804 this._length = 0;
3805 this._front = 0;
3806 if (isArray(capacity)) {
3807 var len = capacity.length;
3808 for (var i = 0; i < len; ++i) {
3809 this[i] = capacity[i];
3810 }
3811 this._length = len;
3812 }
3813}
3814
3815Deque.prototype.toArray = function Deque$toArray() {
3816 var len = this._length;
3817 var ret = new Array(len);
3818 var front = this._front;
3819 var capacity = this._capacity;
3820 for (var j = 0; j < len; ++j) {
3821 ret[j] = this[(front + j) & (capacity - 1)];
3822 }
3823 return ret;
3824};
3825
3826Deque.prototype.push = function Deque$push(item) {
3827 var argsLength = arguments.length;
3828 var length = this._length;
3829 if (argsLength > 1) {
3830 var capacity = this._capacity;
3831 if (length + argsLength > capacity) {
3832 for (var i = 0; i < argsLength; ++i) {
3833 this._checkCapacity(length + 1);
3834 var j = (this._front + length) & (this._capacity - 1);
3835 this[j] = arguments[i];
3836 length++;
3837 this._length = length;
3838 }
3839 return length;
3840 }
3841 else {
3842 var j = this._front;
3843 for (var i = 0; i < argsLength; ++i) {
3844 this[(j + length) & (capacity - 1)] = arguments[i];
3845 j++;
3846 }
3847 this._length = length + argsLength;
3848 return length + argsLength;
3849 }
3850
3851 }
3852
3853 if (argsLength === 0) return length;
3854
3855 this._checkCapacity(length + 1);
3856 var i = (this._front + length) & (this._capacity - 1);
3857 this[i] = item;
3858 this._length = length + 1;
3859 return length + 1;
3860};
3861
3862Deque.prototype.pop = function Deque$pop() {
3863 var length = this._length;
3864 if (length === 0) {
3865 return void 0;
3866 }
3867 var i = (this._front + length - 1) & (this._capacity - 1);
3868 var ret = this[i];
3869 this[i] = void 0;
3870 this._length = length - 1;
3871 return ret;
3872};
3873
3874Deque.prototype.shift = function Deque$shift() {
3875 var length = this._length;
3876 if (length === 0) {
3877 return void 0;
3878 }
3879 var front = this._front;
3880 var ret = this[front];
3881 this[front] = void 0;
3882 this._front = (front + 1) & (this._capacity - 1);
3883 this._length = length - 1;
3884 return ret;
3885};
3886
3887Deque.prototype.unshift = function Deque$unshift(item) {
3888 var length = this._length;
3889 var argsLength = arguments.length;
3890
3891
3892 if (argsLength > 1) {
3893 var capacity = this._capacity;
3894 if (length + argsLength > capacity) {
3895 for (var i = argsLength - 1; i >= 0; i--) {
3896 this._checkCapacity(length + 1);
3897 var capacity = this._capacity;
3898 var j = (((( this._front - 1 ) &
3899 ( capacity - 1) ) ^ capacity ) - capacity );
3900 this[j] = arguments[i];
3901 length++;
3902 this._length = length;
3903 this._front = j;
3904 }
3905 return length;
3906 }
3907 else {
3908 var front = this._front;
3909 for (var i = argsLength - 1; i >= 0; i--) {
3910 var j = (((( front - 1 ) &
3911 ( capacity - 1) ) ^ capacity ) - capacity );
3912 this[j] = arguments[i];
3913 front = j;
3914 }
3915 this._front = front;
3916 this._length = length + argsLength;
3917 return length + argsLength;
3918 }
3919 }
3920
3921 if (argsLength === 0) return length;
3922
3923 this._checkCapacity(length + 1);
3924 var capacity = this._capacity;
3925 var i = (((( this._front - 1 ) &
3926 ( capacity - 1) ) ^ capacity ) - capacity );
3927 this[i] = item;
3928 this._length = length + 1;
3929 this._front = i;
3930 return length + 1;
3931};
3932
3933Deque.prototype.peekBack = function Deque$peekBack() {
3934 var length = this._length;
3935 if (length === 0) {
3936 return void 0;
3937 }
3938 var index = (this._front + length - 1) & (this._capacity - 1);
3939 return this[index];
3940};
3941
3942Deque.prototype.peekFront = function Deque$peekFront() {
3943 if (this._length === 0) {
3944 return void 0;
3945 }
3946 return this[this._front];
3947};
3948
3949Deque.prototype.get = function Deque$get(index) {
3950 var i = index;
3951 if ((i !== (i | 0))) {
3952 return void 0;
3953 }
3954 var len = this._length;
3955 if (i < 0) {
3956 i = i + len;
3957 }
3958 if (i < 0 || i >= len) {
3959 return void 0;
3960 }
3961 return this[(this._front + i) & (this._capacity - 1)];
3962};
3963
3964Deque.prototype.isEmpty = function Deque$isEmpty() {
3965 return this._length === 0;
3966};
3967
3968Deque.prototype.clear = function Deque$clear() {
3969 var len = this._length;
3970 var front = this._front;
3971 var capacity = this._capacity;
3972 for (var j = 0; j < len; ++j) {
3973 this[(front + j) & (capacity - 1)] = void 0;
3974 }
3975 this._length = 0;
3976 this._front = 0;
3977};
3978
3979Deque.prototype.toString = function Deque$toString() {
3980 return this.toArray().toString();
3981};
3982
3983Deque.prototype.valueOf = Deque.prototype.toString;
3984Deque.prototype.removeFront = Deque.prototype.shift;
3985Deque.prototype.removeBack = Deque.prototype.pop;
3986Deque.prototype.insertFront = Deque.prototype.unshift;
3987Deque.prototype.insertBack = Deque.prototype.push;
3988Deque.prototype.enqueue = Deque.prototype.push;
3989Deque.prototype.dequeue = Deque.prototype.shift;
3990Deque.prototype.toJSON = Deque.prototype.toArray;
3991
3992Object.defineProperty(Deque.prototype, "length", {
3993 get: function() {
3994 return this._length;
3995 },
3996 set: function() {
3997 throw new RangeError("");
3998 }
3999});
4000
4001Deque.prototype._checkCapacity = function Deque$_checkCapacity(size) {
4002 if (this._capacity < size) {
4003 this._resizeTo(getCapacity(this._capacity * 1.5 + 16));
4004 }
4005};
4006
4007Deque.prototype._resizeTo = function Deque$_resizeTo(capacity) {
4008 var oldCapacity = this._capacity;
4009 this._capacity = capacity;
4010 var front = this._front;
4011 var length = this._length;
4012 if (front + length > oldCapacity) {
4013 var moveItemsCount = (front + length) & (oldCapacity - 1);
4014 arrayMove(this, 0, this, oldCapacity, moveItemsCount);
4015 }
4016};
4017
4018
4019var isArray = Array.isArray;
4020
4021function arrayMove(src, srcIndex, dst, dstIndex, len) {
4022 for (var j = 0; j < len; ++j) {
4023 dst[j + dstIndex] = src[j + srcIndex];
4024 src[j + srcIndex] = void 0;
4025 }
4026}
4027
4028function pow2AtLeast(n) {
4029 n = n >>> 0;
4030 n = n - 1;
4031 n = n | (n >> 1);
4032 n = n | (n >> 2);
4033 n = n | (n >> 4);
4034 n = n | (n >> 8);
4035 n = n | (n >> 16);
4036 return n + 1;
4037}
4038
4039function getCapacity(capacity) {
4040 if (typeof capacity !== "number") {
4041 if (isArray(capacity)) {
4042 capacity = capacity.length;
4043 }
4044 else {
4045 return 16;
4046 }
4047 }
4048 return pow2AtLeast(
4049 Math.min(
4050 Math.max(16, capacity), 1073741824)
4051 );
4052}
4053
4054module.exports = Deque;
4055
4056},{}],16:[function(_dereq_,module,exports){
4057var prr = _dereq_(69)
4058
4059function init (type, message, cause) {
4060 if (!!message && typeof message != 'string') {
4061 message = message.message || message.name
4062 }
4063 prr(this, {
4064 type : type
4065 , name : type
4066 // can be passed just a 'cause'
4067 , cause : typeof message != 'string' ? message : cause
4068 , message : message
4069 }, 'ewr')
4070}
4071
4072// generic prototype, not intended to be actually used - helpful for `instanceof`
4073function CustomError (message, cause) {
4074 Error.call(this)
4075 if (Error.captureStackTrace)
4076 Error.captureStackTrace(this, this.constructor)
4077 init.call(this, 'CustomError', message, cause)
4078}
4079
4080CustomError.prototype = new Error()
4081
4082function createError (errno, type, proto) {
4083 var err = function (message, cause) {
4084 init.call(this, type, message, cause)
4085 //TODO: the specificity here is stupid, errno should be available everywhere
4086 if (type == 'FilesystemError') {
4087 this.code = this.cause.code
4088 this.path = this.cause.path
4089 this.errno = this.cause.errno
4090 this.message =
4091 (errno.errno[this.cause.errno]
4092 ? errno.errno[this.cause.errno].description
4093 : this.cause.message)
4094 + (this.cause.path ? ' [' + this.cause.path + ']' : '')
4095 }
4096 Error.call(this)
4097 if (Error.captureStackTrace)
4098 Error.captureStackTrace(this, err)
4099 }
4100 err.prototype = !!proto ? new proto() : new CustomError()
4101 return err
4102}
4103
4104module.exports = function (errno) {
4105 var ce = function (type, proto) {
4106 return createError(errno, type, proto)
4107 }
4108 return {
4109 CustomError : CustomError
4110 , FilesystemError : ce('FilesystemError')
4111 , createError : ce
4112 }
4113}
4114
4115},{"69":69}],17:[function(_dereq_,module,exports){
4116var all = module.exports.all = [
4117 {
4118 errno: -2,
4119 code: 'ENOENT',
4120 description: 'no such file or directory'
4121 },
4122 {
4123 errno: -1,
4124 code: 'UNKNOWN',
4125 description: 'unknown error'
4126 },
4127 {
4128 errno: 0,
4129 code: 'OK',
4130 description: 'success'
4131 },
4132 {
4133 errno: 1,
4134 code: 'EOF',
4135 description: 'end of file'
4136 },
4137 {
4138 errno: 2,
4139 code: 'EADDRINFO',
4140 description: 'getaddrinfo error'
4141 },
4142 {
4143 errno: 3,
4144 code: 'EACCES',
4145 description: 'permission denied'
4146 },
4147 {
4148 errno: 4,
4149 code: 'EAGAIN',
4150 description: 'resource temporarily unavailable'
4151 },
4152 {
4153 errno: 5,
4154 code: 'EADDRINUSE',
4155 description: 'address already in use'
4156 },
4157 {
4158 errno: 6,
4159 code: 'EADDRNOTAVAIL',
4160 description: 'address not available'
4161 },
4162 {
4163 errno: 7,
4164 code: 'EAFNOSUPPORT',
4165 description: 'address family not supported'
4166 },
4167 {
4168 errno: 8,
4169 code: 'EALREADY',
4170 description: 'connection already in progress'
4171 },
4172 {
4173 errno: 9,
4174 code: 'EBADF',
4175 description: 'bad file descriptor'
4176 },
4177 {
4178 errno: 10,
4179 code: 'EBUSY',
4180 description: 'resource busy or locked'
4181 },
4182 {
4183 errno: 11,
4184 code: 'ECONNABORTED',
4185 description: 'software caused connection abort'
4186 },
4187 {
4188 errno: 12,
4189 code: 'ECONNREFUSED',
4190 description: 'connection refused'
4191 },
4192 {
4193 errno: 13,
4194 code: 'ECONNRESET',
4195 description: 'connection reset by peer'
4196 },
4197 {
4198 errno: 14,
4199 code: 'EDESTADDRREQ',
4200 description: 'destination address required'
4201 },
4202 {
4203 errno: 15,
4204 code: 'EFAULT',
4205 description: 'bad address in system call argument'
4206 },
4207 {
4208 errno: 16,
4209 code: 'EHOSTUNREACH',
4210 description: 'host is unreachable'
4211 },
4212 {
4213 errno: 17,
4214 code: 'EINTR',
4215 description: 'interrupted system call'
4216 },
4217 {
4218 errno: 18,
4219 code: 'EINVAL',
4220 description: 'invalid argument'
4221 },
4222 {
4223 errno: 19,
4224 code: 'EISCONN',
4225 description: 'socket is already connected'
4226 },
4227 {
4228 errno: 20,
4229 code: 'EMFILE',
4230 description: 'too many open files'
4231 },
4232 {
4233 errno: 21,
4234 code: 'EMSGSIZE',
4235 description: 'message too long'
4236 },
4237 {
4238 errno: 22,
4239 code: 'ENETDOWN',
4240 description: 'network is down'
4241 },
4242 {
4243 errno: 23,
4244 code: 'ENETUNREACH',
4245 description: 'network is unreachable'
4246 },
4247 {
4248 errno: 24,
4249 code: 'ENFILE',
4250 description: 'file table overflow'
4251 },
4252 {
4253 errno: 25,
4254 code: 'ENOBUFS',
4255 description: 'no buffer space available'
4256 },
4257 {
4258 errno: 26,
4259 code: 'ENOMEM',
4260 description: 'not enough memory'
4261 },
4262 {
4263 errno: 27,
4264 code: 'ENOTDIR',
4265 description: 'not a directory'
4266 },
4267 {
4268 errno: 28,
4269 code: 'EISDIR',
4270 description: 'illegal operation on a directory'
4271 },
4272 {
4273 errno: 29,
4274 code: 'ENONET',
4275 description: 'machine is not on the network'
4276 },
4277 {
4278 errno: 31,
4279 code: 'ENOTCONN',
4280 description: 'socket is not connected'
4281 },
4282 {
4283 errno: 32,
4284 code: 'ENOTSOCK',
4285 description: 'socket operation on non-socket'
4286 },
4287 {
4288 errno: 33,
4289 code: 'ENOTSUP',
4290 description: 'operation not supported on socket'
4291 },
4292 {
4293 errno: 34,
4294 code: 'ENOENT',
4295 description: 'no such file or directory'
4296 },
4297 {
4298 errno: 35,
4299 code: 'ENOSYS',
4300 description: 'function not implemented'
4301 },
4302 {
4303 errno: 36,
4304 code: 'EPIPE',
4305 description: 'broken pipe'
4306 },
4307 {
4308 errno: 37,
4309 code: 'EPROTO',
4310 description: 'protocol error'
4311 },
4312 {
4313 errno: 38,
4314 code: 'EPROTONOSUPPORT',
4315 description: 'protocol not supported'
4316 },
4317 {
4318 errno: 39,
4319 code: 'EPROTOTYPE',
4320 description: 'protocol wrong type for socket'
4321 },
4322 {
4323 errno: 40,
4324 code: 'ETIMEDOUT',
4325 description: 'connection timed out'
4326 },
4327 {
4328 errno: 41,
4329 code: 'ECHARSET',
4330 description: 'invalid Unicode character'
4331 },
4332 {
4333 errno: 42,
4334 code: 'EAIFAMNOSUPPORT',
4335 description: 'address family for hostname not supported'
4336 },
4337 {
4338 errno: 44,
4339 code: 'EAISERVICE',
4340 description: 'servname not supported for ai_socktype'
4341 },
4342 {
4343 errno: 45,
4344 code: 'EAISOCKTYPE',
4345 description: 'ai_socktype not supported'
4346 },
4347 {
4348 errno: 46,
4349 code: 'ESHUTDOWN',
4350 description: 'cannot send after transport endpoint shutdown'
4351 },
4352 {
4353 errno: 47,
4354 code: 'EEXIST',
4355 description: 'file already exists'
4356 },
4357 {
4358 errno: 48,
4359 code: 'ESRCH',
4360 description: 'no such process'
4361 },
4362 {
4363 errno: 49,
4364 code: 'ENAMETOOLONG',
4365 description: 'name too long'
4366 },
4367 {
4368 errno: 50,
4369 code: 'EPERM',
4370 description: 'operation not permitted'
4371 },
4372 {
4373 errno: 51,
4374 code: 'ELOOP',
4375 description: 'too many symbolic links encountered'
4376 },
4377 {
4378 errno: 52,
4379 code: 'EXDEV',
4380 description: 'cross-device link not permitted'
4381 },
4382 {
4383 errno: 53,
4384 code: 'ENOTEMPTY',
4385 description: 'directory not empty'
4386 },
4387 {
4388 errno: 54,
4389 code: 'ENOSPC',
4390 description: 'no space left on device'
4391 },
4392 {
4393 errno: 55,
4394 code: 'EIO',
4395 description: 'i/o error'
4396 },
4397 {
4398 errno: 56,
4399 code: 'EROFS',
4400 description: 'read-only file system'
4401 },
4402 {
4403 errno: 57,
4404 code: 'ENODEV',
4405 description: 'no such device'
4406 },
4407 {
4408 errno: 58,
4409 code: 'ESPIPE',
4410 description: 'invalid seek'
4411 },
4412 {
4413 errno: 59,
4414 code: 'ECANCELED',
4415 description: 'operation canceled'
4416 }
4417]
4418
4419module.exports.errno = {}
4420module.exports.code = {}
4421
4422all.forEach(function (error) {
4423 module.exports.errno[error.errno] = error
4424 module.exports.code[error.code] = error
4425})
4426
4427module.exports.custom = _dereq_(16)(module.exports)
4428module.exports.create = module.exports.custom.createError
4429
4430},{"16":16}],18:[function(_dereq_,module,exports){
4431// Copyright Joyent, Inc. and other Node contributors.
4432//
4433// Permission is hereby granted, free of charge, to any person obtaining a
4434// copy of this software and associated documentation files (the
4435// "Software"), to deal in the Software without restriction, including
4436// without limitation the rights to use, copy, modify, merge, publish,
4437// distribute, sublicense, and/or sell copies of the Software, and to permit
4438// persons to whom the Software is furnished to do so, subject to the
4439// following conditions:
4440//
4441// The above copyright notice and this permission notice shall be included
4442// in all copies or substantial portions of the Software.
4443//
4444// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4445// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4446// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4447// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4448// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4449// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4450// USE OR OTHER DEALINGS IN THE SOFTWARE.
4451
4452var objectCreate = Object.create || objectCreatePolyfill
4453var objectKeys = Object.keys || objectKeysPolyfill
4454var bind = Function.prototype.bind || functionBindPolyfill
4455
4456function EventEmitter() {
4457 if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
4458 this._events = objectCreate(null);
4459 this._eventsCount = 0;
4460 }
4461
4462 this._maxListeners = this._maxListeners || undefined;
4463}
4464module.exports = EventEmitter;
4465
4466// Backwards-compat with node 0.10.x
4467EventEmitter.EventEmitter = EventEmitter;
4468
4469EventEmitter.prototype._events = undefined;
4470EventEmitter.prototype._maxListeners = undefined;
4471
4472// By default EventEmitters will print a warning if more than 10 listeners are
4473// added to it. This is a useful default which helps finding memory leaks.
4474var defaultMaxListeners = 10;
4475
4476var hasDefineProperty;
4477try {
4478 var o = {};
4479 if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
4480 hasDefineProperty = o.x === 0;
4481} catch (err) { hasDefineProperty = false }
4482if (hasDefineProperty) {
4483 Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
4484 enumerable: true,
4485 get: function() {
4486 return defaultMaxListeners;
4487 },
4488 set: function(arg) {
4489 // check whether the input is a positive number (whose value is zero or
4490 // greater and not a NaN).
4491 if (typeof arg !== 'number' || arg < 0 || arg !== arg)
4492 throw new TypeError('"defaultMaxListeners" must be a positive number');
4493 defaultMaxListeners = arg;
4494 }
4495 });
4496} else {
4497 EventEmitter.defaultMaxListeners = defaultMaxListeners;
4498}
4499
4500// Obviously not all Emitters should be limited to 10. This function allows
4501// that to be increased. Set to zero for unlimited.
4502EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
4503 if (typeof n !== 'number' || n < 0 || isNaN(n))
4504 throw new TypeError('"n" argument must be a positive number');
4505 this._maxListeners = n;
4506 return this;
4507};
4508
4509function $getMaxListeners(that) {
4510 if (that._maxListeners === undefined)
4511 return EventEmitter.defaultMaxListeners;
4512 return that._maxListeners;
4513}
4514
4515EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
4516 return $getMaxListeners(this);
4517};
4518
4519// These standalone emit* functions are used to optimize calling of event
4520// handlers for fast cases because emit() itself often has a variable number of
4521// arguments and can be deoptimized because of that. These functions always have
4522// the same number of arguments and thus do not get deoptimized, so the code
4523// inside them can execute faster.
4524function emitNone(handler, isFn, self) {
4525 if (isFn)
4526 handler.call(self);
4527 else {
4528 var len = handler.length;
4529 var listeners = arrayClone(handler, len);
4530 for (var i = 0; i < len; ++i)
4531 listeners[i].call(self);
4532 }
4533}
4534function emitOne(handler, isFn, self, arg1) {
4535 if (isFn)
4536 handler.call(self, arg1);
4537 else {
4538 var len = handler.length;
4539 var listeners = arrayClone(handler, len);
4540 for (var i = 0; i < len; ++i)
4541 listeners[i].call(self, arg1);
4542 }
4543}
4544function emitTwo(handler, isFn, self, arg1, arg2) {
4545 if (isFn)
4546 handler.call(self, arg1, arg2);
4547 else {
4548 var len = handler.length;
4549 var listeners = arrayClone(handler, len);
4550 for (var i = 0; i < len; ++i)
4551 listeners[i].call(self, arg1, arg2);
4552 }
4553}
4554function emitThree(handler, isFn, self, arg1, arg2, arg3) {
4555 if (isFn)
4556 handler.call(self, arg1, arg2, arg3);
4557 else {
4558 var len = handler.length;
4559 var listeners = arrayClone(handler, len);
4560 for (var i = 0; i < len; ++i)
4561 listeners[i].call(self, arg1, arg2, arg3);
4562 }
4563}
4564
4565function emitMany(handler, isFn, self, args) {
4566 if (isFn)
4567 handler.apply(self, args);
4568 else {
4569 var len = handler.length;
4570 var listeners = arrayClone(handler, len);
4571 for (var i = 0; i < len; ++i)
4572 listeners[i].apply(self, args);
4573 }
4574}
4575
4576EventEmitter.prototype.emit = function emit(type) {
4577 var er, handler, len, args, i, events;
4578 var doError = (type === 'error');
4579
4580 events = this._events;
4581 if (events)
4582 doError = (doError && events.error == null);
4583 else if (!doError)
4584 return false;
4585
4586 // If there is no 'error' event listener then throw.
4587 if (doError) {
4588 if (arguments.length > 1)
4589 er = arguments[1];
4590 if (er instanceof Error) {
4591 throw er; // Unhandled 'error' event
4592 } else {
4593 // At least give some kind of context to the user
4594 var err = new Error('Unhandled "error" event. (' + er + ')');
4595 err.context = er;
4596 throw err;
4597 }
4598 return false;
4599 }
4600
4601 handler = events[type];
4602
4603 if (!handler)
4604 return false;
4605
4606 var isFn = typeof handler === 'function';
4607 len = arguments.length;
4608 switch (len) {
4609 // fast cases
4610 case 1:
4611 emitNone(handler, isFn, this);
4612 break;
4613 case 2:
4614 emitOne(handler, isFn, this, arguments[1]);
4615 break;
4616 case 3:
4617 emitTwo(handler, isFn, this, arguments[1], arguments[2]);
4618 break;
4619 case 4:
4620 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
4621 break;
4622 // slower
4623 default:
4624 args = new Array(len - 1);
4625 for (i = 1; i < len; i++)
4626 args[i - 1] = arguments[i];
4627 emitMany(handler, isFn, this, args);
4628 }
4629
4630 return true;
4631};
4632
4633function _addListener(target, type, listener, prepend) {
4634 var m;
4635 var events;
4636 var existing;
4637
4638 if (typeof listener !== 'function')
4639 throw new TypeError('"listener" argument must be a function');
4640
4641 events = target._events;
4642 if (!events) {
4643 events = target._events = objectCreate(null);
4644 target._eventsCount = 0;
4645 } else {
4646 // To avoid recursion in the case that type === "newListener"! Before
4647 // adding it to the listeners, first emit "newListener".
4648 if (events.newListener) {
4649 target.emit('newListener', type,
4650 listener.listener ? listener.listener : listener);
4651
4652 // Re-assign `events` because a newListener handler could have caused the
4653 // this._events to be assigned to a new object
4654 events = target._events;
4655 }
4656 existing = events[type];
4657 }
4658
4659 if (!existing) {
4660 // Optimize the case of one listener. Don't need the extra array object.
4661 existing = events[type] = listener;
4662 ++target._eventsCount;
4663 } else {
4664 if (typeof existing === 'function') {
4665 // Adding the second element, need to change to array.
4666 existing = events[type] =
4667 prepend ? [listener, existing] : [existing, listener];
4668 } else {
4669 // If we've already got an array, just append.
4670 if (prepend) {
4671 existing.unshift(listener);
4672 } else {
4673 existing.push(listener);
4674 }
4675 }
4676
4677 // Check for listener leak
4678 if (!existing.warned) {
4679 m = $getMaxListeners(target);
4680 if (m && m > 0 && existing.length > m) {
4681 existing.warned = true;
4682 var w = new Error('Possible EventEmitter memory leak detected. ' +
4683 existing.length + ' "' + String(type) + '" listeners ' +
4684 'added. Use emitter.setMaxListeners() to ' +
4685 'increase limit.');
4686 w.name = 'MaxListenersExceededWarning';
4687 w.emitter = target;
4688 w.type = type;
4689 w.count = existing.length;
4690 if (typeof console === 'object' && console.warn) {
4691 console.warn('%s: %s', w.name, w.message);
4692 }
4693 }
4694 }
4695 }
4696
4697 return target;
4698}
4699
4700EventEmitter.prototype.addListener = function addListener(type, listener) {
4701 return _addListener(this, type, listener, false);
4702};
4703
4704EventEmitter.prototype.on = EventEmitter.prototype.addListener;
4705
4706EventEmitter.prototype.prependListener =
4707 function prependListener(type, listener) {
4708 return _addListener(this, type, listener, true);
4709 };
4710
4711function onceWrapper() {
4712 if (!this.fired) {
4713 this.target.removeListener(this.type, this.wrapFn);
4714 this.fired = true;
4715 switch (arguments.length) {
4716 case 0:
4717 return this.listener.call(this.target);
4718 case 1:
4719 return this.listener.call(this.target, arguments[0]);
4720 case 2:
4721 return this.listener.call(this.target, arguments[0], arguments[1]);
4722 case 3:
4723 return this.listener.call(this.target, arguments[0], arguments[1],
4724 arguments[2]);
4725 default:
4726 var args = new Array(arguments.length);
4727 for (var i = 0; i < args.length; ++i)
4728 args[i] = arguments[i];
4729 this.listener.apply(this.target, args);
4730 }
4731 }
4732}
4733
4734function _onceWrap(target, type, listener) {
4735 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
4736 var wrapped = bind.call(onceWrapper, state);
4737 wrapped.listener = listener;
4738 state.wrapFn = wrapped;
4739 return wrapped;
4740}
4741
4742EventEmitter.prototype.once = function once(type, listener) {
4743 if (typeof listener !== 'function')
4744 throw new TypeError('"listener" argument must be a function');
4745 this.on(type, _onceWrap(this, type, listener));
4746 return this;
4747};
4748
4749EventEmitter.prototype.prependOnceListener =
4750 function prependOnceListener(type, listener) {
4751 if (typeof listener !== 'function')
4752 throw new TypeError('"listener" argument must be a function');
4753 this.prependListener(type, _onceWrap(this, type, listener));
4754 return this;
4755 };
4756
4757// Emits a 'removeListener' event if and only if the listener was removed.
4758EventEmitter.prototype.removeListener =
4759 function removeListener(type, listener) {
4760 var list, events, position, i, originalListener;
4761
4762 if (typeof listener !== 'function')
4763 throw new TypeError('"listener" argument must be a function');
4764
4765 events = this._events;
4766 if (!events)
4767 return this;
4768
4769 list = events[type];
4770 if (!list)
4771 return this;
4772
4773 if (list === listener || list.listener === listener) {
4774 if (--this._eventsCount === 0)
4775 this._events = objectCreate(null);
4776 else {
4777 delete events[type];
4778 if (events.removeListener)
4779 this.emit('removeListener', type, list.listener || listener);
4780 }
4781 } else if (typeof list !== 'function') {
4782 position = -1;
4783
4784 for (i = list.length - 1; i >= 0; i--) {
4785 if (list[i] === listener || list[i].listener === listener) {
4786 originalListener = list[i].listener;
4787 position = i;
4788 break;
4789 }
4790 }
4791
4792 if (position < 0)
4793 return this;
4794
4795 if (position === 0)
4796 list.shift();
4797 else
4798 spliceOne(list, position);
4799
4800 if (list.length === 1)
4801 events[type] = list[0];
4802
4803 if (events.removeListener)
4804 this.emit('removeListener', type, originalListener || listener);
4805 }
4806
4807 return this;
4808 };
4809
4810EventEmitter.prototype.removeAllListeners =
4811 function removeAllListeners(type) {
4812 var listeners, events, i;
4813
4814 events = this._events;
4815 if (!events)
4816 return this;
4817
4818 // not listening for removeListener, no need to emit
4819 if (!events.removeListener) {
4820 if (arguments.length === 0) {
4821 this._events = objectCreate(null);
4822 this._eventsCount = 0;
4823 } else if (events[type]) {
4824 if (--this._eventsCount === 0)
4825 this._events = objectCreate(null);
4826 else
4827 delete events[type];
4828 }
4829 return this;
4830 }
4831
4832 // emit removeListener for all listeners on all events
4833 if (arguments.length === 0) {
4834 var keys = objectKeys(events);
4835 var key;
4836 for (i = 0; i < keys.length; ++i) {
4837 key = keys[i];
4838 if (key === 'removeListener') continue;
4839 this.removeAllListeners(key);
4840 }
4841 this.removeAllListeners('removeListener');
4842 this._events = objectCreate(null);
4843 this._eventsCount = 0;
4844 return this;
4845 }
4846
4847 listeners = events[type];
4848
4849 if (typeof listeners === 'function') {
4850 this.removeListener(type, listeners);
4851 } else if (listeners) {
4852 // LIFO order
4853 for (i = listeners.length - 1; i >= 0; i--) {
4854 this.removeListener(type, listeners[i]);
4855 }
4856 }
4857
4858 return this;
4859 };
4860
4861function _listeners(target, type, unwrap) {
4862 var events = target._events;
4863
4864 if (!events)
4865 return [];
4866
4867 var evlistener = events[type];
4868 if (!evlistener)
4869 return [];
4870
4871 if (typeof evlistener === 'function')
4872 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
4873
4874 return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
4875}
4876
4877EventEmitter.prototype.listeners = function listeners(type) {
4878 return _listeners(this, type, true);
4879};
4880
4881EventEmitter.prototype.rawListeners = function rawListeners(type) {
4882 return _listeners(this, type, false);
4883};
4884
4885EventEmitter.listenerCount = function(emitter, type) {
4886 if (typeof emitter.listenerCount === 'function') {
4887 return emitter.listenerCount(type);
4888 } else {
4889 return listenerCount.call(emitter, type);
4890 }
4891};
4892
4893EventEmitter.prototype.listenerCount = listenerCount;
4894function listenerCount(type) {
4895 var events = this._events;
4896
4897 if (events) {
4898 var evlistener = events[type];
4899
4900 if (typeof evlistener === 'function') {
4901 return 1;
4902 } else if (evlistener) {
4903 return evlistener.length;
4904 }
4905 }
4906
4907 return 0;
4908}
4909
4910EventEmitter.prototype.eventNames = function eventNames() {
4911 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
4912};
4913
4914// About 1.5x faster than the two-arg version of Array#splice().
4915function spliceOne(list, index) {
4916 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
4917 list[i] = list[k];
4918 list.pop();
4919}
4920
4921function arrayClone(arr, n) {
4922 var copy = new Array(n);
4923 for (var i = 0; i < n; ++i)
4924 copy[i] = arr[i];
4925 return copy;
4926}
4927
4928function unwrapListeners(arr) {
4929 var ret = new Array(arr.length);
4930 for (var i = 0; i < ret.length; ++i) {
4931 ret[i] = arr[i].listener || arr[i];
4932 }
4933 return ret;
4934}
4935
4936function objectCreatePolyfill(proto) {
4937 var F = function() {};
4938 F.prototype = proto;
4939 return new F;
4940}
4941function objectKeysPolyfill(obj) {
4942 var keys = [];
4943 for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
4944 keys.push(k);
4945 }
4946 return k;
4947}
4948function functionBindPolyfill(context) {
4949 var fn = this;
4950 return function () {
4951 return fn.apply(context, arguments);
4952 };
4953}
4954
4955},{}],19:[function(_dereq_,module,exports){
4956/**
4957 * # hasLocalStorage()
4958 *
4959 * returns `true` or `false` depending on whether localStorage is supported or not.
4960 * Beware that some browsers like Safari do not support localStorage in private mode.
4961 *
4962 * inspired by this cappuccino commit
4963 * https://github.com/cappuccino/cappuccino/commit/063b05d9643c35b303568a28809e4eb3224f71ec
4964 *
4965 * @returns {Boolean}
4966 */
4967function hasLocalStorage() {
4968 try {
4969
4970 // we've to put this in here. I've seen Firefox throwing `Security error: 1000`
4971 // when cookies have been disabled
4972 if (typeof localStorage === 'undefined') {
4973 return false;
4974 }
4975
4976 // Just because localStorage exists does not mean it works. In particular it might be disabled
4977 // as it is when Safari's private browsing mode is active.
4978 localStorage.setItem('Storage-Test', '1');
4979
4980 // that should not happen ...
4981 if (localStorage.getItem('Storage-Test') !== '1') {
4982 return false;
4983 }
4984
4985 // okay, let's clean up if we got here.
4986 localStorage.removeItem('Storage-Test');
4987 } catch (_error) {
4988
4989 // in case of an error, like Safari's Private Mode, return false
4990 return false;
4991 }
4992
4993 // we're good.
4994 return true;
4995}
4996
4997
4998if (typeof exports === 'object') {
4999 module.exports = hasLocalStorage;
5000}
5001
5002},{}],20:[function(_dereq_,module,exports){
5003(function (global){
5004var exports = module.exports = {};
5005var localStorageMemory = _dereq_(64);
5006exports.hasLocalStorage = _dereq_(19);
5007
5008/**
5009 * returns localStorage-compatible API, either backed by window.localStorage
5010 * or memory if it's not available or not persistent.
5011 *
5012 * It also adds an object API (`.getObject(key)`,
5013 * `.setObject(key, properties)`) and a `isPresistent` property
5014 *
5015 * @returns {Object}
5016 */
5017exports.create = function () {
5018 var api;
5019
5020 if (!exports.hasLocalStorage()) {
5021 api = localStorageMemory;
5022 api.isPersistent = false;
5023 } else {
5024 api = global.localStorage;
5025 api = {
5026 get length() { return global.localStorage.length; },
5027 getItem: global.localStorage.getItem.bind(global.localStorage),
5028 setItem: global.localStorage.setItem.bind(global.localStorage),
5029 removeItem: global.localStorage.removeItem.bind(global.localStorage),
5030 key: global.localStorage.key.bind(global.localStorage),
5031 clear: global.localStorage.clear.bind(global.localStorage),
5032 };
5033
5034 api.isPersistent = true;
5035 }
5036
5037 api.getObject = exports.getObject.bind(null, api);
5038 api.setObject = exports.setObject.bind(null, api);
5039
5040 return api;
5041};
5042
5043/**
5044 * sets key to passed Object.
5045 *
5046 * @returns undefined
5047 */
5048exports.setObject = function (store, key, object) {
5049 if (typeof object !== 'object') {
5050 return store.setItem(key, object);
5051 }
5052
5053 return store.setItem(key, JSON.stringify(object));
5054};
5055
5056/**
5057 * returns Object for key, or null
5058 *
5059 * @returns {Object|null}
5060 */
5061exports.getObject = function (store, key) {
5062 var item = store.getItem(key);
5063
5064 if (!item) {
5065 return null;
5066 }
5067
5068 try {
5069 return JSON.parse(item);
5070 } catch (e) {
5071 return item;
5072 }
5073};
5074
5075}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5076},{"19":19,"64":64}],21:[function(_dereq_,module,exports){
5077var api = _dereq_(20);
5078module.exports = api.create();
5079
5080},{"20":20}],22:[function(_dereq_,module,exports){
5081exports.read = function (buffer, offset, isLE, mLen, nBytes) {
5082 var e, m
5083 var eLen = (nBytes * 8) - mLen - 1
5084 var eMax = (1 << eLen) - 1
5085 var eBias = eMax >> 1
5086 var nBits = -7
5087 var i = isLE ? (nBytes - 1) : 0
5088 var d = isLE ? -1 : 1
5089 var s = buffer[offset + i]
5090
5091 i += d
5092
5093 e = s & ((1 << (-nBits)) - 1)
5094 s >>= (-nBits)
5095 nBits += eLen
5096 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
5097
5098 m = e & ((1 << (-nBits)) - 1)
5099 e >>= (-nBits)
5100 nBits += mLen
5101 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
5102
5103 if (e === 0) {
5104 e = 1 - eBias
5105 } else if (e === eMax) {
5106 return m ? NaN : ((s ? -1 : 1) * Infinity)
5107 } else {
5108 m = m + Math.pow(2, mLen)
5109 e = e - eBias
5110 }
5111 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
5112}
5113
5114exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
5115 var e, m, c
5116 var eLen = (nBytes * 8) - mLen - 1
5117 var eMax = (1 << eLen) - 1
5118 var eBias = eMax >> 1
5119 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
5120 var i = isLE ? 0 : (nBytes - 1)
5121 var d = isLE ? 1 : -1
5122 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
5123
5124 value = Math.abs(value)
5125
5126 if (isNaN(value) || value === Infinity) {
5127 m = isNaN(value) ? 1 : 0
5128 e = eMax
5129 } else {
5130 e = Math.floor(Math.log(value) / Math.LN2)
5131 if (value * (c = Math.pow(2, -e)) < 1) {
5132 e--
5133 c *= 2
5134 }
5135 if (e + eBias >= 1) {
5136 value += rt / c
5137 } else {
5138 value += rt * Math.pow(2, 1 - eBias)
5139 }
5140 if (value * c >= 2) {
5141 e++
5142 c /= 2
5143 }
5144
5145 if (e + eBias >= eMax) {
5146 m = 0
5147 e = eMax
5148 } else if (e + eBias >= 1) {
5149 m = ((value * c) - 1) * Math.pow(2, mLen)
5150 e = e + eBias
5151 } else {
5152 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
5153 e = 0
5154 }
5155 }
5156
5157 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
5158
5159 e = (e << mLen) | m
5160 eLen += mLen
5161 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
5162
5163 buffer[offset + i - d] |= s * 128
5164}
5165
5166},{}],23:[function(_dereq_,module,exports){
5167(function (global){
5168'use strict';
5169var Mutation = global.MutationObserver || global.WebKitMutationObserver;
5170
5171var scheduleDrain;
5172
5173{
5174 if (Mutation) {
5175 var called = 0;
5176 var observer = new Mutation(nextTick);
5177 var element = global.document.createTextNode('');
5178 observer.observe(element, {
5179 characterData: true
5180 });
5181 scheduleDrain = function () {
5182 element.data = (called = ++called % 2);
5183 };
5184 } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
5185 var channel = new global.MessageChannel();
5186 channel.port1.onmessage = nextTick;
5187 scheduleDrain = function () {
5188 channel.port2.postMessage(0);
5189 };
5190 } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
5191 scheduleDrain = function () {
5192
5193 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
5194 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
5195 var scriptEl = global.document.createElement('script');
5196 scriptEl.onreadystatechange = function () {
5197 nextTick();
5198
5199 scriptEl.onreadystatechange = null;
5200 scriptEl.parentNode.removeChild(scriptEl);
5201 scriptEl = null;
5202 };
5203 global.document.documentElement.appendChild(scriptEl);
5204 };
5205 } else {
5206 scheduleDrain = function () {
5207 setTimeout(nextTick, 0);
5208 };
5209 }
5210}
5211
5212var draining;
5213var queue = [];
5214//named nextTick for less confusing stack traces
5215function nextTick() {
5216 draining = true;
5217 var i, oldQueue;
5218 var len = queue.length;
5219 while (len) {
5220 oldQueue = queue;
5221 queue = [];
5222 i = -1;
5223 while (++i < len) {
5224 oldQueue[i]();
5225 }
5226 len = queue.length;
5227 }
5228 draining = false;
5229}
5230
5231module.exports = immediate;
5232function immediate(task) {
5233 if (queue.push(task) === 1 && !draining) {
5234 scheduleDrain();
5235 }
5236}
5237
5238}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5239},{}],24:[function(_dereq_,module,exports){
5240if (typeof Object.create === 'function') {
5241 // implementation from standard node.js 'util' module
5242 module.exports = function inherits(ctor, superCtor) {
5243 if (superCtor) {
5244 ctor.super_ = superCtor
5245 ctor.prototype = Object.create(superCtor.prototype, {
5246 constructor: {
5247 value: ctor,
5248 enumerable: false,
5249 writable: true,
5250 configurable: true
5251 }
5252 })
5253 }
5254 };
5255} else {
5256 // old school shim for old browsers
5257 module.exports = function inherits(ctor, superCtor) {
5258 if (superCtor) {
5259 ctor.super_ = superCtor
5260 var TempCtor = function () {}
5261 TempCtor.prototype = superCtor.prototype
5262 ctor.prototype = new TempCtor()
5263 ctor.prototype.constructor = ctor
5264 }
5265 }
5266}
5267
5268},{}],25:[function(_dereq_,module,exports){
5269/*!
5270 * Determine if an object is a Buffer
5271 *
5272 * @author Feross Aboukhadijeh <https://feross.org>
5273 * @license MIT
5274 */
5275
5276// The _isBuffer check is for Safari 5-7 support, because it's missing
5277// Object.prototype.constructor. Remove this eventually
5278module.exports = function (obj) {
5279 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
5280}
5281
5282function isBuffer (obj) {
5283 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
5284}
5285
5286// For Node v0.10 support. Remove this eventually.
5287function isSlowBuffer (obj) {
5288 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
5289}
5290
5291},{}],26:[function(_dereq_,module,exports){
5292module.exports = Array.isArray || function (arr) {
5293 return Object.prototype.toString.call(arr) == '[object Array]';
5294};
5295
5296},{}],27:[function(_dereq_,module,exports){
5297var encodings = _dereq_(28)
5298
5299module.exports = Codec
5300
5301function Codec (opts) {
5302 if (!(this instanceof Codec)) {
5303 return new Codec(opts)
5304 }
5305 this.opts = opts || {}
5306 this.encodings = encodings
5307}
5308
5309Codec.prototype._encoding = function (encoding) {
5310 if (typeof encoding === 'string') encoding = encodings[encoding]
5311 if (!encoding) encoding = encodings.id
5312 return encoding
5313}
5314
5315Codec.prototype._keyEncoding = function (opts, batchOpts) {
5316 return this._encoding((batchOpts && batchOpts.keyEncoding) ||
5317 (opts && opts.keyEncoding) ||
5318 this.opts.keyEncoding)
5319}
5320
5321Codec.prototype._valueEncoding = function (opts, batchOpts) {
5322 return this._encoding((batchOpts && (batchOpts.valueEncoding || batchOpts.encoding)) ||
5323 (opts && (opts.valueEncoding || opts.encoding)) ||
5324 (this.opts.valueEncoding || this.opts.encoding))
5325}
5326
5327Codec.prototype.encodeKey = function (key, opts, batchOpts) {
5328 return this._keyEncoding(opts, batchOpts).encode(key)
5329}
5330
5331Codec.prototype.encodeValue = function (value, opts, batchOpts) {
5332 return this._valueEncoding(opts, batchOpts).encode(value)
5333}
5334
5335Codec.prototype.decodeKey = function (key, opts) {
5336 return this._keyEncoding(opts).decode(key)
5337}
5338
5339Codec.prototype.decodeValue = function (value, opts) {
5340 return this._valueEncoding(opts).decode(value)
5341}
5342
5343Codec.prototype.encodeBatch = function (ops, opts) {
5344 var self = this
5345
5346 return ops.map(function (_op) {
5347 var op = {
5348 type: _op.type,
5349 key: self.encodeKey(_op.key, opts, _op)
5350 }
5351 if (self.keyAsBuffer(opts, _op)) op.keyEncoding = 'binary'
5352 if (_op.prefix) op.prefix = _op.prefix
5353 if ('value' in _op) {
5354 op.value = self.encodeValue(_op.value, opts, _op)
5355 if (self.valueAsBuffer(opts, _op)) op.valueEncoding = 'binary'
5356 }
5357 return op
5358 })
5359}
5360
5361var ltgtKeys = ['lt', 'gt', 'lte', 'gte', 'start', 'end']
5362
5363Codec.prototype.encodeLtgt = function (ltgt) {
5364 var self = this
5365 var ret = {}
5366 Object.keys(ltgt).forEach(function (key) {
5367 ret[key] = ltgtKeys.indexOf(key) > -1
5368 ? self.encodeKey(ltgt[key], ltgt)
5369 : ltgt[key]
5370 })
5371 return ret
5372}
5373
5374Codec.prototype.createStreamDecoder = function (opts) {
5375 var self = this
5376
5377 if (opts.keys && opts.values) {
5378 return function (key, value) {
5379 return {
5380 key: self.decodeKey(key, opts),
5381 value: self.decodeValue(value, opts)
5382 }
5383 }
5384 } else if (opts.keys) {
5385 return function (key) {
5386 return self.decodeKey(key, opts)
5387 }
5388 } else if (opts.values) {
5389 return function (_, value) {
5390 return self.decodeValue(value, opts)
5391 }
5392 } else {
5393 return function () {}
5394 }
5395}
5396
5397Codec.prototype.keyAsBuffer = function (opts) {
5398 return this._keyEncoding(opts).buffer
5399}
5400
5401Codec.prototype.valueAsBuffer = function (opts) {
5402 return this._valueEncoding(opts).buffer
5403}
5404
5405},{"28":28}],28:[function(_dereq_,module,exports){
5406(function (Buffer){
5407exports.utf8 = exports['utf-8'] = {
5408 encode: function (data) {
5409 return isBinary(data) ? data : String(data)
5410 },
5411 decode: identity,
5412 buffer: false,
5413 type: 'utf8'
5414}
5415
5416exports.json = {
5417 encode: JSON.stringify,
5418 decode: JSON.parse,
5419 buffer: false,
5420 type: 'json'
5421}
5422
5423exports.binary = {
5424 encode: function (data) {
5425 return isBinary(data) ? data : Buffer.from(data)
5426 },
5427 decode: identity,
5428 buffer: true,
5429 type: 'binary'
5430}
5431
5432exports.none = {
5433 encode: identity,
5434 decode: identity,
5435 buffer: false,
5436 type: 'id'
5437}
5438
5439exports.id = exports.none
5440
5441var bufferEncodings = [
5442 'hex',
5443 'ascii',
5444 'base64',
5445 'ucs2',
5446 'ucs-2',
5447 'utf16le',
5448 'utf-16le'
5449]
5450
5451bufferEncodings.forEach(function (type) {
5452 exports[type] = {
5453 encode: function (data) {
5454 return isBinary(data) ? data : Buffer.from(data, type)
5455 },
5456 decode: function (buffer) {
5457 return buffer.toString(type)
5458 },
5459 buffer: true,
5460 type: type
5461 }
5462})
5463
5464function identity (value) {
5465 return value
5466}
5467
5468function isBinary (data) {
5469 return data === undefined || data === null || Buffer.isBuffer(data)
5470}
5471
5472}).call(this,_dereq_(12).Buffer)
5473},{"12":12}],29:[function(_dereq_,module,exports){
5474var createError = _dereq_(17).create
5475var LevelUPError = createError('LevelUPError')
5476var NotFoundError = createError('NotFoundError', LevelUPError)
5477
5478NotFoundError.prototype.notFound = true
5479NotFoundError.prototype.status = 404
5480
5481module.exports = {
5482 LevelUPError: LevelUPError,
5483 InitializationError: createError('InitializationError', LevelUPError),
5484 OpenError: createError('OpenError', LevelUPError),
5485 ReadError: createError('ReadError', LevelUPError),
5486 WriteError: createError('WriteError', LevelUPError),
5487 NotFoundError: NotFoundError,
5488 EncodingError: createError('EncodingError', LevelUPError)
5489}
5490
5491},{"17":17}],30:[function(_dereq_,module,exports){
5492var inherits = _dereq_(24)
5493var Readable = _dereq_(45).Readable
5494var extend = _dereq_(46)
5495
5496module.exports = ReadStream
5497inherits(ReadStream, Readable)
5498
5499function ReadStream (iterator, options) {
5500 if (!(this instanceof ReadStream)) return new ReadStream(iterator, options)
5501 options = options || {}
5502 Readable.call(this, extend(options, {
5503 objectMode: true
5504 }))
5505 this._iterator = iterator
5506 this._options = options
5507 this.on('end', this.destroy.bind(this, null, null))
5508}
5509
5510ReadStream.prototype._read = function () {
5511 var self = this
5512 var options = this._options
5513 if (this.destroyed) return
5514
5515 this._iterator.next(function (err, key, value) {
5516 if (self.destroyed) return
5517 if (err) return self.destroy(err)
5518
5519 if (key === undefined && value === undefined) {
5520 self.push(null)
5521 } else if (options.keys !== false && options.values === false) {
5522 self.push(key)
5523 } else if (options.keys === false && options.values !== false) {
5524 self.push(value)
5525 } else {
5526 self.push({ key: key, value: value })
5527 }
5528 })
5529}
5530
5531ReadStream.prototype._destroy = function (err, callback) {
5532 this._iterator.end(function (err2) {
5533 callback(err || err2)
5534 })
5535}
5536
5537},{"24":24,"45":45,"46":46}],31:[function(_dereq_,module,exports){
5538'use strict';
5539
5540function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
5541
5542var codes = {};
5543
5544function createErrorType(code, message, Base) {
5545 if (!Base) {
5546 Base = Error;
5547 }
5548
5549 function getMessage(arg1, arg2, arg3) {
5550 if (typeof message === 'string') {
5551 return message;
5552 } else {
5553 return message(arg1, arg2, arg3);
5554 }
5555 }
5556
5557 var NodeError =
5558 /*#__PURE__*/
5559 function (_Base) {
5560 _inheritsLoose(NodeError, _Base);
5561
5562 function NodeError(arg1, arg2, arg3) {
5563 return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
5564 }
5565
5566 return NodeError;
5567 }(Base);
5568
5569 NodeError.prototype.name = Base.name;
5570 NodeError.prototype.code = code;
5571 codes[code] = NodeError;
5572} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
5573
5574
5575function oneOf(expected, thing) {
5576 if (Array.isArray(expected)) {
5577 var len = expected.length;
5578 expected = expected.map(function (i) {
5579 return String(i);
5580 });
5581
5582 if (len > 2) {
5583 return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
5584 } else if (len === 2) {
5585 return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
5586 } else {
5587 return "of ".concat(thing, " ").concat(expected[0]);
5588 }
5589 } else {
5590 return "of ".concat(thing, " ").concat(String(expected));
5591 }
5592} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
5593
5594
5595function startsWith(str, search, pos) {
5596 return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
5597} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
5598
5599
5600function endsWith(str, search, this_len) {
5601 if (this_len === undefined || this_len > str.length) {
5602 this_len = str.length;
5603 }
5604
5605 return str.substring(this_len - search.length, this_len) === search;
5606} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
5607
5608
5609function includes(str, search, start) {
5610 if (typeof start !== 'number') {
5611 start = 0;
5612 }
5613
5614 if (start + search.length > str.length) {
5615 return false;
5616 } else {
5617 return str.indexOf(search, start) !== -1;
5618 }
5619}
5620
5621createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
5622 return 'The value "' + value + '" is invalid for option "' + name + '"';
5623}, TypeError);
5624createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
5625 // determiner: 'must be' or 'must not be'
5626 var determiner;
5627
5628 if (typeof expected === 'string' && startsWith(expected, 'not ')) {
5629 determiner = 'must not be';
5630 expected = expected.replace(/^not /, '');
5631 } else {
5632 determiner = 'must be';
5633 }
5634
5635 var msg;
5636
5637 if (endsWith(name, ' argument')) {
5638 // For cases like 'first argument'
5639 msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
5640 } else {
5641 var type = includes(name, '.') ? 'property' : 'argument';
5642 msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
5643 }
5644
5645 msg += ". Received type ".concat(typeof actual);
5646 return msg;
5647}, TypeError);
5648createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
5649createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
5650 return 'The ' + name + ' method is not implemented';
5651});
5652createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
5653createErrorType('ERR_STREAM_DESTROYED', function (name) {
5654 return 'Cannot call ' + name + ' after a stream was destroyed';
5655});
5656createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
5657createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
5658createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
5659createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
5660createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
5661 return 'Unknown encoding: ' + arg;
5662}, TypeError);
5663createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
5664module.exports.codes = codes;
5665
5666},{}],32:[function(_dereq_,module,exports){
5667(function (process){
5668// Copyright Joyent, Inc. and other Node contributors.
5669//
5670// Permission is hereby granted, free of charge, to any person obtaining a
5671// copy of this software and associated documentation files (the
5672// "Software"), to deal in the Software without restriction, including
5673// without limitation the rights to use, copy, modify, merge, publish,
5674// distribute, sublicense, and/or sell copies of the Software, and to permit
5675// persons to whom the Software is furnished to do so, subject to the
5676// following conditions:
5677//
5678// The above copyright notice and this permission notice shall be included
5679// in all copies or substantial portions of the Software.
5680//
5681// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5682// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5683// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5684// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5685// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5686// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5687// USE OR OTHER DEALINGS IN THE SOFTWARE.
5688// a duplex stream is just a stream that is both readable and writable.
5689// Since JS doesn't have multiple prototypal inheritance, this class
5690// prototypally inherits from Readable, and then parasitically from
5691// Writable.
5692'use strict';
5693/*<replacement>*/
5694
5695var objectKeys = Object.keys || function (obj) {
5696 var keys = [];
5697
5698 for (var key in obj) {
5699 keys.push(key);
5700 }
5701
5702 return keys;
5703};
5704/*</replacement>*/
5705
5706
5707module.exports = Duplex;
5708
5709var Readable = _dereq_(34);
5710
5711var Writable = _dereq_(36);
5712
5713_dereq_(24)(Duplex, Readable);
5714
5715{
5716 // Allow the keys array to be GC'ed.
5717 var keys = objectKeys(Writable.prototype);
5718
5719 for (var v = 0; v < keys.length; v++) {
5720 var method = keys[v];
5721 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
5722 }
5723}
5724
5725function Duplex(options) {
5726 if (!(this instanceof Duplex)) return new Duplex(options);
5727 Readable.call(this, options);
5728 Writable.call(this, options);
5729 this.allowHalfOpen = true;
5730
5731 if (options) {
5732 if (options.readable === false) this.readable = false;
5733 if (options.writable === false) this.writable = false;
5734
5735 if (options.allowHalfOpen === false) {
5736 this.allowHalfOpen = false;
5737 this.once('end', onend);
5738 }
5739 }
5740}
5741
5742Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
5743 // making it explicit this property is not enumerable
5744 // because otherwise some prototype manipulation in
5745 // userland will fail
5746 enumerable: false,
5747 get: function get() {
5748 return this._writableState.highWaterMark;
5749 }
5750});
5751Object.defineProperty(Duplex.prototype, 'writableBuffer', {
5752 // making it explicit this property is not enumerable
5753 // because otherwise some prototype manipulation in
5754 // userland will fail
5755 enumerable: false,
5756 get: function get() {
5757 return this._writableState && this._writableState.getBuffer();
5758 }
5759});
5760Object.defineProperty(Duplex.prototype, 'writableLength', {
5761 // making it explicit this property is not enumerable
5762 // because otherwise some prototype manipulation in
5763 // userland will fail
5764 enumerable: false,
5765 get: function get() {
5766 return this._writableState.length;
5767 }
5768}); // the no-half-open enforcer
5769
5770function onend() {
5771 // If the writable side ended, then we're ok.
5772 if (this._writableState.ended) return; // no more data can be written.
5773 // But allow more writes to happen in this tick.
5774
5775 process.nextTick(onEndNT, this);
5776}
5777
5778function onEndNT(self) {
5779 self.end();
5780}
5781
5782Object.defineProperty(Duplex.prototype, 'destroyed', {
5783 // making it explicit this property is not enumerable
5784 // because otherwise some prototype manipulation in
5785 // userland will fail
5786 enumerable: false,
5787 get: function get() {
5788 if (this._readableState === undefined || this._writableState === undefined) {
5789 return false;
5790 }
5791
5792 return this._readableState.destroyed && this._writableState.destroyed;
5793 },
5794 set: function set(value) {
5795 // we ignore the value if the stream
5796 // has not been initialized yet
5797 if (this._readableState === undefined || this._writableState === undefined) {
5798 return;
5799 } // backward compatibility, the user is explicitly
5800 // managing destroyed
5801
5802
5803 this._readableState.destroyed = value;
5804 this._writableState.destroyed = value;
5805 }
5806});
5807}).call(this,_dereq_(68))
5808},{"24":24,"34":34,"36":36,"68":68}],33:[function(_dereq_,module,exports){
5809// Copyright Joyent, Inc. and other Node contributors.
5810//
5811// Permission is hereby granted, free of charge, to any person obtaining a
5812// copy of this software and associated documentation files (the
5813// "Software"), to deal in the Software without restriction, including
5814// without limitation the rights to use, copy, modify, merge, publish,
5815// distribute, sublicense, and/or sell copies of the Software, and to permit
5816// persons to whom the Software is furnished to do so, subject to the
5817// following conditions:
5818//
5819// The above copyright notice and this permission notice shall be included
5820// in all copies or substantial portions of the Software.
5821//
5822// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5823// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5824// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5825// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5826// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5827// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5828// USE OR OTHER DEALINGS IN THE SOFTWARE.
5829// a passthrough stream.
5830// basically just the most minimal sort of Transform stream.
5831// Every written chunk gets output as-is.
5832'use strict';
5833
5834module.exports = PassThrough;
5835
5836var Transform = _dereq_(35);
5837
5838_dereq_(24)(PassThrough, Transform);
5839
5840function PassThrough(options) {
5841 if (!(this instanceof PassThrough)) return new PassThrough(options);
5842 Transform.call(this, options);
5843}
5844
5845PassThrough.prototype._transform = function (chunk, encoding, cb) {
5846 cb(null, chunk);
5847};
5848},{"24":24,"35":35}],34:[function(_dereq_,module,exports){
5849(function (process,global){
5850// Copyright Joyent, Inc. and other Node contributors.
5851//
5852// Permission is hereby granted, free of charge, to any person obtaining a
5853// copy of this software and associated documentation files (the
5854// "Software"), to deal in the Software without restriction, including
5855// without limitation the rights to use, copy, modify, merge, publish,
5856// distribute, sublicense, and/or sell copies of the Software, and to permit
5857// persons to whom the Software is furnished to do so, subject to the
5858// following conditions:
5859//
5860// The above copyright notice and this permission notice shall be included
5861// in all copies or substantial portions of the Software.
5862//
5863// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5864// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5865// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5866// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5867// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5868// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5869// USE OR OTHER DEALINGS IN THE SOFTWARE.
5870'use strict';
5871
5872module.exports = Readable;
5873/*<replacement>*/
5874
5875var Duplex;
5876/*</replacement>*/
5877
5878Readable.ReadableState = ReadableState;
5879/*<replacement>*/
5880
5881var EE = _dereq_(18).EventEmitter;
5882
5883var EElistenerCount = function EElistenerCount(emitter, type) {
5884 return emitter.listeners(type).length;
5885};
5886/*</replacement>*/
5887
5888/*<replacement>*/
5889
5890
5891var Stream = _dereq_(44);
5892/*</replacement>*/
5893
5894
5895var Buffer = _dereq_(12).Buffer;
5896
5897var OurUint8Array = global.Uint8Array || function () {};
5898
5899function _uint8ArrayToBuffer(chunk) {
5900 return Buffer.from(chunk);
5901}
5902
5903function _isUint8Array(obj) {
5904 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
5905}
5906/*<replacement>*/
5907
5908
5909var debugUtil = _dereq_(10);
5910
5911var debug;
5912
5913if (debugUtil && debugUtil.debuglog) {
5914 debug = debugUtil.debuglog('stream');
5915} else {
5916 debug = function debug() {};
5917}
5918/*</replacement>*/
5919
5920
5921var BufferList = _dereq_(38);
5922
5923var destroyImpl = _dereq_(39);
5924
5925var _require = _dereq_(43),
5926 getHighWaterMark = _require.getHighWaterMark;
5927
5928var _require$codes = _dereq_(31).codes,
5929 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
5930 ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
5931 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
5932 ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.
5933
5934
5935var StringDecoder;
5936var createReadableStreamAsyncIterator;
5937var from;
5938
5939_dereq_(24)(Readable, Stream);
5940
5941var errorOrDestroy = destroyImpl.errorOrDestroy;
5942var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
5943
5944function prependListener(emitter, event, fn) {
5945 // Sadly this is not cacheable as some libraries bundle their own
5946 // event emitter implementation with them.
5947 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any
5948 // userland ones. NEVER DO THIS. This is here only because this code needs
5949 // to continue to work with older versions of Node.js that do not include
5950 // the prependListener() method. The goal is to eventually remove this hack.
5951
5952 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]];
5953}
5954
5955function ReadableState(options, stream, isDuplex) {
5956 Duplex = Duplex || _dereq_(32);
5957 options = options || {}; // Duplex streams are both readable and writable, but share
5958 // the same options object.
5959 // However, some cases require setting options to different
5960 // values for the readable and the writable sides of the duplex stream.
5961 // These options can be provided separately as readableXXX and writableXXX.
5962
5963 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to
5964 // make all the buffer merging and length checks go away
5965
5966 this.objectMode = !!options.objectMode;
5967 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
5968 // Note: 0 is a valid value, means "don't call _read preemptively ever"
5969
5970 this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the
5971 // linked list can remove elements from the beginning faster than
5972 // array.shift()
5973
5974 this.buffer = new BufferList();
5975 this.length = 0;
5976 this.pipes = null;
5977 this.pipesCount = 0;
5978 this.flowing = null;
5979 this.ended = false;
5980 this.endEmitted = false;
5981 this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted
5982 // immediately, or on a later tick. We set this to true at first, because
5983 // any actions that shouldn't happen until "later" should generally also
5984 // not happen before the first read call.
5985
5986 this.sync = true; // whenever we return null, then we set a flag to say
5987 // that we're awaiting a 'readable' event emission.
5988
5989 this.needReadable = false;
5990 this.emittedReadable = false;
5991 this.readableListening = false;
5992 this.resumeScheduled = false;
5993 this.paused = true; // Should close be emitted on destroy. Defaults to true.
5994
5995 this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')
5996
5997 this.autoDestroy = !!options.autoDestroy; // has it been destroyed
5998
5999 this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string
6000 // encoding is 'binary' so we have to make this configurable.
6001 // Everything else in the universe uses 'utf8', though.
6002
6003 this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s
6004
6005 this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled
6006
6007 this.readingMore = false;
6008 this.decoder = null;
6009 this.encoding = null;
6010
6011 if (options.encoding) {
6012 if (!StringDecoder) StringDecoder = _dereq_(96).StringDecoder;
6013 this.decoder = new StringDecoder(options.encoding);
6014 this.encoding = options.encoding;
6015 }
6016}
6017
6018function Readable(options) {
6019 Duplex = Duplex || _dereq_(32);
6020 if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside
6021 // the ReadableState constructor, at least with V8 6.5
6022
6023 var isDuplex = this instanceof Duplex;
6024 this._readableState = new ReadableState(options, this, isDuplex); // legacy
6025
6026 this.readable = true;
6027
6028 if (options) {
6029 if (typeof options.read === 'function') this._read = options.read;
6030 if (typeof options.destroy === 'function') this._destroy = options.destroy;
6031 }
6032
6033 Stream.call(this);
6034}
6035
6036Object.defineProperty(Readable.prototype, 'destroyed', {
6037 // making it explicit this property is not enumerable
6038 // because otherwise some prototype manipulation in
6039 // userland will fail
6040 enumerable: false,
6041 get: function get() {
6042 if (this._readableState === undefined) {
6043 return false;
6044 }
6045
6046 return this._readableState.destroyed;
6047 },
6048 set: function set(value) {
6049 // we ignore the value if the stream
6050 // has not been initialized yet
6051 if (!this._readableState) {
6052 return;
6053 } // backward compatibility, the user is explicitly
6054 // managing destroyed
6055
6056
6057 this._readableState.destroyed = value;
6058 }
6059});
6060Readable.prototype.destroy = destroyImpl.destroy;
6061Readable.prototype._undestroy = destroyImpl.undestroy;
6062
6063Readable.prototype._destroy = function (err, cb) {
6064 cb(err);
6065}; // Manually shove something into the read() buffer.
6066// This returns true if the highWaterMark has not been hit yet,
6067// similar to how Writable.write() returns true if you should
6068// write() some more.
6069
6070
6071Readable.prototype.push = function (chunk, encoding) {
6072 var state = this._readableState;
6073 var skipChunkCheck;
6074
6075 if (!state.objectMode) {
6076 if (typeof chunk === 'string') {
6077 encoding = encoding || state.defaultEncoding;
6078
6079 if (encoding !== state.encoding) {
6080 chunk = Buffer.from(chunk, encoding);
6081 encoding = '';
6082 }
6083
6084 skipChunkCheck = true;
6085 }
6086 } else {
6087 skipChunkCheck = true;
6088 }
6089
6090 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
6091}; // Unshift should *always* be something directly out of read()
6092
6093
6094Readable.prototype.unshift = function (chunk) {
6095 return readableAddChunk(this, chunk, null, true, false);
6096};
6097
6098function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
6099 debug('readableAddChunk', chunk);
6100 var state = stream._readableState;
6101
6102 if (chunk === null) {
6103 state.reading = false;
6104 onEofChunk(stream, state);
6105 } else {
6106 var er;
6107 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
6108
6109 if (er) {
6110 errorOrDestroy(stream, er);
6111 } else if (state.objectMode || chunk && chunk.length > 0) {
6112 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
6113 chunk = _uint8ArrayToBuffer(chunk);
6114 }
6115
6116 if (addToFront) {
6117 if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
6118 } else if (state.ended) {
6119 errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
6120 } else if (state.destroyed) {
6121 return false;
6122 } else {
6123 state.reading = false;
6124
6125 if (state.decoder && !encoding) {
6126 chunk = state.decoder.write(chunk);
6127 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
6128 } else {
6129 addChunk(stream, state, chunk, false);
6130 }
6131 }
6132 } else if (!addToFront) {
6133 state.reading = false;
6134 maybeReadMore(stream, state);
6135 }
6136 } // We can push more data if we are below the highWaterMark.
6137 // Also, if we have no data yet, we can stand some more bytes.
6138 // This is to work around cases where hwm=0, such as the repl.
6139
6140
6141 return !state.ended && (state.length < state.highWaterMark || state.length === 0);
6142}
6143
6144function addChunk(stream, state, chunk, addToFront) {
6145 if (state.flowing && state.length === 0 && !state.sync) {
6146 state.awaitDrain = 0;
6147 stream.emit('data', chunk);
6148 } else {
6149 // update the buffer info.
6150 state.length += state.objectMode ? 1 : chunk.length;
6151 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
6152 if (state.needReadable) emitReadable(stream);
6153 }
6154
6155 maybeReadMore(stream, state);
6156}
6157
6158function chunkInvalid(state, chunk) {
6159 var er;
6160
6161 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
6162 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
6163 }
6164
6165 return er;
6166}
6167
6168Readable.prototype.isPaused = function () {
6169 return this._readableState.flowing === false;
6170}; // backwards compatibility.
6171
6172
6173Readable.prototype.setEncoding = function (enc) {
6174 if (!StringDecoder) StringDecoder = _dereq_(96).StringDecoder;
6175 var decoder = new StringDecoder(enc);
6176 this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8
6177
6178 this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:
6179
6180 var p = this._readableState.buffer.head;
6181 var content = '';
6182
6183 while (p !== null) {
6184 content += decoder.write(p.data);
6185 p = p.next;
6186 }
6187
6188 this._readableState.buffer.clear();
6189
6190 if (content !== '') this._readableState.buffer.push(content);
6191 this._readableState.length = content.length;
6192 return this;
6193}; // Don't raise the hwm > 1GB
6194
6195
6196var MAX_HWM = 0x40000000;
6197
6198function computeNewHighWaterMark(n) {
6199 if (n >= MAX_HWM) {
6200 // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
6201 n = MAX_HWM;
6202 } else {
6203 // Get the next highest power of 2 to prevent increasing hwm excessively in
6204 // tiny amounts
6205 n--;
6206 n |= n >>> 1;
6207 n |= n >>> 2;
6208 n |= n >>> 4;
6209 n |= n >>> 8;
6210 n |= n >>> 16;
6211 n++;
6212 }
6213
6214 return n;
6215} // This function is designed to be inlinable, so please take care when making
6216// changes to the function body.
6217
6218
6219function howMuchToRead(n, state) {
6220 if (n <= 0 || state.length === 0 && state.ended) return 0;
6221 if (state.objectMode) return 1;
6222
6223 if (n !== n) {
6224 // Only flow one buffer at a time
6225 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
6226 } // If we're asking for more than the current hwm, then raise the hwm.
6227
6228
6229 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
6230 if (n <= state.length) return n; // Don't have enough
6231
6232 if (!state.ended) {
6233 state.needReadable = true;
6234 return 0;
6235 }
6236
6237 return state.length;
6238} // you can override either this method, or the async _read(n) below.
6239
6240
6241Readable.prototype.read = function (n) {
6242 debug('read', n);
6243 n = parseInt(n, 10);
6244 var state = this._readableState;
6245 var nOrig = n;
6246 if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we
6247 // already have a bunch of data in the buffer, then just trigger
6248 // the 'readable' event and move on.
6249
6250 if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
6251 debug('read: emitReadable', state.length, state.ended);
6252 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
6253 return null;
6254 }
6255
6256 n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.
6257
6258 if (n === 0 && state.ended) {
6259 if (state.length === 0) endReadable(this);
6260 return null;
6261 } // All the actual chunk generation logic needs to be
6262 // *below* the call to _read. The reason is that in certain
6263 // synthetic stream cases, such as passthrough streams, _read
6264 // may be a completely synchronous operation which may change
6265 // the state of the read buffer, providing enough data when
6266 // before there was *not* enough.
6267 //
6268 // So, the steps are:
6269 // 1. Figure out what the state of things will be after we do
6270 // a read from the buffer.
6271 //
6272 // 2. If that resulting state will trigger a _read, then call _read.
6273 // Note that this may be asynchronous, or synchronous. Yes, it is
6274 // deeply ugly to write APIs this way, but that still doesn't mean
6275 // that the Readable class should behave improperly, as streams are
6276 // designed to be sync/async agnostic.
6277 // Take note if the _read call is sync or async (ie, if the read call
6278 // has returned yet), so that we know whether or not it's safe to emit
6279 // 'readable' etc.
6280 //
6281 // 3. Actually pull the requested chunks out of the buffer and return.
6282 // if we need a readable event, then we need to do some reading.
6283
6284
6285 var doRead = state.needReadable;
6286 debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some
6287
6288 if (state.length === 0 || state.length - n < state.highWaterMark) {
6289 doRead = true;
6290 debug('length less than watermark', doRead);
6291 } // however, if we've ended, then there's no point, and if we're already
6292 // reading, then it's unnecessary.
6293
6294
6295 if (state.ended || state.reading) {
6296 doRead = false;
6297 debug('reading or ended', doRead);
6298 } else if (doRead) {
6299 debug('do read');
6300 state.reading = true;
6301 state.sync = true; // if the length is currently zero, then we *need* a readable event.
6302
6303 if (state.length === 0) state.needReadable = true; // call internal read method
6304
6305 this._read(state.highWaterMark);
6306
6307 state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
6308 // and we need to re-evaluate how much data we can return to the user.
6309
6310 if (!state.reading) n = howMuchToRead(nOrig, state);
6311 }
6312
6313 var ret;
6314 if (n > 0) ret = fromList(n, state);else ret = null;
6315
6316 if (ret === null) {
6317 state.needReadable = state.length <= state.highWaterMark;
6318 n = 0;
6319 } else {
6320 state.length -= n;
6321 state.awaitDrain = 0;
6322 }
6323
6324 if (state.length === 0) {
6325 // If we have nothing in the buffer, then we want to know
6326 // as soon as we *do* get something into the buffer.
6327 if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
6328
6329 if (nOrig !== n && state.ended) endReadable(this);
6330 }
6331
6332 if (ret !== null) this.emit('data', ret);
6333 return ret;
6334};
6335
6336function onEofChunk(stream, state) {
6337 debug('onEofChunk');
6338 if (state.ended) return;
6339
6340 if (state.decoder) {
6341 var chunk = state.decoder.end();
6342
6343 if (chunk && chunk.length) {
6344 state.buffer.push(chunk);
6345 state.length += state.objectMode ? 1 : chunk.length;
6346 }
6347 }
6348
6349 state.ended = true;
6350
6351 if (state.sync) {
6352 // if we are sync, wait until next tick to emit the data.
6353 // Otherwise we risk emitting data in the flow()
6354 // the readable code triggers during a read() call
6355 emitReadable(stream);
6356 } else {
6357 // emit 'readable' now to make sure it gets picked up.
6358 state.needReadable = false;
6359
6360 if (!state.emittedReadable) {
6361 state.emittedReadable = true;
6362 emitReadable_(stream);
6363 }
6364 }
6365} // Don't emit readable right away in sync mode, because this can trigger
6366// another read() call => stack overflow. This way, it might trigger
6367// a nextTick recursion warning, but that's not so bad.
6368
6369
6370function emitReadable(stream) {
6371 var state = stream._readableState;
6372 debug('emitReadable', state.needReadable, state.emittedReadable);
6373 state.needReadable = false;
6374
6375 if (!state.emittedReadable) {
6376 debug('emitReadable', state.flowing);
6377 state.emittedReadable = true;
6378 process.nextTick(emitReadable_, stream);
6379 }
6380}
6381
6382function emitReadable_(stream) {
6383 var state = stream._readableState;
6384 debug('emitReadable_', state.destroyed, state.length, state.ended);
6385
6386 if (!state.destroyed && (state.length || state.ended)) {
6387 stream.emit('readable');
6388 state.emittedReadable = false;
6389 } // The stream needs another readable event if
6390 // 1. It is not flowing, as the flow mechanism will take
6391 // care of it.
6392 // 2. It is not ended.
6393 // 3. It is below the highWaterMark, so we can schedule
6394 // another readable later.
6395
6396
6397 state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
6398 flow(stream);
6399} // at this point, the user has presumably seen the 'readable' event,
6400// and called read() to consume some data. that may have triggered
6401// in turn another _read(n) call, in which case reading = true if
6402// it's in progress.
6403// However, if we're not ended, or reading, and the length < hwm,
6404// then go ahead and try to read some more preemptively.
6405
6406
6407function maybeReadMore(stream, state) {
6408 if (!state.readingMore) {
6409 state.readingMore = true;
6410 process.nextTick(maybeReadMore_, stream, state);
6411 }
6412}
6413
6414function maybeReadMore_(stream, state) {
6415 // Attempt to read more data if we should.
6416 //
6417 // The conditions for reading more data are (one of):
6418 // - Not enough data buffered (state.length < state.highWaterMark). The loop
6419 // is responsible for filling the buffer with enough data if such data
6420 // is available. If highWaterMark is 0 and we are not in the flowing mode
6421 // we should _not_ attempt to buffer any extra data. We'll get more data
6422 // when the stream consumer calls read() instead.
6423 // - No data in the buffer, and the stream is in flowing mode. In this mode
6424 // the loop below is responsible for ensuring read() is called. Failing to
6425 // call read here would abort the flow and there's no other mechanism for
6426 // continuing the flow if the stream consumer has just subscribed to the
6427 // 'data' event.
6428 //
6429 // In addition to the above conditions to keep reading data, the following
6430 // conditions prevent the data from being read:
6431 // - The stream has ended (state.ended).
6432 // - There is already a pending 'read' operation (state.reading). This is a
6433 // case where the the stream has called the implementation defined _read()
6434 // method, but they are processing the call asynchronously and have _not_
6435 // called push() with new data. In this case we skip performing more
6436 // read()s. The execution ends in this method again after the _read() ends
6437 // up calling push() with more data.
6438 while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
6439 var len = state.length;
6440 debug('maybeReadMore read 0');
6441 stream.read(0);
6442 if (len === state.length) // didn't get any data, stop spinning.
6443 break;
6444 }
6445
6446 state.readingMore = false;
6447} // abstract method. to be overridden in specific implementation classes.
6448// call cb(er, data) where data is <= n in length.
6449// for virtual (non-string, non-buffer) streams, "length" is somewhat
6450// arbitrary, and perhaps not very meaningful.
6451
6452
6453Readable.prototype._read = function (n) {
6454 errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
6455};
6456
6457Readable.prototype.pipe = function (dest, pipeOpts) {
6458 var src = this;
6459 var state = this._readableState;
6460
6461 switch (state.pipesCount) {
6462 case 0:
6463 state.pipes = dest;
6464 break;
6465
6466 case 1:
6467 state.pipes = [state.pipes, dest];
6468 break;
6469
6470 default:
6471 state.pipes.push(dest);
6472 break;
6473 }
6474
6475 state.pipesCount += 1;
6476 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
6477 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
6478 var endFn = doEnd ? onend : unpipe;
6479 if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
6480 dest.on('unpipe', onunpipe);
6481
6482 function onunpipe(readable, unpipeInfo) {
6483 debug('onunpipe');
6484
6485 if (readable === src) {
6486 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
6487 unpipeInfo.hasUnpiped = true;
6488 cleanup();
6489 }
6490 }
6491 }
6492
6493 function onend() {
6494 debug('onend');
6495 dest.end();
6496 } // when the dest drains, it reduces the awaitDrain counter
6497 // on the source. This would be more elegant with a .once()
6498 // handler in flow(), but adding and removing repeatedly is
6499 // too slow.
6500
6501
6502 var ondrain = pipeOnDrain(src);
6503 dest.on('drain', ondrain);
6504 var cleanedUp = false;
6505
6506 function cleanup() {
6507 debug('cleanup'); // cleanup event handlers once the pipe is broken
6508
6509 dest.removeListener('close', onclose);
6510 dest.removeListener('finish', onfinish);
6511 dest.removeListener('drain', ondrain);
6512 dest.removeListener('error', onerror);
6513 dest.removeListener('unpipe', onunpipe);
6514 src.removeListener('end', onend);
6515 src.removeListener('end', unpipe);
6516 src.removeListener('data', ondata);
6517 cleanedUp = true; // if the reader is waiting for a drain event from this
6518 // specific writer, then it would cause it to never start
6519 // flowing again.
6520 // So, if this is awaiting a drain, then we just call it now.
6521 // If we don't know, then assume that we are waiting for one.
6522
6523 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
6524 }
6525
6526 src.on('data', ondata);
6527
6528 function ondata(chunk) {
6529 debug('ondata');
6530 var ret = dest.write(chunk);
6531 debug('dest.write', ret);
6532
6533 if (ret === false) {
6534 // If the user unpiped during `dest.write()`, it is possible
6535 // to get stuck in a permanently paused state if that write
6536 // also returned false.
6537 // => Check whether `dest` is still a piping destination.
6538 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
6539 debug('false write response, pause', state.awaitDrain);
6540 state.awaitDrain++;
6541 }
6542
6543 src.pause();
6544 }
6545 } // if the dest has an error, then stop piping into it.
6546 // however, don't suppress the throwing behavior for this.
6547
6548
6549 function onerror(er) {
6550 debug('onerror', er);
6551 unpipe();
6552 dest.removeListener('error', onerror);
6553 if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
6554 } // Make sure our error handler is attached before userland ones.
6555
6556
6557 prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
6558
6559 function onclose() {
6560 dest.removeListener('finish', onfinish);
6561 unpipe();
6562 }
6563
6564 dest.once('close', onclose);
6565
6566 function onfinish() {
6567 debug('onfinish');
6568 dest.removeListener('close', onclose);
6569 unpipe();
6570 }
6571
6572 dest.once('finish', onfinish);
6573
6574 function unpipe() {
6575 debug('unpipe');
6576 src.unpipe(dest);
6577 } // tell the dest that it's being piped to
6578
6579
6580 dest.emit('pipe', src); // start the flow if it hasn't been started already.
6581
6582 if (!state.flowing) {
6583 debug('pipe resume');
6584 src.resume();
6585 }
6586
6587 return dest;
6588};
6589
6590function pipeOnDrain(src) {
6591 return function pipeOnDrainFunctionResult() {
6592 var state = src._readableState;
6593 debug('pipeOnDrain', state.awaitDrain);
6594 if (state.awaitDrain) state.awaitDrain--;
6595
6596 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
6597 state.flowing = true;
6598 flow(src);
6599 }
6600 };
6601}
6602
6603Readable.prototype.unpipe = function (dest) {
6604 var state = this._readableState;
6605 var unpipeInfo = {
6606 hasUnpiped: false
6607 }; // if we're not piping anywhere, then do nothing.
6608
6609 if (state.pipesCount === 0) return this; // just one destination. most common case.
6610
6611 if (state.pipesCount === 1) {
6612 // passed in one, but it's not the right one.
6613 if (dest && dest !== state.pipes) return this;
6614 if (!dest) dest = state.pipes; // got a match.
6615
6616 state.pipes = null;
6617 state.pipesCount = 0;
6618 state.flowing = false;
6619 if (dest) dest.emit('unpipe', this, unpipeInfo);
6620 return this;
6621 } // slow case. multiple pipe destinations.
6622
6623
6624 if (!dest) {
6625 // remove all.
6626 var dests = state.pipes;
6627 var len = state.pipesCount;
6628 state.pipes = null;
6629 state.pipesCount = 0;
6630 state.flowing = false;
6631
6632 for (var i = 0; i < len; i++) {
6633 dests[i].emit('unpipe', this, {
6634 hasUnpiped: false
6635 });
6636 }
6637
6638 return this;
6639 } // try to find the right one.
6640
6641
6642 var index = indexOf(state.pipes, dest);
6643 if (index === -1) return this;
6644 state.pipes.splice(index, 1);
6645 state.pipesCount -= 1;
6646 if (state.pipesCount === 1) state.pipes = state.pipes[0];
6647 dest.emit('unpipe', this, unpipeInfo);
6648 return this;
6649}; // set up data events if they are asked for
6650// Ensure readable listeners eventually get something
6651
6652
6653Readable.prototype.on = function (ev, fn) {
6654 var res = Stream.prototype.on.call(this, ev, fn);
6655 var state = this._readableState;
6656
6657 if (ev === 'data') {
6658 // update readableListening so that resume() may be a no-op
6659 // a few lines down. This is needed to support once('readable').
6660 state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused
6661
6662 if (state.flowing !== false) this.resume();
6663 } else if (ev === 'readable') {
6664 if (!state.endEmitted && !state.readableListening) {
6665 state.readableListening = state.needReadable = true;
6666 state.flowing = false;
6667 state.emittedReadable = false;
6668 debug('on readable', state.length, state.reading);
6669
6670 if (state.length) {
6671 emitReadable(this);
6672 } else if (!state.reading) {
6673 process.nextTick(nReadingNextTick, this);
6674 }
6675 }
6676 }
6677
6678 return res;
6679};
6680
6681Readable.prototype.addListener = Readable.prototype.on;
6682
6683Readable.prototype.removeListener = function (ev, fn) {
6684 var res = Stream.prototype.removeListener.call(this, ev, fn);
6685
6686 if (ev === 'readable') {
6687 // We need to check if there is someone still listening to
6688 // readable and reset the state. However this needs to happen
6689 // after readable has been emitted but before I/O (nextTick) to
6690 // support once('readable', fn) cycles. This means that calling
6691 // resume within the same tick will have no
6692 // effect.
6693 process.nextTick(updateReadableListening, this);
6694 }
6695
6696 return res;
6697};
6698
6699Readable.prototype.removeAllListeners = function (ev) {
6700 var res = Stream.prototype.removeAllListeners.apply(this, arguments);
6701
6702 if (ev === 'readable' || ev === undefined) {
6703 // We need to check if there is someone still listening to
6704 // readable and reset the state. However this needs to happen
6705 // after readable has been emitted but before I/O (nextTick) to
6706 // support once('readable', fn) cycles. This means that calling
6707 // resume within the same tick will have no
6708 // effect.
6709 process.nextTick(updateReadableListening, this);
6710 }
6711
6712 return res;
6713};
6714
6715function updateReadableListening(self) {
6716 var state = self._readableState;
6717 state.readableListening = self.listenerCount('readable') > 0;
6718
6719 if (state.resumeScheduled && !state.paused) {
6720 // flowing needs to be set to true now, otherwise
6721 // the upcoming resume will not flow.
6722 state.flowing = true; // crude way to check if we should resume
6723 } else if (self.listenerCount('data') > 0) {
6724 self.resume();
6725 }
6726}
6727
6728function nReadingNextTick(self) {
6729 debug('readable nexttick read 0');
6730 self.read(0);
6731} // pause() and resume() are remnants of the legacy readable stream API
6732// If the user uses them, then switch into old mode.
6733
6734
6735Readable.prototype.resume = function () {
6736 var state = this._readableState;
6737
6738 if (!state.flowing) {
6739 debug('resume'); // we flow only if there is no one listening
6740 // for readable, but we still have to call
6741 // resume()
6742
6743 state.flowing = !state.readableListening;
6744 resume(this, state);
6745 }
6746
6747 state.paused = false;
6748 return this;
6749};
6750
6751function resume(stream, state) {
6752 if (!state.resumeScheduled) {
6753 state.resumeScheduled = true;
6754 process.nextTick(resume_, stream, state);
6755 }
6756}
6757
6758function resume_(stream, state) {
6759 debug('resume', state.reading);
6760
6761 if (!state.reading) {
6762 stream.read(0);
6763 }
6764
6765 state.resumeScheduled = false;
6766 stream.emit('resume');
6767 flow(stream);
6768 if (state.flowing && !state.reading) stream.read(0);
6769}
6770
6771Readable.prototype.pause = function () {
6772 debug('call pause flowing=%j', this._readableState.flowing);
6773
6774 if (this._readableState.flowing !== false) {
6775 debug('pause');
6776 this._readableState.flowing = false;
6777 this.emit('pause');
6778 }
6779
6780 this._readableState.paused = true;
6781 return this;
6782};
6783
6784function flow(stream) {
6785 var state = stream._readableState;
6786 debug('flow', state.flowing);
6787
6788 while (state.flowing && stream.read() !== null) {
6789 ;
6790 }
6791} // wrap an old-style stream as the async data source.
6792// This is *not* part of the readable stream interface.
6793// It is an ugly unfortunate mess of history.
6794
6795
6796Readable.prototype.wrap = function (stream) {
6797 var _this = this;
6798
6799 var state = this._readableState;
6800 var paused = false;
6801 stream.on('end', function () {
6802 debug('wrapped end');
6803
6804 if (state.decoder && !state.ended) {
6805 var chunk = state.decoder.end();
6806 if (chunk && chunk.length) _this.push(chunk);
6807 }
6808
6809 _this.push(null);
6810 });
6811 stream.on('data', function (chunk) {
6812 debug('wrapped data');
6813 if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
6814
6815 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
6816
6817 var ret = _this.push(chunk);
6818
6819 if (!ret) {
6820 paused = true;
6821 stream.pause();
6822 }
6823 }); // proxy all the other methods.
6824 // important when wrapping filters and duplexes.
6825
6826 for (var i in stream) {
6827 if (this[i] === undefined && typeof stream[i] === 'function') {
6828 this[i] = function methodWrap(method) {
6829 return function methodWrapReturnFunction() {
6830 return stream[method].apply(stream, arguments);
6831 };
6832 }(i);
6833 }
6834 } // proxy certain important events.
6835
6836
6837 for (var n = 0; n < kProxyEvents.length; n++) {
6838 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
6839 } // when we try to consume some more bytes, simply unpause the
6840 // underlying stream.
6841
6842
6843 this._read = function (n) {
6844 debug('wrapped _read', n);
6845
6846 if (paused) {
6847 paused = false;
6848 stream.resume();
6849 }
6850 };
6851
6852 return this;
6853};
6854
6855if (typeof Symbol === 'function') {
6856 Readable.prototype[Symbol.asyncIterator] = function () {
6857 if (createReadableStreamAsyncIterator === undefined) {
6858 createReadableStreamAsyncIterator = _dereq_(37);
6859 }
6860
6861 return createReadableStreamAsyncIterator(this);
6862 };
6863}
6864
6865Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
6866 // making it explicit this property is not enumerable
6867 // because otherwise some prototype manipulation in
6868 // userland will fail
6869 enumerable: false,
6870 get: function get() {
6871 return this._readableState.highWaterMark;
6872 }
6873});
6874Object.defineProperty(Readable.prototype, 'readableBuffer', {
6875 // making it explicit this property is not enumerable
6876 // because otherwise some prototype manipulation in
6877 // userland will fail
6878 enumerable: false,
6879 get: function get() {
6880 return this._readableState && this._readableState.buffer;
6881 }
6882});
6883Object.defineProperty(Readable.prototype, 'readableFlowing', {
6884 // making it explicit this property is not enumerable
6885 // because otherwise some prototype manipulation in
6886 // userland will fail
6887 enumerable: false,
6888 get: function get() {
6889 return this._readableState.flowing;
6890 },
6891 set: function set(state) {
6892 if (this._readableState) {
6893 this._readableState.flowing = state;
6894 }
6895 }
6896}); // exposed for testing purposes only.
6897
6898Readable._fromList = fromList;
6899Object.defineProperty(Readable.prototype, 'readableLength', {
6900 // making it explicit this property is not enumerable
6901 // because otherwise some prototype manipulation in
6902 // userland will fail
6903 enumerable: false,
6904 get: function get() {
6905 return this._readableState.length;
6906 }
6907}); // Pluck off n bytes from an array of buffers.
6908// Length is the combined lengths of all the buffers in the list.
6909// This function is designed to be inlinable, so please take care when making
6910// changes to the function body.
6911
6912function fromList(n, state) {
6913 // nothing buffered
6914 if (state.length === 0) return null;
6915 var ret;
6916 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
6917 // read it all, truncate the list
6918 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
6919 state.buffer.clear();
6920 } else {
6921 // read part of list
6922 ret = state.buffer.consume(n, state.decoder);
6923 }
6924 return ret;
6925}
6926
6927function endReadable(stream) {
6928 var state = stream._readableState;
6929 debug('endReadable', state.endEmitted);
6930
6931 if (!state.endEmitted) {
6932 state.ended = true;
6933 process.nextTick(endReadableNT, state, stream);
6934 }
6935}
6936
6937function endReadableNT(state, stream) {
6938 debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.
6939
6940 if (!state.endEmitted && state.length === 0) {
6941 state.endEmitted = true;
6942 stream.readable = false;
6943 stream.emit('end');
6944
6945 if (state.autoDestroy) {
6946 // In case of duplex streams we need a way to detect
6947 // if the writable side is ready for autoDestroy as well
6948 var wState = stream._writableState;
6949
6950 if (!wState || wState.autoDestroy && wState.finished) {
6951 stream.destroy();
6952 }
6953 }
6954 }
6955}
6956
6957if (typeof Symbol === 'function') {
6958 Readable.from = function (iterable, opts) {
6959 if (from === undefined) {
6960 from = _dereq_(41);
6961 }
6962
6963 return from(Readable, iterable, opts);
6964 };
6965}
6966
6967function indexOf(xs, x) {
6968 for (var i = 0, l = xs.length; i < l; i++) {
6969 if (xs[i] === x) return i;
6970 }
6971
6972 return -1;
6973}
6974}).call(this,_dereq_(68),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
6975},{"10":10,"12":12,"18":18,"24":24,"31":31,"32":32,"37":37,"38":38,"39":39,"41":41,"43":43,"44":44,"68":68,"96":96}],35:[function(_dereq_,module,exports){
6976// Copyright Joyent, Inc. and other Node contributors.
6977//
6978// Permission is hereby granted, free of charge, to any person obtaining a
6979// copy of this software and associated documentation files (the
6980// "Software"), to deal in the Software without restriction, including
6981// without limitation the rights to use, copy, modify, merge, publish,
6982// distribute, sublicense, and/or sell copies of the Software, and to permit
6983// persons to whom the Software is furnished to do so, subject to the
6984// following conditions:
6985//
6986// The above copyright notice and this permission notice shall be included
6987// in all copies or substantial portions of the Software.
6988//
6989// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6990// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6991// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6992// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6993// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6994// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6995// USE OR OTHER DEALINGS IN THE SOFTWARE.
6996// a transform stream is a readable/writable stream where you do
6997// something with the data. Sometimes it's called a "filter",
6998// but that's not a great name for it, since that implies a thing where
6999// some bits pass through, and others are simply ignored. (That would
7000// be a valid example of a transform, of course.)
7001//
7002// While the output is causally related to the input, it's not a
7003// necessarily symmetric or synchronous transformation. For example,
7004// a zlib stream might take multiple plain-text writes(), and then
7005// emit a single compressed chunk some time in the future.
7006//
7007// Here's how this works:
7008//
7009// The Transform stream has all the aspects of the readable and writable
7010// stream classes. When you write(chunk), that calls _write(chunk,cb)
7011// internally, and returns false if there's a lot of pending writes
7012// buffered up. When you call read(), that calls _read(n) until
7013// there's enough pending readable data buffered up.
7014//
7015// In a transform stream, the written data is placed in a buffer. When
7016// _read(n) is called, it transforms the queued up data, calling the
7017// buffered _write cb's as it consumes chunks. If consuming a single
7018// written chunk would result in multiple output chunks, then the first
7019// outputted bit calls the readcb, and subsequent chunks just go into
7020// the read buffer, and will cause it to emit 'readable' if necessary.
7021//
7022// This way, back-pressure is actually determined by the reading side,
7023// since _read has to be called to start processing a new chunk. However,
7024// a pathological inflate type of transform can cause excessive buffering
7025// here. For example, imagine a stream where every byte of input is
7026// interpreted as an integer from 0-255, and then results in that many
7027// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
7028// 1kb of data being output. In this case, you could write a very small
7029// amount of input, and end up with a very large amount of output. In
7030// such a pathological inflating mechanism, there'd be no way to tell
7031// the system to stop doing the transform. A single 4MB write could
7032// cause the system to run out of memory.
7033//
7034// However, even in such a pathological case, only a single written chunk
7035// would be consumed, and then the rest would wait (un-transformed) until
7036// the results of the previous transformed chunk were consumed.
7037'use strict';
7038
7039module.exports = Transform;
7040
7041var _require$codes = _dereq_(31).codes,
7042 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
7043 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
7044 ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
7045 ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
7046
7047var Duplex = _dereq_(32);
7048
7049_dereq_(24)(Transform, Duplex);
7050
7051function afterTransform(er, data) {
7052 var ts = this._transformState;
7053 ts.transforming = false;
7054 var cb = ts.writecb;
7055
7056 if (cb === null) {
7057 return this.emit('error', new ERR_MULTIPLE_CALLBACK());
7058 }
7059
7060 ts.writechunk = null;
7061 ts.writecb = null;
7062 if (data != null) // single equals check for both `null` and `undefined`
7063 this.push(data);
7064 cb(er);
7065 var rs = this._readableState;
7066 rs.reading = false;
7067
7068 if (rs.needReadable || rs.length < rs.highWaterMark) {
7069 this._read(rs.highWaterMark);
7070 }
7071}
7072
7073function Transform(options) {
7074 if (!(this instanceof Transform)) return new Transform(options);
7075 Duplex.call(this, options);
7076 this._transformState = {
7077 afterTransform: afterTransform.bind(this),
7078 needTransform: false,
7079 transforming: false,
7080 writecb: null,
7081 writechunk: null,
7082 writeencoding: null
7083 }; // start out asking for a readable event once data is transformed.
7084
7085 this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
7086 // that Readable wants before the first _read call, so unset the
7087 // sync guard flag.
7088
7089 this._readableState.sync = false;
7090
7091 if (options) {
7092 if (typeof options.transform === 'function') this._transform = options.transform;
7093 if (typeof options.flush === 'function') this._flush = options.flush;
7094 } // When the writable side finishes, then flush out anything remaining.
7095
7096
7097 this.on('prefinish', prefinish);
7098}
7099
7100function prefinish() {
7101 var _this = this;
7102
7103 if (typeof this._flush === 'function' && !this._readableState.destroyed) {
7104 this._flush(function (er, data) {
7105 done(_this, er, data);
7106 });
7107 } else {
7108 done(this, null, null);
7109 }
7110}
7111
7112Transform.prototype.push = function (chunk, encoding) {
7113 this._transformState.needTransform = false;
7114 return Duplex.prototype.push.call(this, chunk, encoding);
7115}; // This is the part where you do stuff!
7116// override this function in implementation classes.
7117// 'chunk' is an input chunk.
7118//
7119// Call `push(newChunk)` to pass along transformed output
7120// to the readable side. You may call 'push' zero or more times.
7121//
7122// Call `cb(err)` when you are done with this chunk. If you pass
7123// an error, then that'll put the hurt on the whole operation. If you
7124// never call cb(), then you'll never get another chunk.
7125
7126
7127Transform.prototype._transform = function (chunk, encoding, cb) {
7128 cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
7129};
7130
7131Transform.prototype._write = function (chunk, encoding, cb) {
7132 var ts = this._transformState;
7133 ts.writecb = cb;
7134 ts.writechunk = chunk;
7135 ts.writeencoding = encoding;
7136
7137 if (!ts.transforming) {
7138 var rs = this._readableState;
7139 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
7140 }
7141}; // Doesn't matter what the args are here.
7142// _transform does all the work.
7143// That we got here means that the readable side wants more data.
7144
7145
7146Transform.prototype._read = function (n) {
7147 var ts = this._transformState;
7148
7149 if (ts.writechunk !== null && !ts.transforming) {
7150 ts.transforming = true;
7151
7152 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
7153 } else {
7154 // mark that we need a transform, so that any data that comes in
7155 // will get processed, now that we've asked for it.
7156 ts.needTransform = true;
7157 }
7158};
7159
7160Transform.prototype._destroy = function (err, cb) {
7161 Duplex.prototype._destroy.call(this, err, function (err2) {
7162 cb(err2);
7163 });
7164};
7165
7166function done(stream, er, data) {
7167 if (er) return stream.emit('error', er);
7168 if (data != null) // single equals check for both `null` and `undefined`
7169 stream.push(data); // TODO(BridgeAR): Write a test for these two error cases
7170 // if there's nothing in the write buffer, then that means
7171 // that nothing more will ever be provided
7172
7173 if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
7174 if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
7175 return stream.push(null);
7176}
7177},{"24":24,"31":31,"32":32}],36:[function(_dereq_,module,exports){
7178(function (process,global){
7179// Copyright Joyent, Inc. and other Node contributors.
7180//
7181// Permission is hereby granted, free of charge, to any person obtaining a
7182// copy of this software and associated documentation files (the
7183// "Software"), to deal in the Software without restriction, including
7184// without limitation the rights to use, copy, modify, merge, publish,
7185// distribute, sublicense, and/or sell copies of the Software, and to permit
7186// persons to whom the Software is furnished to do so, subject to the
7187// following conditions:
7188//
7189// The above copyright notice and this permission notice shall be included
7190// in all copies or substantial portions of the Software.
7191//
7192// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7193// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7194// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7195// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7196// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7197// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7198// USE OR OTHER DEALINGS IN THE SOFTWARE.
7199// A bit simpler than readable streams.
7200// Implement an async ._write(chunk, encoding, cb), and it'll handle all
7201// the drain event emission and buffering.
7202'use strict';
7203
7204module.exports = Writable;
7205/* <replacement> */
7206
7207function WriteReq(chunk, encoding, cb) {
7208 this.chunk = chunk;
7209 this.encoding = encoding;
7210 this.callback = cb;
7211 this.next = null;
7212} // It seems a linked list but it is not
7213// there will be only 2 of these for each stream
7214
7215
7216function CorkedRequest(state) {
7217 var _this = this;
7218
7219 this.next = null;
7220 this.entry = null;
7221
7222 this.finish = function () {
7223 onCorkedFinish(_this, state);
7224 };
7225}
7226/* </replacement> */
7227
7228/*<replacement>*/
7229
7230
7231var Duplex;
7232/*</replacement>*/
7233
7234Writable.WritableState = WritableState;
7235/*<replacement>*/
7236
7237var internalUtil = {
7238 deprecate: _dereq_(115)
7239};
7240/*</replacement>*/
7241
7242/*<replacement>*/
7243
7244var Stream = _dereq_(44);
7245/*</replacement>*/
7246
7247
7248var Buffer = _dereq_(12).Buffer;
7249
7250var OurUint8Array = global.Uint8Array || function () {};
7251
7252function _uint8ArrayToBuffer(chunk) {
7253 return Buffer.from(chunk);
7254}
7255
7256function _isUint8Array(obj) {
7257 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
7258}
7259
7260var destroyImpl = _dereq_(39);
7261
7262var _require = _dereq_(43),
7263 getHighWaterMark = _require.getHighWaterMark;
7264
7265var _require$codes = _dereq_(31).codes,
7266 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
7267 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
7268 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
7269 ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
7270 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
7271 ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
7272 ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
7273 ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
7274
7275var errorOrDestroy = destroyImpl.errorOrDestroy;
7276
7277_dereq_(24)(Writable, Stream);
7278
7279function nop() {}
7280
7281function WritableState(options, stream, isDuplex) {
7282 Duplex = Duplex || _dereq_(32);
7283 options = options || {}; // Duplex streams are both readable and writable, but share
7284 // the same options object.
7285 // However, some cases require setting options to different
7286 // values for the readable and the writable sides of the duplex stream,
7287 // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
7288
7289 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream
7290 // contains buffers or objects.
7291
7292 this.objectMode = !!options.objectMode;
7293 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
7294 // Note: 0 is a valid value, means that we always return false if
7295 // the entire buffer is not flushed immediately on write()
7296
7297 this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called
7298
7299 this.finalCalled = false; // drain event flag.
7300
7301 this.needDrain = false; // at the start of calling end()
7302
7303 this.ending = false; // when end() has been called, and returned
7304
7305 this.ended = false; // when 'finish' is emitted
7306
7307 this.finished = false; // has it been destroyed
7308
7309 this.destroyed = false; // should we decode strings into buffers before passing to _write?
7310 // this is here so that some node-core streams can optimize string
7311 // handling at a lower level.
7312
7313 var noDecode = options.decodeStrings === false;
7314 this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string
7315 // encoding is 'binary' so we have to make this configurable.
7316 // Everything else in the universe uses 'utf8', though.
7317
7318 this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement
7319 // of how much we're waiting to get pushed to some underlying
7320 // socket or file.
7321
7322 this.length = 0; // a flag to see when we're in the middle of a write.
7323
7324 this.writing = false; // when true all writes will be buffered until .uncork() call
7325
7326 this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,
7327 // or on a later tick. We set this to true at first, because any
7328 // actions that shouldn't happen until "later" should generally also
7329 // not happen before the first write call.
7330
7331 this.sync = true; // a flag to know if we're processing previously buffered items, which
7332 // may call the _write() callback in the same tick, so that we don't
7333 // end up in an overlapped onwrite situation.
7334
7335 this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)
7336
7337 this.onwrite = function (er) {
7338 onwrite(stream, er);
7339 }; // the callback that the user supplies to write(chunk,encoding,cb)
7340
7341
7342 this.writecb = null; // the amount that is being written when _write is called.
7343
7344 this.writelen = 0;
7345 this.bufferedRequest = null;
7346 this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
7347 // this must be 0 before 'finish' can be emitted
7348
7349 this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
7350 // This is relevant for synchronous Transform streams
7351
7352 this.prefinished = false; // True if the error was already emitted and should not be thrown again
7353
7354 this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.
7355
7356 this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')
7357
7358 this.autoDestroy = !!options.autoDestroy; // count buffered requests
7359
7360 this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always
7361 // one allocated and free to use, and we maintain at most two
7362
7363 this.corkedRequestsFree = new CorkedRequest(this);
7364}
7365
7366WritableState.prototype.getBuffer = function getBuffer() {
7367 var current = this.bufferedRequest;
7368 var out = [];
7369
7370 while (current) {
7371 out.push(current);
7372 current = current.next;
7373 }
7374
7375 return out;
7376};
7377
7378(function () {
7379 try {
7380 Object.defineProperty(WritableState.prototype, 'buffer', {
7381 get: internalUtil.deprecate(function writableStateBufferGetter() {
7382 return this.getBuffer();
7383 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
7384 });
7385 } catch (_) {}
7386})(); // Test _writableState for inheritance to account for Duplex streams,
7387// whose prototype chain only points to Readable.
7388
7389
7390var realHasInstance;
7391
7392if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
7393 realHasInstance = Function.prototype[Symbol.hasInstance];
7394 Object.defineProperty(Writable, Symbol.hasInstance, {
7395 value: function value(object) {
7396 if (realHasInstance.call(this, object)) return true;
7397 if (this !== Writable) return false;
7398 return object && object._writableState instanceof WritableState;
7399 }
7400 });
7401} else {
7402 realHasInstance = function realHasInstance(object) {
7403 return object instanceof this;
7404 };
7405}
7406
7407function Writable(options) {
7408 Duplex = Duplex || _dereq_(32); // Writable ctor is applied to Duplexes, too.
7409 // `realHasInstance` is necessary because using plain `instanceof`
7410 // would return false, as no `_writableState` property is attached.
7411 // Trying to use the custom `instanceof` for Writable here will also break the
7412 // Node.js LazyTransform implementation, which has a non-trivial getter for
7413 // `_writableState` that would lead to infinite recursion.
7414 // Checking for a Stream.Duplex instance is faster here instead of inside
7415 // the WritableState constructor, at least with V8 6.5
7416
7417 var isDuplex = this instanceof Duplex;
7418 if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
7419 this._writableState = new WritableState(options, this, isDuplex); // legacy.
7420
7421 this.writable = true;
7422
7423 if (options) {
7424 if (typeof options.write === 'function') this._write = options.write;
7425 if (typeof options.writev === 'function') this._writev = options.writev;
7426 if (typeof options.destroy === 'function') this._destroy = options.destroy;
7427 if (typeof options.final === 'function') this._final = options.final;
7428 }
7429
7430 Stream.call(this);
7431} // Otherwise people can pipe Writable streams, which is just wrong.
7432
7433
7434Writable.prototype.pipe = function () {
7435 errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
7436};
7437
7438function writeAfterEnd(stream, cb) {
7439 var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
7440
7441 errorOrDestroy(stream, er);
7442 process.nextTick(cb, er);
7443} // Checks that a user-supplied chunk is valid, especially for the particular
7444// mode the stream is in. Currently this means that `null` is never accepted
7445// and undefined/non-string values are only allowed in object mode.
7446
7447
7448function validChunk(stream, state, chunk, cb) {
7449 var er;
7450
7451 if (chunk === null) {
7452 er = new ERR_STREAM_NULL_VALUES();
7453 } else if (typeof chunk !== 'string' && !state.objectMode) {
7454 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
7455 }
7456
7457 if (er) {
7458 errorOrDestroy(stream, er);
7459 process.nextTick(cb, er);
7460 return false;
7461 }
7462
7463 return true;
7464}
7465
7466Writable.prototype.write = function (chunk, encoding, cb) {
7467 var state = this._writableState;
7468 var ret = false;
7469
7470 var isBuf = !state.objectMode && _isUint8Array(chunk);
7471
7472 if (isBuf && !Buffer.isBuffer(chunk)) {
7473 chunk = _uint8ArrayToBuffer(chunk);
7474 }
7475
7476 if (typeof encoding === 'function') {
7477 cb = encoding;
7478 encoding = null;
7479 }
7480
7481 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
7482 if (typeof cb !== 'function') cb = nop;
7483 if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
7484 state.pendingcb++;
7485 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
7486 }
7487 return ret;
7488};
7489
7490Writable.prototype.cork = function () {
7491 this._writableState.corked++;
7492};
7493
7494Writable.prototype.uncork = function () {
7495 var state = this._writableState;
7496
7497 if (state.corked) {
7498 state.corked--;
7499 if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
7500 }
7501};
7502
7503Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
7504 // node::ParseEncoding() requires lower case.
7505 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
7506 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);
7507 this._writableState.defaultEncoding = encoding;
7508 return this;
7509};
7510
7511Object.defineProperty(Writable.prototype, 'writableBuffer', {
7512 // making it explicit this property is not enumerable
7513 // because otherwise some prototype manipulation in
7514 // userland will fail
7515 enumerable: false,
7516 get: function get() {
7517 return this._writableState && this._writableState.getBuffer();
7518 }
7519});
7520
7521function decodeChunk(state, chunk, encoding) {
7522 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
7523 chunk = Buffer.from(chunk, encoding);
7524 }
7525
7526 return chunk;
7527}
7528
7529Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
7530 // making it explicit this property is not enumerable
7531 // because otherwise some prototype manipulation in
7532 // userland will fail
7533 enumerable: false,
7534 get: function get() {
7535 return this._writableState.highWaterMark;
7536 }
7537}); // if we're already writing something, then just put this
7538// in the queue, and wait our turn. Otherwise, call _write
7539// If we return false, then we need a drain event, so set that flag.
7540
7541function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
7542 if (!isBuf) {
7543 var newChunk = decodeChunk(state, chunk, encoding);
7544
7545 if (chunk !== newChunk) {
7546 isBuf = true;
7547 encoding = 'buffer';
7548 chunk = newChunk;
7549 }
7550 }
7551
7552 var len = state.objectMode ? 1 : chunk.length;
7553 state.length += len;
7554 var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
7555
7556 if (!ret) state.needDrain = true;
7557
7558 if (state.writing || state.corked) {
7559 var last = state.lastBufferedRequest;
7560 state.lastBufferedRequest = {
7561 chunk: chunk,
7562 encoding: encoding,
7563 isBuf: isBuf,
7564 callback: cb,
7565 next: null
7566 };
7567
7568 if (last) {
7569 last.next = state.lastBufferedRequest;
7570 } else {
7571 state.bufferedRequest = state.lastBufferedRequest;
7572 }
7573
7574 state.bufferedRequestCount += 1;
7575 } else {
7576 doWrite(stream, state, false, len, chunk, encoding, cb);
7577 }
7578
7579 return ret;
7580}
7581
7582function doWrite(stream, state, writev, len, chunk, encoding, cb) {
7583 state.writelen = len;
7584 state.writecb = cb;
7585 state.writing = true;
7586 state.sync = true;
7587 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);
7588 state.sync = false;
7589}
7590
7591function onwriteError(stream, state, sync, er, cb) {
7592 --state.pendingcb;
7593
7594 if (sync) {
7595 // defer the callback if we are being called synchronously
7596 // to avoid piling up things on the stack
7597 process.nextTick(cb, er); // this can emit finish, and it will always happen
7598 // after error
7599
7600 process.nextTick(finishMaybe, stream, state);
7601 stream._writableState.errorEmitted = true;
7602 errorOrDestroy(stream, er);
7603 } else {
7604 // the caller expect this to happen before if
7605 // it is async
7606 cb(er);
7607 stream._writableState.errorEmitted = true;
7608 errorOrDestroy(stream, er); // this can emit finish, but finish must
7609 // always follow error
7610
7611 finishMaybe(stream, state);
7612 }
7613}
7614
7615function onwriteStateUpdate(state) {
7616 state.writing = false;
7617 state.writecb = null;
7618 state.length -= state.writelen;
7619 state.writelen = 0;
7620}
7621
7622function onwrite(stream, er) {
7623 var state = stream._writableState;
7624 var sync = state.sync;
7625 var cb = state.writecb;
7626 if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
7627 onwriteStateUpdate(state);
7628 if (er) onwriteError(stream, state, sync, er, cb);else {
7629 // Check if we're actually ready to finish, but don't emit yet
7630 var finished = needFinish(state) || stream.destroyed;
7631
7632 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
7633 clearBuffer(stream, state);
7634 }
7635
7636 if (sync) {
7637 process.nextTick(afterWrite, stream, state, finished, cb);
7638 } else {
7639 afterWrite(stream, state, finished, cb);
7640 }
7641 }
7642}
7643
7644function afterWrite(stream, state, finished, cb) {
7645 if (!finished) onwriteDrain(stream, state);
7646 state.pendingcb--;
7647 cb();
7648 finishMaybe(stream, state);
7649} // Must force callback to be called on nextTick, so that we don't
7650// emit 'drain' before the write() consumer gets the 'false' return
7651// value, and has a chance to attach a 'drain' listener.
7652
7653
7654function onwriteDrain(stream, state) {
7655 if (state.length === 0 && state.needDrain) {
7656 state.needDrain = false;
7657 stream.emit('drain');
7658 }
7659} // if there's something in the buffer waiting, then process it
7660
7661
7662function clearBuffer(stream, state) {
7663 state.bufferProcessing = true;
7664 var entry = state.bufferedRequest;
7665
7666 if (stream._writev && entry && entry.next) {
7667 // Fast case, write everything using _writev()
7668 var l = state.bufferedRequestCount;
7669 var buffer = new Array(l);
7670 var holder = state.corkedRequestsFree;
7671 holder.entry = entry;
7672 var count = 0;
7673 var allBuffers = true;
7674
7675 while (entry) {
7676 buffer[count] = entry;
7677 if (!entry.isBuf) allBuffers = false;
7678 entry = entry.next;
7679 count += 1;
7680 }
7681
7682 buffer.allBuffers = allBuffers;
7683 doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
7684 // as the hot path ends with doWrite
7685
7686 state.pendingcb++;
7687 state.lastBufferedRequest = null;
7688
7689 if (holder.next) {
7690 state.corkedRequestsFree = holder.next;
7691 holder.next = null;
7692 } else {
7693 state.corkedRequestsFree = new CorkedRequest(state);
7694 }
7695
7696 state.bufferedRequestCount = 0;
7697 } else {
7698 // Slow case, write chunks one-by-one
7699 while (entry) {
7700 var chunk = entry.chunk;
7701 var encoding = entry.encoding;
7702 var cb = entry.callback;
7703 var len = state.objectMode ? 1 : chunk.length;
7704 doWrite(stream, state, false, len, chunk, encoding, cb);
7705 entry = entry.next;
7706 state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then
7707 // it means that we need to wait until it does.
7708 // also, that means that the chunk and cb are currently
7709 // being processed, so move the buffer counter past them.
7710
7711 if (state.writing) {
7712 break;
7713 }
7714 }
7715
7716 if (entry === null) state.lastBufferedRequest = null;
7717 }
7718
7719 state.bufferedRequest = entry;
7720 state.bufferProcessing = false;
7721}
7722
7723Writable.prototype._write = function (chunk, encoding, cb) {
7724 cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
7725};
7726
7727Writable.prototype._writev = null;
7728
7729Writable.prototype.end = function (chunk, encoding, cb) {
7730 var state = this._writableState;
7731
7732 if (typeof chunk === 'function') {
7733 cb = chunk;
7734 chunk = null;
7735 encoding = null;
7736 } else if (typeof encoding === 'function') {
7737 cb = encoding;
7738 encoding = null;
7739 }
7740
7741 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks
7742
7743 if (state.corked) {
7744 state.corked = 1;
7745 this.uncork();
7746 } // ignore unnecessary end() calls.
7747
7748
7749 if (!state.ending) endWritable(this, state, cb);
7750 return this;
7751};
7752
7753Object.defineProperty(Writable.prototype, 'writableLength', {
7754 // making it explicit this property is not enumerable
7755 // because otherwise some prototype manipulation in
7756 // userland will fail
7757 enumerable: false,
7758 get: function get() {
7759 return this._writableState.length;
7760 }
7761});
7762
7763function needFinish(state) {
7764 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
7765}
7766
7767function callFinal(stream, state) {
7768 stream._final(function (err) {
7769 state.pendingcb--;
7770
7771 if (err) {
7772 errorOrDestroy(stream, err);
7773 }
7774
7775 state.prefinished = true;
7776 stream.emit('prefinish');
7777 finishMaybe(stream, state);
7778 });
7779}
7780
7781function prefinish(stream, state) {
7782 if (!state.prefinished && !state.finalCalled) {
7783 if (typeof stream._final === 'function' && !state.destroyed) {
7784 state.pendingcb++;
7785 state.finalCalled = true;
7786 process.nextTick(callFinal, stream, state);
7787 } else {
7788 state.prefinished = true;
7789 stream.emit('prefinish');
7790 }
7791 }
7792}
7793
7794function finishMaybe(stream, state) {
7795 var need = needFinish(state);
7796
7797 if (need) {
7798 prefinish(stream, state);
7799
7800 if (state.pendingcb === 0) {
7801 state.finished = true;
7802 stream.emit('finish');
7803
7804 if (state.autoDestroy) {
7805 // In case of duplex streams we need a way to detect
7806 // if the readable side is ready for autoDestroy as well
7807 var rState = stream._readableState;
7808
7809 if (!rState || rState.autoDestroy && rState.endEmitted) {
7810 stream.destroy();
7811 }
7812 }
7813 }
7814 }
7815
7816 return need;
7817}
7818
7819function endWritable(stream, state, cb) {
7820 state.ending = true;
7821 finishMaybe(stream, state);
7822
7823 if (cb) {
7824 if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
7825 }
7826
7827 state.ended = true;
7828 stream.writable = false;
7829}
7830
7831function onCorkedFinish(corkReq, state, err) {
7832 var entry = corkReq.entry;
7833 corkReq.entry = null;
7834
7835 while (entry) {
7836 var cb = entry.callback;
7837 state.pendingcb--;
7838 cb(err);
7839 entry = entry.next;
7840 } // reuse the free corkReq.
7841
7842
7843 state.corkedRequestsFree.next = corkReq;
7844}
7845
7846Object.defineProperty(Writable.prototype, 'destroyed', {
7847 // making it explicit this property is not enumerable
7848 // because otherwise some prototype manipulation in
7849 // userland will fail
7850 enumerable: false,
7851 get: function get() {
7852 if (this._writableState === undefined) {
7853 return false;
7854 }
7855
7856 return this._writableState.destroyed;
7857 },
7858 set: function set(value) {
7859 // we ignore the value if the stream
7860 // has not been initialized yet
7861 if (!this._writableState) {
7862 return;
7863 } // backward compatibility, the user is explicitly
7864 // managing destroyed
7865
7866
7867 this._writableState.destroyed = value;
7868 }
7869});
7870Writable.prototype.destroy = destroyImpl.destroy;
7871Writable.prototype._undestroy = destroyImpl.undestroy;
7872
7873Writable.prototype._destroy = function (err, cb) {
7874 cb(err);
7875};
7876}).call(this,_dereq_(68),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
7877},{"115":115,"12":12,"24":24,"31":31,"32":32,"39":39,"43":43,"44":44,"68":68}],37:[function(_dereq_,module,exports){
7878(function (process){
7879'use strict';
7880
7881var _Object$setPrototypeO;
7882
7883function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
7884
7885var finished = _dereq_(40);
7886
7887var kLastResolve = Symbol('lastResolve');
7888var kLastReject = Symbol('lastReject');
7889var kError = Symbol('error');
7890var kEnded = Symbol('ended');
7891var kLastPromise = Symbol('lastPromise');
7892var kHandlePromise = Symbol('handlePromise');
7893var kStream = Symbol('stream');
7894
7895function createIterResult(value, done) {
7896 return {
7897 value: value,
7898 done: done
7899 };
7900}
7901
7902function readAndResolve(iter) {
7903 var resolve = iter[kLastResolve];
7904
7905 if (resolve !== null) {
7906 var data = iter[kStream].read(); // we defer if data is null
7907 // we can be expecting either 'end' or
7908 // 'error'
7909
7910 if (data !== null) {
7911 iter[kLastPromise] = null;
7912 iter[kLastResolve] = null;
7913 iter[kLastReject] = null;
7914 resolve(createIterResult(data, false));
7915 }
7916 }
7917}
7918
7919function onReadable(iter) {
7920 // we wait for the next tick, because it might
7921 // emit an error with process.nextTick
7922 process.nextTick(readAndResolve, iter);
7923}
7924
7925function wrapForNext(lastPromise, iter) {
7926 return function (resolve, reject) {
7927 lastPromise.then(function () {
7928 if (iter[kEnded]) {
7929 resolve(createIterResult(undefined, true));
7930 return;
7931 }
7932
7933 iter[kHandlePromise](resolve, reject);
7934 }, reject);
7935 };
7936}
7937
7938var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
7939var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
7940 get stream() {
7941 return this[kStream];
7942 },
7943
7944 next: function next() {
7945 var _this = this;
7946
7947 // if we have detected an error in the meanwhile
7948 // reject straight away
7949 var error = this[kError];
7950
7951 if (error !== null) {
7952 return Promise.reject(error);
7953 }
7954
7955 if (this[kEnded]) {
7956 return Promise.resolve(createIterResult(undefined, true));
7957 }
7958
7959 if (this[kStream].destroyed) {
7960 // We need to defer via nextTick because if .destroy(err) is
7961 // called, the error will be emitted via nextTick, and
7962 // we cannot guarantee that there is no error lingering around
7963 // waiting to be emitted.
7964 return new Promise(function (resolve, reject) {
7965 process.nextTick(function () {
7966 if (_this[kError]) {
7967 reject(_this[kError]);
7968 } else {
7969 resolve(createIterResult(undefined, true));
7970 }
7971 });
7972 });
7973 } // if we have multiple next() calls
7974 // we will wait for the previous Promise to finish
7975 // this logic is optimized to support for await loops,
7976 // where next() is only called once at a time
7977
7978
7979 var lastPromise = this[kLastPromise];
7980 var promise;
7981
7982 if (lastPromise) {
7983 promise = new Promise(wrapForNext(lastPromise, this));
7984 } else {
7985 // fast path needed to support multiple this.push()
7986 // without triggering the next() queue
7987 var data = this[kStream].read();
7988
7989 if (data !== null) {
7990 return Promise.resolve(createIterResult(data, false));
7991 }
7992
7993 promise = new Promise(this[kHandlePromise]);
7994 }
7995
7996 this[kLastPromise] = promise;
7997 return promise;
7998 }
7999}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
8000 return this;
8001}), _defineProperty(_Object$setPrototypeO, "return", function _return() {
8002 var _this2 = this;
8003
8004 // destroy(err, cb) is a private API
8005 // we can guarantee we have that here, because we control the
8006 // Readable class this is attached to
8007 return new Promise(function (resolve, reject) {
8008 _this2[kStream].destroy(null, function (err) {
8009 if (err) {
8010 reject(err);
8011 return;
8012 }
8013
8014 resolve(createIterResult(undefined, true));
8015 });
8016 });
8017}), _Object$setPrototypeO), AsyncIteratorPrototype);
8018
8019var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
8020 var _Object$create;
8021
8022 var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
8023 value: stream,
8024 writable: true
8025 }), _defineProperty(_Object$create, kLastResolve, {
8026 value: null,
8027 writable: true
8028 }), _defineProperty(_Object$create, kLastReject, {
8029 value: null,
8030 writable: true
8031 }), _defineProperty(_Object$create, kError, {
8032 value: null,
8033 writable: true
8034 }), _defineProperty(_Object$create, kEnded, {
8035 value: stream._readableState.endEmitted,
8036 writable: true
8037 }), _defineProperty(_Object$create, kHandlePromise, {
8038 value: function value(resolve, reject) {
8039 var data = iterator[kStream].read();
8040
8041 if (data) {
8042 iterator[kLastPromise] = null;
8043 iterator[kLastResolve] = null;
8044 iterator[kLastReject] = null;
8045 resolve(createIterResult(data, false));
8046 } else {
8047 iterator[kLastResolve] = resolve;
8048 iterator[kLastReject] = reject;
8049 }
8050 },
8051 writable: true
8052 }), _Object$create));
8053 iterator[kLastPromise] = null;
8054 finished(stream, function (err) {
8055 if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
8056 var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise
8057 // returned by next() and store the error
8058
8059 if (reject !== null) {
8060 iterator[kLastPromise] = null;
8061 iterator[kLastResolve] = null;
8062 iterator[kLastReject] = null;
8063 reject(err);
8064 }
8065
8066 iterator[kError] = err;
8067 return;
8068 }
8069
8070 var resolve = iterator[kLastResolve];
8071
8072 if (resolve !== null) {
8073 iterator[kLastPromise] = null;
8074 iterator[kLastResolve] = null;
8075 iterator[kLastReject] = null;
8076 resolve(createIterResult(undefined, true));
8077 }
8078
8079 iterator[kEnded] = true;
8080 });
8081 stream.on('readable', onReadable.bind(null, iterator));
8082 return iterator;
8083};
8084
8085module.exports = createReadableStreamAsyncIterator;
8086}).call(this,_dereq_(68))
8087},{"40":40,"68":68}],38:[function(_dereq_,module,exports){
8088'use strict';
8089
8090function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
8091
8092function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
8093
8094function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
8095
8096function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
8097
8098function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
8099
8100function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
8101
8102var _require = _dereq_(12),
8103 Buffer = _require.Buffer;
8104
8105var _require2 = _dereq_(10),
8106 inspect = _require2.inspect;
8107
8108var custom = inspect && inspect.custom || 'inspect';
8109
8110function copyBuffer(src, target, offset) {
8111 Buffer.prototype.copy.call(src, target, offset);
8112}
8113
8114module.exports =
8115/*#__PURE__*/
8116function () {
8117 function BufferList() {
8118 _classCallCheck(this, BufferList);
8119
8120 this.head = null;
8121 this.tail = null;
8122 this.length = 0;
8123 }
8124
8125 _createClass(BufferList, [{
8126 key: "push",
8127 value: function push(v) {
8128 var entry = {
8129 data: v,
8130 next: null
8131 };
8132 if (this.length > 0) this.tail.next = entry;else this.head = entry;
8133 this.tail = entry;
8134 ++this.length;
8135 }
8136 }, {
8137 key: "unshift",
8138 value: function unshift(v) {
8139 var entry = {
8140 data: v,
8141 next: this.head
8142 };
8143 if (this.length === 0) this.tail = entry;
8144 this.head = entry;
8145 ++this.length;
8146 }
8147 }, {
8148 key: "shift",
8149 value: function shift() {
8150 if (this.length === 0) return;
8151 var ret = this.head.data;
8152 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
8153 --this.length;
8154 return ret;
8155 }
8156 }, {
8157 key: "clear",
8158 value: function clear() {
8159 this.head = this.tail = null;
8160 this.length = 0;
8161 }
8162 }, {
8163 key: "join",
8164 value: function join(s) {
8165 if (this.length === 0) return '';
8166 var p = this.head;
8167 var ret = '' + p.data;
8168
8169 while (p = p.next) {
8170 ret += s + p.data;
8171 }
8172
8173 return ret;
8174 }
8175 }, {
8176 key: "concat",
8177 value: function concat(n) {
8178 if (this.length === 0) return Buffer.alloc(0);
8179 var ret = Buffer.allocUnsafe(n >>> 0);
8180 var p = this.head;
8181 var i = 0;
8182
8183 while (p) {
8184 copyBuffer(p.data, ret, i);
8185 i += p.data.length;
8186 p = p.next;
8187 }
8188
8189 return ret;
8190 } // Consumes a specified amount of bytes or characters from the buffered data.
8191
8192 }, {
8193 key: "consume",
8194 value: function consume(n, hasStrings) {
8195 var ret;
8196
8197 if (n < this.head.data.length) {
8198 // `slice` is the same for buffers and strings.
8199 ret = this.head.data.slice(0, n);
8200 this.head.data = this.head.data.slice(n);
8201 } else if (n === this.head.data.length) {
8202 // First chunk is a perfect match.
8203 ret = this.shift();
8204 } else {
8205 // Result spans more than one buffer.
8206 ret = hasStrings ? this._getString(n) : this._getBuffer(n);
8207 }
8208
8209 return ret;
8210 }
8211 }, {
8212 key: "first",
8213 value: function first() {
8214 return this.head.data;
8215 } // Consumes a specified amount of characters from the buffered data.
8216
8217 }, {
8218 key: "_getString",
8219 value: function _getString(n) {
8220 var p = this.head;
8221 var c = 1;
8222 var ret = p.data;
8223 n -= ret.length;
8224
8225 while (p = p.next) {
8226 var str = p.data;
8227 var nb = n > str.length ? str.length : n;
8228 if (nb === str.length) ret += str;else ret += str.slice(0, n);
8229 n -= nb;
8230
8231 if (n === 0) {
8232 if (nb === str.length) {
8233 ++c;
8234 if (p.next) this.head = p.next;else this.head = this.tail = null;
8235 } else {
8236 this.head = p;
8237 p.data = str.slice(nb);
8238 }
8239
8240 break;
8241 }
8242
8243 ++c;
8244 }
8245
8246 this.length -= c;
8247 return ret;
8248 } // Consumes a specified amount of bytes from the buffered data.
8249
8250 }, {
8251 key: "_getBuffer",
8252 value: function _getBuffer(n) {
8253 var ret = Buffer.allocUnsafe(n);
8254 var p = this.head;
8255 var c = 1;
8256 p.data.copy(ret);
8257 n -= p.data.length;
8258
8259 while (p = p.next) {
8260 var buf = p.data;
8261 var nb = n > buf.length ? buf.length : n;
8262 buf.copy(ret, ret.length - n, 0, nb);
8263 n -= nb;
8264
8265 if (n === 0) {
8266 if (nb === buf.length) {
8267 ++c;
8268 if (p.next) this.head = p.next;else this.head = this.tail = null;
8269 } else {
8270 this.head = p;
8271 p.data = buf.slice(nb);
8272 }
8273
8274 break;
8275 }
8276
8277 ++c;
8278 }
8279
8280 this.length -= c;
8281 return ret;
8282 } // Make sure the linked list only shows the minimal necessary information.
8283
8284 }, {
8285 key: custom,
8286 value: function value(_, options) {
8287 return inspect(this, _objectSpread({}, options, {
8288 // Only inspect one level.
8289 depth: 0,
8290 // It should not recurse.
8291 customInspect: false
8292 }));
8293 }
8294 }]);
8295
8296 return BufferList;
8297}();
8298},{"10":10,"12":12}],39:[function(_dereq_,module,exports){
8299(function (process){
8300'use strict'; // undocumented cb() API, needed for core, not for public API
8301
8302function destroy(err, cb) {
8303 var _this = this;
8304
8305 var readableDestroyed = this._readableState && this._readableState.destroyed;
8306 var writableDestroyed = this._writableState && this._writableState.destroyed;
8307
8308 if (readableDestroyed || writableDestroyed) {
8309 if (cb) {
8310 cb(err);
8311 } else if (err) {
8312 if (!this._writableState) {
8313 process.nextTick(emitErrorNT, this, err);
8314 } else if (!this._writableState.errorEmitted) {
8315 this._writableState.errorEmitted = true;
8316 process.nextTick(emitErrorNT, this, err);
8317 }
8318 }
8319
8320 return this;
8321 } // we set destroyed to true before firing error callbacks in order
8322 // to make it re-entrance safe in case destroy() is called within callbacks
8323
8324
8325 if (this._readableState) {
8326 this._readableState.destroyed = true;
8327 } // if this is a duplex stream mark the writable part as destroyed as well
8328
8329
8330 if (this._writableState) {
8331 this._writableState.destroyed = true;
8332 }
8333
8334 this._destroy(err || null, function (err) {
8335 if (!cb && err) {
8336 if (!_this._writableState) {
8337 process.nextTick(emitErrorAndCloseNT, _this, err);
8338 } else if (!_this._writableState.errorEmitted) {
8339 _this._writableState.errorEmitted = true;
8340 process.nextTick(emitErrorAndCloseNT, _this, err);
8341 } else {
8342 process.nextTick(emitCloseNT, _this);
8343 }
8344 } else if (cb) {
8345 process.nextTick(emitCloseNT, _this);
8346 cb(err);
8347 } else {
8348 process.nextTick(emitCloseNT, _this);
8349 }
8350 });
8351
8352 return this;
8353}
8354
8355function emitErrorAndCloseNT(self, err) {
8356 emitErrorNT(self, err);
8357 emitCloseNT(self);
8358}
8359
8360function emitCloseNT(self) {
8361 if (self._writableState && !self._writableState.emitClose) return;
8362 if (self._readableState && !self._readableState.emitClose) return;
8363 self.emit('close');
8364}
8365
8366function undestroy() {
8367 if (this._readableState) {
8368 this._readableState.destroyed = false;
8369 this._readableState.reading = false;
8370 this._readableState.ended = false;
8371 this._readableState.endEmitted = false;
8372 }
8373
8374 if (this._writableState) {
8375 this._writableState.destroyed = false;
8376 this._writableState.ended = false;
8377 this._writableState.ending = false;
8378 this._writableState.finalCalled = false;
8379 this._writableState.prefinished = false;
8380 this._writableState.finished = false;
8381 this._writableState.errorEmitted = false;
8382 }
8383}
8384
8385function emitErrorNT(self, err) {
8386 self.emit('error', err);
8387}
8388
8389function errorOrDestroy(stream, err) {
8390 // We have tests that rely on errors being emitted
8391 // in the same tick, so changing this is semver major.
8392 // For now when you opt-in to autoDestroy we allow
8393 // the error to be emitted nextTick. In a future
8394 // semver major update we should change the default to this.
8395 var rState = stream._readableState;
8396 var wState = stream._writableState;
8397 if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
8398}
8399
8400module.exports = {
8401 destroy: destroy,
8402 undestroy: undestroy,
8403 errorOrDestroy: errorOrDestroy
8404};
8405}).call(this,_dereq_(68))
8406},{"68":68}],40:[function(_dereq_,module,exports){
8407// Ported from https://github.com/mafintosh/end-of-stream with
8408// permission from the author, Mathias Buus (@mafintosh).
8409'use strict';
8410
8411var ERR_STREAM_PREMATURE_CLOSE = _dereq_(31).codes.ERR_STREAM_PREMATURE_CLOSE;
8412
8413function once(callback) {
8414 var called = false;
8415 return function () {
8416 if (called) return;
8417 called = true;
8418
8419 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
8420 args[_key] = arguments[_key];
8421 }
8422
8423 callback.apply(this, args);
8424 };
8425}
8426
8427function noop() {}
8428
8429function isRequest(stream) {
8430 return stream.setHeader && typeof stream.abort === 'function';
8431}
8432
8433function eos(stream, opts, callback) {
8434 if (typeof opts === 'function') return eos(stream, null, opts);
8435 if (!opts) opts = {};
8436 callback = once(callback || noop);
8437 var readable = opts.readable || opts.readable !== false && stream.readable;
8438 var writable = opts.writable || opts.writable !== false && stream.writable;
8439
8440 var onlegacyfinish = function onlegacyfinish() {
8441 if (!stream.writable) onfinish();
8442 };
8443
8444 var writableEnded = stream._writableState && stream._writableState.finished;
8445
8446 var onfinish = function onfinish() {
8447 writable = false;
8448 writableEnded = true;
8449 if (!readable) callback.call(stream);
8450 };
8451
8452 var readableEnded = stream._readableState && stream._readableState.endEmitted;
8453
8454 var onend = function onend() {
8455 readable = false;
8456 readableEnded = true;
8457 if (!writable) callback.call(stream);
8458 };
8459
8460 var onerror = function onerror(err) {
8461 callback.call(stream, err);
8462 };
8463
8464 var onclose = function onclose() {
8465 var err;
8466
8467 if (readable && !readableEnded) {
8468 if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
8469 return callback.call(stream, err);
8470 }
8471
8472 if (writable && !writableEnded) {
8473 if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
8474 return callback.call(stream, err);
8475 }
8476 };
8477
8478 var onrequest = function onrequest() {
8479 stream.req.on('finish', onfinish);
8480 };
8481
8482 if (isRequest(stream)) {
8483 stream.on('complete', onfinish);
8484 stream.on('abort', onclose);
8485 if (stream.req) onrequest();else stream.on('request', onrequest);
8486 } else if (writable && !stream._writableState) {
8487 // legacy streams
8488 stream.on('end', onlegacyfinish);
8489 stream.on('close', onlegacyfinish);
8490 }
8491
8492 stream.on('end', onend);
8493 stream.on('finish', onfinish);
8494 if (opts.error !== false) stream.on('error', onerror);
8495 stream.on('close', onclose);
8496 return function () {
8497 stream.removeListener('complete', onfinish);
8498 stream.removeListener('abort', onclose);
8499 stream.removeListener('request', onrequest);
8500 if (stream.req) stream.req.removeListener('finish', onfinish);
8501 stream.removeListener('end', onlegacyfinish);
8502 stream.removeListener('close', onlegacyfinish);
8503 stream.removeListener('finish', onfinish);
8504 stream.removeListener('end', onend);
8505 stream.removeListener('error', onerror);
8506 stream.removeListener('close', onclose);
8507 };
8508}
8509
8510module.exports = eos;
8511},{"31":31}],41:[function(_dereq_,module,exports){
8512module.exports = function () {
8513 throw new Error('Readable.from is not available in the browser')
8514};
8515
8516},{}],42:[function(_dereq_,module,exports){
8517// Ported from https://github.com/mafintosh/pump with
8518// permission from the author, Mathias Buus (@mafintosh).
8519'use strict';
8520
8521var eos;
8522
8523function once(callback) {
8524 var called = false;
8525 return function () {
8526 if (called) return;
8527 called = true;
8528 callback.apply(void 0, arguments);
8529 };
8530}
8531
8532var _require$codes = _dereq_(31).codes,
8533 ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
8534 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
8535
8536function noop(err) {
8537 // Rethrow the error if it exists to avoid swallowing it
8538 if (err) throw err;
8539}
8540
8541function isRequest(stream) {
8542 return stream.setHeader && typeof stream.abort === 'function';
8543}
8544
8545function destroyer(stream, reading, writing, callback) {
8546 callback = once(callback);
8547 var closed = false;
8548 stream.on('close', function () {
8549 closed = true;
8550 });
8551 if (eos === undefined) eos = _dereq_(40);
8552 eos(stream, {
8553 readable: reading,
8554 writable: writing
8555 }, function (err) {
8556 if (err) return callback(err);
8557 closed = true;
8558 callback();
8559 });
8560 var destroyed = false;
8561 return function (err) {
8562 if (closed) return;
8563 if (destroyed) return;
8564 destroyed = true; // request.destroy just do .end - .abort is what we want
8565
8566 if (isRequest(stream)) return stream.abort();
8567 if (typeof stream.destroy === 'function') return stream.destroy();
8568 callback(err || new ERR_STREAM_DESTROYED('pipe'));
8569 };
8570}
8571
8572function call(fn) {
8573 fn();
8574}
8575
8576function pipe(from, to) {
8577 return from.pipe(to);
8578}
8579
8580function popCallback(streams) {
8581 if (!streams.length) return noop;
8582 if (typeof streams[streams.length - 1] !== 'function') return noop;
8583 return streams.pop();
8584}
8585
8586function pipeline() {
8587 for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
8588 streams[_key] = arguments[_key];
8589 }
8590
8591 var callback = popCallback(streams);
8592 if (Array.isArray(streams[0])) streams = streams[0];
8593
8594 if (streams.length < 2) {
8595 throw new ERR_MISSING_ARGS('streams');
8596 }
8597
8598 var error;
8599 var destroys = streams.map(function (stream, i) {
8600 var reading = i < streams.length - 1;
8601 var writing = i > 0;
8602 return destroyer(stream, reading, writing, function (err) {
8603 if (!error) error = err;
8604 if (err) destroys.forEach(call);
8605 if (reading) return;
8606 destroys.forEach(call);
8607 callback(error);
8608 });
8609 });
8610 return streams.reduce(pipe);
8611}
8612
8613module.exports = pipeline;
8614},{"31":31,"40":40}],43:[function(_dereq_,module,exports){
8615'use strict';
8616
8617var ERR_INVALID_OPT_VALUE = _dereq_(31).codes.ERR_INVALID_OPT_VALUE;
8618
8619function highWaterMarkFrom(options, isDuplex, duplexKey) {
8620 return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
8621}
8622
8623function getHighWaterMark(state, options, duplexKey, isDuplex) {
8624 var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
8625
8626 if (hwm != null) {
8627 if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
8628 var name = isDuplex ? duplexKey : 'highWaterMark';
8629 throw new ERR_INVALID_OPT_VALUE(name, hwm);
8630 }
8631
8632 return Math.floor(hwm);
8633 } // Default value
8634
8635
8636 return state.objectMode ? 16 : 16 * 1024;
8637}
8638
8639module.exports = {
8640 getHighWaterMark: getHighWaterMark
8641};
8642},{"31":31}],44:[function(_dereq_,module,exports){
8643module.exports = _dereq_(18).EventEmitter;
8644
8645},{"18":18}],45:[function(_dereq_,module,exports){
8646exports = module.exports = _dereq_(34);
8647exports.Stream = exports;
8648exports.Readable = exports;
8649exports.Writable = _dereq_(36);
8650exports.Duplex = _dereq_(32);
8651exports.Transform = _dereq_(35);
8652exports.PassThrough = _dereq_(33);
8653exports.finished = _dereq_(40);
8654exports.pipeline = _dereq_(42);
8655
8656},{"32":32,"33":33,"34":34,"35":35,"36":36,"40":40,"42":42}],46:[function(_dereq_,module,exports){
8657module.exports = extend
8658
8659var hasOwnProperty = Object.prototype.hasOwnProperty;
8660
8661function extend() {
8662 var target = {}
8663
8664 for (var i = 0; i < arguments.length; i++) {
8665 var source = arguments[i]
8666
8667 for (var key in source) {
8668 if (hasOwnProperty.call(source, key)) {
8669 target[key] = source[key]
8670 }
8671 }
8672 }
8673
8674 return target
8675}
8676
8677},{}],47:[function(_dereq_,module,exports){
8678var WriteError = _dereq_(29).WriteError
8679var promisify = _dereq_(50)
8680var getCallback = _dereq_(48).getCallback
8681var getOptions = _dereq_(48).getOptions
8682
8683function Batch (levelup) {
8684 this._levelup = levelup
8685 this.batch = levelup.db.batch()
8686 this.ops = []
8687 this.length = 0
8688}
8689
8690Batch.prototype.put = function (key, value) {
8691 try {
8692 this.batch.put(key, value)
8693 } catch (e) {
8694 throw new WriteError(e)
8695 }
8696
8697 this.ops.push({ type: 'put', key: key, value: value })
8698 this.length++
8699
8700 return this
8701}
8702
8703Batch.prototype.del = function (key) {
8704 try {
8705 this.batch.del(key)
8706 } catch (err) {
8707 throw new WriteError(err)
8708 }
8709
8710 this.ops.push({ type: 'del', key: key })
8711 this.length++
8712
8713 return this
8714}
8715
8716Batch.prototype.clear = function () {
8717 try {
8718 this.batch.clear()
8719 } catch (err) {
8720 throw new WriteError(err)
8721 }
8722
8723 this.ops = []
8724 this.length = 0
8725
8726 return this
8727}
8728
8729Batch.prototype.write = function (options, callback) {
8730 var levelup = this._levelup
8731 var ops = this.ops
8732 var promise
8733
8734 callback = getCallback(options, callback)
8735
8736 if (!callback) {
8737 callback = promisify()
8738 promise = callback.promise
8739 }
8740
8741 options = getOptions(options)
8742
8743 try {
8744 this.batch.write(options, function (err) {
8745 if (err) { return callback(new WriteError(err)) }
8746 levelup.emit('batch', ops)
8747 callback()
8748 })
8749 } catch (err) {
8750 throw new WriteError(err)
8751 }
8752
8753 return promise
8754}
8755
8756module.exports = Batch
8757
8758},{"29":29,"48":48,"50":50}],48:[function(_dereq_,module,exports){
8759exports.getCallback = function (options, callback) {
8760 return typeof options === 'function' ? options : callback
8761}
8762
8763exports.getOptions = function (options) {
8764 return typeof options === 'object' && options !== null ? options : {}
8765}
8766
8767},{}],49:[function(_dereq_,module,exports){
8768(function (process){
8769var EventEmitter = _dereq_(18).EventEmitter
8770var inherits = _dereq_(118).inherits
8771var extend = _dereq_(57)
8772var DeferredLevelDOWN = _dereq_(56)
8773var IteratorStream = _dereq_(30)
8774var Batch = _dereq_(47)
8775var errors = _dereq_(29)
8776var assert = _dereq_(5)
8777var promisify = _dereq_(50)
8778var getCallback = _dereq_(48).getCallback
8779var getOptions = _dereq_(48).getOptions
8780
8781var WriteError = errors.WriteError
8782var ReadError = errors.ReadError
8783var NotFoundError = errors.NotFoundError
8784var OpenError = errors.OpenError
8785var InitializationError = errors.InitializationError
8786
8787// Possible AbstractLevelDOWN#status values:
8788// - 'new' - newly created, not opened or closed
8789// - 'opening' - waiting for the database to be opened, post open()
8790// - 'open' - successfully opened the database, available for use
8791// - 'closing' - waiting for the database to be closed, post close()
8792// - 'closed' - database has been successfully closed, should not be
8793// used except for another open() operation
8794
8795function LevelUP (db, options, callback) {
8796 if (!(this instanceof LevelUP)) {
8797 return new LevelUP(db, options, callback)
8798 }
8799
8800 var error
8801
8802 EventEmitter.call(this)
8803 this.setMaxListeners(Infinity)
8804
8805 if (typeof options === 'function') {
8806 callback = options
8807 options = {}
8808 }
8809
8810 options = options || {}
8811
8812 if (!db || typeof db !== 'object') {
8813 error = new InitializationError('First argument must be an abstract-leveldown compliant store')
8814 if (typeof callback === 'function') {
8815 return process.nextTick(callback, error)
8816 }
8817 throw error
8818 }
8819
8820 assert.strictEqual(typeof db.status, 'string', '.status required, old abstract-leveldown')
8821
8822 this.options = getOptions(options)
8823 this._db = db
8824 this.db = new DeferredLevelDOWN(db)
8825 this.open(callback)
8826}
8827
8828LevelUP.prototype.emit = EventEmitter.prototype.emit
8829LevelUP.prototype.once = EventEmitter.prototype.once
8830inherits(LevelUP, EventEmitter)
8831
8832LevelUP.prototype.open = function (opts, callback) {
8833 var self = this
8834 var promise
8835
8836 if (typeof opts === 'function') {
8837 callback = opts
8838 opts = null
8839 }
8840
8841 if (!callback) {
8842 callback = promisify()
8843 promise = callback.promise
8844 }
8845
8846 if (!opts) {
8847 opts = this.options
8848 }
8849
8850 if (this.isOpen()) {
8851 process.nextTick(callback, null, self)
8852 return promise
8853 }
8854
8855 if (this._isOpening()) {
8856 this.once('open', function () { callback(null, self) })
8857 return promise
8858 }
8859
8860 this.emit('opening')
8861
8862 this.db.open(opts, function (err) {
8863 if (err) {
8864 return callback(new OpenError(err))
8865 }
8866 self.db = self._db
8867 callback(null, self)
8868 self.emit('open')
8869 self.emit('ready')
8870 })
8871
8872 return promise
8873}
8874
8875LevelUP.prototype.close = function (callback) {
8876 var self = this
8877 var promise
8878
8879 if (!callback) {
8880 callback = promisify()
8881 promise = callback.promise
8882 }
8883
8884 if (this.isOpen()) {
8885 this.db.close(function () {
8886 self.emit('closed')
8887 callback.apply(null, arguments)
8888 })
8889 this.emit('closing')
8890 this.db = new DeferredLevelDOWN(this._db)
8891 } else if (this.isClosed()) {
8892 process.nextTick(callback)
8893 } else if (this.db.status === 'closing') {
8894 this.once('closed', callback)
8895 } else if (this._isOpening()) {
8896 this.once('open', function () {
8897 self.close(callback)
8898 })
8899 }
8900
8901 return promise
8902}
8903
8904LevelUP.prototype.isOpen = function () {
8905 return this.db.status === 'open'
8906}
8907
8908LevelUP.prototype._isOpening = function () {
8909 return this.db.status === 'opening'
8910}
8911
8912LevelUP.prototype.isClosed = function () {
8913 return (/^clos|new/).test(this.db.status)
8914}
8915
8916LevelUP.prototype.get = function (key, options, callback) {
8917 if (key === null || key === undefined) {
8918 throw new ReadError('get() requires a key argument')
8919 }
8920
8921 var promise
8922
8923 callback = getCallback(options, callback)
8924
8925 if (!callback) {
8926 callback = promisify()
8927 promise = callback.promise
8928 }
8929
8930 if (maybeError(this, callback)) { return promise }
8931
8932 options = getOptions(options)
8933
8934 this.db.get(key, options, function (err, value) {
8935 if (err) {
8936 if ((/notfound/i).test(err) || err.notFound) {
8937 err = new NotFoundError('Key not found in database [' + key + ']', err)
8938 } else {
8939 err = new ReadError(err)
8940 }
8941 return callback(err)
8942 }
8943 callback(null, value)
8944 })
8945
8946 return promise
8947}
8948
8949LevelUP.prototype.put = function (key, value, options, callback) {
8950 if (key === null || key === undefined) {
8951 throw new WriteError('put() requires a key argument')
8952 }
8953
8954 var self = this
8955 var promise
8956
8957 callback = getCallback(options, callback)
8958
8959 if (!callback) {
8960 callback = promisify()
8961 promise = callback.promise
8962 }
8963
8964 if (maybeError(this, callback)) { return promise }
8965
8966 options = getOptions(options)
8967
8968 this.db.put(key, value, options, function (err) {
8969 if (err) {
8970 return callback(new WriteError(err))
8971 }
8972 self.emit('put', key, value)
8973 callback()
8974 })
8975
8976 return promise
8977}
8978
8979LevelUP.prototype.del = function (key, options, callback) {
8980 if (key === null || key === undefined) {
8981 throw new WriteError('del() requires a key argument')
8982 }
8983
8984 var self = this
8985 var promise
8986
8987 callback = getCallback(options, callback)
8988
8989 if (!callback) {
8990 callback = promisify()
8991 promise = callback.promise
8992 }
8993
8994 if (maybeError(this, callback)) { return promise }
8995
8996 options = getOptions(options)
8997
8998 this.db.del(key, options, function (err) {
8999 if (err) {
9000 return callback(new WriteError(err))
9001 }
9002 self.emit('del', key)
9003 callback()
9004 })
9005
9006 return promise
9007}
9008
9009LevelUP.prototype.batch = function (arr, options, callback) {
9010 if (!arguments.length) {
9011 return new Batch(this)
9012 }
9013
9014 if (!Array.isArray(arr)) {
9015 throw new WriteError('batch() requires an array argument')
9016 }
9017
9018 var self = this
9019 var promise
9020
9021 callback = getCallback(options, callback)
9022
9023 if (!callback) {
9024 callback = promisify()
9025 promise = callback.promise
9026 }
9027
9028 if (maybeError(this, callback)) { return promise }
9029
9030 options = getOptions(options)
9031
9032 this.db.batch(arr, options, function (err) {
9033 if (err) {
9034 return callback(new WriteError(err))
9035 }
9036 self.emit('batch', arr)
9037 callback()
9038 })
9039
9040 return promise
9041}
9042
9043LevelUP.prototype.iterator = function (options) {
9044 return this.db.iterator(options)
9045}
9046
9047LevelUP.prototype.readStream =
9048LevelUP.prototype.createReadStream = function (options) {
9049 options = extend({ keys: true, values: true }, options)
9050 if (typeof options.limit !== 'number') { options.limit = -1 }
9051 return new IteratorStream(this.db.iterator(options), options)
9052}
9053
9054LevelUP.prototype.keyStream =
9055LevelUP.prototype.createKeyStream = function (options) {
9056 return this.createReadStream(extend(options, { keys: true, values: false }))
9057}
9058
9059LevelUP.prototype.valueStream =
9060LevelUP.prototype.createValueStream = function (options) {
9061 return this.createReadStream(extend(options, { keys: false, values: true }))
9062}
9063
9064LevelUP.prototype.toString = function () {
9065 return 'LevelUP'
9066}
9067
9068function maybeError (db, callback) {
9069 if (!db._isOpening() && !db.isOpen()) {
9070 process.nextTick(callback, new ReadError('Database is not open'))
9071 return true
9072 }
9073}
9074
9075LevelUP.errors = errors
9076module.exports = LevelUP.default = LevelUP
9077
9078}).call(this,_dereq_(68))
9079},{"118":118,"18":18,"29":29,"30":30,"47":47,"48":48,"5":5,"50":50,"56":56,"57":57,"68":68}],50:[function(_dereq_,module,exports){
9080function promisify () {
9081 var callback
9082 var promise = new Promise(function (resolve, reject) {
9083 callback = function callback (err, value) {
9084 if (err) reject(err)
9085 else resolve(value)
9086 }
9087 })
9088 callback.promise = promise
9089 return callback
9090}
9091
9092module.exports = promisify
9093
9094},{}],51:[function(_dereq_,module,exports){
9095function AbstractChainedBatch (db) {
9096 if (typeof db !== 'object' || db === null) {
9097 throw new TypeError('First argument must be an abstract-leveldown compliant store')
9098 }
9099
9100 this.db = db
9101 this._operations = []
9102 this._written = false
9103}
9104
9105AbstractChainedBatch.prototype._checkWritten = function () {
9106 if (this._written) {
9107 throw new Error('write() already called on this batch')
9108 }
9109}
9110
9111AbstractChainedBatch.prototype.put = function (key, value) {
9112 this._checkWritten()
9113
9114 var err = this.db._checkKey(key) || this.db._checkValue(value)
9115 if (err) throw err
9116
9117 key = this.db._serializeKey(key)
9118 value = this.db._serializeValue(value)
9119
9120 this._put(key, value)
9121
9122 return this
9123}
9124
9125AbstractChainedBatch.prototype._put = function (key, value) {
9126 this._operations.push({ type: 'put', key: key, value: value })
9127}
9128
9129AbstractChainedBatch.prototype.del = function (key) {
9130 this._checkWritten()
9131
9132 var err = this.db._checkKey(key)
9133 if (err) throw err
9134
9135 key = this.db._serializeKey(key)
9136 this._del(key)
9137
9138 return this
9139}
9140
9141AbstractChainedBatch.prototype._del = function (key) {
9142 this._operations.push({ type: 'del', key: key })
9143}
9144
9145AbstractChainedBatch.prototype.clear = function () {
9146 this._checkWritten()
9147 this._clear()
9148
9149 return this
9150}
9151
9152AbstractChainedBatch.prototype._clear = function () {
9153 this._operations = []
9154}
9155
9156AbstractChainedBatch.prototype.write = function (options, callback) {
9157 this._checkWritten()
9158
9159 if (typeof options === 'function') { callback = options }
9160 if (typeof callback !== 'function') {
9161 throw new Error('write() requires a callback argument')
9162 }
9163 if (typeof options !== 'object' || options === null) {
9164 options = {}
9165 }
9166
9167 this._written = true
9168 this._write(options, callback)
9169}
9170
9171AbstractChainedBatch.prototype._write = function (options, callback) {
9172 this.db._batch(this._operations, options, callback)
9173}
9174
9175module.exports = AbstractChainedBatch
9176
9177},{}],52:[function(_dereq_,module,exports){
9178(function (process){
9179function AbstractIterator (db) {
9180 if (typeof db !== 'object' || db === null) {
9181 throw new TypeError('First argument must be an abstract-leveldown compliant store')
9182 }
9183
9184 this.db = db
9185 this._ended = false
9186 this._nexting = false
9187}
9188
9189AbstractIterator.prototype.next = function (callback) {
9190 var self = this
9191
9192 if (typeof callback !== 'function') {
9193 throw new Error('next() requires a callback argument')
9194 }
9195
9196 if (self._ended) {
9197 process.nextTick(callback, new Error('cannot call next() after end()'))
9198 return self
9199 }
9200
9201 if (self._nexting) {
9202 process.nextTick(callback, new Error('cannot call next() before previous next() has completed'))
9203 return self
9204 }
9205
9206 self._nexting = true
9207 self._next(function () {
9208 self._nexting = false
9209 callback.apply(null, arguments)
9210 })
9211
9212 return self
9213}
9214
9215AbstractIterator.prototype._next = function (callback) {
9216 process.nextTick(callback)
9217}
9218
9219AbstractIterator.prototype.seek = function (target) {
9220 if (this._ended) {
9221 throw new Error('cannot call seek() after end()')
9222 }
9223 if (this._nexting) {
9224 throw new Error('cannot call seek() before next() has completed')
9225 }
9226
9227 target = this.db._serializeKey(target)
9228 this._seek(target)
9229}
9230
9231AbstractIterator.prototype._seek = function (target) {}
9232
9233AbstractIterator.prototype.end = function (callback) {
9234 if (typeof callback !== 'function') {
9235 throw new Error('end() requires a callback argument')
9236 }
9237
9238 if (this._ended) {
9239 return process.nextTick(callback, new Error('end() already called on iterator'))
9240 }
9241
9242 this._ended = true
9243 this._end(callback)
9244}
9245
9246AbstractIterator.prototype._end = function (callback) {
9247 process.nextTick(callback)
9248}
9249
9250module.exports = AbstractIterator
9251
9252}).call(this,_dereq_(68))
9253},{"68":68}],53:[function(_dereq_,module,exports){
9254(function (Buffer,process){
9255var xtend = _dereq_(57)
9256var AbstractIterator = _dereq_(52)
9257var AbstractChainedBatch = _dereq_(51)
9258var hasOwnProperty = Object.prototype.hasOwnProperty
9259var rangeOptions = 'start end gt gte lt lte'.split(' ')
9260
9261function AbstractLevelDOWN () {
9262 this.status = 'new'
9263}
9264
9265AbstractLevelDOWN.prototype.open = function (options, callback) {
9266 var self = this
9267 var oldStatus = this.status
9268
9269 if (typeof options === 'function') callback = options
9270
9271 if (typeof callback !== 'function') {
9272 throw new Error('open() requires a callback argument')
9273 }
9274
9275 if (typeof options !== 'object' || options === null) options = {}
9276
9277 options.createIfMissing = options.createIfMissing !== false
9278 options.errorIfExists = !!options.errorIfExists
9279
9280 this.status = 'opening'
9281 this._open(options, function (err) {
9282 if (err) {
9283 self.status = oldStatus
9284 return callback(err)
9285 }
9286 self.status = 'open'
9287 callback()
9288 })
9289}
9290
9291AbstractLevelDOWN.prototype._open = function (options, callback) {
9292 process.nextTick(callback)
9293}
9294
9295AbstractLevelDOWN.prototype.close = function (callback) {
9296 var self = this
9297 var oldStatus = this.status
9298
9299 if (typeof callback !== 'function') {
9300 throw new Error('close() requires a callback argument')
9301 }
9302
9303 this.status = 'closing'
9304 this._close(function (err) {
9305 if (err) {
9306 self.status = oldStatus
9307 return callback(err)
9308 }
9309 self.status = 'closed'
9310 callback()
9311 })
9312}
9313
9314AbstractLevelDOWN.prototype._close = function (callback) {
9315 process.nextTick(callback)
9316}
9317
9318AbstractLevelDOWN.prototype.get = function (key, options, callback) {
9319 if (typeof options === 'function') callback = options
9320
9321 if (typeof callback !== 'function') {
9322 throw new Error('get() requires a callback argument')
9323 }
9324
9325 var err = this._checkKey(key)
9326 if (err) return process.nextTick(callback, err)
9327
9328 key = this._serializeKey(key)
9329
9330 if (typeof options !== 'object' || options === null) options = {}
9331
9332 options.asBuffer = options.asBuffer !== false
9333
9334 this._get(key, options, callback)
9335}
9336
9337AbstractLevelDOWN.prototype._get = function (key, options, callback) {
9338 process.nextTick(function () { callback(new Error('NotFound')) })
9339}
9340
9341AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
9342 if (typeof options === 'function') callback = options
9343
9344 if (typeof callback !== 'function') {
9345 throw new Error('put() requires a callback argument')
9346 }
9347
9348 var err = this._checkKey(key) || this._checkValue(value)
9349 if (err) return process.nextTick(callback, err)
9350
9351 key = this._serializeKey(key)
9352 value = this._serializeValue(value)
9353
9354 if (typeof options !== 'object' || options === null) options = {}
9355
9356 this._put(key, value, options, callback)
9357}
9358
9359AbstractLevelDOWN.prototype._put = function (key, value, options, callback) {
9360 process.nextTick(callback)
9361}
9362
9363AbstractLevelDOWN.prototype.del = function (key, options, callback) {
9364 if (typeof options === 'function') callback = options
9365
9366 if (typeof callback !== 'function') {
9367 throw new Error('del() requires a callback argument')
9368 }
9369
9370 var err = this._checkKey(key)
9371 if (err) return process.nextTick(callback, err)
9372
9373 key = this._serializeKey(key)
9374
9375 if (typeof options !== 'object' || options === null) options = {}
9376
9377 this._del(key, options, callback)
9378}
9379
9380AbstractLevelDOWN.prototype._del = function (key, options, callback) {
9381 process.nextTick(callback)
9382}
9383
9384AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
9385 if (!arguments.length) return this._chainedBatch()
9386
9387 if (typeof options === 'function') callback = options
9388
9389 if (typeof array === 'function') callback = array
9390
9391 if (typeof callback !== 'function') {
9392 throw new Error('batch(array) requires a callback argument')
9393 }
9394
9395 if (!Array.isArray(array)) {
9396 return process.nextTick(callback, new Error('batch(array) requires an array argument'))
9397 }
9398
9399 if (array.length === 0) {
9400 return process.nextTick(callback)
9401 }
9402
9403 if (typeof options !== 'object' || options === null) options = {}
9404
9405 var serialized = new Array(array.length)
9406
9407 for (var i = 0; i < array.length; i++) {
9408 if (typeof array[i] !== 'object' || array[i] === null) {
9409 return process.nextTick(callback, new Error('batch(array) element must be an object and not `null`'))
9410 }
9411
9412 var e = xtend(array[i])
9413
9414 if (e.type !== 'put' && e.type !== 'del') {
9415 return process.nextTick(callback, new Error("`type` must be 'put' or 'del'"))
9416 }
9417
9418 var err = this._checkKey(e.key)
9419 if (err) return process.nextTick(callback, err)
9420
9421 e.key = this._serializeKey(e.key)
9422
9423 if (e.type === 'put') {
9424 var valueErr = this._checkValue(e.value)
9425 if (valueErr) return process.nextTick(callback, valueErr)
9426
9427 e.value = this._serializeValue(e.value)
9428 }
9429
9430 serialized[i] = e
9431 }
9432
9433 this._batch(serialized, options, callback)
9434}
9435
9436AbstractLevelDOWN.prototype._batch = function (array, options, callback) {
9437 process.nextTick(callback)
9438}
9439
9440AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
9441 options = cleanRangeOptions(this, options)
9442
9443 options.reverse = !!options.reverse
9444 options.keys = options.keys !== false
9445 options.values = options.values !== false
9446 options.limit = 'limit' in options ? options.limit : -1
9447 options.keyAsBuffer = options.keyAsBuffer !== false
9448 options.valueAsBuffer = options.valueAsBuffer !== false
9449
9450 return options
9451}
9452
9453function cleanRangeOptions (db, options) {
9454 var result = {}
9455
9456 for (var k in options) {
9457 if (!hasOwnProperty.call(options, k)) continue
9458
9459 var opt = options[k]
9460
9461 if (isRangeOption(k)) {
9462 // Note that we don't reject nullish and empty options here. While
9463 // those types are invalid as keys, they are valid as range options.
9464 opt = db._serializeKey(opt)
9465 }
9466
9467 result[k] = opt
9468 }
9469
9470 return result
9471}
9472
9473function isRangeOption (k) {
9474 return rangeOptions.indexOf(k) !== -1
9475}
9476
9477AbstractLevelDOWN.prototype.iterator = function (options) {
9478 if (typeof options !== 'object' || options === null) options = {}
9479 options = this._setupIteratorOptions(options)
9480 return this._iterator(options)
9481}
9482
9483AbstractLevelDOWN.prototype._iterator = function (options) {
9484 return new AbstractIterator(this)
9485}
9486
9487AbstractLevelDOWN.prototype._chainedBatch = function () {
9488 return new AbstractChainedBatch(this)
9489}
9490
9491AbstractLevelDOWN.prototype._serializeKey = function (key) {
9492 return key
9493}
9494
9495AbstractLevelDOWN.prototype._serializeValue = function (value) {
9496 return value
9497}
9498
9499AbstractLevelDOWN.prototype._checkKey = function (key) {
9500 if (key === null || key === undefined) {
9501 return new Error('key cannot be `null` or `undefined`')
9502 } else if (Buffer.isBuffer(key) && key.length === 0) {
9503 return new Error('key cannot be an empty Buffer')
9504 } else if (key === '') {
9505 return new Error('key cannot be an empty String')
9506 } else if (Array.isArray(key) && key.length === 0) {
9507 return new Error('key cannot be an empty Array')
9508 }
9509}
9510
9511AbstractLevelDOWN.prototype._checkValue = function (value) {
9512 if (value === null || value === undefined) {
9513 return new Error('value cannot be `null` or `undefined`')
9514 }
9515}
9516
9517module.exports = AbstractLevelDOWN
9518
9519}).call(this,{"isBuffer":_dereq_(25)},_dereq_(68))
9520},{"25":25,"51":51,"52":52,"57":57,"68":68}],54:[function(_dereq_,module,exports){
9521exports.AbstractLevelDOWN = _dereq_(53)
9522exports.AbstractIterator = _dereq_(52)
9523exports.AbstractChainedBatch = _dereq_(51)
9524
9525},{"51":51,"52":52,"53":53}],55:[function(_dereq_,module,exports){
9526var AbstractIterator = _dereq_(54).AbstractIterator
9527var inherits = _dereq_(24)
9528
9529function DeferredIterator (options) {
9530 AbstractIterator.call(this, options)
9531
9532 this._options = options
9533 this._iterator = null
9534 this._operations = []
9535}
9536
9537inherits(DeferredIterator, AbstractIterator)
9538
9539DeferredIterator.prototype.setDb = function (db) {
9540 var it = this._iterator = db.iterator(this._options)
9541 this._operations.forEach(function (op) {
9542 it[op.method].apply(it, op.args)
9543 })
9544}
9545
9546DeferredIterator.prototype._operation = function (method, args) {
9547 if (this._iterator) return this._iterator[method].apply(this._iterator, args)
9548 this._operations.push({ method: method, args: args })
9549}
9550
9551'next end'.split(' ').forEach(function (m) {
9552 DeferredIterator.prototype['_' + m] = function () {
9553 this._operation(m, arguments)
9554 }
9555})
9556
9557// Must defer seek() rather than _seek() because it requires db._serializeKey to be available
9558DeferredIterator.prototype.seek = function () {
9559 this._operation('seek', arguments)
9560}
9561
9562module.exports = DeferredIterator
9563
9564},{"24":24,"54":54}],56:[function(_dereq_,module,exports){
9565var AbstractLevelDOWN = _dereq_(54).AbstractLevelDOWN
9566var inherits = _dereq_(24)
9567var DeferredIterator = _dereq_(55)
9568var deferrables = 'put get del batch'.split(' ')
9569
9570function DeferredLevelDOWN (db) {
9571 AbstractLevelDOWN.call(this, '')
9572 this._db = db
9573 this._operations = []
9574 this._iterators = []
9575 closed(this)
9576}
9577
9578inherits(DeferredLevelDOWN, AbstractLevelDOWN)
9579
9580DeferredLevelDOWN.prototype._open = function (options, callback) {
9581 var self = this
9582
9583 this._db.open(options, function (err) {
9584 if (err) return callback(err)
9585
9586 self._operations.forEach(function (op) {
9587 self._db[op.method].apply(self._db, op.args)
9588 })
9589 self._operations = []
9590 self._iterators.forEach(function (it) {
9591 it.setDb(self._db)
9592 })
9593 self._iterators = []
9594 open(self)
9595 callback()
9596 })
9597}
9598
9599DeferredLevelDOWN.prototype._close = function (callback) {
9600 var self = this
9601
9602 this._db.close(function (err) {
9603 if (err) return callback(err)
9604 closed(self)
9605 callback()
9606 })
9607}
9608
9609function open (self) {
9610 deferrables.concat('iterator').forEach(function (m) {
9611 self['_' + m] = function () {
9612 return this._db[m].apply(this._db, arguments)
9613 }
9614 })
9615 if (self._db.approximateSize) {
9616 self.approximateSize = function () {
9617 return this._db.approximateSize.apply(this._db, arguments)
9618 }
9619 }
9620}
9621
9622function closed (self) {
9623 deferrables.forEach(function (m) {
9624 self['_' + m] = function () {
9625 this._operations.push({ method: m, args: arguments })
9626 }
9627 })
9628 if (typeof self._db.approximateSize === 'function') {
9629 self.approximateSize = function () {
9630 this._operations.push({
9631 method: 'approximateSize',
9632 args: arguments
9633 })
9634 }
9635 }
9636 self._iterator = function (options) {
9637 var it = new DeferredIterator(options)
9638 this._iterators.push(it)
9639 return it
9640 }
9641}
9642
9643DeferredLevelDOWN.prototype._serializeKey = function (key) {
9644 return key
9645}
9646
9647DeferredLevelDOWN.prototype._serializeValue = function (value) {
9648 return value
9649}
9650
9651module.exports = DeferredLevelDOWN
9652module.exports.DeferredIterator = DeferredIterator
9653
9654},{"24":24,"54":54,"55":55}],57:[function(_dereq_,module,exports){
9655arguments[4][46][0].apply(exports,arguments)
9656},{"46":46}],58:[function(_dereq_,module,exports){
9657(function (Buffer,process,global){
9658'use strict';
9659
9660var inherits = _dereq_(24);
9661var bufferFrom = _dereq_(63);
9662var AbstractLevelDOWN = _dereq_(3).AbstractLevelDOWN;
9663var AbstractIterator = _dereq_(3).AbstractIterator;
9664
9665var LocalStorage = _dereq_(60).LocalStorage;
9666var LocalStorageCore = _dereq_(59);
9667var utils = _dereq_(62);
9668
9669// see http://stackoverflow.com/a/15349865/680742
9670var nextTick = global.setImmediate || process.nextTick;
9671
9672function LDIterator(db, options) {
9673
9674 AbstractIterator.call(this, db);
9675
9676 this._reverse = !!options.reverse;
9677 this._endkey = options.end;
9678 this._startkey = options.start;
9679 this._gt = options.gt;
9680 this._gte = options.gte;
9681 this._lt = options.lt;
9682 this._lte = options.lte;
9683 this._exclusiveStart = options.exclusiveStart;
9684 this._keysOnly = options.values === false;
9685 this._limit = options.limit;
9686 this._count = 0;
9687
9688 this.onInitCompleteListeners = [];
9689}
9690
9691inherits(LDIterator, AbstractIterator);
9692
9693LDIterator.prototype._init = function (callback) {
9694 nextTick(function () {
9695 callback();
9696 });
9697};
9698
9699LDIterator.prototype._next = function (callback) {
9700 var self = this;
9701
9702 function onInitComplete() {
9703 if (self._pos === self._keys.length || self._pos < 0) { // done reading
9704 return callback();
9705 }
9706
9707 var key = self._keys[self._pos];
9708
9709 if (!!self._endkey && (self._reverse ? key < self._endkey : key > self._endkey)) {
9710 return callback();
9711 }
9712
9713 if (!!self._limit && self._limit > 0 && self._count++ >= self._limit) {
9714 return callback();
9715 }
9716
9717 if ((self._lt && key >= self._lt) ||
9718 (self._lte && key > self._lte) ||
9719 (self._gt && key <= self._gt) ||
9720 (self._gte && key < self._gte)) {
9721 return callback();
9722 }
9723
9724 self._pos += self._reverse ? -1 : 1;
9725 if (self._keysOnly) {
9726 return callback(null, key);
9727 }
9728
9729 self.db.container.getItem(key, function (err, value) {
9730 if (err) {
9731 if (err.message === 'NotFound') {
9732 return nextTick(function () {
9733 self._next(callback);
9734 });
9735 }
9736 return callback(err);
9737 }
9738 callback(null, key, value);
9739 });
9740 }
9741 if (!self.initStarted) {
9742 process.nextTick(function () {
9743 self.initStarted = true;
9744 self._init(function (err) {
9745 if (err) {
9746 return callback(err);
9747 }
9748 self.db.container.keys(function (err, keys) {
9749 if (err) {
9750 return callback(err);
9751 }
9752 self._keys = keys;
9753 if (self._startkey) {
9754 var index = utils.sortedIndexOf(self._keys, self._startkey);
9755 var startkey = (index >= self._keys.length || index < 0) ?
9756 undefined : self._keys[index];
9757 self._pos = index;
9758 if (self._reverse) {
9759 if (self._exclusiveStart || startkey !== self._startkey) {
9760 self._pos--;
9761 }
9762 } else if (self._exclusiveStart && startkey === self._startkey) {
9763 self._pos++;
9764 }
9765 } else {
9766 self._pos = self._reverse ? self._keys.length - 1 : 0;
9767 }
9768 onInitComplete();
9769
9770 self.initCompleted = true;
9771 var i = -1;
9772 while (++i < self.onInitCompleteListeners.length) {
9773 nextTick(self.onInitCompleteListeners[i]);
9774 }
9775 });
9776 });
9777 });
9778 } else if (!self.initCompleted) {
9779 self.onInitCompleteListeners.push(onInitComplete);
9780 } else {
9781 process.nextTick(onInitComplete);
9782 }
9783};
9784
9785function LD(location) {
9786 if (!(this instanceof LD)) {
9787 return new LD(location);
9788 }
9789 AbstractLevelDOWN.call(this, location);
9790 this.container = new LocalStorage(location);
9791}
9792
9793inherits(LD, AbstractLevelDOWN);
9794
9795LD.prototype._open = function (options, callback) {
9796 this.container.init(callback);
9797};
9798
9799LD.prototype._put = function (key, value, options, callback) {
9800
9801 var err = checkKeyValue(key, 'key');
9802
9803 if (err) {
9804 return nextTick(function () {
9805 callback(err);
9806 });
9807 }
9808
9809 err = checkKeyValue(value, 'value');
9810
9811 if (err) {
9812 return nextTick(function () {
9813 callback(err);
9814 });
9815 }
9816
9817 if (typeof value === 'object' && !Buffer.isBuffer(value) && value.buffer === undefined) {
9818 var obj = {};
9819 obj.storetype = "json";
9820 obj.data = value;
9821 value = JSON.stringify(obj);
9822 }
9823
9824 this.container.setItem(key, value, callback);
9825};
9826
9827LD.prototype._get = function (key, options, callback) {
9828
9829 var err = checkKeyValue(key, 'key');
9830
9831 if (err) {
9832 return nextTick(function () {
9833 callback(err);
9834 });
9835 }
9836
9837 if (!Buffer.isBuffer(key)) {
9838 key = String(key);
9839 }
9840 this.container.getItem(key, function (err, value) {
9841
9842 if (err) {
9843 return callback(err);
9844 }
9845
9846 if (options.asBuffer !== false && !Buffer.isBuffer(value)) {
9847 value = bufferFrom(value);
9848 }
9849
9850
9851 if (options.asBuffer === false) {
9852 if (value.indexOf("{\"storetype\":\"json\",\"data\"") > -1) {
9853 var res = JSON.parse(value);
9854 value = res.data;
9855 }
9856 }
9857 callback(null, value);
9858 });
9859};
9860
9861LD.prototype._del = function (key, options, callback) {
9862
9863 var err = checkKeyValue(key, 'key');
9864
9865 if (err) {
9866 return nextTick(function () {
9867 callback(err);
9868 });
9869 }
9870 if (!Buffer.isBuffer(key)) {
9871 key = String(key);
9872 }
9873
9874 this.container.removeItem(key, callback);
9875};
9876
9877LD.prototype._batch = function (array, options, callback) {
9878 var self = this;
9879 nextTick(function () {
9880 var err;
9881 var key;
9882 var value;
9883
9884 var numDone = 0;
9885 var overallErr;
9886 function checkDone() {
9887 if (++numDone === array.length) {
9888 callback(overallErr);
9889 }
9890 }
9891
9892 if (Array.isArray(array) && array.length) {
9893 for (var i = 0; i < array.length; i++) {
9894 var task = array[i];
9895 if (task) {
9896 key = Buffer.isBuffer(task.key) ? task.key : String(task.key);
9897 err = checkKeyValue(key, 'key');
9898 if (err) {
9899 overallErr = err;
9900 checkDone();
9901 } else if (task.type === 'del') {
9902 self._del(task.key, options, checkDone);
9903 } else if (task.type === 'put') {
9904 value = Buffer.isBuffer(task.value) ? task.value : String(task.value);
9905 err = checkKeyValue(value, 'value');
9906 if (err) {
9907 overallErr = err;
9908 checkDone();
9909 } else {
9910 self._put(key, value, options, checkDone);
9911 }
9912 }
9913 } else {
9914 checkDone();
9915 }
9916 }
9917 } else {
9918 callback();
9919 }
9920 });
9921};
9922
9923LD.prototype._iterator = function (options) {
9924 return new LDIterator(this, options);
9925};
9926
9927LD.destroy = function (name, callback) {
9928 LocalStorageCore.destroy(name, callback);
9929};
9930
9931function checkKeyValue(obj, type) {
9932 if (obj === null || obj === undefined) {
9933 return new Error(type + ' cannot be `null` or `undefined`');
9934 }
9935 if (obj === null || obj === undefined) {
9936 return new Error(type + ' cannot be `null` or `undefined`');
9937 }
9938
9939 if (type === 'key') {
9940
9941 if (obj instanceof Boolean) {
9942 return new Error(type + ' cannot be `null` or `undefined`');
9943 }
9944 if (obj === '') {
9945 return new Error(type + ' cannot be empty');
9946 }
9947 }
9948 if (obj.toString().indexOf("[object ArrayBuffer]") === 0) {
9949 if (obj.byteLength === 0 || obj.byteLength === undefined) {
9950 return new Error(type + ' cannot be an empty Buffer');
9951 }
9952 }
9953
9954 if (Buffer.isBuffer(obj)) {
9955 if (obj.length === 0) {
9956 return new Error(type + ' cannot be an empty Buffer');
9957 }
9958 } else if (String(obj) === '') {
9959 return new Error(type + ' cannot be an empty String');
9960 }
9961}
9962
9963module.exports = LD;
9964
9965}).call(this,{"isBuffer":_dereq_(25)},_dereq_(68),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
9966},{"24":24,"25":25,"3":3,"59":59,"60":60,"62":62,"63":63,"68":68}],59:[function(_dereq_,module,exports){
9967(function (process,global){
9968'use strict';
9969
9970//
9971// Class that should contain everything necessary to interact
9972// with localStorage as a generic key-value store.
9973// The idea is that authors who want to create an AbstractKeyValueDOWN
9974// module (e.g. on lawnchair, S3, whatever) will only have to
9975// reimplement this file.
9976//
9977
9978// see http://stackoverflow.com/a/15349865/680742
9979var nextTick = global.setImmediate || process.nextTick;
9980
9981// We use humble-localstorage as a wrapper for localStorage because
9982// it falls back to an in-memory implementation in environments without
9983// localStorage, like Node or Safari private browsing.
9984var storage = _dereq_(21);
9985
9986function callbackify(callback, fun) {
9987 var val;
9988 var err;
9989 try {
9990 val = fun();
9991 } catch (e) {
9992 err = e;
9993 }
9994 nextTick(function () {
9995 callback(err, val);
9996 });
9997}
9998
9999function createPrefix(dbname) {
10000 return dbname.replace(/!/g, '!!') + '!'; // escape bangs in dbname;
10001}
10002
10003function LocalStorageCore(dbname) {
10004 this._prefix = createPrefix(dbname);
10005}
10006
10007LocalStorageCore.prototype.getKeys = function (callback) {
10008 var self = this;
10009 callbackify(callback, function () {
10010 var keys = [];
10011 var prefixLen = self._prefix.length;
10012 var i = -1;
10013 var len = storage.length;
10014 while (++i < len) {
10015 var fullKey = storage.key(i);
10016 if (fullKey.substring(0, prefixLen) === self._prefix) {
10017 keys.push(fullKey.substring(prefixLen));
10018 }
10019 }
10020 keys.sort();
10021 return keys;
10022 });
10023};
10024
10025LocalStorageCore.prototype.put = function (key, value, callback) {
10026 var self = this;
10027 callbackify(callback, function () {
10028 storage.setItem(self._prefix + key, value);
10029 });
10030};
10031
10032LocalStorageCore.prototype.get = function (key, callback) {
10033 var self = this;
10034 callbackify(callback, function () {
10035 return storage.getItem(self._prefix + key);
10036 });
10037};
10038
10039LocalStorageCore.prototype.remove = function (key, callback) {
10040 var self = this;
10041 callbackify(callback, function () {
10042 storage.removeItem(self._prefix + key);
10043 });
10044};
10045
10046LocalStorageCore.destroy = function (dbname, callback) {
10047 var prefix = createPrefix(dbname);
10048 callbackify(callback, function () {
10049 var keysToDelete = [];
10050 var i = -1;
10051 var len = storage.length;
10052 while (++i < len) {
10053 var key = storage.key(i);
10054 if (key.substring(0, prefix.length) === prefix) {
10055 keysToDelete.push(key);
10056 }
10057 }
10058 keysToDelete.forEach(function (key) {
10059 storage.removeItem(key);
10060 });
10061 });
10062};
10063
10064module.exports = LocalStorageCore;
10065}).call(this,_dereq_(68),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10066},{"21":21,"68":68}],60:[function(_dereq_,module,exports){
10067(function (Buffer){
10068'use strict';
10069
10070// ArrayBuffer/Uint8Array are old formats that date back to before we
10071// had a proper browserified buffer type. they may be removed later
10072var arrayBuffPrefix = 'ArrayBuffer:';
10073var arrayBuffRegex = new RegExp('^' + arrayBuffPrefix);
10074var uintPrefix = 'Uint8Array:';
10075var uintRegex = new RegExp('^' + uintPrefix);
10076
10077// this is the new encoding format used going forward
10078var bufferPrefix = 'Buff:';
10079var bufferRegex = new RegExp('^' + bufferPrefix);
10080
10081var utils = _dereq_(62);
10082var LocalStorageCore = _dereq_(59);
10083var TaskQueue = _dereq_(61);
10084var d64 = _dereq_(14);
10085
10086function LocalStorage(dbname) {
10087 this._store = new LocalStorageCore(dbname);
10088 this._queue = new TaskQueue();
10089}
10090
10091LocalStorage.prototype.sequentialize = function (callback, fun) {
10092 this._queue.add(fun, callback);
10093};
10094
10095LocalStorage.prototype.init = function (callback) {
10096 var self = this;
10097 self.sequentialize(callback, function (callback) {
10098 self._store.getKeys(function (err, keys) {
10099 if (err) {
10100 return callback(err);
10101 }
10102 self._keys = keys;
10103 return callback();
10104 });
10105 });
10106};
10107
10108LocalStorage.prototype.keys = function (callback) {
10109 var self = this;
10110 self.sequentialize(callback, function (callback) {
10111 self._store.getKeys(function (err, keys) {
10112 callback(null, keys.slice());
10113 });
10114 });
10115};
10116
10117//setItem: Saves and item at the key provided.
10118LocalStorage.prototype.setItem = function (key, value, callback) {
10119 var self = this;
10120 self.sequentialize(callback, function (callback) {
10121 if (Buffer.isBuffer(value)) {
10122 value = bufferPrefix + d64.encode(value);
10123 }
10124
10125 var idx = utils.sortedIndexOf(self._keys, key);
10126 if (self._keys[idx] !== key) {
10127 self._keys.splice(idx, 0, key);
10128 }
10129 self._store.put(key, value, callback);
10130 });
10131};
10132
10133//getItem: Returns the item identified by it's key.
10134LocalStorage.prototype.getItem = function (key, callback) {
10135 var self = this;
10136 self.sequentialize(callback, function (callback) {
10137 self._store.get(key, function (err, retval) {
10138 if (err) {
10139 return callback(err);
10140 }
10141 if (typeof retval === 'undefined' || retval === null) {
10142 // 'NotFound' error, consistent with LevelDOWN API
10143 return callback(new Error('NotFound'));
10144 }
10145 if (typeof retval !== 'undefined') {
10146 if (bufferRegex.test(retval)) {
10147 retval = d64.decode(retval.substring(bufferPrefix.length));
10148 } else if (arrayBuffRegex.test(retval)) {
10149 // this type is kept for backwards
10150 // compatibility with older databases, but may be removed
10151 // after a major version bump
10152 retval = retval.substring(arrayBuffPrefix.length);
10153 retval = new ArrayBuffer(atob(retval).split('').map(function (c) {
10154 return c.charCodeAt(0);
10155 }));
10156 } else if (uintRegex.test(retval)) {
10157 // ditto
10158 retval = retval.substring(uintPrefix.length);
10159 retval = new Uint8Array(atob(retval).split('').map(function (c) {
10160 return c.charCodeAt(0);
10161 }));
10162 }
10163 }
10164 callback(null, retval);
10165 });
10166 });
10167};
10168
10169//removeItem: Removes the item identified by it's key.
10170LocalStorage.prototype.removeItem = function (key, callback) {
10171 var self = this;
10172 self.sequentialize(callback, function (callback) {
10173 var idx = utils.sortedIndexOf(self._keys, key);
10174 if (self._keys[idx] === key) {
10175 self._keys.splice(idx, 1);
10176 self._store.remove(key, function (err) {
10177 if (err) {
10178 return callback(err);
10179 }
10180 callback();
10181 });
10182 } else {
10183 callback();
10184 }
10185 });
10186};
10187
10188LocalStorage.prototype.length = function (callback) {
10189 var self = this;
10190 self.sequentialize(callback, function (callback) {
10191 callback(null, self._keys.length);
10192 });
10193};
10194
10195exports.LocalStorage = LocalStorage;
10196
10197}).call(this,{"isBuffer":_dereq_(25)})
10198},{"14":14,"25":25,"59":59,"61":61,"62":62}],61:[function(_dereq_,module,exports){
10199(function (process,global){
10200'use strict';
10201
10202var argsarray = _dereq_(4);
10203var Queue = _dereq_(114);
10204
10205// see http://stackoverflow.com/a/15349865/680742
10206var nextTick = global.setImmediate || process.nextTick;
10207
10208function TaskQueue() {
10209 this.queue = new Queue();
10210 this.running = false;
10211}
10212
10213TaskQueue.prototype.add = function (fun, callback) {
10214 this.queue.push({fun: fun, callback: callback});
10215 this.processNext();
10216};
10217
10218TaskQueue.prototype.processNext = function () {
10219 var self = this;
10220 if (self.running || !self.queue.length) {
10221 return;
10222 }
10223 self.running = true;
10224
10225 var task = self.queue.shift();
10226 nextTick(function () {
10227 task.fun(argsarray(function (args) {
10228 task.callback.apply(null, args);
10229 self.running = false;
10230 self.processNext();
10231 }));
10232 });
10233};
10234
10235module.exports = TaskQueue;
10236
10237}).call(this,_dereq_(68),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10238},{"114":114,"4":4,"68":68}],62:[function(_dereq_,module,exports){
10239'use strict';
10240// taken from rvagg/memdown commit 2078b40
10241exports.sortedIndexOf = function(arr, item) {
10242 var low = 0;
10243 var high = arr.length;
10244 var mid;
10245 while (low < high) {
10246 mid = (low + high) >>> 1;
10247 if (arr[mid] < item) {
10248 low = mid + 1;
10249 } else {
10250 high = mid;
10251 }
10252 }
10253 return low;
10254};
10255
10256},{}],63:[function(_dereq_,module,exports){
10257arguments[4][11][0].apply(exports,arguments)
10258},{"11":11,"12":12}],64:[function(_dereq_,module,exports){
10259(function (root) {
10260 var localStorageMemory = {}
10261 var cache = {}
10262
10263 /**
10264 * number of stored items.
10265 */
10266 localStorageMemory.length = 0
10267
10268 /**
10269 * returns item for passed key, or null
10270 *
10271 * @para {String} key
10272 * name of item to be returned
10273 * @returns {String|null}
10274 */
10275 localStorageMemory.getItem = function (key) {
10276 if (key in cache) {
10277 return cache[key]
10278 }
10279
10280 return null
10281 }
10282
10283 /**
10284 * sets item for key to passed value, as String
10285 *
10286 * @para {String} key
10287 * name of item to be set
10288 * @para {String} value
10289 * value, will always be turned into a String
10290 * @returns {undefined}
10291 */
10292 localStorageMemory.setItem = function (key, value) {
10293 if (typeof value === 'undefined') {
10294 localStorageMemory.removeItem(key)
10295 } else {
10296 if (!(cache.hasOwnProperty(key))) {
10297 localStorageMemory.length++
10298 }
10299
10300 cache[key] = '' + value
10301 }
10302 }
10303
10304 /**
10305 * removes item for passed key
10306 *
10307 * @para {String} key
10308 * name of item to be removed
10309 * @returns {undefined}
10310 */
10311 localStorageMemory.removeItem = function (key) {
10312 if (cache.hasOwnProperty(key)) {
10313 delete cache[key]
10314 localStorageMemory.length--
10315 }
10316 }
10317
10318 /**
10319 * returns name of key at passed index
10320 *
10321 * @para {Number} index
10322 * Position for key to be returned (starts at 0)
10323 * @returns {String|null}
10324 */
10325 localStorageMemory.key = function (index) {
10326 return Object.keys(cache)[index] || null
10327 }
10328
10329 /**
10330 * removes all stored items and sets length to 0
10331 *
10332 * @returns {undefined}
10333 */
10334 localStorageMemory.clear = function () {
10335 cache = {}
10336 localStorageMemory.length = 0
10337 }
10338
10339 if (typeof exports === 'object') {
10340 module.exports = localStorageMemory
10341 } else {
10342 root.localStorageMemory = localStorageMemory
10343 }
10344})(this)
10345
10346},{}],65:[function(_dereq_,module,exports){
10347(function (Buffer){
10348
10349exports.compare = function (a, b) {
10350
10351 if(Buffer.isBuffer(a)) {
10352 var l = Math.min(a.length, b.length)
10353 for(var i = 0; i < l; i++) {
10354 var cmp = a[i] - b[i]
10355 if(cmp) return cmp
10356 }
10357 return a.length - b.length
10358 }
10359
10360 return a < b ? -1 : a > b ? 1 : 0
10361}
10362
10363// to be compatible with the current abstract-leveldown tests
10364// nullish or empty strings.
10365// I could use !!val but I want to permit numbers and booleans,
10366// if possible.
10367
10368function isDef (val) {
10369 return val !== undefined && val !== ''
10370}
10371
10372function has (range, name) {
10373 return Object.hasOwnProperty.call(range, name)
10374}
10375
10376function hasKey(range, name) {
10377 return Object.hasOwnProperty.call(range, name) && name
10378}
10379
10380var lowerBoundKey = exports.lowerBoundKey = function (range) {
10381 return (
10382 hasKey(range, 'gt')
10383 || hasKey(range, 'gte')
10384 || hasKey(range, 'min')
10385 || (range.reverse ? hasKey(range, 'end') : hasKey(range, 'start'))
10386 || undefined
10387 )
10388}
10389
10390var lowerBound = exports.lowerBound = function (range, def) {
10391 var k = lowerBoundKey(range)
10392 return k ? range[k] : def
10393}
10394
10395var lowerBoundInclusive = exports.lowerBoundInclusive = function (range) {
10396 return has(range, 'gt') ? false : true
10397}
10398
10399var upperBoundInclusive = exports.upperBoundInclusive =
10400 function (range) {
10401 return (has(range, 'lt') /*&& !range.maxEx*/) ? false : true
10402 }
10403
10404var lowerBoundExclusive = exports.lowerBoundExclusive =
10405 function (range) {
10406 return !lowerBoundInclusive(range)
10407 }
10408
10409var upperBoundExclusive = exports.upperBoundExclusive =
10410 function (range) {
10411 return !upperBoundInclusive(range)
10412 }
10413
10414var upperBoundKey = exports.upperBoundKey = function (range) {
10415 return (
10416 hasKey(range, 'lt')
10417 || hasKey(range, 'lte')
10418 || hasKey(range, 'max')
10419 || (range.reverse ? hasKey(range, 'start') : hasKey(range, 'end'))
10420 || undefined
10421 )
10422}
10423
10424var upperBound = exports.upperBound = function (range, def) {
10425 var k = upperBoundKey(range)
10426 return k ? range[k] : def
10427}
10428
10429exports.start = function (range, def) {
10430 return range.reverse ? upperBound(range, def) : lowerBound(range, def)
10431}
10432exports.end = function (range, def) {
10433 return range.reverse ? lowerBound(range, def) : upperBound(range, def)
10434}
10435exports.startInclusive = function (range) {
10436 return (
10437 range.reverse
10438 ? upperBoundInclusive(range)
10439 : lowerBoundInclusive(range)
10440 )
10441}
10442exports.endInclusive = function (range) {
10443 return (
10444 range.reverse
10445 ? lowerBoundInclusive(range)
10446 : upperBoundInclusive(range)
10447 )
10448}
10449
10450function id (e) { return e }
10451
10452exports.toLtgt = function (range, _range, map, lower, upper) {
10453 _range = _range || {}
10454 map = map || id
10455 var defaults = arguments.length > 3
10456 var lb = exports.lowerBoundKey(range)
10457 var ub = exports.upperBoundKey(range)
10458 if(lb) {
10459 if(lb === 'gt') _range.gt = map(range.gt, false)
10460 else _range.gte = map(range[lb], false)
10461 }
10462 else if(defaults)
10463 _range.gte = map(lower, false)
10464
10465 if(ub) {
10466 if(ub === 'lt') _range.lt = map(range.lt, true)
10467 else _range.lte = map(range[ub], true)
10468 }
10469 else if(defaults)
10470 _range.lte = map(upper, true)
10471
10472 if(range.reverse != null)
10473 _range.reverse = !!range.reverse
10474
10475 //if range was used mutably
10476 //(in level-sublevel it's part of an options object
10477 //that has more properties on it.)
10478 if(has(_range, 'max')) delete _range.max
10479 if(has(_range, 'min')) delete _range.min
10480 if(has(_range, 'start')) delete _range.start
10481 if(has(_range, 'end')) delete _range.end
10482
10483 return _range
10484}
10485
10486exports.contains = function (range, key, compare) {
10487 compare = compare || exports.compare
10488
10489 var lb = lowerBound(range)
10490 if(isDef(lb)) {
10491 var cmp = compare(key, lb)
10492 if(cmp < 0 || (cmp === 0 && lowerBoundExclusive(range)))
10493 return false
10494 }
10495
10496 var ub = upperBound(range)
10497 if(isDef(ub)) {
10498 var cmp = compare(key, ub)
10499 if(cmp > 0 || (cmp === 0) && upperBoundExclusive(range))
10500 return false
10501 }
10502
10503 return true
10504}
10505
10506exports.filter = function (range, compare) {
10507 return function (key) {
10508 return exports.contains(range, key, compare)
10509 }
10510}
10511
10512
10513
10514}).call(this,{"isBuffer":_dereq_(25)})
10515},{"25":25}],66:[function(_dereq_,module,exports){
10516/*
10517object-assign
10518(c) Sindre Sorhus
10519@license MIT
10520*/
10521
10522'use strict';
10523/* eslint-disable no-unused-vars */
10524var getOwnPropertySymbols = Object.getOwnPropertySymbols;
10525var hasOwnProperty = Object.prototype.hasOwnProperty;
10526var propIsEnumerable = Object.prototype.propertyIsEnumerable;
10527
10528function toObject(val) {
10529 if (val === null || val === undefined) {
10530 throw new TypeError('Object.assign cannot be called with null or undefined');
10531 }
10532
10533 return Object(val);
10534}
10535
10536function shouldUseNative() {
10537 try {
10538 if (!Object.assign) {
10539 return false;
10540 }
10541
10542 // Detect buggy property enumeration order in older V8 versions.
10543
10544 // https://bugs.chromium.org/p/v8/issues/detail?id=4118
10545 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
10546 test1[5] = 'de';
10547 if (Object.getOwnPropertyNames(test1)[0] === '5') {
10548 return false;
10549 }
10550
10551 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
10552 var test2 = {};
10553 for (var i = 0; i < 10; i++) {
10554 test2['_' + String.fromCharCode(i)] = i;
10555 }
10556 var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
10557 return test2[n];
10558 });
10559 if (order2.join('') !== '0123456789') {
10560 return false;
10561 }
10562
10563 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
10564 var test3 = {};
10565 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
10566 test3[letter] = letter;
10567 });
10568 if (Object.keys(Object.assign({}, test3)).join('') !==
10569 'abcdefghijklmnopqrst') {
10570 return false;
10571 }
10572
10573 return true;
10574 } catch (err) {
10575 // We don't expect any of the above to throw, but better to be safe.
10576 return false;
10577 }
10578}
10579
10580module.exports = shouldUseNative() ? Object.assign : function (target, source) {
10581 var from;
10582 var to = toObject(target);
10583 var symbols;
10584
10585 for (var s = 1; s < arguments.length; s++) {
10586 from = Object(arguments[s]);
10587
10588 for (var key in from) {
10589 if (hasOwnProperty.call(from, key)) {
10590 to[key] = from[key];
10591 }
10592 }
10593
10594 if (getOwnPropertySymbols) {
10595 symbols = getOwnPropertySymbols(from);
10596 for (var i = 0; i < symbols.length; i++) {
10597 if (propIsEnumerable.call(from, symbols[i])) {
10598 to[symbols[i]] = from[symbols[i]];
10599 }
10600 }
10601 }
10602 }
10603
10604 return to;
10605};
10606
10607},{}],67:[function(_dereq_,module,exports){
10608(function (process){
10609'use strict';
10610
10611if (typeof process === 'undefined' ||
10612 !process.version ||
10613 process.version.indexOf('v0.') === 0 ||
10614 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
10615 module.exports = { nextTick: nextTick };
10616} else {
10617 module.exports = process
10618}
10619
10620function nextTick(fn, arg1, arg2, arg3) {
10621 if (typeof fn !== 'function') {
10622 throw new TypeError('"callback" argument must be a function');
10623 }
10624 var len = arguments.length;
10625 var args, i;
10626 switch (len) {
10627 case 0:
10628 case 1:
10629 return process.nextTick(fn);
10630 case 2:
10631 return process.nextTick(function afterTickOne() {
10632 fn.call(null, arg1);
10633 });
10634 case 3:
10635 return process.nextTick(function afterTickTwo() {
10636 fn.call(null, arg1, arg2);
10637 });
10638 case 4:
10639 return process.nextTick(function afterTickThree() {
10640 fn.call(null, arg1, arg2, arg3);
10641 });
10642 default:
10643 args = new Array(len - 1);
10644 i = 0;
10645 while (i < args.length) {
10646 args[i++] = arguments[i];
10647 }
10648 return process.nextTick(function afterTick() {
10649 fn.apply(null, args);
10650 });
10651 }
10652}
10653
10654
10655}).call(this,_dereq_(68))
10656},{"68":68}],68:[function(_dereq_,module,exports){
10657// shim for using process in browser
10658var process = module.exports = {};
10659
10660// cached from whatever global is present so that test runners that stub it
10661// don't break things. But we need to wrap it in a try catch in case it is
10662// wrapped in strict mode code which doesn't define any globals. It's inside a
10663// function because try/catches deoptimize in certain engines.
10664
10665var cachedSetTimeout;
10666var cachedClearTimeout;
10667
10668function defaultSetTimout() {
10669 throw new Error('setTimeout has not been defined');
10670}
10671function defaultClearTimeout () {
10672 throw new Error('clearTimeout has not been defined');
10673}
10674(function () {
10675 try {
10676 if (typeof setTimeout === 'function') {
10677 cachedSetTimeout = setTimeout;
10678 } else {
10679 cachedSetTimeout = defaultSetTimout;
10680 }
10681 } catch (e) {
10682 cachedSetTimeout = defaultSetTimout;
10683 }
10684 try {
10685 if (typeof clearTimeout === 'function') {
10686 cachedClearTimeout = clearTimeout;
10687 } else {
10688 cachedClearTimeout = defaultClearTimeout;
10689 }
10690 } catch (e) {
10691 cachedClearTimeout = defaultClearTimeout;
10692 }
10693} ())
10694function runTimeout(fun) {
10695 if (cachedSetTimeout === setTimeout) {
10696 //normal enviroments in sane situations
10697 return setTimeout(fun, 0);
10698 }
10699 // if setTimeout wasn't available but was latter defined
10700 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
10701 cachedSetTimeout = setTimeout;
10702 return setTimeout(fun, 0);
10703 }
10704 try {
10705 // when when somebody has screwed with setTimeout but no I.E. maddness
10706 return cachedSetTimeout(fun, 0);
10707 } catch(e){
10708 try {
10709 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
10710 return cachedSetTimeout.call(null, fun, 0);
10711 } catch(e){
10712 // 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
10713 return cachedSetTimeout.call(this, fun, 0);
10714 }
10715 }
10716
10717
10718}
10719function runClearTimeout(marker) {
10720 if (cachedClearTimeout === clearTimeout) {
10721 //normal enviroments in sane situations
10722 return clearTimeout(marker);
10723 }
10724 // if clearTimeout wasn't available but was latter defined
10725 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
10726 cachedClearTimeout = clearTimeout;
10727 return clearTimeout(marker);
10728 }
10729 try {
10730 // when when somebody has screwed with setTimeout but no I.E. maddness
10731 return cachedClearTimeout(marker);
10732 } catch (e){
10733 try {
10734 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
10735 return cachedClearTimeout.call(null, marker);
10736 } catch (e){
10737 // 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.
10738 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
10739 return cachedClearTimeout.call(this, marker);
10740 }
10741 }
10742
10743
10744
10745}
10746var queue = [];
10747var draining = false;
10748var currentQueue;
10749var queueIndex = -1;
10750
10751function cleanUpNextTick() {
10752 if (!draining || !currentQueue) {
10753 return;
10754 }
10755 draining = false;
10756 if (currentQueue.length) {
10757 queue = currentQueue.concat(queue);
10758 } else {
10759 queueIndex = -1;
10760 }
10761 if (queue.length) {
10762 drainQueue();
10763 }
10764}
10765
10766function drainQueue() {
10767 if (draining) {
10768 return;
10769 }
10770 var timeout = runTimeout(cleanUpNextTick);
10771 draining = true;
10772
10773 var len = queue.length;
10774 while(len) {
10775 currentQueue = queue;
10776 queue = [];
10777 while (++queueIndex < len) {
10778 if (currentQueue) {
10779 currentQueue[queueIndex].run();
10780 }
10781 }
10782 queueIndex = -1;
10783 len = queue.length;
10784 }
10785 currentQueue = null;
10786 draining = false;
10787 runClearTimeout(timeout);
10788}
10789
10790process.nextTick = function (fun) {
10791 var args = new Array(arguments.length - 1);
10792 if (arguments.length > 1) {
10793 for (var i = 1; i < arguments.length; i++) {
10794 args[i - 1] = arguments[i];
10795 }
10796 }
10797 queue.push(new Item(fun, args));
10798 if (queue.length === 1 && !draining) {
10799 runTimeout(drainQueue);
10800 }
10801};
10802
10803// v8 likes predictible objects
10804function Item(fun, array) {
10805 this.fun = fun;
10806 this.array = array;
10807}
10808Item.prototype.run = function () {
10809 this.fun.apply(null, this.array);
10810};
10811process.title = 'browser';
10812process.browser = true;
10813process.env = {};
10814process.argv = [];
10815process.version = ''; // empty string to avoid regexp issues
10816process.versions = {};
10817
10818function noop() {}
10819
10820process.on = noop;
10821process.addListener = noop;
10822process.once = noop;
10823process.off = noop;
10824process.removeListener = noop;
10825process.removeAllListeners = noop;
10826process.emit = noop;
10827process.prependListener = noop;
10828process.prependOnceListener = noop;
10829
10830process.listeners = function (name) { return [] }
10831
10832process.binding = function (name) {
10833 throw new Error('process.binding is not supported');
10834};
10835
10836process.cwd = function () { return '/' };
10837process.chdir = function (dir) {
10838 throw new Error('process.chdir is not supported');
10839};
10840process.umask = function() { return 0; };
10841
10842},{}],69:[function(_dereq_,module,exports){
10843/*!
10844 * prr
10845 * (c) 2013 Rod Vagg <rod@vagg.org>
10846 * https://github.com/rvagg/prr
10847 * License: MIT
10848 */
10849
10850(function (name, context, definition) {
10851 if (typeof module != 'undefined' && module.exports)
10852 module.exports = definition()
10853 else
10854 context[name] = definition()
10855})('prr', this, function() {
10856
10857 var setProperty = typeof Object.defineProperty == 'function'
10858 ? function (obj, key, options) {
10859 Object.defineProperty(obj, key, options)
10860 return obj
10861 }
10862 : function (obj, key, options) { // < es5
10863 obj[key] = options.value
10864 return obj
10865 }
10866
10867 , makeOptions = function (value, options) {
10868 var oo = typeof options == 'object'
10869 , os = !oo && typeof options == 'string'
10870 , op = function (p) {
10871 return oo
10872 ? !!options[p]
10873 : os
10874 ? options.indexOf(p[0]) > -1
10875 : false
10876 }
10877
10878 return {
10879 enumerable : op('enumerable')
10880 , configurable : op('configurable')
10881 , writable : op('writable')
10882 , value : value
10883 }
10884 }
10885
10886 , prr = function (obj, key, value, options) {
10887 var k
10888
10889 options = makeOptions(value, options)
10890
10891 if (typeof key == 'object') {
10892 for (k in key) {
10893 if (Object.hasOwnProperty.call(key, k)) {
10894 options.value = key[k]
10895 setProperty(obj, k, options)
10896 }
10897 }
10898 return obj
10899 }
10900
10901 return setProperty(obj, key, options)
10902 }
10903
10904 return prr
10905})
10906},{}],70:[function(_dereq_,module,exports){
10907(function (process){
10908// Copyright Joyent, Inc. and other Node contributors.
10909//
10910// Permission is hereby granted, free of charge, to any person obtaining a
10911// copy of this software and associated documentation files (the
10912// "Software"), to deal in the Software without restriction, including
10913// without limitation the rights to use, copy, modify, merge, publish,
10914// distribute, sublicense, and/or sell copies of the Software, and to permit
10915// persons to whom the Software is furnished to do so, subject to the
10916// following conditions:
10917//
10918// The above copyright notice and this permission notice shall be included
10919// in all copies or substantial portions of the Software.
10920//
10921// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
10922// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
10923// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
10924// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
10925// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
10926// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
10927// USE OR OTHER DEALINGS IN THE SOFTWARE.
10928
10929// a duplex stream is just a stream that is both readable and writable.
10930// Since JS doesn't have multiple prototypal inheritance, this class
10931// prototypally inherits from Readable, and then parasitically from
10932// Writable.
10933
10934module.exports = Duplex;
10935
10936/*<replacement>*/
10937var objectKeys = Object.keys || function (obj) {
10938 var keys = [];
10939 for (var key in obj) keys.push(key);
10940 return keys;
10941}
10942/*</replacement>*/
10943
10944
10945/*<replacement>*/
10946var util = _dereq_(13);
10947util.inherits = _dereq_(24);
10948/*</replacement>*/
10949
10950var Readable = _dereq_(72);
10951var Writable = _dereq_(74);
10952
10953util.inherits(Duplex, Readable);
10954
10955forEach(objectKeys(Writable.prototype), function(method) {
10956 if (!Duplex.prototype[method])
10957 Duplex.prototype[method] = Writable.prototype[method];
10958});
10959
10960function Duplex(options) {
10961 if (!(this instanceof Duplex))
10962 return new Duplex(options);
10963
10964 Readable.call(this, options);
10965 Writable.call(this, options);
10966
10967 if (options && options.readable === false)
10968 this.readable = false;
10969
10970 if (options && options.writable === false)
10971 this.writable = false;
10972
10973 this.allowHalfOpen = true;
10974 if (options && options.allowHalfOpen === false)
10975 this.allowHalfOpen = false;
10976
10977 this.once('end', onend);
10978}
10979
10980// the no-half-open enforcer
10981function onend() {
10982 // if we allow half-open state, or if the writable side ended,
10983 // then we're ok.
10984 if (this.allowHalfOpen || this._writableState.ended)
10985 return;
10986
10987 // no more data can be written.
10988 // But allow more writes to happen in this tick.
10989 process.nextTick(this.end.bind(this));
10990}
10991
10992function forEach (xs, f) {
10993 for (var i = 0, l = xs.length; i < l; i++) {
10994 f(xs[i], i);
10995 }
10996}
10997
10998}).call(this,_dereq_(68))
10999},{"13":13,"24":24,"68":68,"72":72,"74":74}],71:[function(_dereq_,module,exports){
11000// Copyright Joyent, Inc. and other Node contributors.
11001//
11002// Permission is hereby granted, free of charge, to any person obtaining a
11003// copy of this software and associated documentation files (the
11004// "Software"), to deal in the Software without restriction, including
11005// without limitation the rights to use, copy, modify, merge, publish,
11006// distribute, sublicense, and/or sell copies of the Software, and to permit
11007// persons to whom the Software is furnished to do so, subject to the
11008// following conditions:
11009//
11010// The above copyright notice and this permission notice shall be included
11011// in all copies or substantial portions of the Software.
11012//
11013// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11014// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11015// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11016// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11017// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11018// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11019// USE OR OTHER DEALINGS IN THE SOFTWARE.
11020
11021// a passthrough stream.
11022// basically just the most minimal sort of Transform stream.
11023// Every written chunk gets output as-is.
11024
11025module.exports = PassThrough;
11026
11027var Transform = _dereq_(73);
11028
11029/*<replacement>*/
11030var util = _dereq_(13);
11031util.inherits = _dereq_(24);
11032/*</replacement>*/
11033
11034util.inherits(PassThrough, Transform);
11035
11036function PassThrough(options) {
11037 if (!(this instanceof PassThrough))
11038 return new PassThrough(options);
11039
11040 Transform.call(this, options);
11041}
11042
11043PassThrough.prototype._transform = function(chunk, encoding, cb) {
11044 cb(null, chunk);
11045};
11046
11047},{"13":13,"24":24,"73":73}],72:[function(_dereq_,module,exports){
11048(function (process){
11049// Copyright Joyent, Inc. and other Node contributors.
11050//
11051// Permission is hereby granted, free of charge, to any person obtaining a
11052// copy of this software and associated documentation files (the
11053// "Software"), to deal in the Software without restriction, including
11054// without limitation the rights to use, copy, modify, merge, publish,
11055// distribute, sublicense, and/or sell copies of the Software, and to permit
11056// persons to whom the Software is furnished to do so, subject to the
11057// following conditions:
11058//
11059// The above copyright notice and this permission notice shall be included
11060// in all copies or substantial portions of the Software.
11061//
11062// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11063// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11064// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11065// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11066// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11067// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11068// USE OR OTHER DEALINGS IN THE SOFTWARE.
11069
11070module.exports = Readable;
11071
11072/*<replacement>*/
11073var isArray = _dereq_(26);
11074/*</replacement>*/
11075
11076
11077/*<replacement>*/
11078var Buffer = _dereq_(12).Buffer;
11079/*</replacement>*/
11080
11081Readable.ReadableState = ReadableState;
11082
11083var EE = _dereq_(18).EventEmitter;
11084
11085/*<replacement>*/
11086if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
11087 return emitter.listeners(type).length;
11088};
11089/*</replacement>*/
11090
11091var Stream = _dereq_(79);
11092
11093/*<replacement>*/
11094var util = _dereq_(13);
11095util.inherits = _dereq_(24);
11096/*</replacement>*/
11097
11098var StringDecoder;
11099
11100util.inherits(Readable, Stream);
11101
11102function ReadableState(options, stream) {
11103 options = options || {};
11104
11105 // the point at which it stops calling _read() to fill the buffer
11106 // Note: 0 is a valid value, means "don't call _read preemptively ever"
11107 var hwm = options.highWaterMark;
11108 this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
11109
11110 // cast to ints.
11111 this.highWaterMark = ~~this.highWaterMark;
11112
11113 this.buffer = [];
11114 this.length = 0;
11115 this.pipes = null;
11116 this.pipesCount = 0;
11117 this.flowing = false;
11118 this.ended = false;
11119 this.endEmitted = false;
11120 this.reading = false;
11121
11122 // In streams that never have any data, and do push(null) right away,
11123 // the consumer can miss the 'end' event if they do some I/O before
11124 // consuming the stream. So, we don't emit('end') until some reading
11125 // happens.
11126 this.calledRead = false;
11127
11128 // a flag to be able to tell if the onwrite cb is called immediately,
11129 // or on a later tick. We set this to true at first, becuase any
11130 // actions that shouldn't happen until "later" should generally also
11131 // not happen before the first write call.
11132 this.sync = true;
11133
11134 // whenever we return null, then we set a flag to say
11135 // that we're awaiting a 'readable' event emission.
11136 this.needReadable = false;
11137 this.emittedReadable = false;
11138 this.readableListening = false;
11139
11140
11141 // object stream flag. Used to make read(n) ignore n and to
11142 // make all the buffer merging and length checks go away
11143 this.objectMode = !!options.objectMode;
11144
11145 // Crypto is kind of old and crusty. Historically, its default string
11146 // encoding is 'binary' so we have to make this configurable.
11147 // Everything else in the universe uses 'utf8', though.
11148 this.defaultEncoding = options.defaultEncoding || 'utf8';
11149
11150 // when piping, we only care about 'readable' events that happen
11151 // after read()ing all the bytes and not getting any pushback.
11152 this.ranOut = false;
11153
11154 // the number of writers that are awaiting a drain event in .pipe()s
11155 this.awaitDrain = 0;
11156
11157 // if true, a maybeReadMore has been scheduled
11158 this.readingMore = false;
11159
11160 this.decoder = null;
11161 this.encoding = null;
11162 if (options.encoding) {
11163 if (!StringDecoder)
11164 StringDecoder = _dereq_(75).StringDecoder;
11165 this.decoder = new StringDecoder(options.encoding);
11166 this.encoding = options.encoding;
11167 }
11168}
11169
11170function Readable(options) {
11171 if (!(this instanceof Readable))
11172 return new Readable(options);
11173
11174 this._readableState = new ReadableState(options, this);
11175
11176 // legacy
11177 this.readable = true;
11178
11179 Stream.call(this);
11180}
11181
11182// Manually shove something into the read() buffer.
11183// This returns true if the highWaterMark has not been hit yet,
11184// similar to how Writable.write() returns true if you should
11185// write() some more.
11186Readable.prototype.push = function(chunk, encoding) {
11187 var state = this._readableState;
11188
11189 if (typeof chunk === 'string' && !state.objectMode) {
11190 encoding = encoding || state.defaultEncoding;
11191 if (encoding !== state.encoding) {
11192 chunk = new Buffer(chunk, encoding);
11193 encoding = '';
11194 }
11195 }
11196
11197 return readableAddChunk(this, state, chunk, encoding, false);
11198};
11199
11200// Unshift should *always* be something directly out of read()
11201Readable.prototype.unshift = function(chunk) {
11202 var state = this._readableState;
11203 return readableAddChunk(this, state, chunk, '', true);
11204};
11205
11206function readableAddChunk(stream, state, chunk, encoding, addToFront) {
11207 var er = chunkInvalid(state, chunk);
11208 if (er) {
11209 stream.emit('error', er);
11210 } else if (chunk === null || chunk === undefined) {
11211 state.reading = false;
11212 if (!state.ended)
11213 onEofChunk(stream, state);
11214 } else if (state.objectMode || chunk && chunk.length > 0) {
11215 if (state.ended && !addToFront) {
11216 var e = new Error('stream.push() after EOF');
11217 stream.emit('error', e);
11218 } else if (state.endEmitted && addToFront) {
11219 var e = new Error('stream.unshift() after end event');
11220 stream.emit('error', e);
11221 } else {
11222 if (state.decoder && !addToFront && !encoding)
11223 chunk = state.decoder.write(chunk);
11224
11225 // update the buffer info.
11226 state.length += state.objectMode ? 1 : chunk.length;
11227 if (addToFront) {
11228 state.buffer.unshift(chunk);
11229 } else {
11230 state.reading = false;
11231 state.buffer.push(chunk);
11232 }
11233
11234 if (state.needReadable)
11235 emitReadable(stream);
11236
11237 maybeReadMore(stream, state);
11238 }
11239 } else if (!addToFront) {
11240 state.reading = false;
11241 }
11242
11243 return needMoreData(state);
11244}
11245
11246
11247
11248// if it's past the high water mark, we can push in some more.
11249// Also, if we have no data yet, we can stand some
11250// more bytes. This is to work around cases where hwm=0,
11251// such as the repl. Also, if the push() triggered a
11252// readable event, and the user called read(largeNumber) such that
11253// needReadable was set, then we ought to push more, so that another
11254// 'readable' event will be triggered.
11255function needMoreData(state) {
11256 return !state.ended &&
11257 (state.needReadable ||
11258 state.length < state.highWaterMark ||
11259 state.length === 0);
11260}
11261
11262// backwards compatibility.
11263Readable.prototype.setEncoding = function(enc) {
11264 if (!StringDecoder)
11265 StringDecoder = _dereq_(75).StringDecoder;
11266 this._readableState.decoder = new StringDecoder(enc);
11267 this._readableState.encoding = enc;
11268};
11269
11270// Don't raise the hwm > 128MB
11271var MAX_HWM = 0x800000;
11272function roundUpToNextPowerOf2(n) {
11273 if (n >= MAX_HWM) {
11274 n = MAX_HWM;
11275 } else {
11276 // Get the next highest power of 2
11277 n--;
11278 for (var p = 1; p < 32; p <<= 1) n |= n >> p;
11279 n++;
11280 }
11281 return n;
11282}
11283
11284function howMuchToRead(n, state) {
11285 if (state.length === 0 && state.ended)
11286 return 0;
11287
11288 if (state.objectMode)
11289 return n === 0 ? 0 : 1;
11290
11291 if (n === null || isNaN(n)) {
11292 // only flow one buffer at a time
11293 if (state.flowing && state.buffer.length)
11294 return state.buffer[0].length;
11295 else
11296 return state.length;
11297 }
11298
11299 if (n <= 0)
11300 return 0;
11301
11302 // If we're asking for more than the target buffer level,
11303 // then raise the water mark. Bump up to the next highest
11304 // power of 2, to prevent increasing it excessively in tiny
11305 // amounts.
11306 if (n > state.highWaterMark)
11307 state.highWaterMark = roundUpToNextPowerOf2(n);
11308
11309 // don't have that much. return null, unless we've ended.
11310 if (n > state.length) {
11311 if (!state.ended) {
11312 state.needReadable = true;
11313 return 0;
11314 } else
11315 return state.length;
11316 }
11317
11318 return n;
11319}
11320
11321// you can override either this method, or the async _read(n) below.
11322Readable.prototype.read = function(n) {
11323 var state = this._readableState;
11324 state.calledRead = true;
11325 var nOrig = n;
11326 var ret;
11327
11328 if (typeof n !== 'number' || n > 0)
11329 state.emittedReadable = false;
11330
11331 // if we're doing read(0) to trigger a readable event, but we
11332 // already have a bunch of data in the buffer, then just trigger
11333 // the 'readable' event and move on.
11334 if (n === 0 &&
11335 state.needReadable &&
11336 (state.length >= state.highWaterMark || state.ended)) {
11337 emitReadable(this);
11338 return null;
11339 }
11340
11341 n = howMuchToRead(n, state);
11342
11343 // if we've ended, and we're now clear, then finish it up.
11344 if (n === 0 && state.ended) {
11345 ret = null;
11346
11347 // In cases where the decoder did not receive enough data
11348 // to produce a full chunk, then immediately received an
11349 // EOF, state.buffer will contain [<Buffer >, <Buffer 00 ...>].
11350 // howMuchToRead will see this and coerce the amount to
11351 // read to zero (because it's looking at the length of the
11352 // first <Buffer > in state.buffer), and we'll end up here.
11353 //
11354 // This can only happen via state.decoder -- no other venue
11355 // exists for pushing a zero-length chunk into state.buffer
11356 // and triggering this behavior. In this case, we return our
11357 // remaining data and end the stream, if appropriate.
11358 if (state.length > 0 && state.decoder) {
11359 ret = fromList(n, state);
11360 state.length -= ret.length;
11361 }
11362
11363 if (state.length === 0)
11364 endReadable(this);
11365
11366 return ret;
11367 }
11368
11369 // All the actual chunk generation logic needs to be
11370 // *below* the call to _read. The reason is that in certain
11371 // synthetic stream cases, such as passthrough streams, _read
11372 // may be a completely synchronous operation which may change
11373 // the state of the read buffer, providing enough data when
11374 // before there was *not* enough.
11375 //
11376 // So, the steps are:
11377 // 1. Figure out what the state of things will be after we do
11378 // a read from the buffer.
11379 //
11380 // 2. If that resulting state will trigger a _read, then call _read.
11381 // Note that this may be asynchronous, or synchronous. Yes, it is
11382 // deeply ugly to write APIs this way, but that still doesn't mean
11383 // that the Readable class should behave improperly, as streams are
11384 // designed to be sync/async agnostic.
11385 // Take note if the _read call is sync or async (ie, if the read call
11386 // has returned yet), so that we know whether or not it's safe to emit
11387 // 'readable' etc.
11388 //
11389 // 3. Actually pull the requested chunks out of the buffer and return.
11390
11391 // if we need a readable event, then we need to do some reading.
11392 var doRead = state.needReadable;
11393
11394 // if we currently have less than the highWaterMark, then also read some
11395 if (state.length - n <= state.highWaterMark)
11396 doRead = true;
11397
11398 // however, if we've ended, then there's no point, and if we're already
11399 // reading, then it's unnecessary.
11400 if (state.ended || state.reading)
11401 doRead = false;
11402
11403 if (doRead) {
11404 state.reading = true;
11405 state.sync = true;
11406 // if the length is currently zero, then we *need* a readable event.
11407 if (state.length === 0)
11408 state.needReadable = true;
11409 // call internal read method
11410 this._read(state.highWaterMark);
11411 state.sync = false;
11412 }
11413
11414 // If _read called its callback synchronously, then `reading`
11415 // will be false, and we need to re-evaluate how much data we
11416 // can return to the user.
11417 if (doRead && !state.reading)
11418 n = howMuchToRead(nOrig, state);
11419
11420 if (n > 0)
11421 ret = fromList(n, state);
11422 else
11423 ret = null;
11424
11425 if (ret === null) {
11426 state.needReadable = true;
11427 n = 0;
11428 }
11429
11430 state.length -= n;
11431
11432 // If we have nothing in the buffer, then we want to know
11433 // as soon as we *do* get something into the buffer.
11434 if (state.length === 0 && !state.ended)
11435 state.needReadable = true;
11436
11437 // If we happened to read() exactly the remaining amount in the
11438 // buffer, and the EOF has been seen at this point, then make sure
11439 // that we emit 'end' on the very next tick.
11440 if (state.ended && !state.endEmitted && state.length === 0)
11441 endReadable(this);
11442
11443 return ret;
11444};
11445
11446function chunkInvalid(state, chunk) {
11447 var er = null;
11448 if (!Buffer.isBuffer(chunk) &&
11449 'string' !== typeof chunk &&
11450 chunk !== null &&
11451 chunk !== undefined &&
11452 !state.objectMode) {
11453 er = new TypeError('Invalid non-string/buffer chunk');
11454 }
11455 return er;
11456}
11457
11458
11459function onEofChunk(stream, state) {
11460 if (state.decoder && !state.ended) {
11461 var chunk = state.decoder.end();
11462 if (chunk && chunk.length) {
11463 state.buffer.push(chunk);
11464 state.length += state.objectMode ? 1 : chunk.length;
11465 }
11466 }
11467 state.ended = true;
11468
11469 // if we've ended and we have some data left, then emit
11470 // 'readable' now to make sure it gets picked up.
11471 if (state.length > 0)
11472 emitReadable(stream);
11473 else
11474 endReadable(stream);
11475}
11476
11477// Don't emit readable right away in sync mode, because this can trigger
11478// another read() call => stack overflow. This way, it might trigger
11479// a nextTick recursion warning, but that's not so bad.
11480function emitReadable(stream) {
11481 var state = stream._readableState;
11482 state.needReadable = false;
11483 if (state.emittedReadable)
11484 return;
11485
11486 state.emittedReadable = true;
11487 if (state.sync)
11488 process.nextTick(function() {
11489 emitReadable_(stream);
11490 });
11491 else
11492 emitReadable_(stream);
11493}
11494
11495function emitReadable_(stream) {
11496 stream.emit('readable');
11497}
11498
11499
11500// at this point, the user has presumably seen the 'readable' event,
11501// and called read() to consume some data. that may have triggered
11502// in turn another _read(n) call, in which case reading = true if
11503// it's in progress.
11504// However, if we're not ended, or reading, and the length < hwm,
11505// then go ahead and try to read some more preemptively.
11506function maybeReadMore(stream, state) {
11507 if (!state.readingMore) {
11508 state.readingMore = true;
11509 process.nextTick(function() {
11510 maybeReadMore_(stream, state);
11511 });
11512 }
11513}
11514
11515function maybeReadMore_(stream, state) {
11516 var len = state.length;
11517 while (!state.reading && !state.flowing && !state.ended &&
11518 state.length < state.highWaterMark) {
11519 stream.read(0);
11520 if (len === state.length)
11521 // didn't get any data, stop spinning.
11522 break;
11523 else
11524 len = state.length;
11525 }
11526 state.readingMore = false;
11527}
11528
11529// abstract method. to be overridden in specific implementation classes.
11530// call cb(er, data) where data is <= n in length.
11531// for virtual (non-string, non-buffer) streams, "length" is somewhat
11532// arbitrary, and perhaps not very meaningful.
11533Readable.prototype._read = function(n) {
11534 this.emit('error', new Error('not implemented'));
11535};
11536
11537Readable.prototype.pipe = function(dest, pipeOpts) {
11538 var src = this;
11539 var state = this._readableState;
11540
11541 switch (state.pipesCount) {
11542 case 0:
11543 state.pipes = dest;
11544 break;
11545 case 1:
11546 state.pipes = [state.pipes, dest];
11547 break;
11548 default:
11549 state.pipes.push(dest);
11550 break;
11551 }
11552 state.pipesCount += 1;
11553
11554 var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
11555 dest !== process.stdout &&
11556 dest !== process.stderr;
11557
11558 var endFn = doEnd ? onend : cleanup;
11559 if (state.endEmitted)
11560 process.nextTick(endFn);
11561 else
11562 src.once('end', endFn);
11563
11564 dest.on('unpipe', onunpipe);
11565 function onunpipe(readable) {
11566 if (readable !== src) return;
11567 cleanup();
11568 }
11569
11570 function onend() {
11571 dest.end();
11572 }
11573
11574 // when the dest drains, it reduces the awaitDrain counter
11575 // on the source. This would be more elegant with a .once()
11576 // handler in flow(), but adding and removing repeatedly is
11577 // too slow.
11578 var ondrain = pipeOnDrain(src);
11579 dest.on('drain', ondrain);
11580
11581 function cleanup() {
11582 // cleanup event handlers once the pipe is broken
11583 dest.removeListener('close', onclose);
11584 dest.removeListener('finish', onfinish);
11585 dest.removeListener('drain', ondrain);
11586 dest.removeListener('error', onerror);
11587 dest.removeListener('unpipe', onunpipe);
11588 src.removeListener('end', onend);
11589 src.removeListener('end', cleanup);
11590
11591 // if the reader is waiting for a drain event from this
11592 // specific writer, then it would cause it to never start
11593 // flowing again.
11594 // So, if this is awaiting a drain, then we just call it now.
11595 // If we don't know, then assume that we are waiting for one.
11596 if (!dest._writableState || dest._writableState.needDrain)
11597 ondrain();
11598 }
11599
11600 // if the dest has an error, then stop piping into it.
11601 // however, don't suppress the throwing behavior for this.
11602 function onerror(er) {
11603 unpipe();
11604 dest.removeListener('error', onerror);
11605 if (EE.listenerCount(dest, 'error') === 0)
11606 dest.emit('error', er);
11607 }
11608 // This is a brutally ugly hack to make sure that our error handler
11609 // is attached before any userland ones. NEVER DO THIS.
11610 if (!dest._events || !dest._events.error)
11611 dest.on('error', onerror);
11612 else if (isArray(dest._events.error))
11613 dest._events.error.unshift(onerror);
11614 else
11615 dest._events.error = [onerror, dest._events.error];
11616
11617
11618
11619 // Both close and finish should trigger unpipe, but only once.
11620 function onclose() {
11621 dest.removeListener('finish', onfinish);
11622 unpipe();
11623 }
11624 dest.once('close', onclose);
11625 function onfinish() {
11626 dest.removeListener('close', onclose);
11627 unpipe();
11628 }
11629 dest.once('finish', onfinish);
11630
11631 function unpipe() {
11632 src.unpipe(dest);
11633 }
11634
11635 // tell the dest that it's being piped to
11636 dest.emit('pipe', src);
11637
11638 // start the flow if it hasn't been started already.
11639 if (!state.flowing) {
11640 // the handler that waits for readable events after all
11641 // the data gets sucked out in flow.
11642 // This would be easier to follow with a .once() handler
11643 // in flow(), but that is too slow.
11644 this.on('readable', pipeOnReadable);
11645
11646 state.flowing = true;
11647 process.nextTick(function() {
11648 flow(src);
11649 });
11650 }
11651
11652 return dest;
11653};
11654
11655function pipeOnDrain(src) {
11656 return function() {
11657 var dest = this;
11658 var state = src._readableState;
11659 state.awaitDrain--;
11660 if (state.awaitDrain === 0)
11661 flow(src);
11662 };
11663}
11664
11665function flow(src) {
11666 var state = src._readableState;
11667 var chunk;
11668 state.awaitDrain = 0;
11669
11670 function write(dest, i, list) {
11671 var written = dest.write(chunk);
11672 if (false === written) {
11673 state.awaitDrain++;
11674 }
11675 }
11676
11677 while (state.pipesCount && null !== (chunk = src.read())) {
11678
11679 if (state.pipesCount === 1)
11680 write(state.pipes, 0, null);
11681 else
11682 forEach(state.pipes, write);
11683
11684 src.emit('data', chunk);
11685
11686 // if anyone needs a drain, then we have to wait for that.
11687 if (state.awaitDrain > 0)
11688 return;
11689 }
11690
11691 // if every destination was unpiped, either before entering this
11692 // function, or in the while loop, then stop flowing.
11693 //
11694 // NB: This is a pretty rare edge case.
11695 if (state.pipesCount === 0) {
11696 state.flowing = false;
11697
11698 // if there were data event listeners added, then switch to old mode.
11699 if (EE.listenerCount(src, 'data') > 0)
11700 emitDataEvents(src);
11701 return;
11702 }
11703
11704 // at this point, no one needed a drain, so we just ran out of data
11705 // on the next readable event, start it over again.
11706 state.ranOut = true;
11707}
11708
11709function pipeOnReadable() {
11710 if (this._readableState.ranOut) {
11711 this._readableState.ranOut = false;
11712 flow(this);
11713 }
11714}
11715
11716
11717Readable.prototype.unpipe = function(dest) {
11718 var state = this._readableState;
11719
11720 // if we're not piping anywhere, then do nothing.
11721 if (state.pipesCount === 0)
11722 return this;
11723
11724 // just one destination. most common case.
11725 if (state.pipesCount === 1) {
11726 // passed in one, but it's not the right one.
11727 if (dest && dest !== state.pipes)
11728 return this;
11729
11730 if (!dest)
11731 dest = state.pipes;
11732
11733 // got a match.
11734 state.pipes = null;
11735 state.pipesCount = 0;
11736 this.removeListener('readable', pipeOnReadable);
11737 state.flowing = false;
11738 if (dest)
11739 dest.emit('unpipe', this);
11740 return this;
11741 }
11742
11743 // slow case. multiple pipe destinations.
11744
11745 if (!dest) {
11746 // remove all.
11747 var dests = state.pipes;
11748 var len = state.pipesCount;
11749 state.pipes = null;
11750 state.pipesCount = 0;
11751 this.removeListener('readable', pipeOnReadable);
11752 state.flowing = false;
11753
11754 for (var i = 0; i < len; i++)
11755 dests[i].emit('unpipe', this);
11756 return this;
11757 }
11758
11759 // try to find the right one.
11760 var i = indexOf(state.pipes, dest);
11761 if (i === -1)
11762 return this;
11763
11764 state.pipes.splice(i, 1);
11765 state.pipesCount -= 1;
11766 if (state.pipesCount === 1)
11767 state.pipes = state.pipes[0];
11768
11769 dest.emit('unpipe', this);
11770
11771 return this;
11772};
11773
11774// set up data events if they are asked for
11775// Ensure readable listeners eventually get something
11776Readable.prototype.on = function(ev, fn) {
11777 var res = Stream.prototype.on.call(this, ev, fn);
11778
11779 if (ev === 'data' && !this._readableState.flowing)
11780 emitDataEvents(this);
11781
11782 if (ev === 'readable' && this.readable) {
11783 var state = this._readableState;
11784 if (!state.readableListening) {
11785 state.readableListening = true;
11786 state.emittedReadable = false;
11787 state.needReadable = true;
11788 if (!state.reading) {
11789 this.read(0);
11790 } else if (state.length) {
11791 emitReadable(this, state);
11792 }
11793 }
11794 }
11795
11796 return res;
11797};
11798Readable.prototype.addListener = Readable.prototype.on;
11799
11800// pause() and resume() are remnants of the legacy readable stream API
11801// If the user uses them, then switch into old mode.
11802Readable.prototype.resume = function() {
11803 emitDataEvents(this);
11804 this.read(0);
11805 this.emit('resume');
11806};
11807
11808Readable.prototype.pause = function() {
11809 emitDataEvents(this, true);
11810 this.emit('pause');
11811};
11812
11813function emitDataEvents(stream, startPaused) {
11814 var state = stream._readableState;
11815
11816 if (state.flowing) {
11817 // https://github.com/isaacs/readable-stream/issues/16
11818 throw new Error('Cannot switch to old mode now.');
11819 }
11820
11821 var paused = startPaused || false;
11822 var readable = false;
11823
11824 // convert to an old-style stream.
11825 stream.readable = true;
11826 stream.pipe = Stream.prototype.pipe;
11827 stream.on = stream.addListener = Stream.prototype.on;
11828
11829 stream.on('readable', function() {
11830 readable = true;
11831
11832 var c;
11833 while (!paused && (null !== (c = stream.read())))
11834 stream.emit('data', c);
11835
11836 if (c === null) {
11837 readable = false;
11838 stream._readableState.needReadable = true;
11839 }
11840 });
11841
11842 stream.pause = function() {
11843 paused = true;
11844 this.emit('pause');
11845 };
11846
11847 stream.resume = function() {
11848 paused = false;
11849 if (readable)
11850 process.nextTick(function() {
11851 stream.emit('readable');
11852 });
11853 else
11854 this.read(0);
11855 this.emit('resume');
11856 };
11857
11858 // now make it start, just in case it hadn't already.
11859 stream.emit('readable');
11860}
11861
11862// wrap an old-style stream as the async data source.
11863// This is *not* part of the readable stream interface.
11864// It is an ugly unfortunate mess of history.
11865Readable.prototype.wrap = function(stream) {
11866 var state = this._readableState;
11867 var paused = false;
11868
11869 var self = this;
11870 stream.on('end', function() {
11871 if (state.decoder && !state.ended) {
11872 var chunk = state.decoder.end();
11873 if (chunk && chunk.length)
11874 self.push(chunk);
11875 }
11876
11877 self.push(null);
11878 });
11879
11880 stream.on('data', function(chunk) {
11881 if (state.decoder)
11882 chunk = state.decoder.write(chunk);
11883
11884 // don't skip over falsy values in objectMode
11885 //if (state.objectMode && util.isNullOrUndefined(chunk))
11886 if (state.objectMode && (chunk === null || chunk === undefined))
11887 return;
11888 else if (!state.objectMode && (!chunk || !chunk.length))
11889 return;
11890
11891 var ret = self.push(chunk);
11892 if (!ret) {
11893 paused = true;
11894 stream.pause();
11895 }
11896 });
11897
11898 // proxy all the other methods.
11899 // important when wrapping filters and duplexes.
11900 for (var i in stream) {
11901 if (typeof stream[i] === 'function' &&
11902 typeof this[i] === 'undefined') {
11903 this[i] = function(method) { return function() {
11904 return stream[method].apply(stream, arguments);
11905 }}(i);
11906 }
11907 }
11908
11909 // proxy certain important events.
11910 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
11911 forEach(events, function(ev) {
11912 stream.on(ev, self.emit.bind(self, ev));
11913 });
11914
11915 // when we try to consume some more bytes, simply unpause the
11916 // underlying stream.
11917 self._read = function(n) {
11918 if (paused) {
11919 paused = false;
11920 stream.resume();
11921 }
11922 };
11923
11924 return self;
11925};
11926
11927
11928
11929// exposed for testing purposes only.
11930Readable._fromList = fromList;
11931
11932// Pluck off n bytes from an array of buffers.
11933// Length is the combined lengths of all the buffers in the list.
11934function fromList(n, state) {
11935 var list = state.buffer;
11936 var length = state.length;
11937 var stringMode = !!state.decoder;
11938 var objectMode = !!state.objectMode;
11939 var ret;
11940
11941 // nothing in the list, definitely empty.
11942 if (list.length === 0)
11943 return null;
11944
11945 if (length === 0)
11946 ret = null;
11947 else if (objectMode)
11948 ret = list.shift();
11949 else if (!n || n >= length) {
11950 // read it all, truncate the array.
11951 if (stringMode)
11952 ret = list.join('');
11953 else
11954 ret = Buffer.concat(list, length);
11955 list.length = 0;
11956 } else {
11957 // read just some of it.
11958 if (n < list[0].length) {
11959 // just take a part of the first list item.
11960 // slice is the same for buffers and strings.
11961 var buf = list[0];
11962 ret = buf.slice(0, n);
11963 list[0] = buf.slice(n);
11964 } else if (n === list[0].length) {
11965 // first list is a perfect match
11966 ret = list.shift();
11967 } else {
11968 // complex case.
11969 // we have enough to cover it, but it spans past the first buffer.
11970 if (stringMode)
11971 ret = '';
11972 else
11973 ret = new Buffer(n);
11974
11975 var c = 0;
11976 for (var i = 0, l = list.length; i < l && c < n; i++) {
11977 var buf = list[0];
11978 var cpy = Math.min(n - c, buf.length);
11979
11980 if (stringMode)
11981 ret += buf.slice(0, cpy);
11982 else
11983 buf.copy(ret, c, 0, cpy);
11984
11985 if (cpy < buf.length)
11986 list[0] = buf.slice(cpy);
11987 else
11988 list.shift();
11989
11990 c += cpy;
11991 }
11992 }
11993 }
11994
11995 return ret;
11996}
11997
11998function endReadable(stream) {
11999 var state = stream._readableState;
12000
12001 // If we get here before consuming all the bytes, then that is a
12002 // bug in node. Should never happen.
12003 if (state.length > 0)
12004 throw new Error('endReadable called on non-empty stream');
12005
12006 if (!state.endEmitted && state.calledRead) {
12007 state.ended = true;
12008 process.nextTick(function() {
12009 // Check that we didn't get one last unshift.
12010 if (!state.endEmitted && state.length === 0) {
12011 state.endEmitted = true;
12012 stream.readable = false;
12013 stream.emit('end');
12014 }
12015 });
12016 }
12017}
12018
12019function forEach (xs, f) {
12020 for (var i = 0, l = xs.length; i < l; i++) {
12021 f(xs[i], i);
12022 }
12023}
12024
12025function indexOf (xs, x) {
12026 for (var i = 0, l = xs.length; i < l; i++) {
12027 if (xs[i] === x) return i;
12028 }
12029 return -1;
12030}
12031
12032}).call(this,_dereq_(68))
12033},{"12":12,"13":13,"18":18,"24":24,"26":26,"68":68,"75":75,"79":79}],73:[function(_dereq_,module,exports){
12034// Copyright Joyent, Inc. and other Node contributors.
12035//
12036// Permission is hereby granted, free of charge, to any person obtaining a
12037// copy of this software and associated documentation files (the
12038// "Software"), to deal in the Software without restriction, including
12039// without limitation the rights to use, copy, modify, merge, publish,
12040// distribute, sublicense, and/or sell copies of the Software, and to permit
12041// persons to whom the Software is furnished to do so, subject to the
12042// following conditions:
12043//
12044// The above copyright notice and this permission notice shall be included
12045// in all copies or substantial portions of the Software.
12046//
12047// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12048// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12049// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12050// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12051// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12052// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12053// USE OR OTHER DEALINGS IN THE SOFTWARE.
12054
12055
12056// a transform stream is a readable/writable stream where you do
12057// something with the data. Sometimes it's called a "filter",
12058// but that's not a great name for it, since that implies a thing where
12059// some bits pass through, and others are simply ignored. (That would
12060// be a valid example of a transform, of course.)
12061//
12062// While the output is causally related to the input, it's not a
12063// necessarily symmetric or synchronous transformation. For example,
12064// a zlib stream might take multiple plain-text writes(), and then
12065// emit a single compressed chunk some time in the future.
12066//
12067// Here's how this works:
12068//
12069// The Transform stream has all the aspects of the readable and writable
12070// stream classes. When you write(chunk), that calls _write(chunk,cb)
12071// internally, and returns false if there's a lot of pending writes
12072// buffered up. When you call read(), that calls _read(n) until
12073// there's enough pending readable data buffered up.
12074//
12075// In a transform stream, the written data is placed in a buffer. When
12076// _read(n) is called, it transforms the queued up data, calling the
12077// buffered _write cb's as it consumes chunks. If consuming a single
12078// written chunk would result in multiple output chunks, then the first
12079// outputted bit calls the readcb, and subsequent chunks just go into
12080// the read buffer, and will cause it to emit 'readable' if necessary.
12081//
12082// This way, back-pressure is actually determined by the reading side,
12083// since _read has to be called to start processing a new chunk. However,
12084// a pathological inflate type of transform can cause excessive buffering
12085// here. For example, imagine a stream where every byte of input is
12086// interpreted as an integer from 0-255, and then results in that many
12087// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
12088// 1kb of data being output. In this case, you could write a very small
12089// amount of input, and end up with a very large amount of output. In
12090// such a pathological inflating mechanism, there'd be no way to tell
12091// the system to stop doing the transform. A single 4MB write could
12092// cause the system to run out of memory.
12093//
12094// However, even in such a pathological case, only a single written chunk
12095// would be consumed, and then the rest would wait (un-transformed) until
12096// the results of the previous transformed chunk were consumed.
12097
12098module.exports = Transform;
12099
12100var Duplex = _dereq_(70);
12101
12102/*<replacement>*/
12103var util = _dereq_(13);
12104util.inherits = _dereq_(24);
12105/*</replacement>*/
12106
12107util.inherits(Transform, Duplex);
12108
12109
12110function TransformState(options, stream) {
12111 this.afterTransform = function(er, data) {
12112 return afterTransform(stream, er, data);
12113 };
12114
12115 this.needTransform = false;
12116 this.transforming = false;
12117 this.writecb = null;
12118 this.writechunk = null;
12119}
12120
12121function afterTransform(stream, er, data) {
12122 var ts = stream._transformState;
12123 ts.transforming = false;
12124
12125 var cb = ts.writecb;
12126
12127 if (!cb)
12128 return stream.emit('error', new Error('no writecb in Transform class'));
12129
12130 ts.writechunk = null;
12131 ts.writecb = null;
12132
12133 if (data !== null && data !== undefined)
12134 stream.push(data);
12135
12136 if (cb)
12137 cb(er);
12138
12139 var rs = stream._readableState;
12140 rs.reading = false;
12141 if (rs.needReadable || rs.length < rs.highWaterMark) {
12142 stream._read(rs.highWaterMark);
12143 }
12144}
12145
12146
12147function Transform(options) {
12148 if (!(this instanceof Transform))
12149 return new Transform(options);
12150
12151 Duplex.call(this, options);
12152
12153 var ts = this._transformState = new TransformState(options, this);
12154
12155 // when the writable side finishes, then flush out anything remaining.
12156 var stream = this;
12157
12158 // start out asking for a readable event once data is transformed.
12159 this._readableState.needReadable = true;
12160
12161 // we have implemented the _read method, and done the other things
12162 // that Readable wants before the first _read call, so unset the
12163 // sync guard flag.
12164 this._readableState.sync = false;
12165
12166 this.once('finish', function() {
12167 if ('function' === typeof this._flush)
12168 this._flush(function(er) {
12169 done(stream, er);
12170 });
12171 else
12172 done(stream);
12173 });
12174}
12175
12176Transform.prototype.push = function(chunk, encoding) {
12177 this._transformState.needTransform = false;
12178 return Duplex.prototype.push.call(this, chunk, encoding);
12179};
12180
12181// This is the part where you do stuff!
12182// override this function in implementation classes.
12183// 'chunk' is an input chunk.
12184//
12185// Call `push(newChunk)` to pass along transformed output
12186// to the readable side. You may call 'push' zero or more times.
12187//
12188// Call `cb(err)` when you are done with this chunk. If you pass
12189// an error, then that'll put the hurt on the whole operation. If you
12190// never call cb(), then you'll never get another chunk.
12191Transform.prototype._transform = function(chunk, encoding, cb) {
12192 throw new Error('not implemented');
12193};
12194
12195Transform.prototype._write = function(chunk, encoding, cb) {
12196 var ts = this._transformState;
12197 ts.writecb = cb;
12198 ts.writechunk = chunk;
12199 ts.writeencoding = encoding;
12200 if (!ts.transforming) {
12201 var rs = this._readableState;
12202 if (ts.needTransform ||
12203 rs.needReadable ||
12204 rs.length < rs.highWaterMark)
12205 this._read(rs.highWaterMark);
12206 }
12207};
12208
12209// Doesn't matter what the args are here.
12210// _transform does all the work.
12211// That we got here means that the readable side wants more data.
12212Transform.prototype._read = function(n) {
12213 var ts = this._transformState;
12214
12215 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
12216 ts.transforming = true;
12217 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
12218 } else {
12219 // mark that we need a transform, so that any data that comes in
12220 // will get processed, now that we've asked for it.
12221 ts.needTransform = true;
12222 }
12223};
12224
12225
12226function done(stream, er) {
12227 if (er)
12228 return stream.emit('error', er);
12229
12230 // if there's nothing in the write buffer, then that means
12231 // that nothing more will ever be provided
12232 var ws = stream._writableState;
12233 var rs = stream._readableState;
12234 var ts = stream._transformState;
12235
12236 if (ws.length)
12237 throw new Error('calling transform done when ws.length != 0');
12238
12239 if (ts.transforming)
12240 throw new Error('calling transform done when still transforming');
12241
12242 return stream.push(null);
12243}
12244
12245},{"13":13,"24":24,"70":70}],74:[function(_dereq_,module,exports){
12246(function (process){
12247// Copyright Joyent, Inc. and other Node contributors.
12248//
12249// Permission is hereby granted, free of charge, to any person obtaining a
12250// copy of this software and associated documentation files (the
12251// "Software"), to deal in the Software without restriction, including
12252// without limitation the rights to use, copy, modify, merge, publish,
12253// distribute, sublicense, and/or sell copies of the Software, and to permit
12254// persons to whom the Software is furnished to do so, subject to the
12255// following conditions:
12256//
12257// The above copyright notice and this permission notice shall be included
12258// in all copies or substantial portions of the Software.
12259//
12260// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12261// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12262// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12263// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12264// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12265// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12266// USE OR OTHER DEALINGS IN THE SOFTWARE.
12267
12268// A bit simpler than readable streams.
12269// Implement an async ._write(chunk, cb), and it'll handle all
12270// the drain event emission and buffering.
12271
12272module.exports = Writable;
12273
12274/*<replacement>*/
12275var Buffer = _dereq_(12).Buffer;
12276/*</replacement>*/
12277
12278Writable.WritableState = WritableState;
12279
12280
12281/*<replacement>*/
12282var util = _dereq_(13);
12283util.inherits = _dereq_(24);
12284/*</replacement>*/
12285
12286var Stream = _dereq_(79);
12287
12288util.inherits(Writable, Stream);
12289
12290function WriteReq(chunk, encoding, cb) {
12291 this.chunk = chunk;
12292 this.encoding = encoding;
12293 this.callback = cb;
12294}
12295
12296function WritableState(options, stream) {
12297 options = options || {};
12298
12299 // the point at which write() starts returning false
12300 // Note: 0 is a valid value, means that we always return false if
12301 // the entire buffer is not flushed immediately on write()
12302 var hwm = options.highWaterMark;
12303 this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
12304
12305 // object stream flag to indicate whether or not this stream
12306 // contains buffers or objects.
12307 this.objectMode = !!options.objectMode;
12308
12309 // cast to ints.
12310 this.highWaterMark = ~~this.highWaterMark;
12311
12312 this.needDrain = false;
12313 // at the start of calling end()
12314 this.ending = false;
12315 // when end() has been called, and returned
12316 this.ended = false;
12317 // when 'finish' is emitted
12318 this.finished = false;
12319
12320 // should we decode strings into buffers before passing to _write?
12321 // this is here so that some node-core streams can optimize string
12322 // handling at a lower level.
12323 var noDecode = options.decodeStrings === false;
12324 this.decodeStrings = !noDecode;
12325
12326 // Crypto is kind of old and crusty. Historically, its default string
12327 // encoding is 'binary' so we have to make this configurable.
12328 // Everything else in the universe uses 'utf8', though.
12329 this.defaultEncoding = options.defaultEncoding || 'utf8';
12330
12331 // not an actual buffer we keep track of, but a measurement
12332 // of how much we're waiting to get pushed to some underlying
12333 // socket or file.
12334 this.length = 0;
12335
12336 // a flag to see when we're in the middle of a write.
12337 this.writing = false;
12338
12339 // a flag to be able to tell if the onwrite cb is called immediately,
12340 // or on a later tick. We set this to true at first, becuase any
12341 // actions that shouldn't happen until "later" should generally also
12342 // not happen before the first write call.
12343 this.sync = true;
12344
12345 // a flag to know if we're processing previously buffered items, which
12346 // may call the _write() callback in the same tick, so that we don't
12347 // end up in an overlapped onwrite situation.
12348 this.bufferProcessing = false;
12349
12350 // the callback that's passed to _write(chunk,cb)
12351 this.onwrite = function(er) {
12352 onwrite(stream, er);
12353 };
12354
12355 // the callback that the user supplies to write(chunk,encoding,cb)
12356 this.writecb = null;
12357
12358 // the amount that is being written when _write is called.
12359 this.writelen = 0;
12360
12361 this.buffer = [];
12362
12363 // True if the error was already emitted and should not be thrown again
12364 this.errorEmitted = false;
12365}
12366
12367function Writable(options) {
12368 var Duplex = _dereq_(70);
12369
12370 // Writable ctor is applied to Duplexes, though they're not
12371 // instanceof Writable, they're instanceof Readable.
12372 if (!(this instanceof Writable) && !(this instanceof Duplex))
12373 return new Writable(options);
12374
12375 this._writableState = new WritableState(options, this);
12376
12377 // legacy.
12378 this.writable = true;
12379
12380 Stream.call(this);
12381}
12382
12383// Otherwise people can pipe Writable streams, which is just wrong.
12384Writable.prototype.pipe = function() {
12385 this.emit('error', new Error('Cannot pipe. Not readable.'));
12386};
12387
12388
12389function writeAfterEnd(stream, state, cb) {
12390 var er = new Error('write after end');
12391 // TODO: defer error events consistently everywhere, not just the cb
12392 stream.emit('error', er);
12393 process.nextTick(function() {
12394 cb(er);
12395 });
12396}
12397
12398// If we get something that is not a buffer, string, null, or undefined,
12399// and we're not in objectMode, then that's an error.
12400// Otherwise stream chunks are all considered to be of length=1, and the
12401// watermarks determine how many objects to keep in the buffer, rather than
12402// how many bytes or characters.
12403function validChunk(stream, state, chunk, cb) {
12404 var valid = true;
12405 if (!Buffer.isBuffer(chunk) &&
12406 'string' !== typeof chunk &&
12407 chunk !== null &&
12408 chunk !== undefined &&
12409 !state.objectMode) {
12410 var er = new TypeError('Invalid non-string/buffer chunk');
12411 stream.emit('error', er);
12412 process.nextTick(function() {
12413 cb(er);
12414 });
12415 valid = false;
12416 }
12417 return valid;
12418}
12419
12420Writable.prototype.write = function(chunk, encoding, cb) {
12421 var state = this._writableState;
12422 var ret = false;
12423
12424 if (typeof encoding === 'function') {
12425 cb = encoding;
12426 encoding = null;
12427 }
12428
12429 if (Buffer.isBuffer(chunk))
12430 encoding = 'buffer';
12431 else if (!encoding)
12432 encoding = state.defaultEncoding;
12433
12434 if (typeof cb !== 'function')
12435 cb = function() {};
12436
12437 if (state.ended)
12438 writeAfterEnd(this, state, cb);
12439 else if (validChunk(this, state, chunk, cb))
12440 ret = writeOrBuffer(this, state, chunk, encoding, cb);
12441
12442 return ret;
12443};
12444
12445function decodeChunk(state, chunk, encoding) {
12446 if (!state.objectMode &&
12447 state.decodeStrings !== false &&
12448 typeof chunk === 'string') {
12449 chunk = new Buffer(chunk, encoding);
12450 }
12451 return chunk;
12452}
12453
12454// if we're already writing something, then just put this
12455// in the queue, and wait our turn. Otherwise, call _write
12456// If we return false, then we need a drain event, so set that flag.
12457function writeOrBuffer(stream, state, chunk, encoding, cb) {
12458 chunk = decodeChunk(state, chunk, encoding);
12459 if (Buffer.isBuffer(chunk))
12460 encoding = 'buffer';
12461 var len = state.objectMode ? 1 : chunk.length;
12462
12463 state.length += len;
12464
12465 var ret = state.length < state.highWaterMark;
12466 // we must ensure that previous needDrain will not be reset to false.
12467 if (!ret)
12468 state.needDrain = true;
12469
12470 if (state.writing)
12471 state.buffer.push(new WriteReq(chunk, encoding, cb));
12472 else
12473 doWrite(stream, state, len, chunk, encoding, cb);
12474
12475 return ret;
12476}
12477
12478function doWrite(stream, state, len, chunk, encoding, cb) {
12479 state.writelen = len;
12480 state.writecb = cb;
12481 state.writing = true;
12482 state.sync = true;
12483 stream._write(chunk, encoding, state.onwrite);
12484 state.sync = false;
12485}
12486
12487function onwriteError(stream, state, sync, er, cb) {
12488 if (sync)
12489 process.nextTick(function() {
12490 cb(er);
12491 });
12492 else
12493 cb(er);
12494
12495 stream._writableState.errorEmitted = true;
12496 stream.emit('error', er);
12497}
12498
12499function onwriteStateUpdate(state) {
12500 state.writing = false;
12501 state.writecb = null;
12502 state.length -= state.writelen;
12503 state.writelen = 0;
12504}
12505
12506function onwrite(stream, er) {
12507 var state = stream._writableState;
12508 var sync = state.sync;
12509 var cb = state.writecb;
12510
12511 onwriteStateUpdate(state);
12512
12513 if (er)
12514 onwriteError(stream, state, sync, er, cb);
12515 else {
12516 // Check if we're actually ready to finish, but don't emit yet
12517 var finished = needFinish(stream, state);
12518
12519 if (!finished && !state.bufferProcessing && state.buffer.length)
12520 clearBuffer(stream, state);
12521
12522 if (sync) {
12523 process.nextTick(function() {
12524 afterWrite(stream, state, finished, cb);
12525 });
12526 } else {
12527 afterWrite(stream, state, finished, cb);
12528 }
12529 }
12530}
12531
12532function afterWrite(stream, state, finished, cb) {
12533 if (!finished)
12534 onwriteDrain(stream, state);
12535 cb();
12536 if (finished)
12537 finishMaybe(stream, state);
12538}
12539
12540// Must force callback to be called on nextTick, so that we don't
12541// emit 'drain' before the write() consumer gets the 'false' return
12542// value, and has a chance to attach a 'drain' listener.
12543function onwriteDrain(stream, state) {
12544 if (state.length === 0 && state.needDrain) {
12545 state.needDrain = false;
12546 stream.emit('drain');
12547 }
12548}
12549
12550
12551// if there's something in the buffer waiting, then process it
12552function clearBuffer(stream, state) {
12553 state.bufferProcessing = true;
12554
12555 for (var c = 0; c < state.buffer.length; c++) {
12556 var entry = state.buffer[c];
12557 var chunk = entry.chunk;
12558 var encoding = entry.encoding;
12559 var cb = entry.callback;
12560 var len = state.objectMode ? 1 : chunk.length;
12561
12562 doWrite(stream, state, len, chunk, encoding, cb);
12563
12564 // if we didn't call the onwrite immediately, then
12565 // it means that we need to wait until it does.
12566 // also, that means that the chunk and cb are currently
12567 // being processed, so move the buffer counter past them.
12568 if (state.writing) {
12569 c++;
12570 break;
12571 }
12572 }
12573
12574 state.bufferProcessing = false;
12575 if (c < state.buffer.length)
12576 state.buffer = state.buffer.slice(c);
12577 else
12578 state.buffer.length = 0;
12579}
12580
12581Writable.prototype._write = function(chunk, encoding, cb) {
12582 cb(new Error('not implemented'));
12583};
12584
12585Writable.prototype.end = function(chunk, encoding, cb) {
12586 var state = this._writableState;
12587
12588 if (typeof chunk === 'function') {
12589 cb = chunk;
12590 chunk = null;
12591 encoding = null;
12592 } else if (typeof encoding === 'function') {
12593 cb = encoding;
12594 encoding = null;
12595 }
12596
12597 if (typeof chunk !== 'undefined' && chunk !== null)
12598 this.write(chunk, encoding);
12599
12600 // ignore unnecessary end() calls.
12601 if (!state.ending && !state.finished)
12602 endWritable(this, state, cb);
12603};
12604
12605
12606function needFinish(stream, state) {
12607 return (state.ending &&
12608 state.length === 0 &&
12609 !state.finished &&
12610 !state.writing);
12611}
12612
12613function finishMaybe(stream, state) {
12614 var need = needFinish(stream, state);
12615 if (need) {
12616 state.finished = true;
12617 stream.emit('finish');
12618 }
12619 return need;
12620}
12621
12622function endWritable(stream, state, cb) {
12623 state.ending = true;
12624 finishMaybe(stream, state);
12625 if (cb) {
12626 if (state.finished)
12627 process.nextTick(cb);
12628 else
12629 stream.once('finish', cb);
12630 }
12631 state.ended = true;
12632}
12633
12634}).call(this,_dereq_(68))
12635},{"12":12,"13":13,"24":24,"68":68,"70":70,"79":79}],75:[function(_dereq_,module,exports){
12636// Copyright Joyent, Inc. and other Node contributors.
12637//
12638// Permission is hereby granted, free of charge, to any person obtaining a
12639// copy of this software and associated documentation files (the
12640// "Software"), to deal in the Software without restriction, including
12641// without limitation the rights to use, copy, modify, merge, publish,
12642// distribute, sublicense, and/or sell copies of the Software, and to permit
12643// persons to whom the Software is furnished to do so, subject to the
12644// following conditions:
12645//
12646// The above copyright notice and this permission notice shall be included
12647// in all copies or substantial portions of the Software.
12648//
12649// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12650// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12651// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12652// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12653// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12654// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12655// USE OR OTHER DEALINGS IN THE SOFTWARE.
12656
12657var Buffer = _dereq_(12).Buffer;
12658
12659var isBufferEncoding = Buffer.isEncoding
12660 || function(encoding) {
12661 switch (encoding && encoding.toLowerCase()) {
12662 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;
12663 default: return false;
12664 }
12665 }
12666
12667
12668function assertEncoding(encoding) {
12669 if (encoding && !isBufferEncoding(encoding)) {
12670 throw new Error('Unknown encoding: ' + encoding);
12671 }
12672}
12673
12674// StringDecoder provides an interface for efficiently splitting a series of
12675// buffers into a series of JS strings without breaking apart multi-byte
12676// characters. CESU-8 is handled as part of the UTF-8 encoding.
12677//
12678// @TODO Handling all encodings inside a single object makes it very difficult
12679// to reason about this code, so it should be split up in the future.
12680// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
12681// points as used by CESU-8.
12682var StringDecoder = exports.StringDecoder = function(encoding) {
12683 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
12684 assertEncoding(encoding);
12685 switch (this.encoding) {
12686 case 'utf8':
12687 // CESU-8 represents each of Surrogate Pair by 3-bytes
12688 this.surrogateSize = 3;
12689 break;
12690 case 'ucs2':
12691 case 'utf16le':
12692 // UTF-16 represents each of Surrogate Pair by 2-bytes
12693 this.surrogateSize = 2;
12694 this.detectIncompleteChar = utf16DetectIncompleteChar;
12695 break;
12696 case 'base64':
12697 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
12698 this.surrogateSize = 3;
12699 this.detectIncompleteChar = base64DetectIncompleteChar;
12700 break;
12701 default:
12702 this.write = passThroughWrite;
12703 return;
12704 }
12705
12706 // Enough space to store all bytes of a single character. UTF-8 needs 4
12707 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
12708 this.charBuffer = new Buffer(6);
12709 // Number of bytes received for the current incomplete multi-byte character.
12710 this.charReceived = 0;
12711 // Number of bytes expected for the current incomplete multi-byte character.
12712 this.charLength = 0;
12713};
12714
12715
12716// write decodes the given buffer and returns it as JS string that is
12717// guaranteed to not contain any partial multi-byte characters. Any partial
12718// character found at the end of the buffer is buffered up, and will be
12719// returned when calling write again with the remaining bytes.
12720//
12721// Note: Converting a Buffer containing an orphan surrogate to a String
12722// currently works, but converting a String to a Buffer (via `new Buffer`, or
12723// Buffer#write) will replace incomplete surrogates with the unicode
12724// replacement character. See https://codereview.chromium.org/121173009/ .
12725StringDecoder.prototype.write = function(buffer) {
12726 var charStr = '';
12727 // if our last write ended with an incomplete multibyte character
12728 while (this.charLength) {
12729 // determine how many remaining bytes this buffer has to offer for this char
12730 var available = (buffer.length >= this.charLength - this.charReceived) ?
12731 this.charLength - this.charReceived :
12732 buffer.length;
12733
12734 // add the new bytes to the char buffer
12735 buffer.copy(this.charBuffer, this.charReceived, 0, available);
12736 this.charReceived += available;
12737
12738 if (this.charReceived < this.charLength) {
12739 // still not enough chars in this buffer? wait for more ...
12740 return '';
12741 }
12742
12743 // remove bytes belonging to the current character from the buffer
12744 buffer = buffer.slice(available, buffer.length);
12745
12746 // get the character that was split
12747 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
12748
12749 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
12750 var charCode = charStr.charCodeAt(charStr.length - 1);
12751 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
12752 this.charLength += this.surrogateSize;
12753 charStr = '';
12754 continue;
12755 }
12756 this.charReceived = this.charLength = 0;
12757
12758 // if there are no more bytes in this buffer, just emit our char
12759 if (buffer.length === 0) {
12760 return charStr;
12761 }
12762 break;
12763 }
12764
12765 // determine and set charLength / charReceived
12766 this.detectIncompleteChar(buffer);
12767
12768 var end = buffer.length;
12769 if (this.charLength) {
12770 // buffer the incomplete character bytes we got
12771 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
12772 end -= this.charReceived;
12773 }
12774
12775 charStr += buffer.toString(this.encoding, 0, end);
12776
12777 var end = charStr.length - 1;
12778 var charCode = charStr.charCodeAt(end);
12779 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
12780 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
12781 var size = this.surrogateSize;
12782 this.charLength += size;
12783 this.charReceived += size;
12784 this.charBuffer.copy(this.charBuffer, size, 0, size);
12785 buffer.copy(this.charBuffer, 0, 0, size);
12786 return charStr.substring(0, end);
12787 }
12788
12789 // or just emit the charStr
12790 return charStr;
12791};
12792
12793// detectIncompleteChar determines if there is an incomplete UTF-8 character at
12794// the end of the given buffer. If so, it sets this.charLength to the byte
12795// length that character, and sets this.charReceived to the number of bytes
12796// that are available for this character.
12797StringDecoder.prototype.detectIncompleteChar = function(buffer) {
12798 // determine how many bytes we have to check at the end of this buffer
12799 var i = (buffer.length >= 3) ? 3 : buffer.length;
12800
12801 // Figure out if one of the last i bytes of our buffer announces an
12802 // incomplete char.
12803 for (; i > 0; i--) {
12804 var c = buffer[buffer.length - i];
12805
12806 // See http://en.wikipedia.org/wiki/UTF-8#Description
12807
12808 // 110XXXXX
12809 if (i == 1 && c >> 5 == 0x06) {
12810 this.charLength = 2;
12811 break;
12812 }
12813
12814 // 1110XXXX
12815 if (i <= 2 && c >> 4 == 0x0E) {
12816 this.charLength = 3;
12817 break;
12818 }
12819
12820 // 11110XXX
12821 if (i <= 3 && c >> 3 == 0x1E) {
12822 this.charLength = 4;
12823 break;
12824 }
12825 }
12826 this.charReceived = i;
12827};
12828
12829StringDecoder.prototype.end = function(buffer) {
12830 var res = '';
12831 if (buffer && buffer.length)
12832 res = this.write(buffer);
12833
12834 if (this.charReceived) {
12835 var cr = this.charReceived;
12836 var buf = this.charBuffer;
12837 var enc = this.encoding;
12838 res += buf.slice(0, cr).toString(enc);
12839 }
12840
12841 return res;
12842};
12843
12844function passThroughWrite(buffer) {
12845 return buffer.toString(this.encoding);
12846}
12847
12848function utf16DetectIncompleteChar(buffer) {
12849 this.charReceived = buffer.length % 2;
12850 this.charLength = this.charReceived ? 2 : 0;
12851}
12852
12853function base64DetectIncompleteChar(buffer) {
12854 this.charReceived = buffer.length % 3;
12855 this.charLength = this.charReceived ? 3 : 0;
12856}
12857
12858},{"12":12}],76:[function(_dereq_,module,exports){
12859var Stream = _dereq_(79); // hack to fix a circular dependency issue when used with browserify
12860exports = module.exports = _dereq_(72);
12861exports.Stream = Stream;
12862exports.Readable = exports;
12863exports.Writable = _dereq_(74);
12864exports.Duplex = _dereq_(70);
12865exports.Transform = _dereq_(73);
12866exports.PassThrough = _dereq_(71);
12867
12868},{"70":70,"71":71,"72":72,"73":73,"74":74,"79":79}],77:[function(_dereq_,module,exports){
12869/* eslint-disable node/no-deprecated-api */
12870var buffer = _dereq_(12)
12871var Buffer = buffer.Buffer
12872
12873// alternative to using Object.keys for old browsers
12874function copyProps (src, dst) {
12875 for (var key in src) {
12876 dst[key] = src[key]
12877 }
12878}
12879if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
12880 module.exports = buffer
12881} else {
12882 // Copy properties from require('buffer')
12883 copyProps(buffer, exports)
12884 exports.Buffer = SafeBuffer
12885}
12886
12887function SafeBuffer (arg, encodingOrOffset, length) {
12888 return Buffer(arg, encodingOrOffset, length)
12889}
12890
12891SafeBuffer.prototype = Object.create(Buffer.prototype)
12892
12893// Copy static methods from Buffer
12894copyProps(Buffer, SafeBuffer)
12895
12896SafeBuffer.from = function (arg, encodingOrOffset, length) {
12897 if (typeof arg === 'number') {
12898 throw new TypeError('Argument must not be a number')
12899 }
12900 return Buffer(arg, encodingOrOffset, length)
12901}
12902
12903SafeBuffer.alloc = function (size, fill, encoding) {
12904 if (typeof size !== 'number') {
12905 throw new TypeError('Argument must be a number')
12906 }
12907 var buf = Buffer(size)
12908 if (fill !== undefined) {
12909 if (typeof encoding === 'string') {
12910 buf.fill(fill, encoding)
12911 } else {
12912 buf.fill(fill)
12913 }
12914 } else {
12915 buf.fill(0)
12916 }
12917 return buf
12918}
12919
12920SafeBuffer.allocUnsafe = function (size) {
12921 if (typeof size !== 'number') {
12922 throw new TypeError('Argument must be a number')
12923 }
12924 return Buffer(size)
12925}
12926
12927SafeBuffer.allocUnsafeSlow = function (size) {
12928 if (typeof size !== 'number') {
12929 throw new TypeError('Argument must be a number')
12930 }
12931 return buffer.SlowBuffer(size)
12932}
12933
12934},{"12":12}],78:[function(_dereq_,module,exports){
12935(function (factory) {
12936 if (typeof exports === 'object') {
12937 // Node/CommonJS
12938 module.exports = factory();
12939 } else if (typeof define === 'function' && define.amd) {
12940 // AMD
12941 define(factory);
12942 } else {
12943 // Browser globals (with support for web workers)
12944 var glob;
12945
12946 try {
12947 glob = window;
12948 } catch (e) {
12949 glob = self;
12950 }
12951
12952 glob.SparkMD5 = factory();
12953 }
12954}(function (undefined) {
12955
12956 'use strict';
12957
12958 /*
12959 * Fastest md5 implementation around (JKM md5).
12960 * Credits: Joseph Myers
12961 *
12962 * @see http://www.myersdaily.org/joseph/javascript/md5-text.html
12963 * @see http://jsperf.com/md5-shootout/7
12964 */
12965
12966 /* this function is much faster,
12967 so if possible we use it. Some IEs
12968 are the only ones I know of that
12969 need the idiotic second function,
12970 generated by an if clause. */
12971 var add32 = function (a, b) {
12972 return (a + b) & 0xFFFFFFFF;
12973 },
12974 hex_chr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
12975
12976
12977 function cmn(q, a, b, x, s, t) {
12978 a = add32(add32(a, q), add32(x, t));
12979 return add32((a << s) | (a >>> (32 - s)), b);
12980 }
12981
12982 function md5cycle(x, k) {
12983 var a = x[0],
12984 b = x[1],
12985 c = x[2],
12986 d = x[3];
12987
12988 a += (b & c | ~b & d) + k[0] - 680876936 | 0;
12989 a = (a << 7 | a >>> 25) + b | 0;
12990 d += (a & b | ~a & c) + k[1] - 389564586 | 0;
12991 d = (d << 12 | d >>> 20) + a | 0;
12992 c += (d & a | ~d & b) + k[2] + 606105819 | 0;
12993 c = (c << 17 | c >>> 15) + d | 0;
12994 b += (c & d | ~c & a) + k[3] - 1044525330 | 0;
12995 b = (b << 22 | b >>> 10) + c | 0;
12996 a += (b & c | ~b & d) + k[4] - 176418897 | 0;
12997 a = (a << 7 | a >>> 25) + b | 0;
12998 d += (a & b | ~a & c) + k[5] + 1200080426 | 0;
12999 d = (d << 12 | d >>> 20) + a | 0;
13000 c += (d & a | ~d & b) + k[6] - 1473231341 | 0;
13001 c = (c << 17 | c >>> 15) + d | 0;
13002 b += (c & d | ~c & a) + k[7] - 45705983 | 0;
13003 b = (b << 22 | b >>> 10) + c | 0;
13004 a += (b & c | ~b & d) + k[8] + 1770035416 | 0;
13005 a = (a << 7 | a >>> 25) + b | 0;
13006 d += (a & b | ~a & c) + k[9] - 1958414417 | 0;
13007 d = (d << 12 | d >>> 20) + a | 0;
13008 c += (d & a | ~d & b) + k[10] - 42063 | 0;
13009 c = (c << 17 | c >>> 15) + d | 0;
13010 b += (c & d | ~c & a) + k[11] - 1990404162 | 0;
13011 b = (b << 22 | b >>> 10) + c | 0;
13012 a += (b & c | ~b & d) + k[12] + 1804603682 | 0;
13013 a = (a << 7 | a >>> 25) + b | 0;
13014 d += (a & b | ~a & c) + k[13] - 40341101 | 0;
13015 d = (d << 12 | d >>> 20) + a | 0;
13016 c += (d & a | ~d & b) + k[14] - 1502002290 | 0;
13017 c = (c << 17 | c >>> 15) + d | 0;
13018 b += (c & d | ~c & a) + k[15] + 1236535329 | 0;
13019 b = (b << 22 | b >>> 10) + c | 0;
13020
13021 a += (b & d | c & ~d) + k[1] - 165796510 | 0;
13022 a = (a << 5 | a >>> 27) + b | 0;
13023 d += (a & c | b & ~c) + k[6] - 1069501632 | 0;
13024 d = (d << 9 | d >>> 23) + a | 0;
13025 c += (d & b | a & ~b) + k[11] + 643717713 | 0;
13026 c = (c << 14 | c >>> 18) + d | 0;
13027 b += (c & a | d & ~a) + k[0] - 373897302 | 0;
13028 b = (b << 20 | b >>> 12) + c | 0;
13029 a += (b & d | c & ~d) + k[5] - 701558691 | 0;
13030 a = (a << 5 | a >>> 27) + b | 0;
13031 d += (a & c | b & ~c) + k[10] + 38016083 | 0;
13032 d = (d << 9 | d >>> 23) + a | 0;
13033 c += (d & b | a & ~b) + k[15] - 660478335 | 0;
13034 c = (c << 14 | c >>> 18) + d | 0;
13035 b += (c & a | d & ~a) + k[4] - 405537848 | 0;
13036 b = (b << 20 | b >>> 12) + c | 0;
13037 a += (b & d | c & ~d) + k[9] + 568446438 | 0;
13038 a = (a << 5 | a >>> 27) + b | 0;
13039 d += (a & c | b & ~c) + k[14] - 1019803690 | 0;
13040 d = (d << 9 | d >>> 23) + a | 0;
13041 c += (d & b | a & ~b) + k[3] - 187363961 | 0;
13042 c = (c << 14 | c >>> 18) + d | 0;
13043 b += (c & a | d & ~a) + k[8] + 1163531501 | 0;
13044 b = (b << 20 | b >>> 12) + c | 0;
13045 a += (b & d | c & ~d) + k[13] - 1444681467 | 0;
13046 a = (a << 5 | a >>> 27) + b | 0;
13047 d += (a & c | b & ~c) + k[2] - 51403784 | 0;
13048 d = (d << 9 | d >>> 23) + a | 0;
13049 c += (d & b | a & ~b) + k[7] + 1735328473 | 0;
13050 c = (c << 14 | c >>> 18) + d | 0;
13051 b += (c & a | d & ~a) + k[12] - 1926607734 | 0;
13052 b = (b << 20 | b >>> 12) + c | 0;
13053
13054 a += (b ^ c ^ d) + k[5] - 378558 | 0;
13055 a = (a << 4 | a >>> 28) + b | 0;
13056 d += (a ^ b ^ c) + k[8] - 2022574463 | 0;
13057 d = (d << 11 | d >>> 21) + a | 0;
13058 c += (d ^ a ^ b) + k[11] + 1839030562 | 0;
13059 c = (c << 16 | c >>> 16) + d | 0;
13060 b += (c ^ d ^ a) + k[14] - 35309556 | 0;
13061 b = (b << 23 | b >>> 9) + c | 0;
13062 a += (b ^ c ^ d) + k[1] - 1530992060 | 0;
13063 a = (a << 4 | a >>> 28) + b | 0;
13064 d += (a ^ b ^ c) + k[4] + 1272893353 | 0;
13065 d = (d << 11 | d >>> 21) + a | 0;
13066 c += (d ^ a ^ b) + k[7] - 155497632 | 0;
13067 c = (c << 16 | c >>> 16) + d | 0;
13068 b += (c ^ d ^ a) + k[10] - 1094730640 | 0;
13069 b = (b << 23 | b >>> 9) + c | 0;
13070 a += (b ^ c ^ d) + k[13] + 681279174 | 0;
13071 a = (a << 4 | a >>> 28) + b | 0;
13072 d += (a ^ b ^ c) + k[0] - 358537222 | 0;
13073 d = (d << 11 | d >>> 21) + a | 0;
13074 c += (d ^ a ^ b) + k[3] - 722521979 | 0;
13075 c = (c << 16 | c >>> 16) + d | 0;
13076 b += (c ^ d ^ a) + k[6] + 76029189 | 0;
13077 b = (b << 23 | b >>> 9) + c | 0;
13078 a += (b ^ c ^ d) + k[9] - 640364487 | 0;
13079 a = (a << 4 | a >>> 28) + b | 0;
13080 d += (a ^ b ^ c) + k[12] - 421815835 | 0;
13081 d = (d << 11 | d >>> 21) + a | 0;
13082 c += (d ^ a ^ b) + k[15] + 530742520 | 0;
13083 c = (c << 16 | c >>> 16) + d | 0;
13084 b += (c ^ d ^ a) + k[2] - 995338651 | 0;
13085 b = (b << 23 | b >>> 9) + c | 0;
13086
13087 a += (c ^ (b | ~d)) + k[0] - 198630844 | 0;
13088 a = (a << 6 | a >>> 26) + b | 0;
13089 d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0;
13090 d = (d << 10 | d >>> 22) + a | 0;
13091 c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0;
13092 c = (c << 15 | c >>> 17) + d | 0;
13093 b += (d ^ (c | ~a)) + k[5] - 57434055 | 0;
13094 b = (b << 21 |b >>> 11) + c | 0;
13095 a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0;
13096 a = (a << 6 | a >>> 26) + b | 0;
13097 d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0;
13098 d = (d << 10 | d >>> 22) + a | 0;
13099 c += (a ^ (d | ~b)) + k[10] - 1051523 | 0;
13100 c = (c << 15 | c >>> 17) + d | 0;
13101 b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0;
13102 b = (b << 21 |b >>> 11) + c | 0;
13103 a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0;
13104 a = (a << 6 | a >>> 26) + b | 0;
13105 d += (b ^ (a | ~c)) + k[15] - 30611744 | 0;
13106 d = (d << 10 | d >>> 22) + a | 0;
13107 c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0;
13108 c = (c << 15 | c >>> 17) + d | 0;
13109 b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0;
13110 b = (b << 21 |b >>> 11) + c | 0;
13111 a += (c ^ (b | ~d)) + k[4] - 145523070 | 0;
13112 a = (a << 6 | a >>> 26) + b | 0;
13113 d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0;
13114 d = (d << 10 | d >>> 22) + a | 0;
13115 c += (a ^ (d | ~b)) + k[2] + 718787259 | 0;
13116 c = (c << 15 | c >>> 17) + d | 0;
13117 b += (d ^ (c | ~a)) + k[9] - 343485551 | 0;
13118 b = (b << 21 | b >>> 11) + c | 0;
13119
13120 x[0] = a + x[0] | 0;
13121 x[1] = b + x[1] | 0;
13122 x[2] = c + x[2] | 0;
13123 x[3] = d + x[3] | 0;
13124 }
13125
13126 function md5blk(s) {
13127 var md5blks = [],
13128 i; /* Andy King said do it this way. */
13129
13130 for (i = 0; i < 64; i += 4) {
13131 md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
13132 }
13133 return md5blks;
13134 }
13135
13136 function md5blk_array(a) {
13137 var md5blks = [],
13138 i; /* Andy King said do it this way. */
13139
13140 for (i = 0; i < 64; i += 4) {
13141 md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);
13142 }
13143 return md5blks;
13144 }
13145
13146 function md51(s) {
13147 var n = s.length,
13148 state = [1732584193, -271733879, -1732584194, 271733878],
13149 i,
13150 length,
13151 tail,
13152 tmp,
13153 lo,
13154 hi;
13155
13156 for (i = 64; i <= n; i += 64) {
13157 md5cycle(state, md5blk(s.substring(i - 64, i)));
13158 }
13159 s = s.substring(i - 64);
13160 length = s.length;
13161 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
13162 for (i = 0; i < length; i += 1) {
13163 tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
13164 }
13165 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13166 if (i > 55) {
13167 md5cycle(state, tail);
13168 for (i = 0; i < 16; i += 1) {
13169 tail[i] = 0;
13170 }
13171 }
13172
13173 // Beware that the final length might not fit in 32 bits so we take care of that
13174 tmp = n * 8;
13175 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
13176 lo = parseInt(tmp[2], 16);
13177 hi = parseInt(tmp[1], 16) || 0;
13178
13179 tail[14] = lo;
13180 tail[15] = hi;
13181
13182 md5cycle(state, tail);
13183 return state;
13184 }
13185
13186 function md51_array(a) {
13187 var n = a.length,
13188 state = [1732584193, -271733879, -1732584194, 271733878],
13189 i,
13190 length,
13191 tail,
13192 tmp,
13193 lo,
13194 hi;
13195
13196 for (i = 64; i <= n; i += 64) {
13197 md5cycle(state, md5blk_array(a.subarray(i - 64, i)));
13198 }
13199
13200 // Not sure if it is a bug, however IE10 will always produce a sub array of length 1
13201 // containing the last element of the parent array if the sub array specified starts
13202 // beyond the length of the parent array - weird.
13203 // https://connect.microsoft.com/IE/feedback/details/771452/typed-array-subarray-issue
13204 a = (i - 64) < n ? a.subarray(i - 64) : new Uint8Array(0);
13205
13206 length = a.length;
13207 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
13208 for (i = 0; i < length; i += 1) {
13209 tail[i >> 2] |= a[i] << ((i % 4) << 3);
13210 }
13211
13212 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13213 if (i > 55) {
13214 md5cycle(state, tail);
13215 for (i = 0; i < 16; i += 1) {
13216 tail[i] = 0;
13217 }
13218 }
13219
13220 // Beware that the final length might not fit in 32 bits so we take care of that
13221 tmp = n * 8;
13222 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
13223 lo = parseInt(tmp[2], 16);
13224 hi = parseInt(tmp[1], 16) || 0;
13225
13226 tail[14] = lo;
13227 tail[15] = hi;
13228
13229 md5cycle(state, tail);
13230
13231 return state;
13232 }
13233
13234 function rhex(n) {
13235 var s = '',
13236 j;
13237 for (j = 0; j < 4; j += 1) {
13238 s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
13239 }
13240 return s;
13241 }
13242
13243 function hex(x) {
13244 var i;
13245 for (i = 0; i < x.length; i += 1) {
13246 x[i] = rhex(x[i]);
13247 }
13248 return x.join('');
13249 }
13250
13251 // In some cases the fast add32 function cannot be used..
13252 if (hex(md51('hello')) !== '5d41402abc4b2a76b9719d911017c592') {
13253 add32 = function (x, y) {
13254 var lsw = (x & 0xFFFF) + (y & 0xFFFF),
13255 msw = (x >> 16) + (y >> 16) + (lsw >> 16);
13256 return (msw << 16) | (lsw & 0xFFFF);
13257 };
13258 }
13259
13260 // ---------------------------------------------------
13261
13262 /**
13263 * ArrayBuffer slice polyfill.
13264 *
13265 * @see https://github.com/ttaubert/node-arraybuffer-slice
13266 */
13267
13268 if (typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.prototype.slice) {
13269 (function () {
13270 function clamp(val, length) {
13271 val = (val | 0) || 0;
13272
13273 if (val < 0) {
13274 return Math.max(val + length, 0);
13275 }
13276
13277 return Math.min(val, length);
13278 }
13279
13280 ArrayBuffer.prototype.slice = function (from, to) {
13281 var length = this.byteLength,
13282 begin = clamp(from, length),
13283 end = length,
13284 num,
13285 target,
13286 targetArray,
13287 sourceArray;
13288
13289 if (to !== undefined) {
13290 end = clamp(to, length);
13291 }
13292
13293 if (begin > end) {
13294 return new ArrayBuffer(0);
13295 }
13296
13297 num = end - begin;
13298 target = new ArrayBuffer(num);
13299 targetArray = new Uint8Array(target);
13300
13301 sourceArray = new Uint8Array(this, begin, num);
13302 targetArray.set(sourceArray);
13303
13304 return target;
13305 };
13306 })();
13307 }
13308
13309 // ---------------------------------------------------
13310
13311 /**
13312 * Helpers.
13313 */
13314
13315 function toUtf8(str) {
13316 if (/[\u0080-\uFFFF]/.test(str)) {
13317 str = unescape(encodeURIComponent(str));
13318 }
13319
13320 return str;
13321 }
13322
13323 function utf8Str2ArrayBuffer(str, returnUInt8Array) {
13324 var length = str.length,
13325 buff = new ArrayBuffer(length),
13326 arr = new Uint8Array(buff),
13327 i;
13328
13329 for (i = 0; i < length; i += 1) {
13330 arr[i] = str.charCodeAt(i);
13331 }
13332
13333 return returnUInt8Array ? arr : buff;
13334 }
13335
13336 function arrayBuffer2Utf8Str(buff) {
13337 return String.fromCharCode.apply(null, new Uint8Array(buff));
13338 }
13339
13340 function concatenateArrayBuffers(first, second, returnUInt8Array) {
13341 var result = new Uint8Array(first.byteLength + second.byteLength);
13342
13343 result.set(new Uint8Array(first));
13344 result.set(new Uint8Array(second), first.byteLength);
13345
13346 return returnUInt8Array ? result : result.buffer;
13347 }
13348
13349 function hexToBinaryString(hex) {
13350 var bytes = [],
13351 length = hex.length,
13352 x;
13353
13354 for (x = 0; x < length - 1; x += 2) {
13355 bytes.push(parseInt(hex.substr(x, 2), 16));
13356 }
13357
13358 return String.fromCharCode.apply(String, bytes);
13359 }
13360
13361 // ---------------------------------------------------
13362
13363 /**
13364 * SparkMD5 OOP implementation.
13365 *
13366 * Use this class to perform an incremental md5, otherwise use the
13367 * static methods instead.
13368 */
13369
13370 function SparkMD5() {
13371 // call reset to init the instance
13372 this.reset();
13373 }
13374
13375 /**
13376 * Appends a string.
13377 * A conversion will be applied if an utf8 string is detected.
13378 *
13379 * @param {String} str The string to be appended
13380 *
13381 * @return {SparkMD5} The instance itself
13382 */
13383 SparkMD5.prototype.append = function (str) {
13384 // Converts the string to utf8 bytes if necessary
13385 // Then append as binary
13386 this.appendBinary(toUtf8(str));
13387
13388 return this;
13389 };
13390
13391 /**
13392 * Appends a binary string.
13393 *
13394 * @param {String} contents The binary string to be appended
13395 *
13396 * @return {SparkMD5} The instance itself
13397 */
13398 SparkMD5.prototype.appendBinary = function (contents) {
13399 this._buff += contents;
13400 this._length += contents.length;
13401
13402 var length = this._buff.length,
13403 i;
13404
13405 for (i = 64; i <= length; i += 64) {
13406 md5cycle(this._hash, md5blk(this._buff.substring(i - 64, i)));
13407 }
13408
13409 this._buff = this._buff.substring(i - 64);
13410
13411 return this;
13412 };
13413
13414 /**
13415 * Finishes the incremental computation, reseting the internal state and
13416 * returning the result.
13417 *
13418 * @param {Boolean} raw True to get the raw string, false to get the hex string
13419 *
13420 * @return {String} The result
13421 */
13422 SparkMD5.prototype.end = function (raw) {
13423 var buff = this._buff,
13424 length = buff.length,
13425 i,
13426 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
13427 ret;
13428
13429 for (i = 0; i < length; i += 1) {
13430 tail[i >> 2] |= buff.charCodeAt(i) << ((i % 4) << 3);
13431 }
13432
13433 this._finish(tail, length);
13434 ret = hex(this._hash);
13435
13436 if (raw) {
13437 ret = hexToBinaryString(ret);
13438 }
13439
13440 this.reset();
13441
13442 return ret;
13443 };
13444
13445 /**
13446 * Resets the internal state of the computation.
13447 *
13448 * @return {SparkMD5} The instance itself
13449 */
13450 SparkMD5.prototype.reset = function () {
13451 this._buff = '';
13452 this._length = 0;
13453 this._hash = [1732584193, -271733879, -1732584194, 271733878];
13454
13455 return this;
13456 };
13457
13458 /**
13459 * Gets the internal state of the computation.
13460 *
13461 * @return {Object} The state
13462 */
13463 SparkMD5.prototype.getState = function () {
13464 return {
13465 buff: this._buff,
13466 length: this._length,
13467 hash: this._hash
13468 };
13469 };
13470
13471 /**
13472 * Gets the internal state of the computation.
13473 *
13474 * @param {Object} state The state
13475 *
13476 * @return {SparkMD5} The instance itself
13477 */
13478 SparkMD5.prototype.setState = function (state) {
13479 this._buff = state.buff;
13480 this._length = state.length;
13481 this._hash = state.hash;
13482
13483 return this;
13484 };
13485
13486 /**
13487 * Releases memory used by the incremental buffer and other additional
13488 * resources. If you plan to use the instance again, use reset instead.
13489 */
13490 SparkMD5.prototype.destroy = function () {
13491 delete this._hash;
13492 delete this._buff;
13493 delete this._length;
13494 };
13495
13496 /**
13497 * Finish the final calculation based on the tail.
13498 *
13499 * @param {Array} tail The tail (will be modified)
13500 * @param {Number} length The length of the remaining buffer
13501 */
13502 SparkMD5.prototype._finish = function (tail, length) {
13503 var i = length,
13504 tmp,
13505 lo,
13506 hi;
13507
13508 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13509 if (i > 55) {
13510 md5cycle(this._hash, tail);
13511 for (i = 0; i < 16; i += 1) {
13512 tail[i] = 0;
13513 }
13514 }
13515
13516 // Do the final computation based on the tail and length
13517 // Beware that the final length may not fit in 32 bits so we take care of that
13518 tmp = this._length * 8;
13519 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
13520 lo = parseInt(tmp[2], 16);
13521 hi = parseInt(tmp[1], 16) || 0;
13522
13523 tail[14] = lo;
13524 tail[15] = hi;
13525 md5cycle(this._hash, tail);
13526 };
13527
13528 /**
13529 * Performs the md5 hash on a string.
13530 * A conversion will be applied if utf8 string is detected.
13531 *
13532 * @param {String} str The string
13533 * @param {Boolean} raw True to get the raw string, false to get the hex string
13534 *
13535 * @return {String} The result
13536 */
13537 SparkMD5.hash = function (str, raw) {
13538 // Converts the string to utf8 bytes if necessary
13539 // Then compute it using the binary function
13540 return SparkMD5.hashBinary(toUtf8(str), raw);
13541 };
13542
13543 /**
13544 * Performs the md5 hash on a binary string.
13545 *
13546 * @param {String} content The binary string
13547 * @param {Boolean} raw True to get the raw string, false to get the hex string
13548 *
13549 * @return {String} The result
13550 */
13551 SparkMD5.hashBinary = function (content, raw) {
13552 var hash = md51(content),
13553 ret = hex(hash);
13554
13555 return raw ? hexToBinaryString(ret) : ret;
13556 };
13557
13558 // ---------------------------------------------------
13559
13560 /**
13561 * SparkMD5 OOP implementation for array buffers.
13562 *
13563 * Use this class to perform an incremental md5 ONLY for array buffers.
13564 */
13565 SparkMD5.ArrayBuffer = function () {
13566 // call reset to init the instance
13567 this.reset();
13568 };
13569
13570 /**
13571 * Appends an array buffer.
13572 *
13573 * @param {ArrayBuffer} arr The array to be appended
13574 *
13575 * @return {SparkMD5.ArrayBuffer} The instance itself
13576 */
13577 SparkMD5.ArrayBuffer.prototype.append = function (arr) {
13578 var buff = concatenateArrayBuffers(this._buff.buffer, arr, true),
13579 length = buff.length,
13580 i;
13581
13582 this._length += arr.byteLength;
13583
13584 for (i = 64; i <= length; i += 64) {
13585 md5cycle(this._hash, md5blk_array(buff.subarray(i - 64, i)));
13586 }
13587
13588 this._buff = (i - 64) < length ? new Uint8Array(buff.buffer.slice(i - 64)) : new Uint8Array(0);
13589
13590 return this;
13591 };
13592
13593 /**
13594 * Finishes the incremental computation, reseting the internal state and
13595 * returning the result.
13596 *
13597 * @param {Boolean} raw True to get the raw string, false to get the hex string
13598 *
13599 * @return {String} The result
13600 */
13601 SparkMD5.ArrayBuffer.prototype.end = function (raw) {
13602 var buff = this._buff,
13603 length = buff.length,
13604 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
13605 i,
13606 ret;
13607
13608 for (i = 0; i < length; i += 1) {
13609 tail[i >> 2] |= buff[i] << ((i % 4) << 3);
13610 }
13611
13612 this._finish(tail, length);
13613 ret = hex(this._hash);
13614
13615 if (raw) {
13616 ret = hexToBinaryString(ret);
13617 }
13618
13619 this.reset();
13620
13621 return ret;
13622 };
13623
13624 /**
13625 * Resets the internal state of the computation.
13626 *
13627 * @return {SparkMD5.ArrayBuffer} The instance itself
13628 */
13629 SparkMD5.ArrayBuffer.prototype.reset = function () {
13630 this._buff = new Uint8Array(0);
13631 this._length = 0;
13632 this._hash = [1732584193, -271733879, -1732584194, 271733878];
13633
13634 return this;
13635 };
13636
13637 /**
13638 * Gets the internal state of the computation.
13639 *
13640 * @return {Object} The state
13641 */
13642 SparkMD5.ArrayBuffer.prototype.getState = function () {
13643 var state = SparkMD5.prototype.getState.call(this);
13644
13645 // Convert buffer to a string
13646 state.buff = arrayBuffer2Utf8Str(state.buff);
13647
13648 return state;
13649 };
13650
13651 /**
13652 * Gets the internal state of the computation.
13653 *
13654 * @param {Object} state The state
13655 *
13656 * @return {SparkMD5.ArrayBuffer} The instance itself
13657 */
13658 SparkMD5.ArrayBuffer.prototype.setState = function (state) {
13659 // Convert string to buffer
13660 state.buff = utf8Str2ArrayBuffer(state.buff, true);
13661
13662 return SparkMD5.prototype.setState.call(this, state);
13663 };
13664
13665 SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
13666
13667 SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
13668
13669 /**
13670 * Performs the md5 hash on an array buffer.
13671 *
13672 * @param {ArrayBuffer} arr The array buffer
13673 * @param {Boolean} raw True to get the raw string, false to get the hex one
13674 *
13675 * @return {String} The result
13676 */
13677 SparkMD5.ArrayBuffer.hash = function (arr, raw) {
13678 var hash = md51_array(new Uint8Array(arr)),
13679 ret = hex(hash);
13680
13681 return raw ? hexToBinaryString(ret) : ret;
13682 };
13683
13684 return SparkMD5;
13685}));
13686
13687},{}],79:[function(_dereq_,module,exports){
13688// Copyright Joyent, Inc. and other Node contributors.
13689//
13690// Permission is hereby granted, free of charge, to any person obtaining a
13691// copy of this software and associated documentation files (the
13692// "Software"), to deal in the Software without restriction, including
13693// without limitation the rights to use, copy, modify, merge, publish,
13694// distribute, sublicense, and/or sell copies of the Software, and to permit
13695// persons to whom the Software is furnished to do so, subject to the
13696// following conditions:
13697//
13698// The above copyright notice and this permission notice shall be included
13699// in all copies or substantial portions of the Software.
13700//
13701// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13702// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13703// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13704// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13705// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13706// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13707// USE OR OTHER DEALINGS IN THE SOFTWARE.
13708
13709module.exports = Stream;
13710
13711var EE = _dereq_(18).EventEmitter;
13712var inherits = _dereq_(24);
13713
13714inherits(Stream, EE);
13715Stream.Readable = _dereq_(91);
13716Stream.Writable = _dereq_(93);
13717Stream.Duplex = _dereq_(81);
13718Stream.Transform = _dereq_(92);
13719Stream.PassThrough = _dereq_(90);
13720
13721// Backwards-compat with node 0.4.x
13722Stream.Stream = Stream;
13723
13724
13725
13726// old-style streams. Note that the pipe method (the only relevant
13727// part of this class) is overridden in the Readable class.
13728
13729function Stream() {
13730 EE.call(this);
13731}
13732
13733Stream.prototype.pipe = function(dest, options) {
13734 var source = this;
13735
13736 function ondata(chunk) {
13737 if (dest.writable) {
13738 if (false === dest.write(chunk) && source.pause) {
13739 source.pause();
13740 }
13741 }
13742 }
13743
13744 source.on('data', ondata);
13745
13746 function ondrain() {
13747 if (source.readable && source.resume) {
13748 source.resume();
13749 }
13750 }
13751
13752 dest.on('drain', ondrain);
13753
13754 // If the 'end' option is not supplied, dest.end() will be called when
13755 // source gets the 'end' or 'close' events. Only dest.end() once.
13756 if (!dest._isStdio && (!options || options.end !== false)) {
13757 source.on('end', onend);
13758 source.on('close', onclose);
13759 }
13760
13761 var didOnEnd = false;
13762 function onend() {
13763 if (didOnEnd) return;
13764 didOnEnd = true;
13765
13766 dest.end();
13767 }
13768
13769
13770 function onclose() {
13771 if (didOnEnd) return;
13772 didOnEnd = true;
13773
13774 if (typeof dest.destroy === 'function') dest.destroy();
13775 }
13776
13777 // don't leave dangling pipes when there are errors.
13778 function onerror(er) {
13779 cleanup();
13780 if (EE.listenerCount(this, 'error') === 0) {
13781 throw er; // Unhandled stream error in pipe.
13782 }
13783 }
13784
13785 source.on('error', onerror);
13786 dest.on('error', onerror);
13787
13788 // remove all the event listeners that were added.
13789 function cleanup() {
13790 source.removeListener('data', ondata);
13791 dest.removeListener('drain', ondrain);
13792
13793 source.removeListener('end', onend);
13794 source.removeListener('close', onclose);
13795
13796 source.removeListener('error', onerror);
13797 dest.removeListener('error', onerror);
13798
13799 source.removeListener('end', cleanup);
13800 source.removeListener('close', cleanup);
13801
13802 dest.removeListener('close', cleanup);
13803 }
13804
13805 source.on('end', cleanup);
13806 source.on('close', cleanup);
13807
13808 dest.on('close', cleanup);
13809
13810 dest.emit('pipe', source);
13811
13812 // Allow for unix-like usage: A.pipe(B).pipe(C)
13813 return dest;
13814};
13815
13816},{"18":18,"24":24,"81":81,"90":90,"91":91,"92":92,"93":93}],80:[function(_dereq_,module,exports){
13817var toString = {}.toString;
13818
13819module.exports = Array.isArray || function (arr) {
13820 return toString.call(arr) == '[object Array]';
13821};
13822
13823},{}],81:[function(_dereq_,module,exports){
13824module.exports = _dereq_(82);
13825
13826},{"82":82}],82:[function(_dereq_,module,exports){
13827// Copyright Joyent, Inc. and other Node contributors.
13828//
13829// Permission is hereby granted, free of charge, to any person obtaining a
13830// copy of this software and associated documentation files (the
13831// "Software"), to deal in the Software without restriction, including
13832// without limitation the rights to use, copy, modify, merge, publish,
13833// distribute, sublicense, and/or sell copies of the Software, and to permit
13834// persons to whom the Software is furnished to do so, subject to the
13835// following conditions:
13836//
13837// The above copyright notice and this permission notice shall be included
13838// in all copies or substantial portions of the Software.
13839//
13840// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13841// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13842// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13843// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13844// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13845// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13846// USE OR OTHER DEALINGS IN THE SOFTWARE.
13847
13848// a duplex stream is just a stream that is both readable and writable.
13849// Since JS doesn't have multiple prototypal inheritance, this class
13850// prototypally inherits from Readable, and then parasitically from
13851// Writable.
13852
13853'use strict';
13854
13855/*<replacement>*/
13856
13857var pna = _dereq_(67);
13858/*</replacement>*/
13859
13860/*<replacement>*/
13861var objectKeys = Object.keys || function (obj) {
13862 var keys = [];
13863 for (var key in obj) {
13864 keys.push(key);
13865 }return keys;
13866};
13867/*</replacement>*/
13868
13869module.exports = Duplex;
13870
13871/*<replacement>*/
13872var util = Object.create(_dereq_(13));
13873util.inherits = _dereq_(24);
13874/*</replacement>*/
13875
13876var Readable = _dereq_(84);
13877var Writable = _dereq_(86);
13878
13879util.inherits(Duplex, Readable);
13880
13881{
13882 // avoid scope creep, the keys array can then be collected
13883 var keys = objectKeys(Writable.prototype);
13884 for (var v = 0; v < keys.length; v++) {
13885 var method = keys[v];
13886 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
13887 }
13888}
13889
13890function Duplex(options) {
13891 if (!(this instanceof Duplex)) return new Duplex(options);
13892
13893 Readable.call(this, options);
13894 Writable.call(this, options);
13895
13896 if (options && options.readable === false) this.readable = false;
13897
13898 if (options && options.writable === false) this.writable = false;
13899
13900 this.allowHalfOpen = true;
13901 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
13902
13903 this.once('end', onend);
13904}
13905
13906Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
13907 // making it explicit this property is not enumerable
13908 // because otherwise some prototype manipulation in
13909 // userland will fail
13910 enumerable: false,
13911 get: function () {
13912 return this._writableState.highWaterMark;
13913 }
13914});
13915
13916// the no-half-open enforcer
13917function onend() {
13918 // if we allow half-open state, or if the writable side ended,
13919 // then we're ok.
13920 if (this.allowHalfOpen || this._writableState.ended) return;
13921
13922 // no more data can be written.
13923 // But allow more writes to happen in this tick.
13924 pna.nextTick(onEndNT, this);
13925}
13926
13927function onEndNT(self) {
13928 self.end();
13929}
13930
13931Object.defineProperty(Duplex.prototype, 'destroyed', {
13932 get: function () {
13933 if (this._readableState === undefined || this._writableState === undefined) {
13934 return false;
13935 }
13936 return this._readableState.destroyed && this._writableState.destroyed;
13937 },
13938 set: function (value) {
13939 // we ignore the value if the stream
13940 // has not been initialized yet
13941 if (this._readableState === undefined || this._writableState === undefined) {
13942 return;
13943 }
13944
13945 // backward compatibility, the user is explicitly
13946 // managing destroyed
13947 this._readableState.destroyed = value;
13948 this._writableState.destroyed = value;
13949 }
13950});
13951
13952Duplex.prototype._destroy = function (err, cb) {
13953 this.push(null);
13954 this.end();
13955
13956 pna.nextTick(cb, err);
13957};
13958},{"13":13,"24":24,"67":67,"84":84,"86":86}],83:[function(_dereq_,module,exports){
13959// Copyright Joyent, Inc. and other Node contributors.
13960//
13961// Permission is hereby granted, free of charge, to any person obtaining a
13962// copy of this software and associated documentation files (the
13963// "Software"), to deal in the Software without restriction, including
13964// without limitation the rights to use, copy, modify, merge, publish,
13965// distribute, sublicense, and/or sell copies of the Software, and to permit
13966// persons to whom the Software is furnished to do so, subject to the
13967// following conditions:
13968//
13969// The above copyright notice and this permission notice shall be included
13970// in all copies or substantial portions of the Software.
13971//
13972// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13973// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13974// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13975// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13976// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13977// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13978// USE OR OTHER DEALINGS IN THE SOFTWARE.
13979
13980// a passthrough stream.
13981// basically just the most minimal sort of Transform stream.
13982// Every written chunk gets output as-is.
13983
13984'use strict';
13985
13986module.exports = PassThrough;
13987
13988var Transform = _dereq_(85);
13989
13990/*<replacement>*/
13991var util = Object.create(_dereq_(13));
13992util.inherits = _dereq_(24);
13993/*</replacement>*/
13994
13995util.inherits(PassThrough, Transform);
13996
13997function PassThrough(options) {
13998 if (!(this instanceof PassThrough)) return new PassThrough(options);
13999
14000 Transform.call(this, options);
14001}
14002
14003PassThrough.prototype._transform = function (chunk, encoding, cb) {
14004 cb(null, chunk);
14005};
14006},{"13":13,"24":24,"85":85}],84:[function(_dereq_,module,exports){
14007(function (process,global){
14008// Copyright Joyent, Inc. and other Node contributors.
14009//
14010// Permission is hereby granted, free of charge, to any person obtaining a
14011// copy of this software and associated documentation files (the
14012// "Software"), to deal in the Software without restriction, including
14013// without limitation the rights to use, copy, modify, merge, publish,
14014// distribute, sublicense, and/or sell copies of the Software, and to permit
14015// persons to whom the Software is furnished to do so, subject to the
14016// following conditions:
14017//
14018// The above copyright notice and this permission notice shall be included
14019// in all copies or substantial portions of the Software.
14020//
14021// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14022// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14023// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14024// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14025// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14026// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14027// USE OR OTHER DEALINGS IN THE SOFTWARE.
14028
14029'use strict';
14030
14031/*<replacement>*/
14032
14033var pna = _dereq_(67);
14034/*</replacement>*/
14035
14036module.exports = Readable;
14037
14038/*<replacement>*/
14039var isArray = _dereq_(80);
14040/*</replacement>*/
14041
14042/*<replacement>*/
14043var Duplex;
14044/*</replacement>*/
14045
14046Readable.ReadableState = ReadableState;
14047
14048/*<replacement>*/
14049var EE = _dereq_(18).EventEmitter;
14050
14051var EElistenerCount = function (emitter, type) {
14052 return emitter.listeners(type).length;
14053};
14054/*</replacement>*/
14055
14056/*<replacement>*/
14057var Stream = _dereq_(89);
14058/*</replacement>*/
14059
14060/*<replacement>*/
14061
14062var Buffer = _dereq_(94).Buffer;
14063var OurUint8Array = global.Uint8Array || function () {};
14064function _uint8ArrayToBuffer(chunk) {
14065 return Buffer.from(chunk);
14066}
14067function _isUint8Array(obj) {
14068 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
14069}
14070
14071/*</replacement>*/
14072
14073/*<replacement>*/
14074var util = Object.create(_dereq_(13));
14075util.inherits = _dereq_(24);
14076/*</replacement>*/
14077
14078/*<replacement>*/
14079var debugUtil = _dereq_(10);
14080var debug = void 0;
14081if (debugUtil && debugUtil.debuglog) {
14082 debug = debugUtil.debuglog('stream');
14083} else {
14084 debug = function () {};
14085}
14086/*</replacement>*/
14087
14088var BufferList = _dereq_(87);
14089var destroyImpl = _dereq_(88);
14090var StringDecoder;
14091
14092util.inherits(Readable, Stream);
14093
14094var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
14095
14096function prependListener(emitter, event, fn) {
14097 // Sadly this is not cacheable as some libraries bundle their own
14098 // event emitter implementation with them.
14099 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
14100
14101 // This is a hack to make sure that our error handler is attached before any
14102 // userland ones. NEVER DO THIS. This is here only because this code needs
14103 // to continue to work with older versions of Node.js that do not include
14104 // the prependListener() method. The goal is to eventually remove this hack.
14105 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]];
14106}
14107
14108function ReadableState(options, stream) {
14109 Duplex = Duplex || _dereq_(82);
14110
14111 options = options || {};
14112
14113 // Duplex streams are both readable and writable, but share
14114 // the same options object.
14115 // However, some cases require setting options to different
14116 // values for the readable and the writable sides of the duplex stream.
14117 // These options can be provided separately as readableXXX and writableXXX.
14118 var isDuplex = stream instanceof Duplex;
14119
14120 // object stream flag. Used to make read(n) ignore n and to
14121 // make all the buffer merging and length checks go away
14122 this.objectMode = !!options.objectMode;
14123
14124 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
14125
14126 // the point at which it stops calling _read() to fill the buffer
14127 // Note: 0 is a valid value, means "don't call _read preemptively ever"
14128 var hwm = options.highWaterMark;
14129 var readableHwm = options.readableHighWaterMark;
14130 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
14131
14132 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
14133
14134 // cast to ints.
14135 this.highWaterMark = Math.floor(this.highWaterMark);
14136
14137 // A linked list is used to store data chunks instead of an array because the
14138 // linked list can remove elements from the beginning faster than
14139 // array.shift()
14140 this.buffer = new BufferList();
14141 this.length = 0;
14142 this.pipes = null;
14143 this.pipesCount = 0;
14144 this.flowing = null;
14145 this.ended = false;
14146 this.endEmitted = false;
14147 this.reading = false;
14148
14149 // a flag to be able to tell if the event 'readable'/'data' is emitted
14150 // immediately, or on a later tick. We set this to true at first, because
14151 // any actions that shouldn't happen until "later" should generally also
14152 // not happen before the first read call.
14153 this.sync = true;
14154
14155 // whenever we return null, then we set a flag to say
14156 // that we're awaiting a 'readable' event emission.
14157 this.needReadable = false;
14158 this.emittedReadable = false;
14159 this.readableListening = false;
14160 this.resumeScheduled = false;
14161
14162 // has it been destroyed
14163 this.destroyed = false;
14164
14165 // Crypto is kind of old and crusty. Historically, its default string
14166 // encoding is 'binary' so we have to make this configurable.
14167 // Everything else in the universe uses 'utf8', though.
14168 this.defaultEncoding = options.defaultEncoding || 'utf8';
14169
14170 // the number of writers that are awaiting a drain event in .pipe()s
14171 this.awaitDrain = 0;
14172
14173 // if true, a maybeReadMore has been scheduled
14174 this.readingMore = false;
14175
14176 this.decoder = null;
14177 this.encoding = null;
14178 if (options.encoding) {
14179 if (!StringDecoder) StringDecoder = _dereq_(95).StringDecoder;
14180 this.decoder = new StringDecoder(options.encoding);
14181 this.encoding = options.encoding;
14182 }
14183}
14184
14185function Readable(options) {
14186 Duplex = Duplex || _dereq_(82);
14187
14188 if (!(this instanceof Readable)) return new Readable(options);
14189
14190 this._readableState = new ReadableState(options, this);
14191
14192 // legacy
14193 this.readable = true;
14194
14195 if (options) {
14196 if (typeof options.read === 'function') this._read = options.read;
14197
14198 if (typeof options.destroy === 'function') this._destroy = options.destroy;
14199 }
14200
14201 Stream.call(this);
14202}
14203
14204Object.defineProperty(Readable.prototype, 'destroyed', {
14205 get: function () {
14206 if (this._readableState === undefined) {
14207 return false;
14208 }
14209 return this._readableState.destroyed;
14210 },
14211 set: function (value) {
14212 // we ignore the value if the stream
14213 // has not been initialized yet
14214 if (!this._readableState) {
14215 return;
14216 }
14217
14218 // backward compatibility, the user is explicitly
14219 // managing destroyed
14220 this._readableState.destroyed = value;
14221 }
14222});
14223
14224Readable.prototype.destroy = destroyImpl.destroy;
14225Readable.prototype._undestroy = destroyImpl.undestroy;
14226Readable.prototype._destroy = function (err, cb) {
14227 this.push(null);
14228 cb(err);
14229};
14230
14231// Manually shove something into the read() buffer.
14232// This returns true if the highWaterMark has not been hit yet,
14233// similar to how Writable.write() returns true if you should
14234// write() some more.
14235Readable.prototype.push = function (chunk, encoding) {
14236 var state = this._readableState;
14237 var skipChunkCheck;
14238
14239 if (!state.objectMode) {
14240 if (typeof chunk === 'string') {
14241 encoding = encoding || state.defaultEncoding;
14242 if (encoding !== state.encoding) {
14243 chunk = Buffer.from(chunk, encoding);
14244 encoding = '';
14245 }
14246 skipChunkCheck = true;
14247 }
14248 } else {
14249 skipChunkCheck = true;
14250 }
14251
14252 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
14253};
14254
14255// Unshift should *always* be something directly out of read()
14256Readable.prototype.unshift = function (chunk) {
14257 return readableAddChunk(this, chunk, null, true, false);
14258};
14259
14260function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
14261 var state = stream._readableState;
14262 if (chunk === null) {
14263 state.reading = false;
14264 onEofChunk(stream, state);
14265 } else {
14266 var er;
14267 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
14268 if (er) {
14269 stream.emit('error', er);
14270 } else if (state.objectMode || chunk && chunk.length > 0) {
14271 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
14272 chunk = _uint8ArrayToBuffer(chunk);
14273 }
14274
14275 if (addToFront) {
14276 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
14277 } else if (state.ended) {
14278 stream.emit('error', new Error('stream.push() after EOF'));
14279 } else {
14280 state.reading = false;
14281 if (state.decoder && !encoding) {
14282 chunk = state.decoder.write(chunk);
14283 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
14284 } else {
14285 addChunk(stream, state, chunk, false);
14286 }
14287 }
14288 } else if (!addToFront) {
14289 state.reading = false;
14290 }
14291 }
14292
14293 return needMoreData(state);
14294}
14295
14296function addChunk(stream, state, chunk, addToFront) {
14297 if (state.flowing && state.length === 0 && !state.sync) {
14298 stream.emit('data', chunk);
14299 stream.read(0);
14300 } else {
14301 // update the buffer info.
14302 state.length += state.objectMode ? 1 : chunk.length;
14303 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
14304
14305 if (state.needReadable) emitReadable(stream);
14306 }
14307 maybeReadMore(stream, state);
14308}
14309
14310function chunkInvalid(state, chunk) {
14311 var er;
14312 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
14313 er = new TypeError('Invalid non-string/buffer chunk');
14314 }
14315 return er;
14316}
14317
14318// if it's past the high water mark, we can push in some more.
14319// Also, if we have no data yet, we can stand some
14320// more bytes. This is to work around cases where hwm=0,
14321// such as the repl. Also, if the push() triggered a
14322// readable event, and the user called read(largeNumber) such that
14323// needReadable was set, then we ought to push more, so that another
14324// 'readable' event will be triggered.
14325function needMoreData(state) {
14326 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
14327}
14328
14329Readable.prototype.isPaused = function () {
14330 return this._readableState.flowing === false;
14331};
14332
14333// backwards compatibility.
14334Readable.prototype.setEncoding = function (enc) {
14335 if (!StringDecoder) StringDecoder = _dereq_(95).StringDecoder;
14336 this._readableState.decoder = new StringDecoder(enc);
14337 this._readableState.encoding = enc;
14338 return this;
14339};
14340
14341// Don't raise the hwm > 8MB
14342var MAX_HWM = 0x800000;
14343function computeNewHighWaterMark(n) {
14344 if (n >= MAX_HWM) {
14345 n = MAX_HWM;
14346 } else {
14347 // Get the next highest power of 2 to prevent increasing hwm excessively in
14348 // tiny amounts
14349 n--;
14350 n |= n >>> 1;
14351 n |= n >>> 2;
14352 n |= n >>> 4;
14353 n |= n >>> 8;
14354 n |= n >>> 16;
14355 n++;
14356 }
14357 return n;
14358}
14359
14360// This function is designed to be inlinable, so please take care when making
14361// changes to the function body.
14362function howMuchToRead(n, state) {
14363 if (n <= 0 || state.length === 0 && state.ended) return 0;
14364 if (state.objectMode) return 1;
14365 if (n !== n) {
14366 // Only flow one buffer at a time
14367 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
14368 }
14369 // If we're asking for more than the current hwm, then raise the hwm.
14370 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
14371 if (n <= state.length) return n;
14372 // Don't have enough
14373 if (!state.ended) {
14374 state.needReadable = true;
14375 return 0;
14376 }
14377 return state.length;
14378}
14379
14380// you can override either this method, or the async _read(n) below.
14381Readable.prototype.read = function (n) {
14382 debug('read', n);
14383 n = parseInt(n, 10);
14384 var state = this._readableState;
14385 var nOrig = n;
14386
14387 if (n !== 0) state.emittedReadable = false;
14388
14389 // if we're doing read(0) to trigger a readable event, but we
14390 // already have a bunch of data in the buffer, then just trigger
14391 // the 'readable' event and move on.
14392 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
14393 debug('read: emitReadable', state.length, state.ended);
14394 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
14395 return null;
14396 }
14397
14398 n = howMuchToRead(n, state);
14399
14400 // if we've ended, and we're now clear, then finish it up.
14401 if (n === 0 && state.ended) {
14402 if (state.length === 0) endReadable(this);
14403 return null;
14404 }
14405
14406 // All the actual chunk generation logic needs to be
14407 // *below* the call to _read. The reason is that in certain
14408 // synthetic stream cases, such as passthrough streams, _read
14409 // may be a completely synchronous operation which may change
14410 // the state of the read buffer, providing enough data when
14411 // before there was *not* enough.
14412 //
14413 // So, the steps are:
14414 // 1. Figure out what the state of things will be after we do
14415 // a read from the buffer.
14416 //
14417 // 2. If that resulting state will trigger a _read, then call _read.
14418 // Note that this may be asynchronous, or synchronous. Yes, it is
14419 // deeply ugly to write APIs this way, but that still doesn't mean
14420 // that the Readable class should behave improperly, as streams are
14421 // designed to be sync/async agnostic.
14422 // Take note if the _read call is sync or async (ie, if the read call
14423 // has returned yet), so that we know whether or not it's safe to emit
14424 // 'readable' etc.
14425 //
14426 // 3. Actually pull the requested chunks out of the buffer and return.
14427
14428 // if we need a readable event, then we need to do some reading.
14429 var doRead = state.needReadable;
14430 debug('need readable', doRead);
14431
14432 // if we currently have less than the highWaterMark, then also read some
14433 if (state.length === 0 || state.length - n < state.highWaterMark) {
14434 doRead = true;
14435 debug('length less than watermark', doRead);
14436 }
14437
14438 // however, if we've ended, then there's no point, and if we're already
14439 // reading, then it's unnecessary.
14440 if (state.ended || state.reading) {
14441 doRead = false;
14442 debug('reading or ended', doRead);
14443 } else if (doRead) {
14444 debug('do read');
14445 state.reading = true;
14446 state.sync = true;
14447 // if the length is currently zero, then we *need* a readable event.
14448 if (state.length === 0) state.needReadable = true;
14449 // call internal read method
14450 this._read(state.highWaterMark);
14451 state.sync = false;
14452 // If _read pushed data synchronously, then `reading` will be false,
14453 // and we need to re-evaluate how much data we can return to the user.
14454 if (!state.reading) n = howMuchToRead(nOrig, state);
14455 }
14456
14457 var ret;
14458 if (n > 0) ret = fromList(n, state);else ret = null;
14459
14460 if (ret === null) {
14461 state.needReadable = true;
14462 n = 0;
14463 } else {
14464 state.length -= n;
14465 }
14466
14467 if (state.length === 0) {
14468 // If we have nothing in the buffer, then we want to know
14469 // as soon as we *do* get something into the buffer.
14470 if (!state.ended) state.needReadable = true;
14471
14472 // If we tried to read() past the EOF, then emit end on the next tick.
14473 if (nOrig !== n && state.ended) endReadable(this);
14474 }
14475
14476 if (ret !== null) this.emit('data', ret);
14477
14478 return ret;
14479};
14480
14481function onEofChunk(stream, state) {
14482 if (state.ended) return;
14483 if (state.decoder) {
14484 var chunk = state.decoder.end();
14485 if (chunk && chunk.length) {
14486 state.buffer.push(chunk);
14487 state.length += state.objectMode ? 1 : chunk.length;
14488 }
14489 }
14490 state.ended = true;
14491
14492 // emit 'readable' now to make sure it gets picked up.
14493 emitReadable(stream);
14494}
14495
14496// Don't emit readable right away in sync mode, because this can trigger
14497// another read() call => stack overflow. This way, it might trigger
14498// a nextTick recursion warning, but that's not so bad.
14499function emitReadable(stream) {
14500 var state = stream._readableState;
14501 state.needReadable = false;
14502 if (!state.emittedReadable) {
14503 debug('emitReadable', state.flowing);
14504 state.emittedReadable = true;
14505 if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
14506 }
14507}
14508
14509function emitReadable_(stream) {
14510 debug('emit readable');
14511 stream.emit('readable');
14512 flow(stream);
14513}
14514
14515// at this point, the user has presumably seen the 'readable' event,
14516// and called read() to consume some data. that may have triggered
14517// in turn another _read(n) call, in which case reading = true if
14518// it's in progress.
14519// However, if we're not ended, or reading, and the length < hwm,
14520// then go ahead and try to read some more preemptively.
14521function maybeReadMore(stream, state) {
14522 if (!state.readingMore) {
14523 state.readingMore = true;
14524 pna.nextTick(maybeReadMore_, stream, state);
14525 }
14526}
14527
14528function maybeReadMore_(stream, state) {
14529 var len = state.length;
14530 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
14531 debug('maybeReadMore read 0');
14532 stream.read(0);
14533 if (len === state.length)
14534 // didn't get any data, stop spinning.
14535 break;else len = state.length;
14536 }
14537 state.readingMore = false;
14538}
14539
14540// abstract method. to be overridden in specific implementation classes.
14541// call cb(er, data) where data is <= n in length.
14542// for virtual (non-string, non-buffer) streams, "length" is somewhat
14543// arbitrary, and perhaps not very meaningful.
14544Readable.prototype._read = function (n) {
14545 this.emit('error', new Error('_read() is not implemented'));
14546};
14547
14548Readable.prototype.pipe = function (dest, pipeOpts) {
14549 var src = this;
14550 var state = this._readableState;
14551
14552 switch (state.pipesCount) {
14553 case 0:
14554 state.pipes = dest;
14555 break;
14556 case 1:
14557 state.pipes = [state.pipes, dest];
14558 break;
14559 default:
14560 state.pipes.push(dest);
14561 break;
14562 }
14563 state.pipesCount += 1;
14564 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
14565
14566 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
14567
14568 var endFn = doEnd ? onend : unpipe;
14569 if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
14570
14571 dest.on('unpipe', onunpipe);
14572 function onunpipe(readable, unpipeInfo) {
14573 debug('onunpipe');
14574 if (readable === src) {
14575 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
14576 unpipeInfo.hasUnpiped = true;
14577 cleanup();
14578 }
14579 }
14580 }
14581
14582 function onend() {
14583 debug('onend');
14584 dest.end();
14585 }
14586
14587 // when the dest drains, it reduces the awaitDrain counter
14588 // on the source. This would be more elegant with a .once()
14589 // handler in flow(), but adding and removing repeatedly is
14590 // too slow.
14591 var ondrain = pipeOnDrain(src);
14592 dest.on('drain', ondrain);
14593
14594 var cleanedUp = false;
14595 function cleanup() {
14596 debug('cleanup');
14597 // cleanup event handlers once the pipe is broken
14598 dest.removeListener('close', onclose);
14599 dest.removeListener('finish', onfinish);
14600 dest.removeListener('drain', ondrain);
14601 dest.removeListener('error', onerror);
14602 dest.removeListener('unpipe', onunpipe);
14603 src.removeListener('end', onend);
14604 src.removeListener('end', unpipe);
14605 src.removeListener('data', ondata);
14606
14607 cleanedUp = true;
14608
14609 // if the reader is waiting for a drain event from this
14610 // specific writer, then it would cause it to never start
14611 // flowing again.
14612 // So, if this is awaiting a drain, then we just call it now.
14613 // If we don't know, then assume that we are waiting for one.
14614 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
14615 }
14616
14617 // If the user pushes more data while we're writing to dest then we'll end up
14618 // in ondata again. However, we only want to increase awaitDrain once because
14619 // dest will only emit one 'drain' event for the multiple writes.
14620 // => Introduce a guard on increasing awaitDrain.
14621 var increasedAwaitDrain = false;
14622 src.on('data', ondata);
14623 function ondata(chunk) {
14624 debug('ondata');
14625 increasedAwaitDrain = false;
14626 var ret = dest.write(chunk);
14627 if (false === ret && !increasedAwaitDrain) {
14628 // If the user unpiped during `dest.write()`, it is possible
14629 // to get stuck in a permanently paused state if that write
14630 // also returned false.
14631 // => Check whether `dest` is still a piping destination.
14632 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
14633 debug('false write response, pause', src._readableState.awaitDrain);
14634 src._readableState.awaitDrain++;
14635 increasedAwaitDrain = true;
14636 }
14637 src.pause();
14638 }
14639 }
14640
14641 // if the dest has an error, then stop piping into it.
14642 // however, don't suppress the throwing behavior for this.
14643 function onerror(er) {
14644 debug('onerror', er);
14645 unpipe();
14646 dest.removeListener('error', onerror);
14647 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
14648 }
14649
14650 // Make sure our error handler is attached before userland ones.
14651 prependListener(dest, 'error', onerror);
14652
14653 // Both close and finish should trigger unpipe, but only once.
14654 function onclose() {
14655 dest.removeListener('finish', onfinish);
14656 unpipe();
14657 }
14658 dest.once('close', onclose);
14659 function onfinish() {
14660 debug('onfinish');
14661 dest.removeListener('close', onclose);
14662 unpipe();
14663 }
14664 dest.once('finish', onfinish);
14665
14666 function unpipe() {
14667 debug('unpipe');
14668 src.unpipe(dest);
14669 }
14670
14671 // tell the dest that it's being piped to
14672 dest.emit('pipe', src);
14673
14674 // start the flow if it hasn't been started already.
14675 if (!state.flowing) {
14676 debug('pipe resume');
14677 src.resume();
14678 }
14679
14680 return dest;
14681};
14682
14683function pipeOnDrain(src) {
14684 return function () {
14685 var state = src._readableState;
14686 debug('pipeOnDrain', state.awaitDrain);
14687 if (state.awaitDrain) state.awaitDrain--;
14688 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
14689 state.flowing = true;
14690 flow(src);
14691 }
14692 };
14693}
14694
14695Readable.prototype.unpipe = function (dest) {
14696 var state = this._readableState;
14697 var unpipeInfo = { hasUnpiped: false };
14698
14699 // if we're not piping anywhere, then do nothing.
14700 if (state.pipesCount === 0) return this;
14701
14702 // just one destination. most common case.
14703 if (state.pipesCount === 1) {
14704 // passed in one, but it's not the right one.
14705 if (dest && dest !== state.pipes) return this;
14706
14707 if (!dest) dest = state.pipes;
14708
14709 // got a match.
14710 state.pipes = null;
14711 state.pipesCount = 0;
14712 state.flowing = false;
14713 if (dest) dest.emit('unpipe', this, unpipeInfo);
14714 return this;
14715 }
14716
14717 // slow case. multiple pipe destinations.
14718
14719 if (!dest) {
14720 // remove all.
14721 var dests = state.pipes;
14722 var len = state.pipesCount;
14723 state.pipes = null;
14724 state.pipesCount = 0;
14725 state.flowing = false;
14726
14727 for (var i = 0; i < len; i++) {
14728 dests[i].emit('unpipe', this, unpipeInfo);
14729 }return this;
14730 }
14731
14732 // try to find the right one.
14733 var index = indexOf(state.pipes, dest);
14734 if (index === -1) return this;
14735
14736 state.pipes.splice(index, 1);
14737 state.pipesCount -= 1;
14738 if (state.pipesCount === 1) state.pipes = state.pipes[0];
14739
14740 dest.emit('unpipe', this, unpipeInfo);
14741
14742 return this;
14743};
14744
14745// set up data events if they are asked for
14746// Ensure readable listeners eventually get something
14747Readable.prototype.on = function (ev, fn) {
14748 var res = Stream.prototype.on.call(this, ev, fn);
14749
14750 if (ev === 'data') {
14751 // Start flowing on next tick if stream isn't explicitly paused
14752 if (this._readableState.flowing !== false) this.resume();
14753 } else if (ev === 'readable') {
14754 var state = this._readableState;
14755 if (!state.endEmitted && !state.readableListening) {
14756 state.readableListening = state.needReadable = true;
14757 state.emittedReadable = false;
14758 if (!state.reading) {
14759 pna.nextTick(nReadingNextTick, this);
14760 } else if (state.length) {
14761 emitReadable(this);
14762 }
14763 }
14764 }
14765
14766 return res;
14767};
14768Readable.prototype.addListener = Readable.prototype.on;
14769
14770function nReadingNextTick(self) {
14771 debug('readable nexttick read 0');
14772 self.read(0);
14773}
14774
14775// pause() and resume() are remnants of the legacy readable stream API
14776// If the user uses them, then switch into old mode.
14777Readable.prototype.resume = function () {
14778 var state = this._readableState;
14779 if (!state.flowing) {
14780 debug('resume');
14781 state.flowing = true;
14782 resume(this, state);
14783 }
14784 return this;
14785};
14786
14787function resume(stream, state) {
14788 if (!state.resumeScheduled) {
14789 state.resumeScheduled = true;
14790 pna.nextTick(resume_, stream, state);
14791 }
14792}
14793
14794function resume_(stream, state) {
14795 if (!state.reading) {
14796 debug('resume read 0');
14797 stream.read(0);
14798 }
14799
14800 state.resumeScheduled = false;
14801 state.awaitDrain = 0;
14802 stream.emit('resume');
14803 flow(stream);
14804 if (state.flowing && !state.reading) stream.read(0);
14805}
14806
14807Readable.prototype.pause = function () {
14808 debug('call pause flowing=%j', this._readableState.flowing);
14809 if (false !== this._readableState.flowing) {
14810 debug('pause');
14811 this._readableState.flowing = false;
14812 this.emit('pause');
14813 }
14814 return this;
14815};
14816
14817function flow(stream) {
14818 var state = stream._readableState;
14819 debug('flow', state.flowing);
14820 while (state.flowing && stream.read() !== null) {}
14821}
14822
14823// wrap an old-style stream as the async data source.
14824// This is *not* part of the readable stream interface.
14825// It is an ugly unfortunate mess of history.
14826Readable.prototype.wrap = function (stream) {
14827 var _this = this;
14828
14829 var state = this._readableState;
14830 var paused = false;
14831
14832 stream.on('end', function () {
14833 debug('wrapped end');
14834 if (state.decoder && !state.ended) {
14835 var chunk = state.decoder.end();
14836 if (chunk && chunk.length) _this.push(chunk);
14837 }
14838
14839 _this.push(null);
14840 });
14841
14842 stream.on('data', function (chunk) {
14843 debug('wrapped data');
14844 if (state.decoder) chunk = state.decoder.write(chunk);
14845
14846 // don't skip over falsy values in objectMode
14847 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
14848
14849 var ret = _this.push(chunk);
14850 if (!ret) {
14851 paused = true;
14852 stream.pause();
14853 }
14854 });
14855
14856 // proxy all the other methods.
14857 // important when wrapping filters and duplexes.
14858 for (var i in stream) {
14859 if (this[i] === undefined && typeof stream[i] === 'function') {
14860 this[i] = function (method) {
14861 return function () {
14862 return stream[method].apply(stream, arguments);
14863 };
14864 }(i);
14865 }
14866 }
14867
14868 // proxy certain important events.
14869 for (var n = 0; n < kProxyEvents.length; n++) {
14870 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
14871 }
14872
14873 // when we try to consume some more bytes, simply unpause the
14874 // underlying stream.
14875 this._read = function (n) {
14876 debug('wrapped _read', n);
14877 if (paused) {
14878 paused = false;
14879 stream.resume();
14880 }
14881 };
14882
14883 return this;
14884};
14885
14886Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
14887 // making it explicit this property is not enumerable
14888 // because otherwise some prototype manipulation in
14889 // userland will fail
14890 enumerable: false,
14891 get: function () {
14892 return this._readableState.highWaterMark;
14893 }
14894});
14895
14896// exposed for testing purposes only.
14897Readable._fromList = fromList;
14898
14899// Pluck off n bytes from an array of buffers.
14900// Length is the combined lengths of all the buffers in the list.
14901// This function is designed to be inlinable, so please take care when making
14902// changes to the function body.
14903function fromList(n, state) {
14904 // nothing buffered
14905 if (state.length === 0) return null;
14906
14907 var ret;
14908 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
14909 // read it all, truncate the list
14910 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);
14911 state.buffer.clear();
14912 } else {
14913 // read part of list
14914 ret = fromListPartial(n, state.buffer, state.decoder);
14915 }
14916
14917 return ret;
14918}
14919
14920// Extracts only enough buffered data to satisfy the amount requested.
14921// This function is designed to be inlinable, so please take care when making
14922// changes to the function body.
14923function fromListPartial(n, list, hasStrings) {
14924 var ret;
14925 if (n < list.head.data.length) {
14926 // slice is the same for buffers and strings
14927 ret = list.head.data.slice(0, n);
14928 list.head.data = list.head.data.slice(n);
14929 } else if (n === list.head.data.length) {
14930 // first chunk is a perfect match
14931 ret = list.shift();
14932 } else {
14933 // result spans more than one buffer
14934 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
14935 }
14936 return ret;
14937}
14938
14939// Copies a specified amount of characters from the list of buffered data
14940// chunks.
14941// This function is designed to be inlinable, so please take care when making
14942// changes to the function body.
14943function copyFromBufferString(n, list) {
14944 var p = list.head;
14945 var c = 1;
14946 var ret = p.data;
14947 n -= ret.length;
14948 while (p = p.next) {
14949 var str = p.data;
14950 var nb = n > str.length ? str.length : n;
14951 if (nb === str.length) ret += str;else ret += str.slice(0, n);
14952 n -= nb;
14953 if (n === 0) {
14954 if (nb === str.length) {
14955 ++c;
14956 if (p.next) list.head = p.next;else list.head = list.tail = null;
14957 } else {
14958 list.head = p;
14959 p.data = str.slice(nb);
14960 }
14961 break;
14962 }
14963 ++c;
14964 }
14965 list.length -= c;
14966 return ret;
14967}
14968
14969// Copies a specified amount of bytes from the list of buffered data chunks.
14970// This function is designed to be inlinable, so please take care when making
14971// changes to the function body.
14972function copyFromBuffer(n, list) {
14973 var ret = Buffer.allocUnsafe(n);
14974 var p = list.head;
14975 var c = 1;
14976 p.data.copy(ret);
14977 n -= p.data.length;
14978 while (p = p.next) {
14979 var buf = p.data;
14980 var nb = n > buf.length ? buf.length : n;
14981 buf.copy(ret, ret.length - n, 0, nb);
14982 n -= nb;
14983 if (n === 0) {
14984 if (nb === buf.length) {
14985 ++c;
14986 if (p.next) list.head = p.next;else list.head = list.tail = null;
14987 } else {
14988 list.head = p;
14989 p.data = buf.slice(nb);
14990 }
14991 break;
14992 }
14993 ++c;
14994 }
14995 list.length -= c;
14996 return ret;
14997}
14998
14999function endReadable(stream) {
15000 var state = stream._readableState;
15001
15002 // If we get here before consuming all the bytes, then that is a
15003 // bug in node. Should never happen.
15004 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
15005
15006 if (!state.endEmitted) {
15007 state.ended = true;
15008 pna.nextTick(endReadableNT, state, stream);
15009 }
15010}
15011
15012function endReadableNT(state, stream) {
15013 // Check that we didn't get one last unshift.
15014 if (!state.endEmitted && state.length === 0) {
15015 state.endEmitted = true;
15016 stream.readable = false;
15017 stream.emit('end');
15018 }
15019}
15020
15021function indexOf(xs, x) {
15022 for (var i = 0, l = xs.length; i < l; i++) {
15023 if (xs[i] === x) return i;
15024 }
15025 return -1;
15026}
15027}).call(this,_dereq_(68),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
15028},{"10":10,"13":13,"18":18,"24":24,"67":67,"68":68,"80":80,"82":82,"87":87,"88":88,"89":89,"94":94,"95":95}],85:[function(_dereq_,module,exports){
15029// Copyright Joyent, Inc. and other Node contributors.
15030//
15031// Permission is hereby granted, free of charge, to any person obtaining a
15032// copy of this software and associated documentation files (the
15033// "Software"), to deal in the Software without restriction, including
15034// without limitation the rights to use, copy, modify, merge, publish,
15035// distribute, sublicense, and/or sell copies of the Software, and to permit
15036// persons to whom the Software is furnished to do so, subject to the
15037// following conditions:
15038//
15039// The above copyright notice and this permission notice shall be included
15040// in all copies or substantial portions of the Software.
15041//
15042// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15043// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15044// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15045// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15046// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15047// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15048// USE OR OTHER DEALINGS IN THE SOFTWARE.
15049
15050// a transform stream is a readable/writable stream where you do
15051// something with the data. Sometimes it's called a "filter",
15052// but that's not a great name for it, since that implies a thing where
15053// some bits pass through, and others are simply ignored. (That would
15054// be a valid example of a transform, of course.)
15055//
15056// While the output is causally related to the input, it's not a
15057// necessarily symmetric or synchronous transformation. For example,
15058// a zlib stream might take multiple plain-text writes(), and then
15059// emit a single compressed chunk some time in the future.
15060//
15061// Here's how this works:
15062//
15063// The Transform stream has all the aspects of the readable and writable
15064// stream classes. When you write(chunk), that calls _write(chunk,cb)
15065// internally, and returns false if there's a lot of pending writes
15066// buffered up. When you call read(), that calls _read(n) until
15067// there's enough pending readable data buffered up.
15068//
15069// In a transform stream, the written data is placed in a buffer. When
15070// _read(n) is called, it transforms the queued up data, calling the
15071// buffered _write cb's as it consumes chunks. If consuming a single
15072// written chunk would result in multiple output chunks, then the first
15073// outputted bit calls the readcb, and subsequent chunks just go into
15074// the read buffer, and will cause it to emit 'readable' if necessary.
15075//
15076// This way, back-pressure is actually determined by the reading side,
15077// since _read has to be called to start processing a new chunk. However,
15078// a pathological inflate type of transform can cause excessive buffering
15079// here. For example, imagine a stream where every byte of input is
15080// interpreted as an integer from 0-255, and then results in that many
15081// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
15082// 1kb of data being output. In this case, you could write a very small
15083// amount of input, and end up with a very large amount of output. In
15084// such a pathological inflating mechanism, there'd be no way to tell
15085// the system to stop doing the transform. A single 4MB write could
15086// cause the system to run out of memory.
15087//
15088// However, even in such a pathological case, only a single written chunk
15089// would be consumed, and then the rest would wait (un-transformed) until
15090// the results of the previous transformed chunk were consumed.
15091
15092'use strict';
15093
15094module.exports = Transform;
15095
15096var Duplex = _dereq_(82);
15097
15098/*<replacement>*/
15099var util = Object.create(_dereq_(13));
15100util.inherits = _dereq_(24);
15101/*</replacement>*/
15102
15103util.inherits(Transform, Duplex);
15104
15105function afterTransform(er, data) {
15106 var ts = this._transformState;
15107 ts.transforming = false;
15108
15109 var cb = ts.writecb;
15110
15111 if (!cb) {
15112 return this.emit('error', new Error('write callback called multiple times'));
15113 }
15114
15115 ts.writechunk = null;
15116 ts.writecb = null;
15117
15118 if (data != null) // single equals check for both `null` and `undefined`
15119 this.push(data);
15120
15121 cb(er);
15122
15123 var rs = this._readableState;
15124 rs.reading = false;
15125 if (rs.needReadable || rs.length < rs.highWaterMark) {
15126 this._read(rs.highWaterMark);
15127 }
15128}
15129
15130function Transform(options) {
15131 if (!(this instanceof Transform)) return new Transform(options);
15132
15133 Duplex.call(this, options);
15134
15135 this._transformState = {
15136 afterTransform: afterTransform.bind(this),
15137 needTransform: false,
15138 transforming: false,
15139 writecb: null,
15140 writechunk: null,
15141 writeencoding: null
15142 };
15143
15144 // start out asking for a readable event once data is transformed.
15145 this._readableState.needReadable = true;
15146
15147 // we have implemented the _read method, and done the other things
15148 // that Readable wants before the first _read call, so unset the
15149 // sync guard flag.
15150 this._readableState.sync = false;
15151
15152 if (options) {
15153 if (typeof options.transform === 'function') this._transform = options.transform;
15154
15155 if (typeof options.flush === 'function') this._flush = options.flush;
15156 }
15157
15158 // When the writable side finishes, then flush out anything remaining.
15159 this.on('prefinish', prefinish);
15160}
15161
15162function prefinish() {
15163 var _this = this;
15164
15165 if (typeof this._flush === 'function') {
15166 this._flush(function (er, data) {
15167 done(_this, er, data);
15168 });
15169 } else {
15170 done(this, null, null);
15171 }
15172}
15173
15174Transform.prototype.push = function (chunk, encoding) {
15175 this._transformState.needTransform = false;
15176 return Duplex.prototype.push.call(this, chunk, encoding);
15177};
15178
15179// This is the part where you do stuff!
15180// override this function in implementation classes.
15181// 'chunk' is an input chunk.
15182//
15183// Call `push(newChunk)` to pass along transformed output
15184// to the readable side. You may call 'push' zero or more times.
15185//
15186// Call `cb(err)` when you are done with this chunk. If you pass
15187// an error, then that'll put the hurt on the whole operation. If you
15188// never call cb(), then you'll never get another chunk.
15189Transform.prototype._transform = function (chunk, encoding, cb) {
15190 throw new Error('_transform() is not implemented');
15191};
15192
15193Transform.prototype._write = function (chunk, encoding, cb) {
15194 var ts = this._transformState;
15195 ts.writecb = cb;
15196 ts.writechunk = chunk;
15197 ts.writeencoding = encoding;
15198 if (!ts.transforming) {
15199 var rs = this._readableState;
15200 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
15201 }
15202};
15203
15204// Doesn't matter what the args are here.
15205// _transform does all the work.
15206// That we got here means that the readable side wants more data.
15207Transform.prototype._read = function (n) {
15208 var ts = this._transformState;
15209
15210 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
15211 ts.transforming = true;
15212 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
15213 } else {
15214 // mark that we need a transform, so that any data that comes in
15215 // will get processed, now that we've asked for it.
15216 ts.needTransform = true;
15217 }
15218};
15219
15220Transform.prototype._destroy = function (err, cb) {
15221 var _this2 = this;
15222
15223 Duplex.prototype._destroy.call(this, err, function (err2) {
15224 cb(err2);
15225 _this2.emit('close');
15226 });
15227};
15228
15229function done(stream, er, data) {
15230 if (er) return stream.emit('error', er);
15231
15232 if (data != null) // single equals check for both `null` and `undefined`
15233 stream.push(data);
15234
15235 // if there's nothing in the write buffer, then that means
15236 // that nothing more will ever be provided
15237 if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
15238
15239 if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
15240
15241 return stream.push(null);
15242}
15243},{"13":13,"24":24,"82":82}],86:[function(_dereq_,module,exports){
15244(function (process,global,setImmediate){
15245// Copyright Joyent, Inc. and other Node contributors.
15246//
15247// Permission is hereby granted, free of charge, to any person obtaining a
15248// copy of this software and associated documentation files (the
15249// "Software"), to deal in the Software without restriction, including
15250// without limitation the rights to use, copy, modify, merge, publish,
15251// distribute, sublicense, and/or sell copies of the Software, and to permit
15252// persons to whom the Software is furnished to do so, subject to the
15253// following conditions:
15254//
15255// The above copyright notice and this permission notice shall be included
15256// in all copies or substantial portions of the Software.
15257//
15258// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15259// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15260// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15261// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15262// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15263// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15264// USE OR OTHER DEALINGS IN THE SOFTWARE.
15265
15266// A bit simpler than readable streams.
15267// Implement an async ._write(chunk, encoding, cb), and it'll handle all
15268// the drain event emission and buffering.
15269
15270'use strict';
15271
15272/*<replacement>*/
15273
15274var pna = _dereq_(67);
15275/*</replacement>*/
15276
15277module.exports = Writable;
15278
15279/* <replacement> */
15280function WriteReq(chunk, encoding, cb) {
15281 this.chunk = chunk;
15282 this.encoding = encoding;
15283 this.callback = cb;
15284 this.next = null;
15285}
15286
15287// It seems a linked list but it is not
15288// there will be only 2 of these for each stream
15289function CorkedRequest(state) {
15290 var _this = this;
15291
15292 this.next = null;
15293 this.entry = null;
15294 this.finish = function () {
15295 onCorkedFinish(_this, state);
15296 };
15297}
15298/* </replacement> */
15299
15300/*<replacement>*/
15301var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
15302/*</replacement>*/
15303
15304/*<replacement>*/
15305var Duplex;
15306/*</replacement>*/
15307
15308Writable.WritableState = WritableState;
15309
15310/*<replacement>*/
15311var util = Object.create(_dereq_(13));
15312util.inherits = _dereq_(24);
15313/*</replacement>*/
15314
15315/*<replacement>*/
15316var internalUtil = {
15317 deprecate: _dereq_(115)
15318};
15319/*</replacement>*/
15320
15321/*<replacement>*/
15322var Stream = _dereq_(89);
15323/*</replacement>*/
15324
15325/*<replacement>*/
15326
15327var Buffer = _dereq_(94).Buffer;
15328var OurUint8Array = global.Uint8Array || function () {};
15329function _uint8ArrayToBuffer(chunk) {
15330 return Buffer.from(chunk);
15331}
15332function _isUint8Array(obj) {
15333 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
15334}
15335
15336/*</replacement>*/
15337
15338var destroyImpl = _dereq_(88);
15339
15340util.inherits(Writable, Stream);
15341
15342function nop() {}
15343
15344function WritableState(options, stream) {
15345 Duplex = Duplex || _dereq_(82);
15346
15347 options = options || {};
15348
15349 // Duplex streams are both readable and writable, but share
15350 // the same options object.
15351 // However, some cases require setting options to different
15352 // values for the readable and the writable sides of the duplex stream.
15353 // These options can be provided separately as readableXXX and writableXXX.
15354 var isDuplex = stream instanceof Duplex;
15355
15356 // object stream flag to indicate whether or not this stream
15357 // contains buffers or objects.
15358 this.objectMode = !!options.objectMode;
15359
15360 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
15361
15362 // the point at which write() starts returning false
15363 // Note: 0 is a valid value, means that we always return false if
15364 // the entire buffer is not flushed immediately on write()
15365 var hwm = options.highWaterMark;
15366 var writableHwm = options.writableHighWaterMark;
15367 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
15368
15369 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
15370
15371 // cast to ints.
15372 this.highWaterMark = Math.floor(this.highWaterMark);
15373
15374 // if _final has been called
15375 this.finalCalled = false;
15376
15377 // drain event flag.
15378 this.needDrain = false;
15379 // at the start of calling end()
15380 this.ending = false;
15381 // when end() has been called, and returned
15382 this.ended = false;
15383 // when 'finish' is emitted
15384 this.finished = false;
15385
15386 // has it been destroyed
15387 this.destroyed = false;
15388
15389 // should we decode strings into buffers before passing to _write?
15390 // this is here so that some node-core streams can optimize string
15391 // handling at a lower level.
15392 var noDecode = options.decodeStrings === false;
15393 this.decodeStrings = !noDecode;
15394
15395 // Crypto is kind of old and crusty. Historically, its default string
15396 // encoding is 'binary' so we have to make this configurable.
15397 // Everything else in the universe uses 'utf8', though.
15398 this.defaultEncoding = options.defaultEncoding || 'utf8';
15399
15400 // not an actual buffer we keep track of, but a measurement
15401 // of how much we're waiting to get pushed to some underlying
15402 // socket or file.
15403 this.length = 0;
15404
15405 // a flag to see when we're in the middle of a write.
15406 this.writing = false;
15407
15408 // when true all writes will be buffered until .uncork() call
15409 this.corked = 0;
15410
15411 // a flag to be able to tell if the onwrite cb is called immediately,
15412 // or on a later tick. We set this to true at first, because any
15413 // actions that shouldn't happen until "later" should generally also
15414 // not happen before the first write call.
15415 this.sync = true;
15416
15417 // a flag to know if we're processing previously buffered items, which
15418 // may call the _write() callback in the same tick, so that we don't
15419 // end up in an overlapped onwrite situation.
15420 this.bufferProcessing = false;
15421
15422 // the callback that's passed to _write(chunk,cb)
15423 this.onwrite = function (er) {
15424 onwrite(stream, er);
15425 };
15426
15427 // the callback that the user supplies to write(chunk,encoding,cb)
15428 this.writecb = null;
15429
15430 // the amount that is being written when _write is called.
15431 this.writelen = 0;
15432
15433 this.bufferedRequest = null;
15434 this.lastBufferedRequest = null;
15435
15436 // number of pending user-supplied write callbacks
15437 // this must be 0 before 'finish' can be emitted
15438 this.pendingcb = 0;
15439
15440 // emit prefinish if the only thing we're waiting for is _write cbs
15441 // This is relevant for synchronous Transform streams
15442 this.prefinished = false;
15443
15444 // True if the error was already emitted and should not be thrown again
15445 this.errorEmitted = false;
15446
15447 // count buffered requests
15448 this.bufferedRequestCount = 0;
15449
15450 // allocate the first CorkedRequest, there is always
15451 // one allocated and free to use, and we maintain at most two
15452 this.corkedRequestsFree = new CorkedRequest(this);
15453}
15454
15455WritableState.prototype.getBuffer = function getBuffer() {
15456 var current = this.bufferedRequest;
15457 var out = [];
15458 while (current) {
15459 out.push(current);
15460 current = current.next;
15461 }
15462 return out;
15463};
15464
15465(function () {
15466 try {
15467 Object.defineProperty(WritableState.prototype, 'buffer', {
15468 get: internalUtil.deprecate(function () {
15469 return this.getBuffer();
15470 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
15471 });
15472 } catch (_) {}
15473})();
15474
15475// Test _writableState for inheritance to account for Duplex streams,
15476// whose prototype chain only points to Readable.
15477var realHasInstance;
15478if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
15479 realHasInstance = Function.prototype[Symbol.hasInstance];
15480 Object.defineProperty(Writable, Symbol.hasInstance, {
15481 value: function (object) {
15482 if (realHasInstance.call(this, object)) return true;
15483 if (this !== Writable) return false;
15484
15485 return object && object._writableState instanceof WritableState;
15486 }
15487 });
15488} else {
15489 realHasInstance = function (object) {
15490 return object instanceof this;
15491 };
15492}
15493
15494function Writable(options) {
15495 Duplex = Duplex || _dereq_(82);
15496
15497 // Writable ctor is applied to Duplexes, too.
15498 // `realHasInstance` is necessary because using plain `instanceof`
15499 // would return false, as no `_writableState` property is attached.
15500
15501 // Trying to use the custom `instanceof` for Writable here will also break the
15502 // Node.js LazyTransform implementation, which has a non-trivial getter for
15503 // `_writableState` that would lead to infinite recursion.
15504 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
15505 return new Writable(options);
15506 }
15507
15508 this._writableState = new WritableState(options, this);
15509
15510 // legacy.
15511 this.writable = true;
15512
15513 if (options) {
15514 if (typeof options.write === 'function') this._write = options.write;
15515
15516 if (typeof options.writev === 'function') this._writev = options.writev;
15517
15518 if (typeof options.destroy === 'function') this._destroy = options.destroy;
15519
15520 if (typeof options.final === 'function') this._final = options.final;
15521 }
15522
15523 Stream.call(this);
15524}
15525
15526// Otherwise people can pipe Writable streams, which is just wrong.
15527Writable.prototype.pipe = function () {
15528 this.emit('error', new Error('Cannot pipe, not readable'));
15529};
15530
15531function writeAfterEnd(stream, cb) {
15532 var er = new Error('write after end');
15533 // TODO: defer error events consistently everywhere, not just the cb
15534 stream.emit('error', er);
15535 pna.nextTick(cb, er);
15536}
15537
15538// Checks that a user-supplied chunk is valid, especially for the particular
15539// mode the stream is in. Currently this means that `null` is never accepted
15540// and undefined/non-string values are only allowed in object mode.
15541function validChunk(stream, state, chunk, cb) {
15542 var valid = true;
15543 var er = false;
15544
15545 if (chunk === null) {
15546 er = new TypeError('May not write null values to stream');
15547 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
15548 er = new TypeError('Invalid non-string/buffer chunk');
15549 }
15550 if (er) {
15551 stream.emit('error', er);
15552 pna.nextTick(cb, er);
15553 valid = false;
15554 }
15555 return valid;
15556}
15557
15558Writable.prototype.write = function (chunk, encoding, cb) {
15559 var state = this._writableState;
15560 var ret = false;
15561 var isBuf = !state.objectMode && _isUint8Array(chunk);
15562
15563 if (isBuf && !Buffer.isBuffer(chunk)) {
15564 chunk = _uint8ArrayToBuffer(chunk);
15565 }
15566
15567 if (typeof encoding === 'function') {
15568 cb = encoding;
15569 encoding = null;
15570 }
15571
15572 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
15573
15574 if (typeof cb !== 'function') cb = nop;
15575
15576 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
15577 state.pendingcb++;
15578 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
15579 }
15580
15581 return ret;
15582};
15583
15584Writable.prototype.cork = function () {
15585 var state = this._writableState;
15586
15587 state.corked++;
15588};
15589
15590Writable.prototype.uncork = function () {
15591 var state = this._writableState;
15592
15593 if (state.corked) {
15594 state.corked--;
15595
15596 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
15597 }
15598};
15599
15600Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
15601 // node::ParseEncoding() requires lower case.
15602 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
15603 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);
15604 this._writableState.defaultEncoding = encoding;
15605 return this;
15606};
15607
15608function decodeChunk(state, chunk, encoding) {
15609 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
15610 chunk = Buffer.from(chunk, encoding);
15611 }
15612 return chunk;
15613}
15614
15615Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
15616 // making it explicit this property is not enumerable
15617 // because otherwise some prototype manipulation in
15618 // userland will fail
15619 enumerable: false,
15620 get: function () {
15621 return this._writableState.highWaterMark;
15622 }
15623});
15624
15625// if we're already writing something, then just put this
15626// in the queue, and wait our turn. Otherwise, call _write
15627// If we return false, then we need a drain event, so set that flag.
15628function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
15629 if (!isBuf) {
15630 var newChunk = decodeChunk(state, chunk, encoding);
15631 if (chunk !== newChunk) {
15632 isBuf = true;
15633 encoding = 'buffer';
15634 chunk = newChunk;
15635 }
15636 }
15637 var len = state.objectMode ? 1 : chunk.length;
15638
15639 state.length += len;
15640
15641 var ret = state.length < state.highWaterMark;
15642 // we must ensure that previous needDrain will not be reset to false.
15643 if (!ret) state.needDrain = true;
15644
15645 if (state.writing || state.corked) {
15646 var last = state.lastBufferedRequest;
15647 state.lastBufferedRequest = {
15648 chunk: chunk,
15649 encoding: encoding,
15650 isBuf: isBuf,
15651 callback: cb,
15652 next: null
15653 };
15654 if (last) {
15655 last.next = state.lastBufferedRequest;
15656 } else {
15657 state.bufferedRequest = state.lastBufferedRequest;
15658 }
15659 state.bufferedRequestCount += 1;
15660 } else {
15661 doWrite(stream, state, false, len, chunk, encoding, cb);
15662 }
15663
15664 return ret;
15665}
15666
15667function doWrite(stream, state, writev, len, chunk, encoding, cb) {
15668 state.writelen = len;
15669 state.writecb = cb;
15670 state.writing = true;
15671 state.sync = true;
15672 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
15673 state.sync = false;
15674}
15675
15676function onwriteError(stream, state, sync, er, cb) {
15677 --state.pendingcb;
15678
15679 if (sync) {
15680 // defer the callback if we are being called synchronously
15681 // to avoid piling up things on the stack
15682 pna.nextTick(cb, er);
15683 // this can emit finish, and it will always happen
15684 // after error
15685 pna.nextTick(finishMaybe, stream, state);
15686 stream._writableState.errorEmitted = true;
15687 stream.emit('error', er);
15688 } else {
15689 // the caller expect this to happen before if
15690 // it is async
15691 cb(er);
15692 stream._writableState.errorEmitted = true;
15693 stream.emit('error', er);
15694 // this can emit finish, but finish must
15695 // always follow error
15696 finishMaybe(stream, state);
15697 }
15698}
15699
15700function onwriteStateUpdate(state) {
15701 state.writing = false;
15702 state.writecb = null;
15703 state.length -= state.writelen;
15704 state.writelen = 0;
15705}
15706
15707function onwrite(stream, er) {
15708 var state = stream._writableState;
15709 var sync = state.sync;
15710 var cb = state.writecb;
15711
15712 onwriteStateUpdate(state);
15713
15714 if (er) onwriteError(stream, state, sync, er, cb);else {
15715 // Check if we're actually ready to finish, but don't emit yet
15716 var finished = needFinish(state);
15717
15718 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
15719 clearBuffer(stream, state);
15720 }
15721
15722 if (sync) {
15723 /*<replacement>*/
15724 asyncWrite(afterWrite, stream, state, finished, cb);
15725 /*</replacement>*/
15726 } else {
15727 afterWrite(stream, state, finished, cb);
15728 }
15729 }
15730}
15731
15732function afterWrite(stream, state, finished, cb) {
15733 if (!finished) onwriteDrain(stream, state);
15734 state.pendingcb--;
15735 cb();
15736 finishMaybe(stream, state);
15737}
15738
15739// Must force callback to be called on nextTick, so that we don't
15740// emit 'drain' before the write() consumer gets the 'false' return
15741// value, and has a chance to attach a 'drain' listener.
15742function onwriteDrain(stream, state) {
15743 if (state.length === 0 && state.needDrain) {
15744 state.needDrain = false;
15745 stream.emit('drain');
15746 }
15747}
15748
15749// if there's something in the buffer waiting, then process it
15750function clearBuffer(stream, state) {
15751 state.bufferProcessing = true;
15752 var entry = state.bufferedRequest;
15753
15754 if (stream._writev && entry && entry.next) {
15755 // Fast case, write everything using _writev()
15756 var l = state.bufferedRequestCount;
15757 var buffer = new Array(l);
15758 var holder = state.corkedRequestsFree;
15759 holder.entry = entry;
15760
15761 var count = 0;
15762 var allBuffers = true;
15763 while (entry) {
15764 buffer[count] = entry;
15765 if (!entry.isBuf) allBuffers = false;
15766 entry = entry.next;
15767 count += 1;
15768 }
15769 buffer.allBuffers = allBuffers;
15770
15771 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
15772
15773 // doWrite is almost always async, defer these to save a bit of time
15774 // as the hot path ends with doWrite
15775 state.pendingcb++;
15776 state.lastBufferedRequest = null;
15777 if (holder.next) {
15778 state.corkedRequestsFree = holder.next;
15779 holder.next = null;
15780 } else {
15781 state.corkedRequestsFree = new CorkedRequest(state);
15782 }
15783 state.bufferedRequestCount = 0;
15784 } else {
15785 // Slow case, write chunks one-by-one
15786 while (entry) {
15787 var chunk = entry.chunk;
15788 var encoding = entry.encoding;
15789 var cb = entry.callback;
15790 var len = state.objectMode ? 1 : chunk.length;
15791
15792 doWrite(stream, state, false, len, chunk, encoding, cb);
15793 entry = entry.next;
15794 state.bufferedRequestCount--;
15795 // if we didn't call the onwrite immediately, then
15796 // it means that we need to wait until it does.
15797 // also, that means that the chunk and cb are currently
15798 // being processed, so move the buffer counter past them.
15799 if (state.writing) {
15800 break;
15801 }
15802 }
15803
15804 if (entry === null) state.lastBufferedRequest = null;
15805 }
15806
15807 state.bufferedRequest = entry;
15808 state.bufferProcessing = false;
15809}
15810
15811Writable.prototype._write = function (chunk, encoding, cb) {
15812 cb(new Error('_write() is not implemented'));
15813};
15814
15815Writable.prototype._writev = null;
15816
15817Writable.prototype.end = function (chunk, encoding, cb) {
15818 var state = this._writableState;
15819
15820 if (typeof chunk === 'function') {
15821 cb = chunk;
15822 chunk = null;
15823 encoding = null;
15824 } else if (typeof encoding === 'function') {
15825 cb = encoding;
15826 encoding = null;
15827 }
15828
15829 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
15830
15831 // .end() fully uncorks
15832 if (state.corked) {
15833 state.corked = 1;
15834 this.uncork();
15835 }
15836
15837 // ignore unnecessary end() calls.
15838 if (!state.ending && !state.finished) endWritable(this, state, cb);
15839};
15840
15841function needFinish(state) {
15842 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
15843}
15844function callFinal(stream, state) {
15845 stream._final(function (err) {
15846 state.pendingcb--;
15847 if (err) {
15848 stream.emit('error', err);
15849 }
15850 state.prefinished = true;
15851 stream.emit('prefinish');
15852 finishMaybe(stream, state);
15853 });
15854}
15855function prefinish(stream, state) {
15856 if (!state.prefinished && !state.finalCalled) {
15857 if (typeof stream._final === 'function') {
15858 state.pendingcb++;
15859 state.finalCalled = true;
15860 pna.nextTick(callFinal, stream, state);
15861 } else {
15862 state.prefinished = true;
15863 stream.emit('prefinish');
15864 }
15865 }
15866}
15867
15868function finishMaybe(stream, state) {
15869 var need = needFinish(state);
15870 if (need) {
15871 prefinish(stream, state);
15872 if (state.pendingcb === 0) {
15873 state.finished = true;
15874 stream.emit('finish');
15875 }
15876 }
15877 return need;
15878}
15879
15880function endWritable(stream, state, cb) {
15881 state.ending = true;
15882 finishMaybe(stream, state);
15883 if (cb) {
15884 if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
15885 }
15886 state.ended = true;
15887 stream.writable = false;
15888}
15889
15890function onCorkedFinish(corkReq, state, err) {
15891 var entry = corkReq.entry;
15892 corkReq.entry = null;
15893 while (entry) {
15894 var cb = entry.callback;
15895 state.pendingcb--;
15896 cb(err);
15897 entry = entry.next;
15898 }
15899 if (state.corkedRequestsFree) {
15900 state.corkedRequestsFree.next = corkReq;
15901 } else {
15902 state.corkedRequestsFree = corkReq;
15903 }
15904}
15905
15906Object.defineProperty(Writable.prototype, 'destroyed', {
15907 get: function () {
15908 if (this._writableState === undefined) {
15909 return false;
15910 }
15911 return this._writableState.destroyed;
15912 },
15913 set: function (value) {
15914 // we ignore the value if the stream
15915 // has not been initialized yet
15916 if (!this._writableState) {
15917 return;
15918 }
15919
15920 // backward compatibility, the user is explicitly
15921 // managing destroyed
15922 this._writableState.destroyed = value;
15923 }
15924});
15925
15926Writable.prototype.destroy = destroyImpl.destroy;
15927Writable.prototype._undestroy = destroyImpl.undestroy;
15928Writable.prototype._destroy = function (err, cb) {
15929 this.end();
15930 cb(err);
15931};
15932}).call(this,_dereq_(68),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_(113).setImmediate)
15933},{"113":113,"115":115,"13":13,"24":24,"67":67,"68":68,"82":82,"88":88,"89":89,"94":94}],87:[function(_dereq_,module,exports){
15934'use strict';
15935
15936function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
15937
15938var Buffer = _dereq_(94).Buffer;
15939var util = _dereq_(10);
15940
15941function copyBuffer(src, target, offset) {
15942 src.copy(target, offset);
15943}
15944
15945module.exports = function () {
15946 function BufferList() {
15947 _classCallCheck(this, BufferList);
15948
15949 this.head = null;
15950 this.tail = null;
15951 this.length = 0;
15952 }
15953
15954 BufferList.prototype.push = function push(v) {
15955 var entry = { data: v, next: null };
15956 if (this.length > 0) this.tail.next = entry;else this.head = entry;
15957 this.tail = entry;
15958 ++this.length;
15959 };
15960
15961 BufferList.prototype.unshift = function unshift(v) {
15962 var entry = { data: v, next: this.head };
15963 if (this.length === 0) this.tail = entry;
15964 this.head = entry;
15965 ++this.length;
15966 };
15967
15968 BufferList.prototype.shift = function shift() {
15969 if (this.length === 0) return;
15970 var ret = this.head.data;
15971 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
15972 --this.length;
15973 return ret;
15974 };
15975
15976 BufferList.prototype.clear = function clear() {
15977 this.head = this.tail = null;
15978 this.length = 0;
15979 };
15980
15981 BufferList.prototype.join = function join(s) {
15982 if (this.length === 0) return '';
15983 var p = this.head;
15984 var ret = '' + p.data;
15985 while (p = p.next) {
15986 ret += s + p.data;
15987 }return ret;
15988 };
15989
15990 BufferList.prototype.concat = function concat(n) {
15991 if (this.length === 0) return Buffer.alloc(0);
15992 if (this.length === 1) return this.head.data;
15993 var ret = Buffer.allocUnsafe(n >>> 0);
15994 var p = this.head;
15995 var i = 0;
15996 while (p) {
15997 copyBuffer(p.data, ret, i);
15998 i += p.data.length;
15999 p = p.next;
16000 }
16001 return ret;
16002 };
16003
16004 return BufferList;
16005}();
16006
16007if (util && util.inspect && util.inspect.custom) {
16008 module.exports.prototype[util.inspect.custom] = function () {
16009 var obj = util.inspect({ length: this.length });
16010 return this.constructor.name + ' ' + obj;
16011 };
16012}
16013},{"10":10,"94":94}],88:[function(_dereq_,module,exports){
16014'use strict';
16015
16016/*<replacement>*/
16017
16018var pna = _dereq_(67);
16019/*</replacement>*/
16020
16021// undocumented cb() API, needed for core, not for public API
16022function destroy(err, cb) {
16023 var _this = this;
16024
16025 var readableDestroyed = this._readableState && this._readableState.destroyed;
16026 var writableDestroyed = this._writableState && this._writableState.destroyed;
16027
16028 if (readableDestroyed || writableDestroyed) {
16029 if (cb) {
16030 cb(err);
16031 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
16032 pna.nextTick(emitErrorNT, this, err);
16033 }
16034 return this;
16035 }
16036
16037 // we set destroyed to true before firing error callbacks in order
16038 // to make it re-entrance safe in case destroy() is called within callbacks
16039
16040 if (this._readableState) {
16041 this._readableState.destroyed = true;
16042 }
16043
16044 // if this is a duplex stream mark the writable part as destroyed as well
16045 if (this._writableState) {
16046 this._writableState.destroyed = true;
16047 }
16048
16049 this._destroy(err || null, function (err) {
16050 if (!cb && err) {
16051 pna.nextTick(emitErrorNT, _this, err);
16052 if (_this._writableState) {
16053 _this._writableState.errorEmitted = true;
16054 }
16055 } else if (cb) {
16056 cb(err);
16057 }
16058 });
16059
16060 return this;
16061}
16062
16063function undestroy() {
16064 if (this._readableState) {
16065 this._readableState.destroyed = false;
16066 this._readableState.reading = false;
16067 this._readableState.ended = false;
16068 this._readableState.endEmitted = false;
16069 }
16070
16071 if (this._writableState) {
16072 this._writableState.destroyed = false;
16073 this._writableState.ended = false;
16074 this._writableState.ending = false;
16075 this._writableState.finished = false;
16076 this._writableState.errorEmitted = false;
16077 }
16078}
16079
16080function emitErrorNT(self, err) {
16081 self.emit('error', err);
16082}
16083
16084module.exports = {
16085 destroy: destroy,
16086 undestroy: undestroy
16087};
16088},{"67":67}],89:[function(_dereq_,module,exports){
16089arguments[4][44][0].apply(exports,arguments)
16090},{"18":18,"44":44}],90:[function(_dereq_,module,exports){
16091module.exports = _dereq_(91).PassThrough
16092
16093},{"91":91}],91:[function(_dereq_,module,exports){
16094exports = module.exports = _dereq_(84);
16095exports.Stream = exports;
16096exports.Readable = exports;
16097exports.Writable = _dereq_(86);
16098exports.Duplex = _dereq_(82);
16099exports.Transform = _dereq_(85);
16100exports.PassThrough = _dereq_(83);
16101
16102},{"82":82,"83":83,"84":84,"85":85,"86":86}],92:[function(_dereq_,module,exports){
16103module.exports = _dereq_(91).Transform
16104
16105},{"91":91}],93:[function(_dereq_,module,exports){
16106module.exports = _dereq_(86);
16107
16108},{"86":86}],94:[function(_dereq_,module,exports){
16109/* eslint-disable node/no-deprecated-api */
16110var buffer = _dereq_(12)
16111var Buffer = buffer.Buffer
16112
16113// alternative to using Object.keys for old browsers
16114function copyProps (src, dst) {
16115 for (var key in src) {
16116 dst[key] = src[key]
16117 }
16118}
16119if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
16120 module.exports = buffer
16121} else {
16122 // Copy properties from require('buffer')
16123 copyProps(buffer, exports)
16124 exports.Buffer = SafeBuffer
16125}
16126
16127function SafeBuffer (arg, encodingOrOffset, length) {
16128 return Buffer(arg, encodingOrOffset, length)
16129}
16130
16131// Copy static methods from Buffer
16132copyProps(Buffer, SafeBuffer)
16133
16134SafeBuffer.from = function (arg, encodingOrOffset, length) {
16135 if (typeof arg === 'number') {
16136 throw new TypeError('Argument must not be a number')
16137 }
16138 return Buffer(arg, encodingOrOffset, length)
16139}
16140
16141SafeBuffer.alloc = function (size, fill, encoding) {
16142 if (typeof size !== 'number') {
16143 throw new TypeError('Argument must be a number')
16144 }
16145 var buf = Buffer(size)
16146 if (fill !== undefined) {
16147 if (typeof encoding === 'string') {
16148 buf.fill(fill, encoding)
16149 } else {
16150 buf.fill(fill)
16151 }
16152 } else {
16153 buf.fill(0)
16154 }
16155 return buf
16156}
16157
16158SafeBuffer.allocUnsafe = function (size) {
16159 if (typeof size !== 'number') {
16160 throw new TypeError('Argument must be a number')
16161 }
16162 return Buffer(size)
16163}
16164
16165SafeBuffer.allocUnsafeSlow = function (size) {
16166 if (typeof size !== 'number') {
16167 throw new TypeError('Argument must be a number')
16168 }
16169 return buffer.SlowBuffer(size)
16170}
16171
16172},{"12":12}],95:[function(_dereq_,module,exports){
16173// Copyright Joyent, Inc. and other Node contributors.
16174//
16175// Permission is hereby granted, free of charge, to any person obtaining a
16176// copy of this software and associated documentation files (the
16177// "Software"), to deal in the Software without restriction, including
16178// without limitation the rights to use, copy, modify, merge, publish,
16179// distribute, sublicense, and/or sell copies of the Software, and to permit
16180// persons to whom the Software is furnished to do so, subject to the
16181// following conditions:
16182//
16183// The above copyright notice and this permission notice shall be included
16184// in all copies or substantial portions of the Software.
16185//
16186// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16187// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16188// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
16189// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
16190// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16191// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
16192// USE OR OTHER DEALINGS IN THE SOFTWARE.
16193
16194'use strict';
16195
16196/*<replacement>*/
16197
16198var Buffer = _dereq_(94).Buffer;
16199/*</replacement>*/
16200
16201var isEncoding = Buffer.isEncoding || function (encoding) {
16202 encoding = '' + encoding;
16203 switch (encoding && encoding.toLowerCase()) {
16204 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':
16205 return true;
16206 default:
16207 return false;
16208 }
16209};
16210
16211function _normalizeEncoding(enc) {
16212 if (!enc) return 'utf8';
16213 var retried;
16214 while (true) {
16215 switch (enc) {
16216 case 'utf8':
16217 case 'utf-8':
16218 return 'utf8';
16219 case 'ucs2':
16220 case 'ucs-2':
16221 case 'utf16le':
16222 case 'utf-16le':
16223 return 'utf16le';
16224 case 'latin1':
16225 case 'binary':
16226 return 'latin1';
16227 case 'base64':
16228 case 'ascii':
16229 case 'hex':
16230 return enc;
16231 default:
16232 if (retried) return; // undefined
16233 enc = ('' + enc).toLowerCase();
16234 retried = true;
16235 }
16236 }
16237};
16238
16239// Do not cache `Buffer.isEncoding` when checking encoding names as some
16240// modules monkey-patch it to support additional encodings
16241function normalizeEncoding(enc) {
16242 var nenc = _normalizeEncoding(enc);
16243 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
16244 return nenc || enc;
16245}
16246
16247// StringDecoder provides an interface for efficiently splitting a series of
16248// buffers into a series of JS strings without breaking apart multi-byte
16249// characters.
16250exports.StringDecoder = StringDecoder;
16251function StringDecoder(encoding) {
16252 this.encoding = normalizeEncoding(encoding);
16253 var nb;
16254 switch (this.encoding) {
16255 case 'utf16le':
16256 this.text = utf16Text;
16257 this.end = utf16End;
16258 nb = 4;
16259 break;
16260 case 'utf8':
16261 this.fillLast = utf8FillLast;
16262 nb = 4;
16263 break;
16264 case 'base64':
16265 this.text = base64Text;
16266 this.end = base64End;
16267 nb = 3;
16268 break;
16269 default:
16270 this.write = simpleWrite;
16271 this.end = simpleEnd;
16272 return;
16273 }
16274 this.lastNeed = 0;
16275 this.lastTotal = 0;
16276 this.lastChar = Buffer.allocUnsafe(nb);
16277}
16278
16279StringDecoder.prototype.write = function (buf) {
16280 if (buf.length === 0) return '';
16281 var r;
16282 var i;
16283 if (this.lastNeed) {
16284 r = this.fillLast(buf);
16285 if (r === undefined) return '';
16286 i = this.lastNeed;
16287 this.lastNeed = 0;
16288 } else {
16289 i = 0;
16290 }
16291 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
16292 return r || '';
16293};
16294
16295StringDecoder.prototype.end = utf8End;
16296
16297// Returns only complete characters in a Buffer
16298StringDecoder.prototype.text = utf8Text;
16299
16300// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
16301StringDecoder.prototype.fillLast = function (buf) {
16302 if (this.lastNeed <= buf.length) {
16303 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
16304 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
16305 }
16306 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
16307 this.lastNeed -= buf.length;
16308};
16309
16310// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
16311// continuation byte. If an invalid byte is detected, -2 is returned.
16312function utf8CheckByte(byte) {
16313 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;
16314 return byte >> 6 === 0x02 ? -1 : -2;
16315}
16316
16317// Checks at most 3 bytes at the end of a Buffer in order to detect an
16318// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
16319// needed to complete the UTF-8 character (if applicable) are returned.
16320function utf8CheckIncomplete(self, buf, i) {
16321 var j = buf.length - 1;
16322 if (j < i) return 0;
16323 var nb = utf8CheckByte(buf[j]);
16324 if (nb >= 0) {
16325 if (nb > 0) self.lastNeed = nb - 1;
16326 return nb;
16327 }
16328 if (--j < i || nb === -2) return 0;
16329 nb = utf8CheckByte(buf[j]);
16330 if (nb >= 0) {
16331 if (nb > 0) self.lastNeed = nb - 2;
16332 return nb;
16333 }
16334 if (--j < i || nb === -2) return 0;
16335 nb = utf8CheckByte(buf[j]);
16336 if (nb >= 0) {
16337 if (nb > 0) {
16338 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
16339 }
16340 return nb;
16341 }
16342 return 0;
16343}
16344
16345// Validates as many continuation bytes for a multi-byte UTF-8 character as
16346// needed or are available. If we see a non-continuation byte where we expect
16347// one, we "replace" the validated continuation bytes we've seen so far with
16348// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
16349// behavior. The continuation byte check is included three times in the case
16350// where all of the continuation bytes for a character exist in the same buffer.
16351// It is also done this way as a slight performance increase instead of using a
16352// loop.
16353function utf8CheckExtraBytes(self, buf, p) {
16354 if ((buf[0] & 0xC0) !== 0x80) {
16355 self.lastNeed = 0;
16356 return '\ufffd';
16357 }
16358 if (self.lastNeed > 1 && buf.length > 1) {
16359 if ((buf[1] & 0xC0) !== 0x80) {
16360 self.lastNeed = 1;
16361 return '\ufffd';
16362 }
16363 if (self.lastNeed > 2 && buf.length > 2) {
16364 if ((buf[2] & 0xC0) !== 0x80) {
16365 self.lastNeed = 2;
16366 return '\ufffd';
16367 }
16368 }
16369 }
16370}
16371
16372// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
16373function utf8FillLast(buf) {
16374 var p = this.lastTotal - this.lastNeed;
16375 var r = utf8CheckExtraBytes(this, buf, p);
16376 if (r !== undefined) return r;
16377 if (this.lastNeed <= buf.length) {
16378 buf.copy(this.lastChar, p, 0, this.lastNeed);
16379 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
16380 }
16381 buf.copy(this.lastChar, p, 0, buf.length);
16382 this.lastNeed -= buf.length;
16383}
16384
16385// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
16386// partial character, the character's bytes are buffered until the required
16387// number of bytes are available.
16388function utf8Text(buf, i) {
16389 var total = utf8CheckIncomplete(this, buf, i);
16390 if (!this.lastNeed) return buf.toString('utf8', i);
16391 this.lastTotal = total;
16392 var end = buf.length - (total - this.lastNeed);
16393 buf.copy(this.lastChar, 0, end);
16394 return buf.toString('utf8', i, end);
16395}
16396
16397// For UTF-8, a replacement character is added when ending on a partial
16398// character.
16399function utf8End(buf) {
16400 var r = buf && buf.length ? this.write(buf) : '';
16401 if (this.lastNeed) return r + '\ufffd';
16402 return r;
16403}
16404
16405// UTF-16LE typically needs two bytes per character, but even if we have an even
16406// number of bytes available, we need to check if we end on a leading/high
16407// surrogate. In that case, we need to wait for the next two bytes in order to
16408// decode the last character properly.
16409function utf16Text(buf, i) {
16410 if ((buf.length - i) % 2 === 0) {
16411 var r = buf.toString('utf16le', i);
16412 if (r) {
16413 var c = r.charCodeAt(r.length - 1);
16414 if (c >= 0xD800 && c <= 0xDBFF) {
16415 this.lastNeed = 2;
16416 this.lastTotal = 4;
16417 this.lastChar[0] = buf[buf.length - 2];
16418 this.lastChar[1] = buf[buf.length - 1];
16419 return r.slice(0, -1);
16420 }
16421 }
16422 return r;
16423 }
16424 this.lastNeed = 1;
16425 this.lastTotal = 2;
16426 this.lastChar[0] = buf[buf.length - 1];
16427 return buf.toString('utf16le', i, buf.length - 1);
16428}
16429
16430// For UTF-16LE we do not explicitly append special replacement characters if we
16431// end on a partial character, we simply let v8 handle that.
16432function utf16End(buf) {
16433 var r = buf && buf.length ? this.write(buf) : '';
16434 if (this.lastNeed) {
16435 var end = this.lastTotal - this.lastNeed;
16436 return r + this.lastChar.toString('utf16le', 0, end);
16437 }
16438 return r;
16439}
16440
16441function base64Text(buf, i) {
16442 var n = (buf.length - i) % 3;
16443 if (n === 0) return buf.toString('base64', i);
16444 this.lastNeed = 3 - n;
16445 this.lastTotal = 3;
16446 if (n === 1) {
16447 this.lastChar[0] = buf[buf.length - 1];
16448 } else {
16449 this.lastChar[0] = buf[buf.length - 2];
16450 this.lastChar[1] = buf[buf.length - 1];
16451 }
16452 return buf.toString('base64', i, buf.length - n);
16453}
16454
16455function base64End(buf) {
16456 var r = buf && buf.length ? this.write(buf) : '';
16457 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
16458 return r;
16459}
16460
16461// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
16462function simpleWrite(buf) {
16463 return buf.toString(this.encoding);
16464}
16465
16466function simpleEnd(buf) {
16467 return buf && buf.length ? this.write(buf) : '';
16468}
16469},{"94":94}],96:[function(_dereq_,module,exports){
16470arguments[4][95][0].apply(exports,arguments)
16471},{"77":77,"95":95}],97:[function(_dereq_,module,exports){
16472arguments[4][31][0].apply(exports,arguments)
16473},{"31":31}],98:[function(_dereq_,module,exports){
16474arguments[4][32][0].apply(exports,arguments)
16475},{"100":100,"102":102,"24":24,"32":32,"68":68}],99:[function(_dereq_,module,exports){
16476arguments[4][33][0].apply(exports,arguments)
16477},{"101":101,"24":24,"33":33}],100:[function(_dereq_,module,exports){
16478arguments[4][34][0].apply(exports,arguments)
16479},{"10":10,"103":103,"104":104,"105":105,"107":107,"109":109,"110":110,"12":12,"18":18,"24":24,"34":34,"68":68,"96":96,"97":97,"98":98}],101:[function(_dereq_,module,exports){
16480arguments[4][35][0].apply(exports,arguments)
16481},{"24":24,"35":35,"97":97,"98":98}],102:[function(_dereq_,module,exports){
16482arguments[4][36][0].apply(exports,arguments)
16483},{"105":105,"109":109,"110":110,"115":115,"12":12,"24":24,"36":36,"68":68,"97":97,"98":98}],103:[function(_dereq_,module,exports){
16484arguments[4][37][0].apply(exports,arguments)
16485},{"106":106,"37":37,"68":68}],104:[function(_dereq_,module,exports){
16486arguments[4][38][0].apply(exports,arguments)
16487},{"10":10,"12":12,"38":38}],105:[function(_dereq_,module,exports){
16488arguments[4][39][0].apply(exports,arguments)
16489},{"39":39,"68":68}],106:[function(_dereq_,module,exports){
16490arguments[4][40][0].apply(exports,arguments)
16491},{"40":40,"97":97}],107:[function(_dereq_,module,exports){
16492arguments[4][41][0].apply(exports,arguments)
16493},{"41":41}],108:[function(_dereq_,module,exports){
16494arguments[4][42][0].apply(exports,arguments)
16495},{"106":106,"42":42,"97":97}],109:[function(_dereq_,module,exports){
16496arguments[4][43][0].apply(exports,arguments)
16497},{"43":43,"97":97}],110:[function(_dereq_,module,exports){
16498arguments[4][44][0].apply(exports,arguments)
16499},{"18":18,"44":44}],111:[function(_dereq_,module,exports){
16500arguments[4][45][0].apply(exports,arguments)
16501},{"100":100,"101":101,"102":102,"106":106,"108":108,"45":45,"98":98,"99":99}],112:[function(_dereq_,module,exports){
16502(function (process){
16503var Transform = _dereq_(111).Transform
16504 , inherits = _dereq_(118).inherits
16505
16506function DestroyableTransform(opts) {
16507 Transform.call(this, opts)
16508 this._destroyed = false
16509}
16510
16511inherits(DestroyableTransform, Transform)
16512
16513DestroyableTransform.prototype.destroy = function(err) {
16514 if (this._destroyed) return
16515 this._destroyed = true
16516
16517 var self = this
16518 process.nextTick(function() {
16519 if (err)
16520 self.emit('error', err)
16521 self.emit('close')
16522 })
16523}
16524
16525// a noop _transform function
16526function noop (chunk, enc, callback) {
16527 callback(null, chunk)
16528}
16529
16530
16531// create a new export function, used by both the main export and
16532// the .ctor export, contains common logic for dealing with arguments
16533function through2 (construct) {
16534 return function (options, transform, flush) {
16535 if (typeof options == 'function') {
16536 flush = transform
16537 transform = options
16538 options = {}
16539 }
16540
16541 if (typeof transform != 'function')
16542 transform = noop
16543
16544 if (typeof flush != 'function')
16545 flush = null
16546
16547 return construct(options, transform, flush)
16548 }
16549}
16550
16551
16552// main export, just make me a transform stream!
16553module.exports = through2(function (options, transform, flush) {
16554 var t2 = new DestroyableTransform(options)
16555
16556 t2._transform = transform
16557
16558 if (flush)
16559 t2._flush = flush
16560
16561 return t2
16562})
16563
16564
16565// make me a reusable prototype that I can `new`, or implicitly `new`
16566// with a constructor call
16567module.exports.ctor = through2(function (options, transform, flush) {
16568 function Through2 (override) {
16569 if (!(this instanceof Through2))
16570 return new Through2(override)
16571
16572 this.options = Object.assign({}, options, override)
16573
16574 DestroyableTransform.call(this, this.options)
16575 }
16576
16577 inherits(Through2, DestroyableTransform)
16578
16579 Through2.prototype._transform = transform
16580
16581 if (flush)
16582 Through2.prototype._flush = flush
16583
16584 return Through2
16585})
16586
16587
16588module.exports.obj = through2(function (options, transform, flush) {
16589 var t2 = new DestroyableTransform(Object.assign({ objectMode: true, highWaterMark: 16 }, options))
16590
16591 t2._transform = transform
16592
16593 if (flush)
16594 t2._flush = flush
16595
16596 return t2
16597})
16598
16599}).call(this,_dereq_(68))
16600},{"111":111,"118":118,"68":68}],113:[function(_dereq_,module,exports){
16601(function (setImmediate,clearImmediate){
16602var nextTick = _dereq_(68).nextTick;
16603var apply = Function.prototype.apply;
16604var slice = Array.prototype.slice;
16605var immediateIds = {};
16606var nextImmediateId = 0;
16607
16608// DOM APIs, for completeness
16609
16610exports.setTimeout = function() {
16611 return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
16612};
16613exports.setInterval = function() {
16614 return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
16615};
16616exports.clearTimeout =
16617exports.clearInterval = function(timeout) { timeout.close(); };
16618
16619function Timeout(id, clearFn) {
16620 this._id = id;
16621 this._clearFn = clearFn;
16622}
16623Timeout.prototype.unref = Timeout.prototype.ref = function() {};
16624Timeout.prototype.close = function() {
16625 this._clearFn.call(window, this._id);
16626};
16627
16628// Does not start the time, just sets up the members needed.
16629exports.enroll = function(item, msecs) {
16630 clearTimeout(item._idleTimeoutId);
16631 item._idleTimeout = msecs;
16632};
16633
16634exports.unenroll = function(item) {
16635 clearTimeout(item._idleTimeoutId);
16636 item._idleTimeout = -1;
16637};
16638
16639exports._unrefActive = exports.active = function(item) {
16640 clearTimeout(item._idleTimeoutId);
16641
16642 var msecs = item._idleTimeout;
16643 if (msecs >= 0) {
16644 item._idleTimeoutId = setTimeout(function onTimeout() {
16645 if (item._onTimeout)
16646 item._onTimeout();
16647 }, msecs);
16648 }
16649};
16650
16651// That's not how node.js implements it but the exposed api is the same.
16652exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
16653 var id = nextImmediateId++;
16654 var args = arguments.length < 2 ? false : slice.call(arguments, 1);
16655
16656 immediateIds[id] = true;
16657
16658 nextTick(function onNextTick() {
16659 if (immediateIds[id]) {
16660 // fn.call() is faster so we optimize for the common use-case
16661 // @see http://jsperf.com/call-apply-segu
16662 if (args) {
16663 fn.apply(null, args);
16664 } else {
16665 fn.call(null);
16666 }
16667 // Prevent ids from leaking
16668 exports.clearImmediate(id);
16669 }
16670 });
16671
16672 return id;
16673};
16674
16675exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
16676 delete immediateIds[id];
16677};
16678}).call(this,_dereq_(113).setImmediate,_dereq_(113).clearImmediate)
16679},{"113":113,"68":68}],114:[function(_dereq_,module,exports){
16680'use strict';
16681
16682// Simple FIFO queue implementation to avoid having to do shift()
16683// on an array, which is slow.
16684
16685function Queue() {
16686 this.length = 0;
16687}
16688
16689Queue.prototype.push = function (item) {
16690 var node = {item: item};
16691 if (this.last) {
16692 this.last = this.last.next = node;
16693 } else {
16694 this.last = this.first = node;
16695 }
16696 this.length++;
16697};
16698
16699Queue.prototype.shift = function () {
16700 var node = this.first;
16701 if (node) {
16702 this.first = node.next;
16703 if (!(--this.length)) {
16704 this.last = undefined;
16705 }
16706 return node.item;
16707 }
16708};
16709
16710Queue.prototype.slice = function (start, end) {
16711 start = typeof start === 'undefined' ? 0 : start;
16712 end = typeof end === 'undefined' ? Infinity : end;
16713
16714 var output = [];
16715
16716 var i = 0;
16717 for (var node = this.first; node; node = node.next) {
16718 if (--end < 0) {
16719 break;
16720 } else if (++i > start) {
16721 output.push(node.item);
16722 }
16723 }
16724 return output;
16725}
16726
16727module.exports = Queue;
16728
16729},{}],115:[function(_dereq_,module,exports){
16730(function (global){
16731
16732/**
16733 * Module exports.
16734 */
16735
16736module.exports = deprecate;
16737
16738/**
16739 * Mark that a method should not be used.
16740 * Returns a modified function which warns once by default.
16741 *
16742 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
16743 *
16744 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
16745 * will throw an Error when invoked.
16746 *
16747 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
16748 * will invoke `console.trace()` instead of `console.error()`.
16749 *
16750 * @param {Function} fn - the function to deprecate
16751 * @param {String} msg - the string to print to the console when `fn` is invoked
16752 * @returns {Function} a new "deprecated" version of `fn`
16753 * @api public
16754 */
16755
16756function deprecate (fn, msg) {
16757 if (config('noDeprecation')) {
16758 return fn;
16759 }
16760
16761 var warned = false;
16762 function deprecated() {
16763 if (!warned) {
16764 if (config('throwDeprecation')) {
16765 throw new Error(msg);
16766 } else if (config('traceDeprecation')) {
16767 console.trace(msg);
16768 } else {
16769 console.warn(msg);
16770 }
16771 warned = true;
16772 }
16773 return fn.apply(this, arguments);
16774 }
16775
16776 return deprecated;
16777}
16778
16779/**
16780 * Checks `localStorage` for boolean values for the given `name`.
16781 *
16782 * @param {String} name
16783 * @returns {Boolean}
16784 * @api private
16785 */
16786
16787function config (name) {
16788 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
16789 try {
16790 if (!global.localStorage) return false;
16791 } catch (_) {
16792 return false;
16793 }
16794 var val = global.localStorage[name];
16795 if (null == val) return false;
16796 return String(val).toLowerCase() === 'true';
16797}
16798
16799}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
16800},{}],116:[function(_dereq_,module,exports){
16801arguments[4][6][0].apply(exports,arguments)
16802},{"6":6}],117:[function(_dereq_,module,exports){
16803arguments[4][7][0].apply(exports,arguments)
16804},{"7":7}],118:[function(_dereq_,module,exports){
16805arguments[4][8][0].apply(exports,arguments)
16806},{"116":116,"117":117,"68":68,"8":8}],119:[function(_dereq_,module,exports){
16807var v1 = _dereq_(122);
16808var v4 = _dereq_(123);
16809
16810var uuid = v4;
16811uuid.v1 = v1;
16812uuid.v4 = v4;
16813
16814module.exports = uuid;
16815
16816},{"122":122,"123":123}],120:[function(_dereq_,module,exports){
16817/**
16818 * Convert array of 16 byte values to UUID string format of the form:
16819 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
16820 */
16821var byteToHex = [];
16822for (var i = 0; i < 256; ++i) {
16823 byteToHex[i] = (i + 0x100).toString(16).substr(1);
16824}
16825
16826function bytesToUuid(buf, offset) {
16827 var i = offset || 0;
16828 var bth = byteToHex;
16829 // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
16830 return ([bth[buf[i++]], bth[buf[i++]],
16831 bth[buf[i++]], bth[buf[i++]], '-',
16832 bth[buf[i++]], bth[buf[i++]], '-',
16833 bth[buf[i++]], bth[buf[i++]], '-',
16834 bth[buf[i++]], bth[buf[i++]], '-',
16835 bth[buf[i++]], bth[buf[i++]],
16836 bth[buf[i++]], bth[buf[i++]],
16837 bth[buf[i++]], bth[buf[i++]]]).join('');
16838}
16839
16840module.exports = bytesToUuid;
16841
16842},{}],121:[function(_dereq_,module,exports){
16843// Unique ID creation requires a high quality random # generator. In the
16844// browser this is a little complicated due to unknown quality of Math.random()
16845// and inconsistent support for the `crypto` API. We do the best we can via
16846// feature-detection
16847
16848// getRandomValues needs to be invoked in a context where "this" is a Crypto
16849// implementation. Also, find the complete implementation of crypto on IE11.
16850var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
16851 (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));
16852
16853if (getRandomValues) {
16854 // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
16855 var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
16856
16857 module.exports = function whatwgRNG() {
16858 getRandomValues(rnds8);
16859 return rnds8;
16860 };
16861} else {
16862 // Math.random()-based (RNG)
16863 //
16864 // If all else fails, use Math.random(). It's fast, but is of unspecified
16865 // quality.
16866 var rnds = new Array(16);
16867
16868 module.exports = function mathRNG() {
16869 for (var i = 0, r; i < 16; i++) {
16870 if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
16871 rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
16872 }
16873
16874 return rnds;
16875 };
16876}
16877
16878},{}],122:[function(_dereq_,module,exports){
16879var rng = _dereq_(121);
16880var bytesToUuid = _dereq_(120);
16881
16882// **`v1()` - Generate time-based UUID**
16883//
16884// Inspired by https://github.com/LiosK/UUID.js
16885// and http://docs.python.org/library/uuid.html
16886
16887var _nodeId;
16888var _clockseq;
16889
16890// Previous uuid creation time
16891var _lastMSecs = 0;
16892var _lastNSecs = 0;
16893
16894// See https://github.com/broofa/node-uuid for API details
16895function v1(options, buf, offset) {
16896 var i = buf && offset || 0;
16897 var b = buf || [];
16898
16899 options = options || {};
16900 var node = options.node || _nodeId;
16901 var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
16902
16903 // node and clockseq need to be initialized to random values if they're not
16904 // specified. We do this lazily to minimize issues related to insufficient
16905 // system entropy. See #189
16906 if (node == null || clockseq == null) {
16907 var seedBytes = rng();
16908 if (node == null) {
16909 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
16910 node = _nodeId = [
16911 seedBytes[0] | 0x01,
16912 seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]
16913 ];
16914 }
16915 if (clockseq == null) {
16916 // Per 4.2.2, randomize (14 bit) clockseq
16917 clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
16918 }
16919 }
16920
16921 // UUID timestamps are 100 nano-second units since the Gregorian epoch,
16922 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
16923 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
16924 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
16925 var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
16926
16927 // Per 4.2.1.2, use count of uuid's generated during the current clock
16928 // cycle to simulate higher resolution clock
16929 var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
16930
16931 // Time since last uuid creation (in msecs)
16932 var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
16933
16934 // Per 4.2.1.2, Bump clockseq on clock regression
16935 if (dt < 0 && options.clockseq === undefined) {
16936 clockseq = clockseq + 1 & 0x3fff;
16937 }
16938
16939 // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
16940 // time interval
16941 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
16942 nsecs = 0;
16943 }
16944
16945 // Per 4.2.1.2 Throw error if too many uuids are requested
16946 if (nsecs >= 10000) {
16947 throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
16948 }
16949
16950 _lastMSecs = msecs;
16951 _lastNSecs = nsecs;
16952 _clockseq = clockseq;
16953
16954 // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
16955 msecs += 12219292800000;
16956
16957 // `time_low`
16958 var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
16959 b[i++] = tl >>> 24 & 0xff;
16960 b[i++] = tl >>> 16 & 0xff;
16961 b[i++] = tl >>> 8 & 0xff;
16962 b[i++] = tl & 0xff;
16963
16964 // `time_mid`
16965 var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
16966 b[i++] = tmh >>> 8 & 0xff;
16967 b[i++] = tmh & 0xff;
16968
16969 // `time_high_and_version`
16970 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
16971 b[i++] = tmh >>> 16 & 0xff;
16972
16973 // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
16974 b[i++] = clockseq >>> 8 | 0x80;
16975
16976 // `clock_seq_low`
16977 b[i++] = clockseq & 0xff;
16978
16979 // `node`
16980 for (var n = 0; n < 6; ++n) {
16981 b[i + n] = node[n];
16982 }
16983
16984 return buf ? buf : bytesToUuid(b);
16985}
16986
16987module.exports = v1;
16988
16989},{"120":120,"121":121}],123:[function(_dereq_,module,exports){
16990var rng = _dereq_(121);
16991var bytesToUuid = _dereq_(120);
16992
16993function v4(options, buf, offset) {
16994 var i = buf && offset || 0;
16995
16996 if (typeof(options) == 'string') {
16997 buf = options === 'binary' ? new Array(16) : null;
16998 options = null;
16999 }
17000 options = options || {};
17001
17002 var rnds = options.random || (options.rng || rng)();
17003
17004 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
17005 rnds[6] = (rnds[6] & 0x0f) | 0x40;
17006 rnds[8] = (rnds[8] & 0x3f) | 0x80;
17007
17008 // Copy bytes to buffer, if provided
17009 if (buf) {
17010 for (var ii = 0; ii < 16; ++ii) {
17011 buf[i + ii] = rnds[ii];
17012 }
17013 }
17014
17015 return buf || bytesToUuid(rnds);
17016}
17017
17018module.exports = v4;
17019
17020},{"120":120,"121":121}],124:[function(_dereq_,module,exports){
17021'use strict';
17022
17023/**
17024 * Stringify/parse functions that don't operate
17025 * recursively, so they avoid call stack exceeded
17026 * errors.
17027 */
17028exports.stringify = function stringify(input) {
17029 var queue = [];
17030 queue.push({obj: input});
17031
17032 var res = '';
17033 var next, obj, prefix, val, i, arrayPrefix, keys, k, key, value, objPrefix;
17034 while ((next = queue.pop())) {
17035 obj = next.obj;
17036 prefix = next.prefix || '';
17037 val = next.val || '';
17038 res += prefix;
17039 if (val) {
17040 res += val;
17041 } else if (typeof obj !== 'object') {
17042 res += typeof obj === 'undefined' ? null : JSON.stringify(obj);
17043 } else if (obj === null) {
17044 res += 'null';
17045 } else if (Array.isArray(obj)) {
17046 queue.push({val: ']'});
17047 for (i = obj.length - 1; i >= 0; i--) {
17048 arrayPrefix = i === 0 ? '' : ',';
17049 queue.push({obj: obj[i], prefix: arrayPrefix});
17050 }
17051 queue.push({val: '['});
17052 } else { // object
17053 keys = [];
17054 for (k in obj) {
17055 if (obj.hasOwnProperty(k)) {
17056 keys.push(k);
17057 }
17058 }
17059 queue.push({val: '}'});
17060 for (i = keys.length - 1; i >= 0; i--) {
17061 key = keys[i];
17062 value = obj[key];
17063 objPrefix = (i > 0 ? ',' : '');
17064 objPrefix += JSON.stringify(key) + ':';
17065 queue.push({obj: value, prefix: objPrefix});
17066 }
17067 queue.push({val: '{'});
17068 }
17069 }
17070 return res;
17071};
17072
17073// Convenience function for the parse function.
17074// This pop function is basically copied from
17075// pouchCollate.parseIndexableString
17076function pop(obj, stack, metaStack) {
17077 var lastMetaElement = metaStack[metaStack.length - 1];
17078 if (obj === lastMetaElement.element) {
17079 // popping a meta-element, e.g. an object whose value is another object
17080 metaStack.pop();
17081 lastMetaElement = metaStack[metaStack.length - 1];
17082 }
17083 var element = lastMetaElement.element;
17084 var lastElementIndex = lastMetaElement.index;
17085 if (Array.isArray(element)) {
17086 element.push(obj);
17087 } else if (lastElementIndex === stack.length - 2) { // obj with key+value
17088 var key = stack.pop();
17089 element[key] = obj;
17090 } else {
17091 stack.push(obj); // obj with key only
17092 }
17093}
17094
17095exports.parse = function (str) {
17096 var stack = [];
17097 var metaStack = []; // stack for arrays and objects
17098 var i = 0;
17099 var collationIndex,parsedNum,numChar;
17100 var parsedString,lastCh,numConsecutiveSlashes,ch;
17101 var arrayElement, objElement;
17102 while (true) {
17103 collationIndex = str[i++];
17104 if (collationIndex === '}' ||
17105 collationIndex === ']' ||
17106 typeof collationIndex === 'undefined') {
17107 if (stack.length === 1) {
17108 return stack.pop();
17109 } else {
17110 pop(stack.pop(), stack, metaStack);
17111 continue;
17112 }
17113 }
17114 switch (collationIndex) {
17115 case ' ':
17116 case '\t':
17117 case '\n':
17118 case ':':
17119 case ',':
17120 break;
17121 case 'n':
17122 i += 3; // 'ull'
17123 pop(null, stack, metaStack);
17124 break;
17125 case 't':
17126 i += 3; // 'rue'
17127 pop(true, stack, metaStack);
17128 break;
17129 case 'f':
17130 i += 4; // 'alse'
17131 pop(false, stack, metaStack);
17132 break;
17133 case '0':
17134 case '1':
17135 case '2':
17136 case '3':
17137 case '4':
17138 case '5':
17139 case '6':
17140 case '7':
17141 case '8':
17142 case '9':
17143 case '-':
17144 parsedNum = '';
17145 i--;
17146 while (true) {
17147 numChar = str[i++];
17148 if (/[\d\.\-e\+]/.test(numChar)) {
17149 parsedNum += numChar;
17150 } else {
17151 i--;
17152 break;
17153 }
17154 }
17155 pop(parseFloat(parsedNum), stack, metaStack);
17156 break;
17157 case '"':
17158 parsedString = '';
17159 lastCh = void 0;
17160 numConsecutiveSlashes = 0;
17161 while (true) {
17162 ch = str[i++];
17163 if (ch !== '"' || (lastCh === '\\' &&
17164 numConsecutiveSlashes % 2 === 1)) {
17165 parsedString += ch;
17166 lastCh = ch;
17167 if (lastCh === '\\') {
17168 numConsecutiveSlashes++;
17169 } else {
17170 numConsecutiveSlashes = 0;
17171 }
17172 } else {
17173 break;
17174 }
17175 }
17176 pop(JSON.parse('"' + parsedString + '"'), stack, metaStack);
17177 break;
17178 case '[':
17179 arrayElement = { element: [], index: stack.length };
17180 stack.push(arrayElement.element);
17181 metaStack.push(arrayElement);
17182 break;
17183 case '{':
17184 objElement = { element: {}, index: stack.length };
17185 stack.push(objElement.element);
17186 metaStack.push(objElement);
17187 break;
17188 default:
17189 throw new Error(
17190 'unexpectedly reached end of input: ' + collationIndex);
17191 }
17192 }
17193};
17194
17195},{}],125:[function(_dereq_,module,exports){
17196module.exports = extend
17197
17198function extend() {
17199 var target = {}
17200
17201 for (var i = 0; i < arguments.length; i++) {
17202 var source = arguments[i]
17203
17204 for (var key in source) {
17205 if (source.hasOwnProperty(key)) {
17206 target[key] = source[key]
17207 }
17208 }
17209 }
17210
17211 return target
17212}
17213
17214},{}],126:[function(_dereq_,module,exports){
17215(function (global){
17216'use strict';
17217
17218function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
17219
17220var immediate = _interopDefault(_dereq_(23));
17221var uuidV4 = _interopDefault(_dereq_(119));
17222var Md5 = _interopDefault(_dereq_(78));
17223var levelup = _interopDefault(_dereq_(49));
17224var ltgt = _interopDefault(_dereq_(65));
17225var events = _dereq_(18);
17226var events__default = _interopDefault(events);
17227var Codec = _interopDefault(_dereq_(27));
17228var ReadableStreamCore = _interopDefault(_dereq_(76));
17229var inherits = _interopDefault(_dereq_(24));
17230var through2 = _dereq_(112);
17231var getArguments = _interopDefault(_dereq_(4));
17232var Deque = _interopDefault(_dereq_(15));
17233var bufferFrom = _interopDefault(_dereq_(11));
17234var vuvuzela = _interopDefault(_dereq_(124));
17235var localstoragedown = _interopDefault(_dereq_(58));
17236
17237function isBinaryObject(object) {
17238 return (typeof ArrayBuffer !== 'undefined' && object instanceof ArrayBuffer) ||
17239 (typeof Blob !== 'undefined' && object instanceof Blob);
17240}
17241
17242function cloneArrayBuffer(buff) {
17243 if (typeof buff.slice === 'function') {
17244 return buff.slice(0);
17245 }
17246 // IE10-11 slice() polyfill
17247 var target = new ArrayBuffer(buff.byteLength);
17248 var targetArray = new Uint8Array(target);
17249 var sourceArray = new Uint8Array(buff);
17250 targetArray.set(sourceArray);
17251 return target;
17252}
17253
17254function cloneBinaryObject(object) {
17255 if (object instanceof ArrayBuffer) {
17256 return cloneArrayBuffer(object);
17257 }
17258 var size = object.size;
17259 var type = object.type;
17260 // Blob
17261 if (typeof object.slice === 'function') {
17262 return object.slice(0, size, type);
17263 }
17264 // PhantomJS slice() replacement
17265 return object.webkitSlice(0, size, type);
17266}
17267
17268// most of this is borrowed from lodash.isPlainObject:
17269// https://github.com/fis-components/lodash.isplainobject/
17270// blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js
17271
17272var funcToString = Function.prototype.toString;
17273var objectCtorString = funcToString.call(Object);
17274
17275function isPlainObject(value) {
17276 var proto = Object.getPrototypeOf(value);
17277 /* istanbul ignore if */
17278 if (proto === null) { // not sure when this happens, but I guess it can
17279 return true;
17280 }
17281 var Ctor = proto.constructor;
17282 return (typeof Ctor == 'function' &&
17283 Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
17284}
17285
17286function clone(object) {
17287 var newObject;
17288 var i;
17289 var len;
17290
17291 if (!object || typeof object !== 'object') {
17292 return object;
17293 }
17294
17295 if (Array.isArray(object)) {
17296 newObject = [];
17297 for (i = 0, len = object.length; i < len; i++) {
17298 newObject[i] = clone(object[i]);
17299 }
17300 return newObject;
17301 }
17302
17303 // special case: to avoid inconsistencies between IndexedDB
17304 // and other backends, we automatically stringify Dates
17305 if (object instanceof Date) {
17306 return object.toISOString();
17307 }
17308
17309 if (isBinaryObject(object)) {
17310 return cloneBinaryObject(object);
17311 }
17312
17313 if (!isPlainObject(object)) {
17314 return object; // don't clone objects like Workers
17315 }
17316
17317 newObject = {};
17318 for (i in object) {
17319 /* istanbul ignore else */
17320 if (Object.prototype.hasOwnProperty.call(object, i)) {
17321 var value = clone(object[i]);
17322 if (typeof value !== 'undefined') {
17323 newObject[i] = value;
17324 }
17325 }
17326 }
17327 return newObject;
17328}
17329
17330function mangle(key) {
17331 return '$' + key;
17332}
17333function unmangle(key) {
17334 return key.substring(1);
17335}
17336function Map$1() {
17337 this._store = {};
17338}
17339Map$1.prototype.get = function (key) {
17340 var mangled = mangle(key);
17341 return this._store[mangled];
17342};
17343Map$1.prototype.set = function (key, value) {
17344 var mangled = mangle(key);
17345 this._store[mangled] = value;
17346 return true;
17347};
17348Map$1.prototype.has = function (key) {
17349 var mangled = mangle(key);
17350 return mangled in this._store;
17351};
17352Map$1.prototype["delete"] = function (key) {
17353 var mangled = mangle(key);
17354 var res = mangled in this._store;
17355 delete this._store[mangled];
17356 return res;
17357};
17358Map$1.prototype.forEach = function (cb) {
17359 var keys = Object.keys(this._store);
17360 for (var i = 0, len = keys.length; i < len; i++) {
17361 var key = keys[i];
17362 var value = this._store[key];
17363 key = unmangle(key);
17364 cb(value, key);
17365 }
17366};
17367Object.defineProperty(Map$1.prototype, 'size', {
17368 get: function () {
17369 return Object.keys(this._store).length;
17370 }
17371});
17372
17373function Set$1(array) {
17374 this._store = new Map$1();
17375
17376 // init with an array
17377 if (array && Array.isArray(array)) {
17378 for (var i = 0, len = array.length; i < len; i++) {
17379 this.add(array[i]);
17380 }
17381 }
17382}
17383Set$1.prototype.add = function (key) {
17384 return this._store.set(key, true);
17385};
17386Set$1.prototype.has = function (key) {
17387 return this._store.has(key);
17388};
17389Set$1.prototype.forEach = function (cb) {
17390 this._store.forEach(function (value, key) {
17391 cb(key);
17392 });
17393};
17394Object.defineProperty(Set$1.prototype, 'size', {
17395 get: function () {
17396 return this._store.size;
17397 }
17398});
17399
17400/* global Map,Set,Symbol */
17401// Based on https://kangax.github.io/compat-table/es6/ we can sniff out
17402// incomplete Map/Set implementations which would otherwise cause our tests to fail.
17403// Notably they fail in IE11 and iOS 8.4, which this prevents.
17404function supportsMapAndSet() {
17405 if (typeof Symbol === 'undefined' || typeof Map === 'undefined' || typeof Set === 'undefined') {
17406 return false;
17407 }
17408 var prop = Object.getOwnPropertyDescriptor(Map, Symbol.species);
17409 return prop && 'get' in prop && Map[Symbol.species] === Map;
17410}
17411
17412// based on https://github.com/montagejs/collections
17413
17414var ExportedSet;
17415var ExportedMap;
17416
17417{
17418 if (supportsMapAndSet()) { // prefer built-in Map/Set
17419 ExportedSet = Set;
17420 ExportedMap = Map;
17421 } else { // fall back to our polyfill
17422 ExportedSet = Set$1;
17423 ExportedMap = Map$1;
17424 }
17425}
17426
17427// like underscore/lodash _.pick()
17428function pick(obj, arr) {
17429 var res = {};
17430 for (var i = 0, len = arr.length; i < len; i++) {
17431 var prop = arr[i];
17432 if (prop in obj) {
17433 res[prop] = obj[prop];
17434 }
17435 }
17436 return res;
17437}
17438
17439var hasLocal;
17440
17441try {
17442 localStorage.setItem('_pouch_check_localstorage', 1);
17443 hasLocal = !!localStorage.getItem('_pouch_check_localstorage');
17444} catch (e) {
17445 hasLocal = false;
17446}
17447
17448function hasLocalStorage() {
17449 return hasLocal;
17450}
17451
17452// Custom nextTick() shim for browsers. In node, this will just be process.nextTick(). We
17453
17454inherits(Changes, events.EventEmitter);
17455
17456/* istanbul ignore next */
17457function attachBrowserEvents(self) {
17458 if (hasLocalStorage()) {
17459 addEventListener("storage", function (e) {
17460 self.emit(e.key);
17461 });
17462 }
17463}
17464
17465function Changes() {
17466 events.EventEmitter.call(this);
17467 this._listeners = {};
17468
17469 attachBrowserEvents(this);
17470}
17471Changes.prototype.addListener = function (dbName, id, db, opts) {
17472 /* istanbul ignore if */
17473 if (this._listeners[id]) {
17474 return;
17475 }
17476 var self = this;
17477 var inprogress = false;
17478 function eventFunction() {
17479 /* istanbul ignore if */
17480 if (!self._listeners[id]) {
17481 return;
17482 }
17483 if (inprogress) {
17484 inprogress = 'waiting';
17485 return;
17486 }
17487 inprogress = true;
17488 var changesOpts = pick(opts, [
17489 'style', 'include_docs', 'attachments', 'conflicts', 'filter',
17490 'doc_ids', 'view', 'since', 'query_params', 'binary', 'return_docs'
17491 ]);
17492
17493 /* istanbul ignore next */
17494 function onError() {
17495 inprogress = false;
17496 }
17497
17498 db.changes(changesOpts).on('change', function (c) {
17499 if (c.seq > opts.since && !opts.cancelled) {
17500 opts.since = c.seq;
17501 opts.onChange(c);
17502 }
17503 }).on('complete', function () {
17504 if (inprogress === 'waiting') {
17505 immediate(eventFunction);
17506 }
17507 inprogress = false;
17508 }).on('error', onError);
17509 }
17510 this._listeners[id] = eventFunction;
17511 this.on(dbName, eventFunction);
17512};
17513
17514Changes.prototype.removeListener = function (dbName, id) {
17515 /* istanbul ignore if */
17516 if (!(id in this._listeners)) {
17517 return;
17518 }
17519 events.EventEmitter.prototype.removeListener.call(this, dbName,
17520 this._listeners[id]);
17521 delete this._listeners[id];
17522};
17523
17524
17525/* istanbul ignore next */
17526Changes.prototype.notifyLocalWindows = function (dbName) {
17527 //do a useless change on a storage thing
17528 //in order to get other windows's listeners to activate
17529 if (hasLocalStorage()) {
17530 localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a";
17531 }
17532};
17533
17534Changes.prototype.notify = function (dbName) {
17535 this.emit(dbName);
17536 this.notifyLocalWindows(dbName);
17537};
17538
17539function guardedConsole(method) {
17540 /* istanbul ignore else */
17541 if (typeof console !== 'undefined' && typeof console[method] === 'function') {
17542 var args = Array.prototype.slice.call(arguments, 1);
17543 console[method].apply(console, args);
17544 }
17545}
17546
17547var assign;
17548{
17549 if (typeof Object.assign === 'function') {
17550 assign = Object.assign;
17551 } else {
17552 // lite Object.assign polyfill based on
17553 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
17554 assign = function (target) {
17555 var to = Object(target);
17556
17557 for (var index = 1; index < arguments.length; index++) {
17558 var nextSource = arguments[index];
17559
17560 if (nextSource != null) { // Skip over if undefined or null
17561 for (var nextKey in nextSource) {
17562 // Avoid bugs when hasOwnProperty is shadowed
17563 if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
17564 to[nextKey] = nextSource[nextKey];
17565 }
17566 }
17567 }
17568 }
17569 return to;
17570 };
17571 }
17572}
17573
17574var $inject_Object_assign = assign;
17575
17576inherits(PouchError, Error);
17577
17578function PouchError(status, error, reason) {
17579 Error.call(this, reason);
17580 this.status = status;
17581 this.name = error;
17582 this.message = reason;
17583 this.error = true;
17584}
17585
17586PouchError.prototype.toString = function () {
17587 return JSON.stringify({
17588 status: this.status,
17589 name: this.name,
17590 message: this.message,
17591 reason: this.reason
17592 });
17593};
17594
17595var UNAUTHORIZED = new PouchError(401, 'unauthorized', "Name or password is incorrect.");
17596var MISSING_BULK_DOCS = new PouchError(400, 'bad_request', "Missing JSON list of 'docs'");
17597var MISSING_DOC = new PouchError(404, 'not_found', 'missing');
17598var REV_CONFLICT = new PouchError(409, 'conflict', 'Document update conflict');
17599var INVALID_ID = new PouchError(400, 'bad_request', '_id field must contain a string');
17600var MISSING_ID = new PouchError(412, 'missing_id', '_id is required for puts');
17601var RESERVED_ID = new PouchError(400, 'bad_request', 'Only reserved document ids may start with underscore.');
17602var NOT_OPEN = new PouchError(412, 'precondition_failed', 'Database not open');
17603var UNKNOWN_ERROR = new PouchError(500, 'unknown_error', 'Database encountered an unknown error');
17604var BAD_ARG = new PouchError(500, 'badarg', 'Some query argument is invalid');
17605var INVALID_REQUEST = new PouchError(400, 'invalid_request', 'Request was invalid');
17606var QUERY_PARSE_ERROR = new PouchError(400, 'query_parse_error', 'Some query parameter is invalid');
17607var DOC_VALIDATION = new PouchError(500, 'doc_validation', 'Bad special document member');
17608var BAD_REQUEST = new PouchError(400, 'bad_request', 'Something wrong with the request');
17609var NOT_AN_OBJECT = new PouchError(400, 'bad_request', 'Document must be a JSON object');
17610var DB_MISSING = new PouchError(404, 'not_found', 'Database not found');
17611var IDB_ERROR = new PouchError(500, 'indexed_db_went_bad', 'unknown');
17612var WSQ_ERROR = new PouchError(500, 'web_sql_went_bad', 'unknown');
17613var LDB_ERROR = new PouchError(500, 'levelDB_went_went_bad', 'unknown');
17614var FORBIDDEN = new PouchError(403, 'forbidden', 'Forbidden by design doc validate_doc_update function');
17615var INVALID_REV = new PouchError(400, 'bad_request', 'Invalid rev format');
17616var FILE_EXISTS = new PouchError(412, 'file_exists', 'The database could not be created, the file already exists.');
17617var MISSING_STUB = new PouchError(412, 'missing_stub', 'A pre-existing attachment stub wasn\'t found');
17618var INVALID_URL = new PouchError(413, 'invalid_url', 'Provided URL is invalid');
17619
17620function createError(error, reason) {
17621 function CustomPouchError(reason) {
17622 // inherit error properties from our parent error manually
17623 // so as to allow proper JSON parsing.
17624 /* jshint ignore:start */
17625 for (var p in error) {
17626 if (typeof error[p] !== 'function') {
17627 this[p] = error[p];
17628 }
17629 }
17630 /* jshint ignore:end */
17631 if (reason !== undefined) {
17632 this.reason = reason;
17633 }
17634 }
17635 CustomPouchError.prototype = PouchError.prototype;
17636 return new CustomPouchError(reason);
17637}
17638
17639function tryFilter(filter, doc, req) {
17640 try {
17641 return !filter(doc, req);
17642 } catch (err) {
17643 var msg = 'Filter function threw: ' + err.toString();
17644 return createError(BAD_REQUEST, msg);
17645 }
17646}
17647
17648function filterChange(opts) {
17649 var req = {};
17650 var hasFilter = opts.filter && typeof opts.filter === 'function';
17651 req.query = opts.query_params;
17652
17653 return function filter(change) {
17654 if (!change.doc) {
17655 // CSG sends events on the changes feed that don't have documents,
17656 // this hack makes a whole lot of existing code robust.
17657 change.doc = {};
17658 }
17659
17660 var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req);
17661
17662 if (typeof filterReturn === 'object') {
17663 return filterReturn;
17664 }
17665
17666 if (filterReturn) {
17667 return false;
17668 }
17669
17670 if (!opts.include_docs) {
17671 delete change.doc;
17672 } else if (!opts.attachments) {
17673 for (var att in change.doc._attachments) {
17674 /* istanbul ignore else */
17675 if (change.doc._attachments.hasOwnProperty(att)) {
17676 change.doc._attachments[att].stub = true;
17677 }
17678 }
17679 }
17680 return true;
17681 };
17682}
17683
17684// shim for Function.prototype.name,
17685// for browsers that don't support it like IE
17686
17687/* istanbul ignore next */
17688function f() {}
17689
17690var hasName = f.name;
17691var res;
17692
17693// We dont run coverage in IE
17694/* istanbul ignore else */
17695if (hasName) {
17696 res = function (fun) {
17697 return fun.name;
17698 };
17699} else {
17700 res = function (fun) {
17701 var match = fun.toString().match(/^\s*function\s*(?:(\S+)\s*)?\(/);
17702 if (match && match[1]) {
17703 return match[1];
17704 }
17705 else {
17706 return '';
17707 }
17708 };
17709}
17710
17711var functionName = res;
17712
17713// Determine id an ID is valid
17714// - invalid IDs begin with an underescore that does not begin '_design' or
17715// '_local'
17716// - any other string value is a valid id
17717// Returns the specific error object for each case
17718function invalidIdError(id) {
17719 var err;
17720 if (!id) {
17721 err = createError(MISSING_ID);
17722 } else if (typeof id !== 'string') {
17723 err = createError(INVALID_ID);
17724 } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {
17725 err = createError(RESERVED_ID);
17726 }
17727 if (err) {
17728 throw err;
17729 }
17730}
17731
17732// Checks if a PouchDB object is "remote" or not. This is
17733
17734// originally parseUri 1.2.2, now patched by us
17735
17736// Based on https://github.com/alexdavid/scope-eval v0.0.3
17737
17738var thisAtob = function (str) {
17739 return atob(str);
17740};
17741
17742var thisBtoa = function (str) {
17743 return btoa(str);
17744};
17745
17746// Abstracts constructing a Blob object, so it also works in older
17747// browsers that don't support the native Blob constructor (e.g.
17748// old QtWebKit versions, Android < 4.4).
17749function createBlob(parts, properties) {
17750 /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
17751 parts = parts || [];
17752 properties = properties || {};
17753 try {
17754 return new Blob(parts, properties);
17755 } catch (e) {
17756 if (e.name !== "TypeError") {
17757 throw e;
17758 }
17759 var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
17760 typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
17761 typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
17762 WebKitBlobBuilder;
17763 var builder = new Builder();
17764 for (var i = 0; i < parts.length; i += 1) {
17765 builder.append(parts[i]);
17766 }
17767 return builder.getBlob(properties.type);
17768 }
17769}
17770
17771// From http://stackoverflow.com/questions/14967647/ (continues on next line)
17772// encode-decode-image-with-base64-breaks-image (2013-04-21)
17773function binaryStringToArrayBuffer(bin) {
17774 var length = bin.length;
17775 var buf = new ArrayBuffer(length);
17776 var arr = new Uint8Array(buf);
17777 for (var i = 0; i < length; i++) {
17778 arr[i] = bin.charCodeAt(i);
17779 }
17780 return buf;
17781}
17782
17783function binStringToBluffer(binString, type) {
17784 return createBlob([binaryStringToArrayBuffer(binString)], {type: type});
17785}
17786
17787//Can't find original post, but this is close
17788//http://stackoverflow.com/questions/6965107/ (continues on next line)
17789//converting-between-strings-and-arraybuffers
17790function arrayBufferToBinaryString(buffer) {
17791 var binary = '';
17792 var bytes = new Uint8Array(buffer);
17793 var length = bytes.byteLength;
17794 for (var i = 0; i < length; i++) {
17795 binary += String.fromCharCode(bytes[i]);
17796 }
17797 return binary;
17798}
17799
17800// shim for browsers that don't support it
17801function readAsBinaryString(blob, callback) {
17802 var reader = new FileReader();
17803 var hasBinaryString = typeof reader.readAsBinaryString === 'function';
17804 reader.onloadend = function (e) {
17805 var result = e.target.result || '';
17806 if (hasBinaryString) {
17807 return callback(result);
17808 }
17809 callback(arrayBufferToBinaryString(result));
17810 };
17811 if (hasBinaryString) {
17812 reader.readAsBinaryString(blob);
17813 } else {
17814 reader.readAsArrayBuffer(blob);
17815 }
17816}
17817
17818// simplified API. universal browser support is assumed
17819function readAsArrayBuffer(blob, callback) {
17820 var reader = new FileReader();
17821 reader.onloadend = function (e) {
17822 var result = e.target.result || new ArrayBuffer(0);
17823 callback(result);
17824 };
17825 reader.readAsArrayBuffer(blob);
17826}
17827
17828// this is not used in the browser
17829
17830var setImmediateShim = global.setImmediate || global.setTimeout;
17831var MD5_CHUNK_SIZE = 32768;
17832
17833function rawToBase64(raw) {
17834 return thisBtoa(raw);
17835}
17836
17837function sliceBlob(blob, start, end) {
17838 if (blob.webkitSlice) {
17839 return blob.webkitSlice(start, end);
17840 }
17841 return blob.slice(start, end);
17842}
17843
17844function appendBlob(buffer, blob, start, end, callback) {
17845 if (start > 0 || end < blob.size) {
17846 // only slice blob if we really need to
17847 blob = sliceBlob(blob, start, end);
17848 }
17849 readAsArrayBuffer(blob, function (arrayBuffer) {
17850 buffer.append(arrayBuffer);
17851 callback();
17852 });
17853}
17854
17855function appendString(buffer, string, start, end, callback) {
17856 if (start > 0 || end < string.length) {
17857 // only create a substring if we really need to
17858 string = string.substring(start, end);
17859 }
17860 buffer.appendBinary(string);
17861 callback();
17862}
17863
17864function binaryMd5(data, callback) {
17865 var inputIsString = typeof data === 'string';
17866 var len = inputIsString ? data.length : data.size;
17867 var chunkSize = Math.min(MD5_CHUNK_SIZE, len);
17868 var chunks = Math.ceil(len / chunkSize);
17869 var currentChunk = 0;
17870 var buffer = inputIsString ? new Md5() : new Md5.ArrayBuffer();
17871
17872 var append = inputIsString ? appendString : appendBlob;
17873
17874 function next() {
17875 setImmediateShim(loadNextChunk);
17876 }
17877
17878 function done() {
17879 var raw = buffer.end(true);
17880 var base64 = rawToBase64(raw);
17881 callback(base64);
17882 buffer.destroy();
17883 }
17884
17885 function loadNextChunk() {
17886 var start = currentChunk * chunkSize;
17887 var end = start + chunkSize;
17888 currentChunk++;
17889 if (currentChunk < chunks) {
17890 append(buffer, data, start, end, next);
17891 } else {
17892 append(buffer, data, start, end, done);
17893 }
17894 }
17895 loadNextChunk();
17896}
17897
17898function stringMd5(string) {
17899 return Md5.hash(string);
17900}
17901
17902function rev(doc, deterministic_revs) {
17903 var clonedDoc = clone(doc);
17904 if (!deterministic_revs) {
17905 return uuidV4.v4().replace(/-/g, '').toLowerCase();
17906 }
17907
17908 delete clonedDoc._rev_tree;
17909 return stringMd5(JSON.stringify(clonedDoc));
17910}
17911
17912var uuid = uuidV4.v4;
17913
17914function isFunction(f) {
17915 return 'function' === typeof f;
17916}
17917
17918function getPrefix(db) {
17919 if (isFunction(db.prefix)) {
17920 return db.prefix();
17921 }
17922 return db;
17923}
17924
17925function clone$1(_obj) {
17926 var obj = {};
17927 for (var k in _obj) {
17928 obj[k] = _obj[k];
17929 }
17930 return obj;
17931}
17932
17933function nut(db, precodec, codec) {
17934 function encodePrefix(prefix, key, opts1, opts2) {
17935 return precodec.encode([ prefix, codec.encodeKey(key, opts1, opts2 ) ]);
17936 }
17937
17938 function addEncodings(op, prefix) {
17939 if (prefix && prefix.options) {
17940 op.keyEncoding =
17941 op.keyEncoding || prefix.options.keyEncoding;
17942 op.valueEncoding =
17943 op.valueEncoding || prefix.options.valueEncoding;
17944 }
17945 return op;
17946 }
17947
17948 db.open(function () { /* no-op */});
17949
17950 return {
17951 apply: function (ops, opts, cb) {
17952 opts = opts || {};
17953
17954 var batch = [];
17955 var i = -1;
17956 var len = ops.length;
17957
17958 while (++i < len) {
17959 var op = ops[i];
17960 addEncodings(op, op.prefix);
17961 op.prefix = getPrefix(op.prefix);
17962 batch.push({
17963 key: encodePrefix(op.prefix, op.key, opts, op),
17964 value: op.type !== 'del' && codec.encodeValue(op.value, opts, op),
17965 type: op.type
17966 });
17967 }
17968 db.db.batch(batch, opts, cb);
17969 },
17970 get: function (key, prefix, opts, cb) {
17971 opts.asBuffer = codec.valueAsBuffer(opts);
17972 return db.db.get(
17973 encodePrefix(prefix, key, opts),
17974 opts,
17975 function (err, value) {
17976 if (err) {
17977 cb(err);
17978 } else {
17979 cb(null, codec.decodeValue(value, opts));
17980 }
17981 }
17982 );
17983 },
17984 createDecoder: function (opts) {
17985 return function (key, value) {
17986 return {
17987 key: codec.decodeKey(precodec.decode(key)[1], opts),
17988 value: codec.decodeValue(value, opts)
17989 };
17990 };
17991 },
17992 isClosed: function isClosed() {
17993 return db.isClosed();
17994 },
17995 close: function close(cb) {
17996 return db.close(cb);
17997 },
17998 iterator: function (_opts) {
17999 var opts = clone$1(_opts || {});
18000 var prefix = _opts.prefix || [];
18001
18002 function encodeKey(key) {
18003 return encodePrefix(prefix, key, opts, {});
18004 }
18005
18006 ltgt.toLtgt(_opts, opts, encodeKey, precodec.lowerBound, precodec.upperBound);
18007
18008 // if these legacy values are in the options, remove them
18009
18010 opts.prefix = null;
18011
18012 //************************************************
18013 //hard coded defaults, for now...
18014 //TODO: pull defaults and encoding out of levelup.
18015 opts.keyAsBuffer = opts.valueAsBuffer = false;
18016 //************************************************
18017
18018
18019 //this is vital, otherwise limit: undefined will
18020 //create an empty stream.
18021 /* istanbul ignore next */
18022 if ('number' !== typeof opts.limit) {
18023 opts.limit = -1;
18024 }
18025
18026 opts.keyAsBuffer = precodec.buffer;
18027 opts.valueAsBuffer = codec.valueAsBuffer(opts);
18028
18029 function wrapIterator(iterator) {
18030 return {
18031 next: function (cb) {
18032 return iterator.next(cb);
18033 },
18034 end: function (cb) {
18035 iterator.end(cb);
18036 }
18037 };
18038 }
18039
18040 return wrapIterator(db.db.iterator(opts));
18041 }
18042 };
18043}
18044
18045function NotFoundError() {
18046 Error.call(this);
18047}
18048
18049inherits(NotFoundError, Error);
18050
18051NotFoundError.prototype.name = 'NotFoundError';
18052
18053var EventEmitter = events__default.EventEmitter;
18054var version = "6.5.4";
18055
18056var NOT_FOUND_ERROR = new NotFoundError();
18057
18058var sublevel = function (nut, prefix, createStream, options) {
18059 var emitter = new EventEmitter();
18060 emitter.sublevels = {};
18061 emitter.options = options;
18062
18063 emitter.version = version;
18064
18065 emitter.methods = {};
18066 prefix = prefix || [];
18067
18068 function mergeOpts(opts) {
18069 var o = {};
18070 var k;
18071 if (options) {
18072 for (k in options) {
18073 if (typeof options[k] !== 'undefined') {
18074 o[k] = options[k];
18075 }
18076 }
18077 }
18078 if (opts) {
18079 for (k in opts) {
18080 if (typeof opts[k] !== 'undefined') {
18081 o[k] = opts[k];
18082 }
18083 }
18084 }
18085 return o;
18086 }
18087
18088 emitter.put = function (key, value, opts, cb) {
18089 if ('function' === typeof opts) {
18090 cb = opts;
18091 opts = {};
18092 }
18093
18094 nut.apply([{
18095 key: key, value: value,
18096 prefix: prefix.slice(), type: 'put'
18097 }], mergeOpts(opts), function (err) {
18098 /* istanbul ignore next */
18099 if (err) {
18100 return cb(err);
18101 }
18102 emitter.emit('put', key, value);
18103 cb(null);
18104 });
18105 };
18106
18107 emitter.prefix = function () {
18108 return prefix.slice();
18109 };
18110
18111 emitter.batch = function (ops, opts, cb) {
18112 if ('function' === typeof opts) {
18113 cb = opts;
18114 opts = {};
18115 }
18116
18117 ops = ops.map(function (op) {
18118 return {
18119 key: op.key,
18120 value: op.value,
18121 prefix: op.prefix || prefix,
18122 keyEncoding: op.keyEncoding, // *
18123 valueEncoding: op.valueEncoding, // * (TODO: encodings on sublevel)
18124 type: op.type
18125 };
18126 });
18127
18128 nut.apply(ops, mergeOpts(opts), function (err) {
18129 /* istanbul ignore next */
18130 if (err) {
18131 return cb(err);
18132 }
18133 emitter.emit('batch', ops);
18134 cb(null);
18135 });
18136 };
18137
18138 emitter.get = function (key, opts, cb) {
18139 /* istanbul ignore else */
18140 if ('function' === typeof opts) {
18141 cb = opts;
18142 opts = {};
18143 }
18144 nut.get(key, prefix, mergeOpts(opts), function (err, value) {
18145 if (err) {
18146 cb(NOT_FOUND_ERROR);
18147 } else {
18148 cb(null, value);
18149 }
18150 });
18151 };
18152
18153 emitter.sublevel = function (name, opts) {
18154 return emitter.sublevels[name] =
18155 emitter.sublevels[name] || sublevel(nut, prefix.concat(name), createStream, mergeOpts(opts));
18156 };
18157
18158 emitter.readStream = emitter.createReadStream = function (opts) {
18159 opts = mergeOpts(opts);
18160 opts.prefix = prefix;
18161 var stream;
18162 var it = nut.iterator(opts);
18163
18164 stream = createStream(opts, nut.createDecoder(opts));
18165 stream.setIterator(it);
18166
18167 return stream;
18168 };
18169
18170 emitter.close = function (cb) {
18171 nut.close(cb);
18172 };
18173
18174 emitter.isOpen = nut.isOpen;
18175 emitter.isClosed = nut.isClosed;
18176
18177 return emitter;
18178};
18179
18180/* Copyright (c) 2012-2014 LevelUP contributors
18181 * See list at <https://github.com/rvagg/node-levelup#contributing>
18182 * MIT License <https://github.com/rvagg/node-levelup/blob/master/LICENSE.md>
18183 */
18184
18185var Readable = ReadableStreamCore.Readable;
18186
18187function ReadStream(options, makeData) {
18188 if (!(this instanceof ReadStream)) {
18189 return new ReadStream(options, makeData);
18190 }
18191
18192 Readable.call(this, { objectMode: true, highWaterMark: options.highWaterMark });
18193
18194 // purely to keep `db` around until we're done so it's not GCed if the user doesn't keep a ref
18195
18196 this._waiting = false;
18197 this._options = options;
18198 this._makeData = makeData;
18199}
18200
18201inherits(ReadStream, Readable);
18202
18203ReadStream.prototype.setIterator = function (it) {
18204 this._iterator = it;
18205 /* istanbul ignore if */
18206 if (this._destroyed) {
18207 return it.end(function () {});
18208 }
18209 /* istanbul ignore if */
18210 if (this._waiting) {
18211 this._waiting = false;
18212 return this._read();
18213 }
18214 return this;
18215};
18216
18217ReadStream.prototype._read = function read() {
18218 var self = this;
18219 /* istanbul ignore if */
18220 if (self._destroyed) {
18221 return;
18222 }
18223 /* istanbul ignore if */
18224 if (!self._iterator) {
18225 return this._waiting = true;
18226 }
18227
18228 self._iterator.next(function (err, key, value) {
18229 if (err || (key === undefined && value === undefined)) {
18230 if (!err && !self._destroyed) {
18231 self.push(null);
18232 }
18233 return self._cleanup(err);
18234 }
18235
18236
18237 value = self._makeData(key, value);
18238 if (!self._destroyed) {
18239 self.push(value);
18240 }
18241 });
18242};
18243
18244ReadStream.prototype._cleanup = function (err) {
18245 if (this._destroyed) {
18246 return;
18247 }
18248
18249 this._destroyed = true;
18250
18251 var self = this;
18252 /* istanbul ignore if */
18253 if (err && err.message !== 'iterator has ended') {
18254 self.emit('error', err);
18255 }
18256
18257 /* istanbul ignore else */
18258 if (self._iterator) {
18259 self._iterator.end(function () {
18260 self._iterator = null;
18261 self.emit('close');
18262 });
18263 } else {
18264 self.emit('close');
18265 }
18266};
18267
18268ReadStream.prototype.destroy = function () {
18269 this._cleanup();
18270};
18271
18272var precodec = {
18273 encode: function (decodedKey) {
18274 return '\xff' + decodedKey[0] + '\xff' + decodedKey[1];
18275 },
18276 decode: function (encodedKeyAsBuffer) {
18277 var str = encodedKeyAsBuffer.toString();
18278 var idx = str.indexOf('\xff', 1);
18279 return [str.substring(1, idx), str.substring(idx + 1)];
18280 },
18281 lowerBound: '\x00',
18282 upperBound: '\xff'
18283};
18284
18285var codec = new Codec();
18286
18287function sublevelPouch(db) {
18288 return sublevel(nut(db, precodec, codec), [], ReadStream, db.options);
18289}
18290
18291function allDocsKeysQuery(api, opts) {
18292 var keys = opts.keys;
18293 var finalResults = {
18294 offset: opts.skip
18295 };
18296 return Promise.all(keys.map(function (key) {
18297 var subOpts = $inject_Object_assign({key: key, deleted: 'ok'}, opts);
18298 ['limit', 'skip', 'keys'].forEach(function (optKey) {
18299 delete subOpts[optKey];
18300 });
18301 return new Promise(function (resolve, reject) {
18302 api._allDocs(subOpts, function (err, res) {
18303 /* istanbul ignore if */
18304 if (err) {
18305 return reject(err);
18306 }
18307 /* istanbul ignore if */
18308 if (opts.update_seq && res.update_seq !== undefined) {
18309 finalResults.update_seq = res.update_seq;
18310 }
18311 finalResults.total_rows = res.total_rows;
18312 resolve(res.rows[0] || {key: key, error: 'not_found'});
18313 });
18314 });
18315 })).then(function (results) {
18316 finalResults.rows = results;
18317 return finalResults;
18318 });
18319}
18320
18321function toObject(array) {
18322 return array.reduce(function (obj, item) {
18323 obj[item] = true;
18324 return obj;
18325 }, {});
18326}
18327// List of top level reserved words for doc
18328var reservedWords = toObject([
18329 '_id',
18330 '_rev',
18331 '_attachments',
18332 '_deleted',
18333 '_revisions',
18334 '_revs_info',
18335 '_conflicts',
18336 '_deleted_conflicts',
18337 '_local_seq',
18338 '_rev_tree',
18339 //replication documents
18340 '_replication_id',
18341 '_replication_state',
18342 '_replication_state_time',
18343 '_replication_state_reason',
18344 '_replication_stats',
18345 // Specific to Couchbase Sync Gateway
18346 '_removed'
18347]);
18348
18349// List of reserved words that should end up the document
18350var dataWords = toObject([
18351 '_attachments',
18352 //replication documents
18353 '_replication_id',
18354 '_replication_state',
18355 '_replication_state_time',
18356 '_replication_state_reason',
18357 '_replication_stats'
18358]);
18359
18360function parseRevisionInfo(rev$$1) {
18361 if (!/^\d+-/.test(rev$$1)) {
18362 return createError(INVALID_REV);
18363 }
18364 var idx = rev$$1.indexOf('-');
18365 var left = rev$$1.substring(0, idx);
18366 var right = rev$$1.substring(idx + 1);
18367 return {
18368 prefix: parseInt(left, 10),
18369 id: right
18370 };
18371}
18372
18373function makeRevTreeFromRevisions(revisions, opts) {
18374 var pos = revisions.start - revisions.ids.length + 1;
18375
18376 var revisionIds = revisions.ids;
18377 var ids = [revisionIds[0], opts, []];
18378
18379 for (var i = 1, len = revisionIds.length; i < len; i++) {
18380 ids = [revisionIds[i], {status: 'missing'}, [ids]];
18381 }
18382
18383 return [{
18384 pos: pos,
18385 ids: ids
18386 }];
18387}
18388
18389// Preprocess documents, parse their revisions, assign an id and a
18390// revision for new writes that are missing them, etc
18391function parseDoc(doc, newEdits, dbOpts) {
18392 if (!dbOpts) {
18393 dbOpts = {
18394 deterministic_revs: true
18395 };
18396 }
18397
18398 var nRevNum;
18399 var newRevId;
18400 var revInfo;
18401 var opts = {status: 'available'};
18402 if (doc._deleted) {
18403 opts.deleted = true;
18404 }
18405
18406 if (newEdits) {
18407 if (!doc._id) {
18408 doc._id = uuid();
18409 }
18410 newRevId = rev(doc, dbOpts.deterministic_revs);
18411 if (doc._rev) {
18412 revInfo = parseRevisionInfo(doc._rev);
18413 if (revInfo.error) {
18414 return revInfo;
18415 }
18416 doc._rev_tree = [{
18417 pos: revInfo.prefix,
18418 ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]]
18419 }];
18420 nRevNum = revInfo.prefix + 1;
18421 } else {
18422 doc._rev_tree = [{
18423 pos: 1,
18424 ids : [newRevId, opts, []]
18425 }];
18426 nRevNum = 1;
18427 }
18428 } else {
18429 if (doc._revisions) {
18430 doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts);
18431 nRevNum = doc._revisions.start;
18432 newRevId = doc._revisions.ids[0];
18433 }
18434 if (!doc._rev_tree) {
18435 revInfo = parseRevisionInfo(doc._rev);
18436 if (revInfo.error) {
18437 return revInfo;
18438 }
18439 nRevNum = revInfo.prefix;
18440 newRevId = revInfo.id;
18441 doc._rev_tree = [{
18442 pos: nRevNum,
18443 ids: [newRevId, opts, []]
18444 }];
18445 }
18446 }
18447
18448 invalidIdError(doc._id);
18449
18450 doc._rev = nRevNum + '-' + newRevId;
18451
18452 var result = {metadata : {}, data : {}};
18453 for (var key in doc) {
18454 /* istanbul ignore else */
18455 if (Object.prototype.hasOwnProperty.call(doc, key)) {
18456 var specialKey = key[0] === '_';
18457 if (specialKey && !reservedWords[key]) {
18458 var error = createError(DOC_VALIDATION, key);
18459 error.message = DOC_VALIDATION.message + ': ' + key;
18460 throw error;
18461 } else if (specialKey && !dataWords[key]) {
18462 result.metadata[key.slice(1)] = doc[key];
18463 } else {
18464 result.data[key] = doc[key];
18465 }
18466 }
18467 }
18468 return result;
18469}
18470
18471// We fetch all leafs of the revision tree, and sort them based on tree length
18472// and whether they were deleted, undeleted documents with the longest revision
18473// tree (most edits) win
18474// The final sort algorithm is slightly documented in a sidebar here:
18475// http://guide.couchdb.org/draft/conflicts.html
18476function winningRev(metadata) {
18477 var winningId;
18478 var winningPos;
18479 var winningDeleted;
18480 var toVisit = metadata.rev_tree.slice();
18481 var node;
18482 while ((node = toVisit.pop())) {
18483 var tree = node.ids;
18484 var branches = tree[2];
18485 var pos = node.pos;
18486 if (branches.length) { // non-leaf
18487 for (var i = 0, len = branches.length; i < len; i++) {
18488 toVisit.push({pos: pos + 1, ids: branches[i]});
18489 }
18490 continue;
18491 }
18492 var deleted = !!tree[1].deleted;
18493 var id = tree[0];
18494 // sort by deleted, then pos, then id
18495 if (!winningId || (winningDeleted !== deleted ? winningDeleted :
18496 winningPos !== pos ? winningPos < pos : winningId < id)) {
18497 winningId = id;
18498 winningPos = pos;
18499 winningDeleted = deleted;
18500 }
18501 }
18502
18503 return winningPos + '-' + winningId;
18504}
18505
18506// Pretty much all below can be combined into a higher order function to
18507// traverse revisions
18508// The return value from the callback will be passed as context to all
18509// children of that node
18510function traverseRevTree(revs, callback) {
18511 var toVisit = revs.slice();
18512
18513 var node;
18514 while ((node = toVisit.pop())) {
18515 var pos = node.pos;
18516 var tree = node.ids;
18517 var branches = tree[2];
18518 var newCtx =
18519 callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]);
18520 for (var i = 0, len = branches.length; i < len; i++) {
18521 toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx});
18522 }
18523 }
18524}
18525
18526function sortByPos(a, b) {
18527 return a.pos - b.pos;
18528}
18529
18530function collectLeaves(revs) {
18531 var leaves = [];
18532 traverseRevTree(revs, function (isLeaf, pos, id, acc, opts) {
18533 if (isLeaf) {
18534 leaves.push({rev: pos + "-" + id, pos: pos, opts: opts});
18535 }
18536 });
18537 leaves.sort(sortByPos).reverse();
18538 for (var i = 0, len = leaves.length; i < len; i++) {
18539 delete leaves[i].pos;
18540 }
18541 return leaves;
18542}
18543
18544// returns revs of all conflicts that is leaves such that
18545// 1. are not deleted and
18546// 2. are different than winning revision
18547function collectConflicts(metadata) {
18548 var win = winningRev(metadata);
18549 var leaves = collectLeaves(metadata.rev_tree);
18550 var conflicts = [];
18551 for (var i = 0, len = leaves.length; i < len; i++) {
18552 var leaf = leaves[i];
18553 if (leaf.rev !== win && !leaf.opts.deleted) {
18554 conflicts.push(leaf.rev);
18555 }
18556 }
18557 return conflicts;
18558}
18559
18560// compact a tree by marking its non-leafs as missing,
18561// and return a list of revs to delete
18562function compactTree(metadata) {
18563 var revs = [];
18564 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
18565 revHash, ctx, opts) {
18566 if (opts.status === 'available' && !isLeaf) {
18567 revs.push(pos + '-' + revHash);
18568 opts.status = 'missing';
18569 }
18570 });
18571 return revs;
18572}
18573
18574// build up a list of all the paths to the leafs in this revision tree
18575function rootToLeaf(revs) {
18576 var paths = [];
18577 var toVisit = revs.slice();
18578 var node;
18579 while ((node = toVisit.pop())) {
18580 var pos = node.pos;
18581 var tree = node.ids;
18582 var id = tree[0];
18583 var opts = tree[1];
18584 var branches = tree[2];
18585 var isLeaf = branches.length === 0;
18586
18587 var history = node.history ? node.history.slice() : [];
18588 history.push({id: id, opts: opts});
18589 if (isLeaf) {
18590 paths.push({pos: (pos + 1 - history.length), ids: history});
18591 }
18592 for (var i = 0, len = branches.length; i < len; i++) {
18593 toVisit.push({pos: pos + 1, ids: branches[i], history: history});
18594 }
18595 }
18596 return paths.reverse();
18597}
18598
18599// for a better overview of what this is doing, read:
18600
18601function sortByPos$1(a, b) {
18602 return a.pos - b.pos;
18603}
18604
18605// classic binary search
18606function binarySearch(arr, item, comparator) {
18607 var low = 0;
18608 var high = arr.length;
18609 var mid;
18610 while (low < high) {
18611 mid = (low + high) >>> 1;
18612 if (comparator(arr[mid], item) < 0) {
18613 low = mid + 1;
18614 } else {
18615 high = mid;
18616 }
18617 }
18618 return low;
18619}
18620
18621// assuming the arr is sorted, insert the item in the proper place
18622function insertSorted(arr, item, comparator) {
18623 var idx = binarySearch(arr, item, comparator);
18624 arr.splice(idx, 0, item);
18625}
18626
18627// Turn a path as a flat array into a tree with a single branch.
18628// If any should be stemmed from the beginning of the array, that's passed
18629// in as the second argument
18630function pathToTree(path, numStemmed) {
18631 var root;
18632 var leaf;
18633 for (var i = numStemmed, len = path.length; i < len; i++) {
18634 var node = path[i];
18635 var currentLeaf = [node.id, node.opts, []];
18636 if (leaf) {
18637 leaf[2].push(currentLeaf);
18638 leaf = currentLeaf;
18639 } else {
18640 root = leaf = currentLeaf;
18641 }
18642 }
18643 return root;
18644}
18645
18646// compare the IDs of two trees
18647function compareTree(a, b) {
18648 return a[0] < b[0] ? -1 : 1;
18649}
18650
18651// Merge two trees together
18652// The roots of tree1 and tree2 must be the same revision
18653function mergeTree(in_tree1, in_tree2) {
18654 var queue = [{tree1: in_tree1, tree2: in_tree2}];
18655 var conflicts = false;
18656 while (queue.length > 0) {
18657 var item = queue.pop();
18658 var tree1 = item.tree1;
18659 var tree2 = item.tree2;
18660
18661 if (tree1[1].status || tree2[1].status) {
18662 tree1[1].status =
18663 (tree1[1].status === 'available' ||
18664 tree2[1].status === 'available') ? 'available' : 'missing';
18665 }
18666
18667 for (var i = 0; i < tree2[2].length; i++) {
18668 if (!tree1[2][0]) {
18669 conflicts = 'new_leaf';
18670 tree1[2][0] = tree2[2][i];
18671 continue;
18672 }
18673
18674 var merged = false;
18675 for (var j = 0; j < tree1[2].length; j++) {
18676 if (tree1[2][j][0] === tree2[2][i][0]) {
18677 queue.push({tree1: tree1[2][j], tree2: tree2[2][i]});
18678 merged = true;
18679 }
18680 }
18681 if (!merged) {
18682 conflicts = 'new_branch';
18683 insertSorted(tree1[2], tree2[2][i], compareTree);
18684 }
18685 }
18686 }
18687 return {conflicts: conflicts, tree: in_tree1};
18688}
18689
18690function doMerge(tree, path, dontExpand) {
18691 var restree = [];
18692 var conflicts = false;
18693 var merged = false;
18694 var res;
18695
18696 if (!tree.length) {
18697 return {tree: [path], conflicts: 'new_leaf'};
18698 }
18699
18700 for (var i = 0, len = tree.length; i < len; i++) {
18701 var branch = tree[i];
18702 if (branch.pos === path.pos && branch.ids[0] === path.ids[0]) {
18703 // Paths start at the same position and have the same root, so they need
18704 // merged
18705 res = mergeTree(branch.ids, path.ids);
18706 restree.push({pos: branch.pos, ids: res.tree});
18707 conflicts = conflicts || res.conflicts;
18708 merged = true;
18709 } else if (dontExpand !== true) {
18710 // The paths start at a different position, take the earliest path and
18711 // traverse up until it as at the same point from root as the path we
18712 // want to merge. If the keys match we return the longer path with the
18713 // other merged After stemming we dont want to expand the trees
18714
18715 var t1 = branch.pos < path.pos ? branch : path;
18716 var t2 = branch.pos < path.pos ? path : branch;
18717 var diff = t2.pos - t1.pos;
18718
18719 var candidateParents = [];
18720
18721 var trees = [];
18722 trees.push({ids: t1.ids, diff: diff, parent: null, parentIdx: null});
18723 while (trees.length > 0) {
18724 var item = trees.pop();
18725 if (item.diff === 0) {
18726 if (item.ids[0] === t2.ids[0]) {
18727 candidateParents.push(item);
18728 }
18729 continue;
18730 }
18731 var elements = item.ids[2];
18732 for (var j = 0, elementsLen = elements.length; j < elementsLen; j++) {
18733 trees.push({
18734 ids: elements[j],
18735 diff: item.diff - 1,
18736 parent: item.ids,
18737 parentIdx: j
18738 });
18739 }
18740 }
18741
18742 var el = candidateParents[0];
18743
18744 if (!el) {
18745 restree.push(branch);
18746 } else {
18747 res = mergeTree(el.ids, t2.ids);
18748 el.parent[2][el.parentIdx] = res.tree;
18749 restree.push({pos: t1.pos, ids: t1.ids});
18750 conflicts = conflicts || res.conflicts;
18751 merged = true;
18752 }
18753 } else {
18754 restree.push(branch);
18755 }
18756 }
18757
18758 // We didnt find
18759 if (!merged) {
18760 restree.push(path);
18761 }
18762
18763 restree.sort(sortByPos$1);
18764
18765 return {
18766 tree: restree,
18767 conflicts: conflicts || 'internal_node'
18768 };
18769}
18770
18771// To ensure we dont grow the revision tree infinitely, we stem old revisions
18772function stem(tree, depth) {
18773 // First we break out the tree into a complete list of root to leaf paths
18774 var paths = rootToLeaf(tree);
18775 var stemmedRevs;
18776
18777 var result;
18778 for (var i = 0, len = paths.length; i < len; i++) {
18779 // Then for each path, we cut off the start of the path based on the
18780 // `depth` to stem to, and generate a new set of flat trees
18781 var path = paths[i];
18782 var stemmed = path.ids;
18783 var node;
18784 if (stemmed.length > depth) {
18785 // only do the stemming work if we actually need to stem
18786 if (!stemmedRevs) {
18787 stemmedRevs = {}; // avoid allocating this object unnecessarily
18788 }
18789 var numStemmed = stemmed.length - depth;
18790 node = {
18791 pos: path.pos + numStemmed,
18792 ids: pathToTree(stemmed, numStemmed)
18793 };
18794
18795 for (var s = 0; s < numStemmed; s++) {
18796 var rev = (path.pos + s) + '-' + stemmed[s].id;
18797 stemmedRevs[rev] = true;
18798 }
18799 } else { // no need to actually stem
18800 node = {
18801 pos: path.pos,
18802 ids: pathToTree(stemmed, 0)
18803 };
18804 }
18805
18806 // Then we remerge all those flat trees together, ensuring that we dont
18807 // connect trees that would go beyond the depth limit
18808 if (result) {
18809 result = doMerge(result, node, true).tree;
18810 } else {
18811 result = [node];
18812 }
18813 }
18814
18815 // this is memory-heavy per Chrome profiler, avoid unless we actually stemmed
18816 if (stemmedRevs) {
18817 traverseRevTree(result, function (isLeaf, pos, revHash) {
18818 // some revisions may have been removed in a branch but not in another
18819 delete stemmedRevs[pos + '-' + revHash];
18820 });
18821 }
18822
18823 return {
18824 tree: result,
18825 revs: stemmedRevs ? Object.keys(stemmedRevs) : []
18826 };
18827}
18828
18829function merge(tree, path, depth) {
18830 var newTree = doMerge(tree, path);
18831 var stemmed = stem(newTree.tree, depth);
18832 return {
18833 tree: stemmed.tree,
18834 stemmedRevs: stemmed.revs,
18835 conflicts: newTree.conflicts
18836 };
18837}
18838
18839// return true if a rev exists in the rev tree, false otherwise
18840function revExists(revs, rev) {
18841 var toVisit = revs.slice();
18842 var splitRev = rev.split('-');
18843 var targetPos = parseInt(splitRev[0], 10);
18844 var targetId = splitRev[1];
18845
18846 var node;
18847 while ((node = toVisit.pop())) {
18848 if (node.pos === targetPos && node.ids[0] === targetId) {
18849 return true;
18850 }
18851 var branches = node.ids[2];
18852 for (var i = 0, len = branches.length; i < len; i++) {
18853 toVisit.push({pos: node.pos + 1, ids: branches[i]});
18854 }
18855 }
18856 return false;
18857}
18858
18859function getTrees(node) {
18860 return node.ids;
18861}
18862
18863// check if a specific revision of a doc has been deleted
18864// - metadata: the metadata object from the doc store
18865// - rev: (optional) the revision to check. defaults to winning revision
18866function isDeleted(metadata, rev) {
18867 if (!rev) {
18868 rev = winningRev(metadata);
18869 }
18870 var id = rev.substring(rev.indexOf('-') + 1);
18871 var toVisit = metadata.rev_tree.map(getTrees);
18872
18873 var tree;
18874 while ((tree = toVisit.pop())) {
18875 if (tree[0] === id) {
18876 return !!tree[1].deleted;
18877 }
18878 toVisit = toVisit.concat(tree[2]);
18879 }
18880}
18881
18882function isLocalId(id) {
18883 return (/^_local/).test(id);
18884}
18885
18886// returns the current leaf node for a given revision
18887function latest(rev, metadata) {
18888 var toVisit = metadata.rev_tree.slice();
18889 var node;
18890 while ((node = toVisit.pop())) {
18891 var pos = node.pos;
18892 var tree = node.ids;
18893 var id = tree[0];
18894 var opts = tree[1];
18895 var branches = tree[2];
18896 var isLeaf = branches.length === 0;
18897
18898 var history = node.history ? node.history.slice() : [];
18899 history.push({id: id, pos: pos, opts: opts});
18900
18901 if (isLeaf) {
18902 for (var i = 0, len = history.length; i < len; i++) {
18903 var historyNode = history[i];
18904 var historyRev = historyNode.pos + '-' + historyNode.id;
18905
18906 if (historyRev === rev) {
18907 // return the rev of this leaf
18908 return pos + '-' + id;
18909 }
18910 }
18911 }
18912
18913 for (var j = 0, l = branches.length; j < l; j++) {
18914 toVisit.push({pos: pos + 1, ids: branches[j], history: history});
18915 }
18916 }
18917
18918 /* istanbul ignore next */
18919 throw new Error('Unable to resolve latest revision for id ' + metadata.id + ', rev ' + rev);
18920}
18921
18922function updateDoc(revLimit, prev, docInfo, results,
18923 i, cb, writeDoc, newEdits) {
18924
18925 if (revExists(prev.rev_tree, docInfo.metadata.rev) && !newEdits) {
18926 results[i] = docInfo;
18927 return cb();
18928 }
18929
18930 // sometimes this is pre-calculated. historically not always
18931 var previousWinningRev = prev.winningRev || winningRev(prev);
18932 var previouslyDeleted = 'deleted' in prev ? prev.deleted :
18933 isDeleted(prev, previousWinningRev);
18934 var deleted = 'deleted' in docInfo.metadata ? docInfo.metadata.deleted :
18935 isDeleted(docInfo.metadata);
18936 var isRoot = /^1-/.test(docInfo.metadata.rev);
18937
18938 if (previouslyDeleted && !deleted && newEdits && isRoot) {
18939 var newDoc = docInfo.data;
18940 newDoc._rev = previousWinningRev;
18941 newDoc._id = docInfo.metadata.id;
18942 docInfo = parseDoc(newDoc, newEdits);
18943 }
18944
18945 var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit);
18946
18947 var inConflict = newEdits && ((
18948 (previouslyDeleted && deleted && merged.conflicts !== 'new_leaf') ||
18949 (!previouslyDeleted && merged.conflicts !== 'new_leaf') ||
18950 (previouslyDeleted && !deleted && merged.conflicts === 'new_branch')));
18951
18952 if (inConflict) {
18953 var err = createError(REV_CONFLICT);
18954 results[i] = err;
18955 return cb();
18956 }
18957
18958 var newRev = docInfo.metadata.rev;
18959 docInfo.metadata.rev_tree = merged.tree;
18960 docInfo.stemmedRevs = merged.stemmedRevs || [];
18961 /* istanbul ignore else */
18962 if (prev.rev_map) {
18963 docInfo.metadata.rev_map = prev.rev_map; // used only by leveldb
18964 }
18965
18966 // recalculate
18967 var winningRev$$1 = winningRev(docInfo.metadata);
18968 var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev$$1);
18969
18970 // calculate the total number of documents that were added/removed,
18971 // from the perspective of total_rows/doc_count
18972 var delta = (previouslyDeleted === winningRevIsDeleted) ? 0 :
18973 previouslyDeleted < winningRevIsDeleted ? -1 : 1;
18974
18975 var newRevIsDeleted;
18976 if (newRev === winningRev$$1) {
18977 // if the new rev is the same as the winning rev, we can reuse that value
18978 newRevIsDeleted = winningRevIsDeleted;
18979 } else {
18980 // if they're not the same, then we need to recalculate
18981 newRevIsDeleted = isDeleted(docInfo.metadata, newRev);
18982 }
18983
18984 writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
18985 true, delta, i, cb);
18986}
18987
18988function rootIsMissing(docInfo) {
18989 return docInfo.metadata.rev_tree[0].ids[1].status === 'missing';
18990}
18991
18992function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results,
18993 writeDoc, opts, overallCallback) {
18994
18995 // Default to 1000 locally
18996 revLimit = revLimit || 1000;
18997
18998 function insertDoc(docInfo, resultsIdx, callback) {
18999 // Cant insert new deleted documents
19000 var winningRev$$1 = winningRev(docInfo.metadata);
19001 var deleted = isDeleted(docInfo.metadata, winningRev$$1);
19002 if ('was_delete' in opts && deleted) {
19003 results[resultsIdx] = createError(MISSING_DOC, 'deleted');
19004 return callback();
19005 }
19006
19007 // 4712 - detect whether a new document was inserted with a _rev
19008 var inConflict = newEdits && rootIsMissing(docInfo);
19009
19010 if (inConflict) {
19011 var err = createError(REV_CONFLICT);
19012 results[resultsIdx] = err;
19013 return callback();
19014 }
19015
19016 var delta = deleted ? 0 : 1;
19017
19018 writeDoc(docInfo, winningRev$$1, deleted, deleted, false,
19019 delta, resultsIdx, callback);
19020 }
19021
19022 var newEdits = opts.new_edits;
19023 var idsToDocs = new ExportedMap();
19024
19025 var docsDone = 0;
19026 var docsToDo = docInfos.length;
19027
19028 function checkAllDocsDone() {
19029 if (++docsDone === docsToDo && overallCallback) {
19030 overallCallback();
19031 }
19032 }
19033
19034 docInfos.forEach(function (currentDoc, resultsIdx) {
19035
19036 if (currentDoc._id && isLocalId(currentDoc._id)) {
19037 var fun = currentDoc._deleted ? '_removeLocal' : '_putLocal';
19038 api[fun](currentDoc, {ctx: tx}, function (err, res) {
19039 results[resultsIdx] = err || res;
19040 checkAllDocsDone();
19041 });
19042 return;
19043 }
19044
19045 var id = currentDoc.metadata.id;
19046 if (idsToDocs.has(id)) {
19047 docsToDo--; // duplicate
19048 idsToDocs.get(id).push([currentDoc, resultsIdx]);
19049 } else {
19050 idsToDocs.set(id, [[currentDoc, resultsIdx]]);
19051 }
19052 });
19053
19054 // in the case of new_edits, the user can provide multiple docs
19055 // with the same id. these need to be processed sequentially
19056 idsToDocs.forEach(function (docs, id) {
19057 var numDone = 0;
19058
19059 function docWritten() {
19060 if (++numDone < docs.length) {
19061 nextDoc();
19062 } else {
19063 checkAllDocsDone();
19064 }
19065 }
19066 function nextDoc() {
19067 var value = docs[numDone];
19068 var currentDoc = value[0];
19069 var resultsIdx = value[1];
19070
19071 if (fetchedDocs.has(id)) {
19072 updateDoc(revLimit, fetchedDocs.get(id), currentDoc, results,
19073 resultsIdx, docWritten, writeDoc, newEdits);
19074 } else {
19075 // Ensure stemming applies to new writes as well
19076 var merged = merge([], currentDoc.metadata.rev_tree[0], revLimit);
19077 currentDoc.metadata.rev_tree = merged.tree;
19078 currentDoc.stemmedRevs = merged.stemmedRevs || [];
19079 insertDoc(currentDoc, resultsIdx, docWritten);
19080 }
19081 }
19082 nextDoc();
19083 });
19084}
19085
19086function safeJsonParse(str) {
19087 // This try/catch guards against stack overflow errors.
19088 // JSON.parse() is faster than vuvuzela.parse() but vuvuzela
19089 // cannot overflow.
19090 try {
19091 return JSON.parse(str);
19092 } catch (e) {
19093 /* istanbul ignore next */
19094 return vuvuzela.parse(str);
19095 }
19096}
19097
19098function safeJsonStringify(json) {
19099 try {
19100 return JSON.stringify(json);
19101 } catch (e) {
19102 /* istanbul ignore next */
19103 return vuvuzela.stringify(json);
19104 }
19105}
19106
19107function readAsBlobOrBuffer(storedObject, type) {
19108 // In the browser, we've stored a binary string. This now comes back as a
19109 // browserified Node-style Buffer (implemented as a typed array),
19110 // but we want a Blob instead.
19111 var byteArray = new Uint8Array(storedObject);
19112 return createBlob([byteArray], {type: type});
19113}
19114
19115// In the browser, we store a binary string
19116function prepareAttachmentForStorage(attData, cb) {
19117 readAsBinaryString(attData, cb);
19118}
19119
19120function createEmptyBlobOrBuffer(type) {
19121 return createBlob([''], {type: type});
19122}
19123
19124function getCacheFor(transaction, store) {
19125 var prefix = store.prefix()[0];
19126 var cache = transaction._cache;
19127 var subCache = cache.get(prefix);
19128 if (!subCache) {
19129 subCache = new ExportedMap();
19130 cache.set(prefix, subCache);
19131 }
19132 return subCache;
19133}
19134
19135function LevelTransaction() {
19136 this._batch = [];
19137 this._cache = new ExportedMap();
19138}
19139
19140LevelTransaction.prototype.get = function (store, key, callback) {
19141 var cache = getCacheFor(this, store);
19142 var exists = cache.get(key);
19143 if (exists) {
19144 return immediate(function () {
19145 callback(null, exists);
19146 });
19147 } else if (exists === null) { // deleted marker
19148 /* istanbul ignore next */
19149 return immediate(function () {
19150 callback({name: 'NotFoundError'});
19151 });
19152 }
19153 store.get(key, function (err, res) {
19154 if (err) {
19155 /* istanbul ignore else */
19156 if (err.name === 'NotFoundError') {
19157 cache.set(key, null);
19158 }
19159 return callback(err);
19160 }
19161 cache.set(key, res);
19162 callback(null, res);
19163 });
19164};
19165
19166LevelTransaction.prototype.batch = function (batch) {
19167 for (var i = 0, len = batch.length; i < len; i++) {
19168 var operation = batch[i];
19169
19170 var cache = getCacheFor(this, operation.prefix);
19171
19172 if (operation.type === 'put') {
19173 cache.set(operation.key, operation.value);
19174 } else {
19175 cache.set(operation.key, null);
19176 }
19177 }
19178 this._batch = this._batch.concat(batch);
19179};
19180
19181LevelTransaction.prototype.execute = function (db, callback) {
19182
19183 var keys = new ExportedSet();
19184 var uniqBatches = [];
19185
19186 // remove duplicates; last one wins
19187 for (var i = this._batch.length - 1; i >= 0; i--) {
19188 var operation = this._batch[i];
19189 var lookupKey = operation.prefix.prefix()[0] + '\xff' + operation.key;
19190 if (keys.has(lookupKey)) {
19191 continue;
19192 }
19193 keys.add(lookupKey);
19194 uniqBatches.push(operation);
19195 }
19196
19197 db.batch(uniqBatches, callback);
19198};
19199
19200var DOC_STORE = 'document-store';
19201var BY_SEQ_STORE = 'by-sequence';
19202var ATTACHMENT_STORE = 'attach-store';
19203var BINARY_STORE = 'attach-binary-store';
19204var LOCAL_STORE = 'local-store';
19205var META_STORE = 'meta-store';
19206
19207// leveldb barks if we try to open a db multiple times
19208// so we cache opened connections here for initstore()
19209var dbStores = new ExportedMap();
19210
19211// store the value of update_seq in the by-sequence store the key name will
19212// never conflict, since the keys in the by-sequence store are integers
19213var UPDATE_SEQ_KEY = '_local_last_update_seq';
19214var DOC_COUNT_KEY = '_local_doc_count';
19215var UUID_KEY = '_local_uuid';
19216
19217var MD5_PREFIX = 'md5-';
19218
19219var safeJsonEncoding = {
19220 encode: safeJsonStringify,
19221 decode: safeJsonParse,
19222 buffer: false,
19223 type: 'cheap-json'
19224};
19225
19226var levelChanges = new Changes();
19227
19228// winningRev and deleted are performance-killers, but
19229// in newer versions of PouchDB, they are cached on the metadata
19230function getWinningRev(metadata) {
19231 return 'winningRev' in metadata ?
19232 metadata.winningRev : winningRev(metadata);
19233}
19234
19235function getIsDeleted(metadata, winningRev$$1) {
19236 return 'deleted' in metadata ?
19237 metadata.deleted : isDeleted(metadata, winningRev$$1);
19238}
19239
19240function fetchAttachment(att, stores, opts) {
19241 var type = att.content_type;
19242 return new Promise(function (resolve, reject) {
19243 stores.binaryStore.get(att.digest, function (err, buffer) {
19244 var data;
19245 if (err) {
19246 /* istanbul ignore if */
19247 if (err.name !== 'NotFoundError') {
19248 return reject(err);
19249 } else {
19250 // empty
19251 if (!opts.binary) {
19252 data = '';
19253 } else {
19254 data = binStringToBluffer('', type);
19255 }
19256 }
19257 } else { // non-empty
19258 if (opts.binary) {
19259 data = readAsBlobOrBuffer(buffer, type);
19260 } else {
19261 data = buffer.toString('base64');
19262 }
19263 }
19264 delete att.stub;
19265 delete att.length;
19266 att.data = data;
19267 resolve();
19268 });
19269 });
19270}
19271
19272function fetchAttachments(results, stores, opts) {
19273 var atts = [];
19274 results.forEach(function (row) {
19275 if (!(row.doc && row.doc._attachments)) {
19276 return;
19277 }
19278 var attNames = Object.keys(row.doc._attachments);
19279 attNames.forEach(function (attName) {
19280 var att = row.doc._attachments[attName];
19281 if (!('data' in att)) {
19282 atts.push(att);
19283 }
19284 });
19285 });
19286
19287 return Promise.all(atts.map(function (att) {
19288 return fetchAttachment(att, stores, opts);
19289 }));
19290}
19291
19292function LevelPouch(opts, callback) {
19293 opts = clone(opts);
19294 var api = this;
19295 var instanceId;
19296 var stores = {};
19297 var revLimit = opts.revs_limit;
19298 var db;
19299 var name = opts.name;
19300 // TODO: this is undocumented and unused probably
19301 /* istanbul ignore else */
19302 if (typeof opts.createIfMissing === 'undefined') {
19303 opts.createIfMissing = true;
19304 }
19305
19306 var leveldown = opts.db;
19307
19308 var dbStore;
19309 var leveldownName = functionName(leveldown);
19310 if (dbStores.has(leveldownName)) {
19311 dbStore = dbStores.get(leveldownName);
19312 } else {
19313 dbStore = new ExportedMap();
19314 dbStores.set(leveldownName, dbStore);
19315 }
19316 if (dbStore.has(name)) {
19317 db = dbStore.get(name);
19318 afterDBCreated();
19319 } else {
19320 dbStore.set(name, sublevelPouch(levelup(leveldown(name), opts, function (err) {
19321 /* istanbul ignore if */
19322 if (err) {
19323 dbStore["delete"](name);
19324 return callback(err);
19325 }
19326 db = dbStore.get(name);
19327 db._docCount = -1;
19328 db._queue = new Deque();
19329 /* istanbul ignore else */
19330 if (typeof opts.migrate === 'object') { // migration for leveldown
19331 opts.migrate.doMigrationOne(name, db, afterDBCreated);
19332 } else {
19333 afterDBCreated();
19334 }
19335 })));
19336 }
19337
19338 function afterDBCreated() {
19339 stores.docStore = db.sublevel(DOC_STORE, {valueEncoding: safeJsonEncoding});
19340 stores.bySeqStore = db.sublevel(BY_SEQ_STORE, {valueEncoding: 'json'});
19341 stores.attachmentStore =
19342 db.sublevel(ATTACHMENT_STORE, {valueEncoding: 'json'});
19343 stores.binaryStore = db.sublevel(BINARY_STORE, {valueEncoding: 'binary'});
19344 stores.localStore = db.sublevel(LOCAL_STORE, {valueEncoding: 'json'});
19345 stores.metaStore = db.sublevel(META_STORE, {valueEncoding: 'json'});
19346 /* istanbul ignore else */
19347 if (typeof opts.migrate === 'object') { // migration for leveldown
19348 opts.migrate.doMigrationTwo(db, stores, afterLastMigration);
19349 } else {
19350 afterLastMigration();
19351 }
19352 }
19353
19354 function afterLastMigration() {
19355 stores.metaStore.get(UPDATE_SEQ_KEY, function (err, value) {
19356 if (typeof db._updateSeq === 'undefined') {
19357 db._updateSeq = value || 0;
19358 }
19359 stores.metaStore.get(DOC_COUNT_KEY, function (err, value) {
19360 db._docCount = !err ? value : 0;
19361 stores.metaStore.get(UUID_KEY, function (err, value) {
19362 instanceId = !err ? value : uuid();
19363 stores.metaStore.put(UUID_KEY, instanceId, function () {
19364 immediate(function () {
19365 callback(null, api);
19366 });
19367 });
19368 });
19369 });
19370 });
19371 }
19372
19373 function countDocs(callback) {
19374 /* istanbul ignore if */
19375 if (db.isClosed()) {
19376 return callback(new Error('database is closed'));
19377 }
19378 return callback(null, db._docCount); // use cached value
19379 }
19380
19381 api._remote = false;
19382 /* istanbul ignore next */
19383 api.type = function () {
19384 return 'leveldb';
19385 };
19386
19387 api._id = function (callback) {
19388 callback(null, instanceId);
19389 };
19390
19391 api._info = function (callback) {
19392 var res = {
19393 doc_count: db._docCount,
19394 update_seq: db._updateSeq,
19395 backend_adapter: functionName(leveldown)
19396 };
19397 return immediate(function () {
19398 callback(null, res);
19399 });
19400 };
19401
19402 function tryCode(fun, args) {
19403 try {
19404 fun.apply(null, args);
19405 } catch (err) {
19406 args[args.length - 1](err);
19407 }
19408 }
19409
19410 function executeNext() {
19411 var firstTask = db._queue.peekFront();
19412
19413 if (firstTask.type === 'read') {
19414 runReadOperation(firstTask);
19415 } else { // write, only do one at a time
19416 runWriteOperation(firstTask);
19417 }
19418 }
19419
19420 function runReadOperation(firstTask) {
19421 // do multiple reads at once simultaneously, because it's safe
19422
19423 var readTasks = [firstTask];
19424 var i = 1;
19425 var nextTask = db._queue.get(i);
19426 while (typeof nextTask !== 'undefined' && nextTask.type === 'read') {
19427 readTasks.push(nextTask);
19428 i++;
19429 nextTask = db._queue.get(i);
19430 }
19431
19432 var numDone = 0;
19433
19434 readTasks.forEach(function (readTask) {
19435 var args = readTask.args;
19436 var callback = args[args.length - 1];
19437 args[args.length - 1] = getArguments(function (cbArgs) {
19438 callback.apply(null, cbArgs);
19439 if (++numDone === readTasks.length) {
19440 immediate(function () {
19441 // all read tasks have finished
19442 readTasks.forEach(function () {
19443 db._queue.shift();
19444 });
19445 if (db._queue.length) {
19446 executeNext();
19447 }
19448 });
19449 }
19450 });
19451 tryCode(readTask.fun, args);
19452 });
19453 }
19454
19455 function runWriteOperation(firstTask) {
19456 var args = firstTask.args;
19457 var callback = args[args.length - 1];
19458 args[args.length - 1] = getArguments(function (cbArgs) {
19459 callback.apply(null, cbArgs);
19460 immediate(function () {
19461 db._queue.shift();
19462 if (db._queue.length) {
19463 executeNext();
19464 }
19465 });
19466 });
19467 tryCode(firstTask.fun, args);
19468 }
19469
19470 // all read/write operations to the database are done in a queue,
19471 // similar to how websql/idb works. this avoids problems such
19472 // as e.g. compaction needing to have a lock on the database while
19473 // it updates stuff. in the future we can revisit this.
19474 function writeLock(fun) {
19475 return getArguments(function (args) {
19476 db._queue.push({
19477 fun: fun,
19478 args: args,
19479 type: 'write'
19480 });
19481
19482 if (db._queue.length === 1) {
19483 immediate(executeNext);
19484 }
19485 });
19486 }
19487
19488 // same as the writelock, but multiple can run at once
19489 function readLock(fun) {
19490 return getArguments(function (args) {
19491 db._queue.push({
19492 fun: fun,
19493 args: args,
19494 type: 'read'
19495 });
19496
19497 if (db._queue.length === 1) {
19498 immediate(executeNext);
19499 }
19500 });
19501 }
19502
19503 function formatSeq(n) {
19504 return ('0000000000000000' + n).slice(-16);
19505 }
19506
19507 function parseSeq(s) {
19508 return parseInt(s, 10);
19509 }
19510
19511 api._get = readLock(function (id, opts, callback) {
19512 opts = clone(opts);
19513
19514 stores.docStore.get(id, function (err, metadata) {
19515
19516 if (err || !metadata) {
19517 return callback(createError(MISSING_DOC, 'missing'));
19518 }
19519
19520 var rev$$1;
19521 if (!opts.rev) {
19522 rev$$1 = getWinningRev(metadata);
19523 var deleted = getIsDeleted(metadata, rev$$1);
19524 if (deleted) {
19525 return callback(createError(MISSING_DOC, "deleted"));
19526 }
19527 } else {
19528 rev$$1 = opts.latest ? latest(opts.rev, metadata) : opts.rev;
19529 }
19530
19531 var seq = metadata.rev_map[rev$$1];
19532
19533 stores.bySeqStore.get(formatSeq(seq), function (err, doc) {
19534 if (!doc) {
19535 return callback(createError(MISSING_DOC));
19536 }
19537 /* istanbul ignore if */
19538 if ('_id' in doc && doc._id !== metadata.id) {
19539 // this failing implies something very wrong
19540 return callback(new Error('wrong doc returned'));
19541 }
19542 doc._id = metadata.id;
19543 if ('_rev' in doc) {
19544 /* istanbul ignore if */
19545 if (doc._rev !== rev$$1) {
19546 // this failing implies something very wrong
19547 return callback(new Error('wrong doc returned'));
19548 }
19549 } else {
19550 // we didn't always store this
19551 doc._rev = rev$$1;
19552 }
19553 return callback(null, {doc: doc, metadata: metadata});
19554 });
19555 });
19556 });
19557
19558 // not technically part of the spec, but if putAttachment has its own
19559 // method...
19560 api._getAttachment = function (docId, attachId, attachment, opts, callback) {
19561 var digest = attachment.digest;
19562 var type = attachment.content_type;
19563
19564 stores.binaryStore.get(digest, function (err, attach) {
19565 if (err) {
19566 /* istanbul ignore if */
19567 if (err.name !== 'NotFoundError') {
19568 return callback(err);
19569 }
19570 // Empty attachment
19571 return callback(null, opts.binary ? createEmptyBlobOrBuffer(type) : '');
19572 }
19573
19574 if (opts.binary) {
19575 callback(null, readAsBlobOrBuffer(attach, type));
19576 } else {
19577 callback(null, attach.toString('base64'));
19578 }
19579 });
19580 };
19581
19582 api._bulkDocs = writeLock(function (req, opts, callback) {
19583 var newEdits = opts.new_edits;
19584 var results = new Array(req.docs.length);
19585 var fetchedDocs = new ExportedMap();
19586 var stemmedRevs = new ExportedMap();
19587
19588 var txn = new LevelTransaction();
19589 var docCountDelta = 0;
19590 var newUpdateSeq = db._updateSeq;
19591
19592 // parse the docs and give each a sequence number
19593 var userDocs = req.docs;
19594 var docInfos = userDocs.map(function (doc) {
19595 if (doc._id && isLocalId(doc._id)) {
19596 return doc;
19597 }
19598 var newDoc = parseDoc(doc, newEdits, api.__opts);
19599
19600 if (newDoc.metadata && !newDoc.metadata.rev_map) {
19601 newDoc.metadata.rev_map = {};
19602 }
19603
19604 return newDoc;
19605 });
19606 var infoErrors = docInfos.filter(function (doc) {
19607 return doc.error;
19608 });
19609
19610 if (infoErrors.length) {
19611 return callback(infoErrors[0]);
19612 }
19613
19614 // verify any stub attachments as a precondition test
19615
19616 function verifyAttachment(digest, callback) {
19617 txn.get(stores.attachmentStore, digest, function (levelErr) {
19618 if (levelErr) {
19619 var err = createError(MISSING_STUB,
19620 'unknown stub attachment with digest ' +
19621 digest);
19622 callback(err);
19623 } else {
19624 callback();
19625 }
19626 });
19627 }
19628
19629 function verifyAttachments(finish) {
19630 var digests = [];
19631 userDocs.forEach(function (doc) {
19632 if (doc && doc._attachments) {
19633 Object.keys(doc._attachments).forEach(function (filename) {
19634 var att = doc._attachments[filename];
19635 if (att.stub) {
19636 digests.push(att.digest);
19637 }
19638 });
19639 }
19640 });
19641 if (!digests.length) {
19642 return finish();
19643 }
19644 var numDone = 0;
19645 var err;
19646
19647 digests.forEach(function (digest) {
19648 verifyAttachment(digest, function (attErr) {
19649 if (attErr && !err) {
19650 err = attErr;
19651 }
19652
19653 if (++numDone === digests.length) {
19654 finish(err);
19655 }
19656 });
19657 });
19658 }
19659
19660 function fetchExistingDocs(finish) {
19661 var numDone = 0;
19662 var overallErr;
19663 function checkDone() {
19664 if (++numDone === userDocs.length) {
19665 return finish(overallErr);
19666 }
19667 }
19668
19669 userDocs.forEach(function (doc) {
19670 if (doc._id && isLocalId(doc._id)) {
19671 // skip local docs
19672 return checkDone();
19673 }
19674 txn.get(stores.docStore, doc._id, function (err, info) {
19675 if (err) {
19676 /* istanbul ignore if */
19677 if (err.name !== 'NotFoundError') {
19678 overallErr = err;
19679 }
19680 } else {
19681 fetchedDocs.set(doc._id, info);
19682 }
19683 checkDone();
19684 });
19685 });
19686 }
19687
19688 function compact(revsMap, callback) {
19689 var promise = Promise.resolve();
19690 revsMap.forEach(function (revs, docId) {
19691 // TODO: parallelize, for now need to be sequential to
19692 // pass orphaned attachment tests
19693 promise = promise.then(function () {
19694 return new Promise(function (resolve, reject) {
19695 api._doCompactionNoLock(docId, revs, {ctx: txn}, function (err) {
19696 /* istanbul ignore if */
19697 if (err) {
19698 return reject(err);
19699 }
19700 resolve();
19701 });
19702 });
19703 });
19704 });
19705
19706 promise.then(function () {
19707 callback();
19708 }, callback);
19709 }
19710
19711 function autoCompact(callback) {
19712 var revsMap = new ExportedMap();
19713 fetchedDocs.forEach(function (metadata, docId) {
19714 revsMap.set(docId, compactTree(metadata));
19715 });
19716 compact(revsMap, callback);
19717 }
19718
19719 function finish() {
19720 compact(stemmedRevs, function (error) {
19721 /* istanbul ignore if */
19722 if (error) {
19723 complete(error);
19724 }
19725 if (api.auto_compaction) {
19726 return autoCompact(complete);
19727 }
19728 complete();
19729 });
19730 }
19731
19732 function writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
19733 isUpdate, delta, resultsIdx, callback2) {
19734 docCountDelta += delta;
19735
19736 var err = null;
19737 var recv = 0;
19738
19739 docInfo.metadata.winningRev = winningRev$$1;
19740 docInfo.metadata.deleted = winningRevIsDeleted;
19741
19742 docInfo.data._id = docInfo.metadata.id;
19743 docInfo.data._rev = docInfo.metadata.rev;
19744
19745 if (newRevIsDeleted) {
19746 docInfo.data._deleted = true;
19747 }
19748
19749 if (docInfo.stemmedRevs.length) {
19750 stemmedRevs.set(docInfo.metadata.id, docInfo.stemmedRevs);
19751 }
19752
19753 var attachments = docInfo.data._attachments ?
19754 Object.keys(docInfo.data._attachments) :
19755 [];
19756
19757 function attachmentSaved(attachmentErr) {
19758 recv++;
19759 if (!err) {
19760 /* istanbul ignore if */
19761 if (attachmentErr) {
19762 err = attachmentErr;
19763 callback2(err);
19764 } else if (recv === attachments.length) {
19765 finish();
19766 }
19767 }
19768 }
19769
19770 function onMD5Load(doc, key, data, attachmentSaved) {
19771 return function (result) {
19772 saveAttachment(doc, MD5_PREFIX + result, key, data, attachmentSaved);
19773 };
19774 }
19775
19776 function doMD5(doc, key, attachmentSaved) {
19777 return function (data) {
19778 binaryMd5(data, onMD5Load(doc, key, data, attachmentSaved));
19779 };
19780 }
19781
19782 for (var i = 0; i < attachments.length; i++) {
19783 var key = attachments[i];
19784 var att = docInfo.data._attachments[key];
19785
19786 if (att.stub) {
19787 // still need to update the refs mapping
19788 var id = docInfo.data._id;
19789 var rev$$1 = docInfo.data._rev;
19790 saveAttachmentRefs(id, rev$$1, att.digest, attachmentSaved);
19791 continue;
19792 }
19793 var data;
19794 if (typeof att.data === 'string') {
19795 // input is assumed to be a base64 string
19796 try {
19797 data = thisAtob(att.data);
19798 } catch (e) {
19799 callback(createError(BAD_ARG,
19800 'Attachment is not a valid base64 string'));
19801 return;
19802 }
19803 doMD5(docInfo, key, attachmentSaved)(data);
19804 } else {
19805 prepareAttachmentForStorage(att.data,
19806 doMD5(docInfo, key, attachmentSaved));
19807 }
19808 }
19809
19810 function finish() {
19811 var seq = docInfo.metadata.rev_map[docInfo.metadata.rev];
19812 /* istanbul ignore if */
19813 if (seq) {
19814 // check that there aren't any existing revisions with the same
19815 // revision id, else we shouldn't do anything
19816 return callback2();
19817 }
19818 seq = ++newUpdateSeq;
19819 docInfo.metadata.rev_map[docInfo.metadata.rev] =
19820 docInfo.metadata.seq = seq;
19821 var seqKey = formatSeq(seq);
19822 var batch = [{
19823 key: seqKey,
19824 value: docInfo.data,
19825 prefix: stores.bySeqStore,
19826 type: 'put'
19827 }, {
19828 key: docInfo.metadata.id,
19829 value: docInfo.metadata,
19830 prefix: stores.docStore,
19831 type: 'put'
19832 }];
19833 txn.batch(batch);
19834 results[resultsIdx] = {
19835 ok: true,
19836 id: docInfo.metadata.id,
19837 rev: docInfo.metadata.rev
19838 };
19839 fetchedDocs.set(docInfo.metadata.id, docInfo.metadata);
19840 callback2();
19841 }
19842
19843 if (!attachments.length) {
19844 finish();
19845 }
19846 }
19847
19848 // attachments are queued per-digest, otherwise the refs could be
19849 // overwritten by concurrent writes in the same bulkDocs session
19850 var attachmentQueues = {};
19851
19852 function saveAttachmentRefs(id, rev$$1, digest, callback) {
19853
19854 function fetchAtt() {
19855 return new Promise(function (resolve, reject) {
19856 txn.get(stores.attachmentStore, digest, function (err, oldAtt) {
19857 /* istanbul ignore if */
19858 if (err && err.name !== 'NotFoundError') {
19859 return reject(err);
19860 }
19861 resolve(oldAtt);
19862 });
19863 });
19864 }
19865
19866 function saveAtt(oldAtt) {
19867 var ref = [id, rev$$1].join('@');
19868 var newAtt = {};
19869
19870 if (oldAtt) {
19871 if (oldAtt.refs) {
19872 // only update references if this attachment already has them
19873 // since we cannot migrate old style attachments here without
19874 // doing a full db scan for references
19875 newAtt.refs = oldAtt.refs;
19876 newAtt.refs[ref] = true;
19877 }
19878 } else {
19879 newAtt.refs = {};
19880 newAtt.refs[ref] = true;
19881 }
19882
19883 return new Promise(function (resolve) {
19884 txn.batch([{
19885 type: 'put',
19886 prefix: stores.attachmentStore,
19887 key: digest,
19888 value: newAtt
19889 }]);
19890 resolve(!oldAtt);
19891 });
19892 }
19893
19894 // put attachments in a per-digest queue, to avoid two docs with the same
19895 // attachment overwriting each other
19896 var queue = attachmentQueues[digest] || Promise.resolve();
19897 attachmentQueues[digest] = queue.then(function () {
19898 return fetchAtt().then(saveAtt).then(function (isNewAttachment) {
19899 callback(null, isNewAttachment);
19900 }, callback);
19901 });
19902 }
19903
19904 function saveAttachment(docInfo, digest, key, data, callback) {
19905 var att = docInfo.data._attachments[key];
19906 delete att.data;
19907 att.digest = digest;
19908 att.length = data.length;
19909 var id = docInfo.metadata.id;
19910 var rev$$1 = docInfo.metadata.rev;
19911 att.revpos = parseInt(rev$$1, 10);
19912
19913 saveAttachmentRefs(id, rev$$1, digest, function (err, isNewAttachment) {
19914 /* istanbul ignore if */
19915 if (err) {
19916 return callback(err);
19917 }
19918 // do not try to store empty attachments
19919 if (data.length === 0) {
19920 return callback(err);
19921 }
19922 if (!isNewAttachment) {
19923 // small optimization - don't bother writing it again
19924 return callback(err);
19925 }
19926 txn.batch([{
19927 type: 'put',
19928 prefix: stores.binaryStore,
19929 key: digest,
19930 value: bufferFrom(data, 'binary')
19931 }]);
19932 callback();
19933 });
19934 }
19935
19936 function complete(err) {
19937 /* istanbul ignore if */
19938 if (err) {
19939 return immediate(function () {
19940 callback(err);
19941 });
19942 }
19943 txn.batch([
19944 {
19945 prefix: stores.metaStore,
19946 type: 'put',
19947 key: UPDATE_SEQ_KEY,
19948 value: newUpdateSeq
19949 },
19950 {
19951 prefix: stores.metaStore,
19952 type: 'put',
19953 key: DOC_COUNT_KEY,
19954 value: db._docCount + docCountDelta
19955 }
19956 ]);
19957 txn.execute(db, function (err) {
19958 /* istanbul ignore if */
19959 if (err) {
19960 return callback(err);
19961 }
19962 db._docCount += docCountDelta;
19963 db._updateSeq = newUpdateSeq;
19964 levelChanges.notify(name);
19965 immediate(function () {
19966 callback(null, results);
19967 });
19968 });
19969 }
19970
19971 if (!docInfos.length) {
19972 return callback(null, []);
19973 }
19974
19975 verifyAttachments(function (err) {
19976 if (err) {
19977 return callback(err);
19978 }
19979 fetchExistingDocs(function (err) {
19980 /* istanbul ignore if */
19981 if (err) {
19982 return callback(err);
19983 }
19984 processDocs(revLimit, docInfos, api, fetchedDocs, txn, results,
19985 writeDoc, opts, finish);
19986 });
19987 });
19988 });
19989 api._allDocs = function (opts, callback) {
19990 if ('keys' in opts) {
19991 return allDocsKeysQuery(this, opts);
19992 }
19993 return readLock(function (opts, callback) {
19994 opts = clone(opts);
19995 countDocs(function (err, docCount) {
19996 /* istanbul ignore if */
19997 if (err) {
19998 return callback(err);
19999 }
20000 var readstreamOpts = {};
20001 var skip = opts.skip || 0;
20002 if (opts.startkey) {
20003 readstreamOpts.gte = opts.startkey;
20004 }
20005 if (opts.endkey) {
20006 readstreamOpts.lte = opts.endkey;
20007 }
20008 if (opts.key) {
20009 readstreamOpts.gte = readstreamOpts.lte = opts.key;
20010 }
20011 if (opts.descending) {
20012 readstreamOpts.reverse = true;
20013 // switch start and ends
20014 var tmp = readstreamOpts.lte;
20015 readstreamOpts.lte = readstreamOpts.gte;
20016 readstreamOpts.gte = tmp;
20017 }
20018 var limit;
20019 if (typeof opts.limit === 'number') {
20020 limit = opts.limit;
20021 }
20022 if (limit === 0 ||
20023 ('gte' in readstreamOpts && 'lte' in readstreamOpts &&
20024 readstreamOpts.gte > readstreamOpts.lte)) {
20025 // should return 0 results when start is greater than end.
20026 // normally level would "fix" this for us by reversing the order,
20027 // so short-circuit instead
20028 var returnVal = {
20029 total_rows: docCount,
20030 offset: opts.skip,
20031 rows: []
20032 };
20033 /* istanbul ignore if */
20034 if (opts.update_seq) {
20035 returnVal.update_seq = db._updateSeq;
20036 }
20037 return callback(null, returnVal);
20038 }
20039 var results = [];
20040 var docstream = stores.docStore.readStream(readstreamOpts);
20041
20042 var throughStream = through2.obj(function (entry, _, next) {
20043 var metadata = entry.value;
20044 // winningRev and deleted are performance-killers, but
20045 // in newer versions of PouchDB, they are cached on the metadata
20046 var winningRev$$1 = getWinningRev(metadata);
20047 var deleted = getIsDeleted(metadata, winningRev$$1);
20048 if (!deleted) {
20049 if (skip-- > 0) {
20050 next();
20051 return;
20052 } else if (typeof limit === 'number' && limit-- <= 0) {
20053 docstream.unpipe();
20054 docstream.destroy();
20055 next();
20056 return;
20057 }
20058 } else if (opts.deleted !== 'ok') {
20059 next();
20060 return;
20061 }
20062 function allDocsInner(data) {
20063 var doc = {
20064 id: metadata.id,
20065 key: metadata.id,
20066 value: {
20067 rev: winningRev$$1
20068 }
20069 };
20070 if (opts.include_docs) {
20071 doc.doc = data;
20072 doc.doc._rev = doc.value.rev;
20073 if (opts.conflicts) {
20074 var conflicts = collectConflicts(metadata);
20075 if (conflicts.length) {
20076 doc.doc._conflicts = conflicts;
20077 }
20078 }
20079 for (var att in doc.doc._attachments) {
20080 if (doc.doc._attachments.hasOwnProperty(att)) {
20081 doc.doc._attachments[att].stub = true;
20082 }
20083 }
20084 }
20085 if (opts.inclusive_end === false && metadata.id === opts.endkey) {
20086 return next();
20087 } else if (deleted) {
20088 if (opts.deleted === 'ok') {
20089 doc.value.deleted = true;
20090 doc.doc = null;
20091 } else {
20092 /* istanbul ignore next */
20093 return next();
20094 }
20095 }
20096 results.push(doc);
20097 next();
20098 }
20099 if (opts.include_docs) {
20100 var seq = metadata.rev_map[winningRev$$1];
20101 stores.bySeqStore.get(formatSeq(seq), function (err, data) {
20102 allDocsInner(data);
20103 });
20104 }
20105 else {
20106 allDocsInner();
20107 }
20108 }, function (next) {
20109 Promise.resolve().then(function () {
20110 if (opts.include_docs && opts.attachments) {
20111 return fetchAttachments(results, stores, opts);
20112 }
20113 }).then(function () {
20114 var returnVal = {
20115 total_rows: docCount,
20116 offset: opts.skip,
20117 rows: results
20118 };
20119
20120 /* istanbul ignore if */
20121 if (opts.update_seq) {
20122 returnVal.update_seq = db._updateSeq;
20123 }
20124 callback(null, returnVal);
20125 }, callback);
20126 next();
20127 }).on('unpipe', function () {
20128 throughStream.end();
20129 });
20130
20131 docstream.on('error', callback);
20132
20133 docstream.pipe(throughStream);
20134 });
20135 })(opts, callback);
20136 };
20137
20138 api._changes = function (opts) {
20139 opts = clone(opts);
20140
20141 if (opts.continuous) {
20142 var id = name + ':' + uuid();
20143 levelChanges.addListener(name, id, api, opts);
20144 levelChanges.notify(name);
20145 return {
20146 cancel: function () {
20147 levelChanges.removeListener(name, id);
20148 }
20149 };
20150 }
20151
20152 var descending = opts.descending;
20153 var results = [];
20154 var lastSeq = opts.since || 0;
20155 var called = 0;
20156 var streamOpts = {
20157 reverse: descending
20158 };
20159 var limit;
20160 if ('limit' in opts && opts.limit > 0) {
20161 limit = opts.limit;
20162 }
20163 if (!streamOpts.reverse) {
20164 streamOpts.start = formatSeq(opts.since || 0);
20165 }
20166
20167 var docIds = opts.doc_ids && new ExportedSet(opts.doc_ids);
20168 var filter = filterChange(opts);
20169 var docIdsToMetadata = new ExportedMap();
20170
20171 function complete() {
20172 opts.done = true;
20173 if (opts.return_docs && opts.limit) {
20174 /* istanbul ignore if */
20175 if (opts.limit < results.length) {
20176 results.length = opts.limit;
20177 }
20178 }
20179 changeStream.unpipe(throughStream);
20180 changeStream.destroy();
20181 if (!opts.continuous && !opts.cancelled) {
20182 if (opts.include_docs && opts.attachments && opts.return_docs) {
20183 fetchAttachments(results, stores, opts).then(function () {
20184 opts.complete(null, {results: results, last_seq: lastSeq});
20185 });
20186 } else {
20187 opts.complete(null, {results: results, last_seq: lastSeq});
20188 }
20189 }
20190 }
20191 var changeStream = stores.bySeqStore.readStream(streamOpts);
20192 var throughStream = through2.obj(function (data, _, next) {
20193 if (limit && called >= limit) {
20194 complete();
20195 return next();
20196 }
20197 if (opts.cancelled || opts.done) {
20198 return next();
20199 }
20200
20201 var seq = parseSeq(data.key);
20202 var doc = data.value;
20203
20204 if (seq === opts.since && !descending) {
20205 // couchdb ignores `since` if descending=true
20206 return next();
20207 }
20208
20209 if (docIds && !docIds.has(doc._id)) {
20210 return next();
20211 }
20212
20213 var metadata;
20214
20215 function onGetMetadata(metadata) {
20216 var winningRev$$1 = getWinningRev(metadata);
20217
20218 function onGetWinningDoc(winningDoc) {
20219
20220 var change = opts.processChange(winningDoc, metadata, opts);
20221 change.seq = metadata.seq;
20222
20223 var filtered = filter(change);
20224 if (typeof filtered === 'object') {
20225 return opts.complete(filtered);
20226 }
20227
20228 if (filtered) {
20229 called++;
20230
20231 if (opts.attachments && opts.include_docs) {
20232 // fetch attachment immediately for the benefit
20233 // of live listeners
20234 fetchAttachments([change], stores, opts).then(function () {
20235 opts.onChange(change);
20236 });
20237 } else {
20238 opts.onChange(change);
20239 }
20240
20241 if (opts.return_docs) {
20242 results.push(change);
20243 }
20244 }
20245 next();
20246 }
20247
20248 if (metadata.seq !== seq) {
20249 // some other seq is later
20250 return next();
20251 }
20252
20253 lastSeq = seq;
20254
20255 if (winningRev$$1 === doc._rev) {
20256 return onGetWinningDoc(doc);
20257 }
20258
20259 // fetch the winner
20260
20261 var winningSeq = metadata.rev_map[winningRev$$1];
20262
20263 stores.bySeqStore.get(formatSeq(winningSeq), function (err, doc) {
20264 onGetWinningDoc(doc);
20265 });
20266 }
20267
20268 metadata = docIdsToMetadata.get(doc._id);
20269 if (metadata) { // cached
20270 return onGetMetadata(metadata);
20271 }
20272 // metadata not cached, have to go fetch it
20273 stores.docStore.get(doc._id, function (err, metadata) {
20274 /* istanbul ignore if */
20275 if (opts.cancelled || opts.done || db.isClosed() ||
20276 isLocalId(metadata.id)) {
20277 return next();
20278 }
20279 docIdsToMetadata.set(doc._id, metadata);
20280 onGetMetadata(metadata);
20281 });
20282 }, function (next) {
20283 if (opts.cancelled) {
20284 return next();
20285 }
20286 if (opts.return_docs && opts.limit) {
20287 /* istanbul ignore if */
20288 if (opts.limit < results.length) {
20289 results.length = opts.limit;
20290 }
20291 }
20292
20293 next();
20294 }).on('unpipe', function () {
20295 throughStream.end();
20296 complete();
20297 });
20298 changeStream.pipe(throughStream);
20299 return {
20300 cancel: function () {
20301 opts.cancelled = true;
20302 complete();
20303 }
20304 };
20305 };
20306
20307 api._close = function (callback) {
20308 /* istanbul ignore if */
20309 if (db.isClosed()) {
20310 return callback(createError(NOT_OPEN));
20311 }
20312 db.close(function (err) {
20313 /* istanbul ignore if */
20314 if (err) {
20315 callback(err);
20316 } else {
20317 dbStore["delete"](name);
20318 callback();
20319 }
20320 });
20321 };
20322
20323 api._getRevisionTree = function (docId, callback) {
20324 stores.docStore.get(docId, function (err, metadata) {
20325 if (err) {
20326 callback(createError(MISSING_DOC));
20327 } else {
20328 callback(null, metadata.rev_tree);
20329 }
20330 });
20331 };
20332
20333 api._doCompaction = writeLock(function (docId, revs, opts, callback) {
20334 api._doCompactionNoLock(docId, revs, opts, callback);
20335 });
20336
20337 // the NoLock version is for use by bulkDocs
20338 api._doCompactionNoLock = function (docId, revs, opts, callback) {
20339 if (typeof opts === 'function') {
20340 callback = opts;
20341 opts = {};
20342 }
20343
20344 if (!revs.length) {
20345 return callback();
20346 }
20347 var txn = opts.ctx || new LevelTransaction();
20348
20349 txn.get(stores.docStore, docId, function (err, metadata) {
20350 /* istanbul ignore if */
20351 if (err) {
20352 return callback(err);
20353 }
20354 var seqs = revs.map(function (rev$$1) {
20355 var seq = metadata.rev_map[rev$$1];
20356 delete metadata.rev_map[rev$$1];
20357 return seq;
20358 });
20359 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
20360 revHash, ctx, opts) {
20361 var rev$$1 = pos + '-' + revHash;
20362 if (revs.indexOf(rev$$1) !== -1) {
20363 opts.status = 'missing';
20364 }
20365 });
20366
20367 var batch = [];
20368 batch.push({
20369 key: metadata.id,
20370 value: metadata,
20371 type: 'put',
20372 prefix: stores.docStore
20373 });
20374
20375 var digestMap = {};
20376 var numDone = 0;
20377 var overallErr;
20378 function checkDone(err) {
20379 /* istanbul ignore if */
20380 if (err) {
20381 overallErr = err;
20382 }
20383 if (++numDone === revs.length) { // done
20384 /* istanbul ignore if */
20385 if (overallErr) {
20386 return callback(overallErr);
20387 }
20388 deleteOrphanedAttachments();
20389 }
20390 }
20391
20392 function finish(err) {
20393 /* istanbul ignore if */
20394 if (err) {
20395 return callback(err);
20396 }
20397 txn.batch(batch);
20398 if (opts.ctx) {
20399 // don't execute immediately
20400 return callback();
20401 }
20402 txn.execute(db, callback);
20403 }
20404
20405 function deleteOrphanedAttachments() {
20406 var possiblyOrphanedAttachments = Object.keys(digestMap);
20407 if (!possiblyOrphanedAttachments.length) {
20408 return finish();
20409 }
20410 var numDone = 0;
20411 var overallErr;
20412 function checkDone(err) {
20413 /* istanbul ignore if */
20414 if (err) {
20415 overallErr = err;
20416 }
20417 if (++numDone === possiblyOrphanedAttachments.length) {
20418 finish(overallErr);
20419 }
20420 }
20421 var refsToDelete = new ExportedMap();
20422 revs.forEach(function (rev$$1) {
20423 refsToDelete.set(docId + '@' + rev$$1, true);
20424 });
20425 possiblyOrphanedAttachments.forEach(function (digest) {
20426 txn.get(stores.attachmentStore, digest, function (err, attData) {
20427 /* istanbul ignore if */
20428 if (err) {
20429 if (err.name === 'NotFoundError') {
20430 return checkDone();
20431 } else {
20432 return checkDone(err);
20433 }
20434 }
20435 var refs = Object.keys(attData.refs || {}).filter(function (ref) {
20436 return !refsToDelete.has(ref);
20437 });
20438 var newRefs = {};
20439 refs.forEach(function (ref) {
20440 newRefs[ref] = true;
20441 });
20442 if (refs.length) { // not orphaned
20443 batch.push({
20444 key: digest,
20445 type: 'put',
20446 value: {refs: newRefs},
20447 prefix: stores.attachmentStore
20448 });
20449 } else { // orphaned, can safely delete
20450 batch = batch.concat([{
20451 key: digest,
20452 type: 'del',
20453 prefix: stores.attachmentStore
20454 }, {
20455 key: digest,
20456 type: 'del',
20457 prefix: stores.binaryStore
20458 }]);
20459 }
20460 checkDone();
20461 });
20462 });
20463 }
20464
20465 seqs.forEach(function (seq) {
20466 batch.push({
20467 key: formatSeq(seq),
20468 type: 'del',
20469 prefix: stores.bySeqStore
20470 });
20471 txn.get(stores.bySeqStore, formatSeq(seq), function (err, doc) {
20472 /* istanbul ignore if */
20473 if (err) {
20474 if (err.name === 'NotFoundError') {
20475 return checkDone();
20476 } else {
20477 return checkDone(err);
20478 }
20479 }
20480 var atts = Object.keys(doc._attachments || {});
20481 atts.forEach(function (attName) {
20482 var digest = doc._attachments[attName].digest;
20483 digestMap[digest] = true;
20484 });
20485 checkDone();
20486 });
20487 });
20488 });
20489 };
20490
20491 api._getLocal = function (id, callback) {
20492 stores.localStore.get(id, function (err, doc) {
20493 if (err) {
20494 callback(createError(MISSING_DOC));
20495 } else {
20496 callback(null, doc);
20497 }
20498 });
20499 };
20500
20501 api._putLocal = function (doc, opts, callback) {
20502 if (typeof opts === 'function') {
20503 callback = opts;
20504 opts = {};
20505 }
20506 if (opts.ctx) {
20507 api._putLocalNoLock(doc, opts, callback);
20508 } else {
20509 api._putLocalWithLock(doc, opts, callback);
20510 }
20511 };
20512
20513 api._putLocalWithLock = writeLock(function (doc, opts, callback) {
20514 api._putLocalNoLock(doc, opts, callback);
20515 });
20516
20517 // the NoLock version is for use by bulkDocs
20518 api._putLocalNoLock = function (doc, opts, callback) {
20519 delete doc._revisions; // ignore this, trust the rev
20520 var oldRev = doc._rev;
20521 var id = doc._id;
20522
20523 var txn = opts.ctx || new LevelTransaction();
20524
20525 txn.get(stores.localStore, id, function (err, resp) {
20526 if (err && oldRev) {
20527 return callback(createError(REV_CONFLICT));
20528 }
20529 if (resp && resp._rev !== oldRev) {
20530 return callback(createError(REV_CONFLICT));
20531 }
20532 doc._rev =
20533 oldRev ? '0-' + (parseInt(oldRev.split('-')[1], 10) + 1) : '0-1';
20534 var batch = [
20535 {
20536 type: 'put',
20537 prefix: stores.localStore,
20538 key: id,
20539 value: doc
20540 }
20541 ];
20542
20543 txn.batch(batch);
20544 var ret = {ok: true, id: doc._id, rev: doc._rev};
20545
20546 if (opts.ctx) {
20547 // don't execute immediately
20548 return callback(null, ret);
20549 }
20550 txn.execute(db, function (err) {
20551 /* istanbul ignore if */
20552 if (err) {
20553 return callback(err);
20554 }
20555 callback(null, ret);
20556 });
20557 });
20558 };
20559
20560 api._removeLocal = function (doc, opts, callback) {
20561 if (typeof opts === 'function') {
20562 callback = opts;
20563 opts = {};
20564 }
20565 if (opts.ctx) {
20566 api._removeLocalNoLock(doc, opts, callback);
20567 } else {
20568 api._removeLocalWithLock(doc, opts, callback);
20569 }
20570 };
20571
20572 api._removeLocalWithLock = writeLock(function (doc, opts, callback) {
20573 api._removeLocalNoLock(doc, opts, callback);
20574 });
20575
20576 // the NoLock version is for use by bulkDocs
20577 api._removeLocalNoLock = function (doc, opts, callback) {
20578 var txn = opts.ctx || new LevelTransaction();
20579 txn.get(stores.localStore, doc._id, function (err, resp) {
20580 if (err) {
20581 /* istanbul ignore if */
20582 if (err.name !== 'NotFoundError') {
20583 return callback(err);
20584 } else {
20585 return callback(createError(MISSING_DOC));
20586 }
20587 }
20588 if (resp._rev !== doc._rev) {
20589 return callback(createError(REV_CONFLICT));
20590 }
20591 txn.batch([{
20592 prefix: stores.localStore,
20593 type: 'del',
20594 key: doc._id
20595 }]);
20596 var ret = {ok: true, id: doc._id, rev: '0-0'};
20597 if (opts.ctx) {
20598 // don't execute immediately
20599 return callback(null, ret);
20600 }
20601 txn.execute(db, function (err) {
20602 /* istanbul ignore if */
20603 if (err) {
20604 return callback(err);
20605 }
20606 callback(null, ret);
20607 });
20608 });
20609 };
20610
20611 // close and delete open leveldb stores
20612 api._destroy = function (opts, callback) {
20613 var dbStore;
20614 var leveldownName = functionName(leveldown);
20615 /* istanbul ignore else */
20616 if (dbStores.has(leveldownName)) {
20617 dbStore = dbStores.get(leveldownName);
20618 } else {
20619 return callDestroy(name, callback);
20620 }
20621
20622 /* istanbul ignore else */
20623 if (dbStore.has(name)) {
20624 levelChanges.removeAllListeners(name);
20625
20626 dbStore.get(name).close(function () {
20627 dbStore["delete"](name);
20628 callDestroy(name, callback);
20629 });
20630 } else {
20631 callDestroy(name, callback);
20632 }
20633 };
20634 function callDestroy(name, cb) {
20635 // May not exist if leveldown is backed by memory adapter
20636 /* istanbul ignore else */
20637 if ('destroy' in leveldown) {
20638 leveldown.destroy(name, cb);
20639 } else {
20640 cb(null);
20641 }
20642 }
20643}
20644
20645function LocalStoragePouch(opts, callback) {
20646 var _opts = $inject_Object_assign({
20647 db: localstoragedown
20648 }, opts);
20649
20650 LevelPouch.call(this, _opts, callback);
20651}
20652
20653// overrides for normal LevelDB behavior on Node
20654LocalStoragePouch.valid = function () {
20655 return typeof localStorage !== 'undefined';
20656};
20657LocalStoragePouch.use_prefix = true;
20658
20659function LocalStoragePouchPlugin (PouchDB) {
20660 PouchDB.adapter('localstorage', LocalStoragePouch, true);
20661}
20662
20663/* global PouchDB */
20664
20665if (typeof PouchDB === 'undefined') {
20666 guardedConsole('error', 'localstorage adapter plugin error: ' +
20667 'Cannot find global "PouchDB" object! ' +
20668 'Did you remember to include pouchdb.js?');
20669} else {
20670 PouchDB.plugin(LocalStoragePouchPlugin);
20671}
20672
20673}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
20674},{"11":11,"112":112,"119":119,"124":124,"15":15,"18":18,"23":23,"24":24,"27":27,"4":4,"49":49,"58":58,"65":65,"76":76,"78":78}]},{},[126]);
20675
\No newline at end of file