UNPKG

583 kBJavaScriptView Raw
1// PouchDB localStorage plugin 7.1.1
2// Based on localstorage-down: https://github.com/No9/localstorage-down
3//
4// (c) 2012-2019 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_(69))
92},{"69":69}],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_(69))
145},{"69":69}],3:[function(_dereq_,module,exports){
146(function (Buffer,process){
147/* Copyright (c) 2013 Rod Vagg, MIT License */
148
149var xtend = _dereq_(124)
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_(32)},_dereq_(69))
407},{"1":1,"124":124,"2":2,"32":32,"69":69}],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_(67);
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},{"67":67,"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_(69),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
1559},{"6":6,"69":69,"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 for (var i = 0; i < len; i += 4) {
1628 tmp =
1629 (revLookup[b64.charCodeAt(i)] << 18) |
1630 (revLookup[b64.charCodeAt(i + 1)] << 12) |
1631 (revLookup[b64.charCodeAt(i + 2)] << 6) |
1632 revLookup[b64.charCodeAt(i + 3)]
1633 arr[curByte++] = (tmp >> 16) & 0xFF
1634 arr[curByte++] = (tmp >> 8) & 0xFF
1635 arr[curByte++] = tmp & 0xFF
1636 }
1637
1638 if (placeHoldersLen === 2) {
1639 tmp =
1640 (revLookup[b64.charCodeAt(i)] << 2) |
1641 (revLookup[b64.charCodeAt(i + 1)] >> 4)
1642 arr[curByte++] = tmp & 0xFF
1643 }
1644
1645 if (placeHoldersLen === 1) {
1646 tmp =
1647 (revLookup[b64.charCodeAt(i)] << 10) |
1648 (revLookup[b64.charCodeAt(i + 1)] << 4) |
1649 (revLookup[b64.charCodeAt(i + 2)] >> 2)
1650 arr[curByte++] = (tmp >> 8) & 0xFF
1651 arr[curByte++] = tmp & 0xFF
1652 }
1653
1654 return arr
1655}
1656
1657function tripletToBase64 (num) {
1658 return lookup[num >> 18 & 0x3F] +
1659 lookup[num >> 12 & 0x3F] +
1660 lookup[num >> 6 & 0x3F] +
1661 lookup[num & 0x3F]
1662}
1663
1664function encodeChunk (uint8, start, end) {
1665 var tmp
1666 var output = []
1667 for (var i = start; i < end; i += 3) {
1668 tmp =
1669 ((uint8[i] << 16) & 0xFF0000) +
1670 ((uint8[i + 1] << 8) & 0xFF00) +
1671 (uint8[i + 2] & 0xFF)
1672 output.push(tripletToBase64(tmp))
1673 }
1674 return output.join('')
1675}
1676
1677function fromByteArray (uint8) {
1678 var tmp
1679 var len = uint8.length
1680 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
1681 var parts = []
1682 var maxChunkLength = 16383 // must be multiple of 3
1683
1684 // go through the array every three bytes, we'll deal with trailing stuff later
1685 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
1686 parts.push(encodeChunk(
1687 uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
1688 ))
1689 }
1690
1691 // pad the end with zeros, but make sure to not forget the extra bytes
1692 if (extraBytes === 1) {
1693 tmp = uint8[len - 1]
1694 parts.push(
1695 lookup[tmp >> 2] +
1696 lookup[(tmp << 4) & 0x3F] +
1697 '=='
1698 )
1699 } else if (extraBytes === 2) {
1700 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
1701 parts.push(
1702 lookup[tmp >> 10] +
1703 lookup[(tmp >> 4) & 0x3F] +
1704 lookup[(tmp << 2) & 0x3F] +
1705 '='
1706 )
1707 }
1708
1709 return parts.join('')
1710}
1711
1712},{}],10:[function(_dereq_,module,exports){
1713
1714},{}],11:[function(_dereq_,module,exports){
1715(function (Buffer){
1716var toString = Object.prototype.toString
1717
1718var isModern = (
1719 typeof Buffer.alloc === 'function' &&
1720 typeof Buffer.allocUnsafe === 'function' &&
1721 typeof Buffer.from === 'function'
1722)
1723
1724function isArrayBuffer (input) {
1725 return toString.call(input).slice(8, -1) === 'ArrayBuffer'
1726}
1727
1728function fromArrayBuffer (obj, byteOffset, length) {
1729 byteOffset >>>= 0
1730
1731 var maxLength = obj.byteLength - byteOffset
1732
1733 if (maxLength < 0) {
1734 throw new RangeError("'offset' is out of bounds")
1735 }
1736
1737 if (length === undefined) {
1738 length = maxLength
1739 } else {
1740 length >>>= 0
1741
1742 if (length > maxLength) {
1743 throw new RangeError("'length' is out of bounds")
1744 }
1745 }
1746
1747 return isModern
1748 ? Buffer.from(obj.slice(byteOffset, byteOffset + length))
1749 : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
1750}
1751
1752function fromString (string, encoding) {
1753 if (typeof encoding !== 'string' || encoding === '') {
1754 encoding = 'utf8'
1755 }
1756
1757 if (!Buffer.isEncoding(encoding)) {
1758 throw new TypeError('"encoding" must be a valid string encoding')
1759 }
1760
1761 return isModern
1762 ? Buffer.from(string, encoding)
1763 : new Buffer(string, encoding)
1764}
1765
1766function bufferFrom (value, encodingOrOffset, length) {
1767 if (typeof value === 'number') {
1768 throw new TypeError('"value" argument must not be a number')
1769 }
1770
1771 if (isArrayBuffer(value)) {
1772 return fromArrayBuffer(value, encodingOrOffset, length)
1773 }
1774
1775 if (typeof value === 'string') {
1776 return fromString(value, encodingOrOffset)
1777 }
1778
1779 return isModern
1780 ? Buffer.from(value)
1781 : new Buffer(value)
1782}
1783
1784module.exports = bufferFrom
1785
1786}).call(this,_dereq_(12).Buffer)
1787},{"12":12}],12:[function(_dereq_,module,exports){
1788(function (Buffer){
1789/*!
1790 * The buffer module from node.js, for the browser.
1791 *
1792 * @author Feross Aboukhadijeh <https://feross.org>
1793 * @license MIT
1794 */
1795/* eslint-disable no-proto */
1796
1797'use strict'
1798
1799var base64 = _dereq_(9)
1800var ieee754 = _dereq_(29)
1801
1802exports.Buffer = Buffer
1803exports.SlowBuffer = SlowBuffer
1804exports.INSPECT_MAX_BYTES = 50
1805
1806var K_MAX_LENGTH = 0x7fffffff
1807exports.kMaxLength = K_MAX_LENGTH
1808
1809/**
1810 * If `Buffer.TYPED_ARRAY_SUPPORT`:
1811 * === true Use Uint8Array implementation (fastest)
1812 * === false Print warning and recommend using `buffer` v4.x which has an Object
1813 * implementation (most compatible, even IE6)
1814 *
1815 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
1816 * Opera 11.6+, iOS 4.2+.
1817 *
1818 * We report that the browser does not support typed arrays if the are not subclassable
1819 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
1820 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
1821 * for __proto__ and has a buggy typed array implementation.
1822 */
1823Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
1824
1825if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
1826 typeof console.error === 'function') {
1827 console.error(
1828 'This browser lacks typed array (Uint8Array) support which is required by ' +
1829 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
1830 )
1831}
1832
1833function typedArraySupport () {
1834 // Can typed array instances can be augmented?
1835 try {
1836 var arr = new Uint8Array(1)
1837 arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
1838 return arr.foo() === 42
1839 } catch (e) {
1840 return false
1841 }
1842}
1843
1844Object.defineProperty(Buffer.prototype, 'parent', {
1845 enumerable: true,
1846 get: function () {
1847 if (!Buffer.isBuffer(this)) return undefined
1848 return this.buffer
1849 }
1850})
1851
1852Object.defineProperty(Buffer.prototype, 'offset', {
1853 enumerable: true,
1854 get: function () {
1855 if (!Buffer.isBuffer(this)) return undefined
1856 return this.byteOffset
1857 }
1858})
1859
1860function createBuffer (length) {
1861 if (length > K_MAX_LENGTH) {
1862 throw new RangeError('The value "' + length + '" is invalid for option "size"')
1863 }
1864 // Return an augmented `Uint8Array` instance
1865 var buf = new Uint8Array(length)
1866 buf.__proto__ = Buffer.prototype
1867 return buf
1868}
1869
1870/**
1871 * The Buffer constructor returns instances of `Uint8Array` that have their
1872 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
1873 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
1874 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
1875 * returns a single octet.
1876 *
1877 * The `Uint8Array` prototype remains unmodified.
1878 */
1879
1880function Buffer (arg, encodingOrOffset, length) {
1881 // Common case.
1882 if (typeof arg === 'number') {
1883 if (typeof encodingOrOffset === 'string') {
1884 throw new TypeError(
1885 'The "string" argument must be of type string. Received type number'
1886 )
1887 }
1888 return allocUnsafe(arg)
1889 }
1890 return from(arg, encodingOrOffset, length)
1891}
1892
1893// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
1894if (typeof Symbol !== 'undefined' && Symbol.species != null &&
1895 Buffer[Symbol.species] === Buffer) {
1896 Object.defineProperty(Buffer, Symbol.species, {
1897 value: null,
1898 configurable: true,
1899 enumerable: false,
1900 writable: false
1901 })
1902}
1903
1904Buffer.poolSize = 8192 // not used by this implementation
1905
1906function from (value, encodingOrOffset, length) {
1907 if (typeof value === 'string') {
1908 return fromString(value, encodingOrOffset)
1909 }
1910
1911 if (ArrayBuffer.isView(value)) {
1912 return fromArrayLike(value)
1913 }
1914
1915 if (value == null) {
1916 throw TypeError(
1917 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
1918 'or Array-like Object. Received type ' + (typeof value)
1919 )
1920 }
1921
1922 if (isInstance(value, ArrayBuffer) ||
1923 (value && isInstance(value.buffer, ArrayBuffer))) {
1924 return fromArrayBuffer(value, encodingOrOffset, length)
1925 }
1926
1927 if (typeof value === 'number') {
1928 throw new TypeError(
1929 'The "value" argument must not be of type number. Received type number'
1930 )
1931 }
1932
1933 var valueOf = value.valueOf && value.valueOf()
1934 if (valueOf != null && valueOf !== value) {
1935 return Buffer.from(valueOf, encodingOrOffset, length)
1936 }
1937
1938 var b = fromObject(value)
1939 if (b) return b
1940
1941 if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
1942 typeof value[Symbol.toPrimitive] === 'function') {
1943 return Buffer.from(
1944 value[Symbol.toPrimitive]('string'), encodingOrOffset, length
1945 )
1946 }
1947
1948 throw new TypeError(
1949 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
1950 'or Array-like Object. Received type ' + (typeof value)
1951 )
1952}
1953
1954/**
1955 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
1956 * if value is a number.
1957 * Buffer.from(str[, encoding])
1958 * Buffer.from(array)
1959 * Buffer.from(buffer)
1960 * Buffer.from(arrayBuffer[, byteOffset[, length]])
1961 **/
1962Buffer.from = function (value, encodingOrOffset, length) {
1963 return from(value, encodingOrOffset, length)
1964}
1965
1966// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
1967// https://github.com/feross/buffer/pull/148
1968Buffer.prototype.__proto__ = Uint8Array.prototype
1969Buffer.__proto__ = Uint8Array
1970
1971function assertSize (size) {
1972 if (typeof size !== 'number') {
1973 throw new TypeError('"size" argument must be of type number')
1974 } else if (size < 0) {
1975 throw new RangeError('The value "' + size + '" is invalid for option "size"')
1976 }
1977}
1978
1979function alloc (size, fill, encoding) {
1980 assertSize(size)
1981 if (size <= 0) {
1982 return createBuffer(size)
1983 }
1984 if (fill !== undefined) {
1985 // Only pay attention to encoding if it's a string. This
1986 // prevents accidentally sending in a number that would
1987 // be interpretted as a start offset.
1988 return typeof encoding === 'string'
1989 ? createBuffer(size).fill(fill, encoding)
1990 : createBuffer(size).fill(fill)
1991 }
1992 return createBuffer(size)
1993}
1994
1995/**
1996 * Creates a new filled Buffer instance.
1997 * alloc(size[, fill[, encoding]])
1998 **/
1999Buffer.alloc = function (size, fill, encoding) {
2000 return alloc(size, fill, encoding)
2001}
2002
2003function allocUnsafe (size) {
2004 assertSize(size)
2005 return createBuffer(size < 0 ? 0 : checked(size) | 0)
2006}
2007
2008/**
2009 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
2010 * */
2011Buffer.allocUnsafe = function (size) {
2012 return allocUnsafe(size)
2013}
2014/**
2015 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
2016 */
2017Buffer.allocUnsafeSlow = function (size) {
2018 return allocUnsafe(size)
2019}
2020
2021function fromString (string, encoding) {
2022 if (typeof encoding !== 'string' || encoding === '') {
2023 encoding = 'utf8'
2024 }
2025
2026 if (!Buffer.isEncoding(encoding)) {
2027 throw new TypeError('Unknown encoding: ' + encoding)
2028 }
2029
2030 var length = byteLength(string, encoding) | 0
2031 var buf = createBuffer(length)
2032
2033 var actual = buf.write(string, encoding)
2034
2035 if (actual !== length) {
2036 // Writing a hex string, for example, that contains invalid characters will
2037 // cause everything after the first invalid character to be ignored. (e.g.
2038 // 'abxxcd' will be treated as 'ab')
2039 buf = buf.slice(0, actual)
2040 }
2041
2042 return buf
2043}
2044
2045function fromArrayLike (array) {
2046 var length = array.length < 0 ? 0 : checked(array.length) | 0
2047 var buf = createBuffer(length)
2048 for (var i = 0; i < length; i += 1) {
2049 buf[i] = array[i] & 255
2050 }
2051 return buf
2052}
2053
2054function fromArrayBuffer (array, byteOffset, length) {
2055 if (byteOffset < 0 || array.byteLength < byteOffset) {
2056 throw new RangeError('"offset" is outside of buffer bounds')
2057 }
2058
2059 if (array.byteLength < byteOffset + (length || 0)) {
2060 throw new RangeError('"length" is outside of buffer bounds')
2061 }
2062
2063 var buf
2064 if (byteOffset === undefined && length === undefined) {
2065 buf = new Uint8Array(array)
2066 } else if (length === undefined) {
2067 buf = new Uint8Array(array, byteOffset)
2068 } else {
2069 buf = new Uint8Array(array, byteOffset, length)
2070 }
2071
2072 // Return an augmented `Uint8Array` instance
2073 buf.__proto__ = Buffer.prototype
2074 return buf
2075}
2076
2077function fromObject (obj) {
2078 if (Buffer.isBuffer(obj)) {
2079 var len = checked(obj.length) | 0
2080 var buf = createBuffer(len)
2081
2082 if (buf.length === 0) {
2083 return buf
2084 }
2085
2086 obj.copy(buf, 0, 0, len)
2087 return buf
2088 }
2089
2090 if (obj.length !== undefined) {
2091 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
2092 return createBuffer(0)
2093 }
2094 return fromArrayLike(obj)
2095 }
2096
2097 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
2098 return fromArrayLike(obj.data)
2099 }
2100}
2101
2102function checked (length) {
2103 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
2104 // length is NaN (which is otherwise coerced to zero.)
2105 if (length >= K_MAX_LENGTH) {
2106 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
2107 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
2108 }
2109 return length | 0
2110}
2111
2112function SlowBuffer (length) {
2113 if (+length != length) { // eslint-disable-line eqeqeq
2114 length = 0
2115 }
2116 return Buffer.alloc(+length)
2117}
2118
2119Buffer.isBuffer = function isBuffer (b) {
2120 return b != null && b._isBuffer === true &&
2121 b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
2122}
2123
2124Buffer.compare = function compare (a, b) {
2125 if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
2126 if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
2127 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
2128 throw new TypeError(
2129 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
2130 )
2131 }
2132
2133 if (a === b) return 0
2134
2135 var x = a.length
2136 var y = b.length
2137
2138 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
2139 if (a[i] !== b[i]) {
2140 x = a[i]
2141 y = b[i]
2142 break
2143 }
2144 }
2145
2146 if (x < y) return -1
2147 if (y < x) return 1
2148 return 0
2149}
2150
2151Buffer.isEncoding = function isEncoding (encoding) {
2152 switch (String(encoding).toLowerCase()) {
2153 case 'hex':
2154 case 'utf8':
2155 case 'utf-8':
2156 case 'ascii':
2157 case 'latin1':
2158 case 'binary':
2159 case 'base64':
2160 case 'ucs2':
2161 case 'ucs-2':
2162 case 'utf16le':
2163 case 'utf-16le':
2164 return true
2165 default:
2166 return false
2167 }
2168}
2169
2170Buffer.concat = function concat (list, length) {
2171 if (!Array.isArray(list)) {
2172 throw new TypeError('"list" argument must be an Array of Buffers')
2173 }
2174
2175 if (list.length === 0) {
2176 return Buffer.alloc(0)
2177 }
2178
2179 var i
2180 if (length === undefined) {
2181 length = 0
2182 for (i = 0; i < list.length; ++i) {
2183 length += list[i].length
2184 }
2185 }
2186
2187 var buffer = Buffer.allocUnsafe(length)
2188 var pos = 0
2189 for (i = 0; i < list.length; ++i) {
2190 var buf = list[i]
2191 if (isInstance(buf, Uint8Array)) {
2192 buf = Buffer.from(buf)
2193 }
2194 if (!Buffer.isBuffer(buf)) {
2195 throw new TypeError('"list" argument must be an Array of Buffers')
2196 }
2197 buf.copy(buffer, pos)
2198 pos += buf.length
2199 }
2200 return buffer
2201}
2202
2203function byteLength (string, encoding) {
2204 if (Buffer.isBuffer(string)) {
2205 return string.length
2206 }
2207 if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
2208 return string.byteLength
2209 }
2210 if (typeof string !== 'string') {
2211 throw new TypeError(
2212 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
2213 'Received type ' + typeof string
2214 )
2215 }
2216
2217 var len = string.length
2218 var mustMatch = (arguments.length > 2 && arguments[2] === true)
2219 if (!mustMatch && len === 0) return 0
2220
2221 // Use a for loop to avoid recursion
2222 var loweredCase = false
2223 for (;;) {
2224 switch (encoding) {
2225 case 'ascii':
2226 case 'latin1':
2227 case 'binary':
2228 return len
2229 case 'utf8':
2230 case 'utf-8':
2231 return utf8ToBytes(string).length
2232 case 'ucs2':
2233 case 'ucs-2':
2234 case 'utf16le':
2235 case 'utf-16le':
2236 return len * 2
2237 case 'hex':
2238 return len >>> 1
2239 case 'base64':
2240 return base64ToBytes(string).length
2241 default:
2242 if (loweredCase) {
2243 return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
2244 }
2245 encoding = ('' + encoding).toLowerCase()
2246 loweredCase = true
2247 }
2248 }
2249}
2250Buffer.byteLength = byteLength
2251
2252function slowToString (encoding, start, end) {
2253 var loweredCase = false
2254
2255 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
2256 // property of a typed array.
2257
2258 // This behaves neither like String nor Uint8Array in that we set start/end
2259 // to their upper/lower bounds if the value passed is out of range.
2260 // undefined is handled specially as per ECMA-262 6th Edition,
2261 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
2262 if (start === undefined || start < 0) {
2263 start = 0
2264 }
2265 // Return early if start > this.length. Done here to prevent potential uint32
2266 // coercion fail below.
2267 if (start > this.length) {
2268 return ''
2269 }
2270
2271 if (end === undefined || end > this.length) {
2272 end = this.length
2273 }
2274
2275 if (end <= 0) {
2276 return ''
2277 }
2278
2279 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
2280 end >>>= 0
2281 start >>>= 0
2282
2283 if (end <= start) {
2284 return ''
2285 }
2286
2287 if (!encoding) encoding = 'utf8'
2288
2289 while (true) {
2290 switch (encoding) {
2291 case 'hex':
2292 return hexSlice(this, start, end)
2293
2294 case 'utf8':
2295 case 'utf-8':
2296 return utf8Slice(this, start, end)
2297
2298 case 'ascii':
2299 return asciiSlice(this, start, end)
2300
2301 case 'latin1':
2302 case 'binary':
2303 return latin1Slice(this, start, end)
2304
2305 case 'base64':
2306 return base64Slice(this, start, end)
2307
2308 case 'ucs2':
2309 case 'ucs-2':
2310 case 'utf16le':
2311 case 'utf-16le':
2312 return utf16leSlice(this, start, end)
2313
2314 default:
2315 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
2316 encoding = (encoding + '').toLowerCase()
2317 loweredCase = true
2318 }
2319 }
2320}
2321
2322// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
2323// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
2324// reliably in a browserify context because there could be multiple different
2325// copies of the 'buffer' package in use. This method works even for Buffer
2326// instances that were created from another copy of the `buffer` package.
2327// See: https://github.com/feross/buffer/issues/154
2328Buffer.prototype._isBuffer = true
2329
2330function swap (b, n, m) {
2331 var i = b[n]
2332 b[n] = b[m]
2333 b[m] = i
2334}
2335
2336Buffer.prototype.swap16 = function swap16 () {
2337 var len = this.length
2338 if (len % 2 !== 0) {
2339 throw new RangeError('Buffer size must be a multiple of 16-bits')
2340 }
2341 for (var i = 0; i < len; i += 2) {
2342 swap(this, i, i + 1)
2343 }
2344 return this
2345}
2346
2347Buffer.prototype.swap32 = function swap32 () {
2348 var len = this.length
2349 if (len % 4 !== 0) {
2350 throw new RangeError('Buffer size must be a multiple of 32-bits')
2351 }
2352 for (var i = 0; i < len; i += 4) {
2353 swap(this, i, i + 3)
2354 swap(this, i + 1, i + 2)
2355 }
2356 return this
2357}
2358
2359Buffer.prototype.swap64 = function swap64 () {
2360 var len = this.length
2361 if (len % 8 !== 0) {
2362 throw new RangeError('Buffer size must be a multiple of 64-bits')
2363 }
2364 for (var i = 0; i < len; i += 8) {
2365 swap(this, i, i + 7)
2366 swap(this, i + 1, i + 6)
2367 swap(this, i + 2, i + 5)
2368 swap(this, i + 3, i + 4)
2369 }
2370 return this
2371}
2372
2373Buffer.prototype.toString = function toString () {
2374 var length = this.length
2375 if (length === 0) return ''
2376 if (arguments.length === 0) return utf8Slice(this, 0, length)
2377 return slowToString.apply(this, arguments)
2378}
2379
2380Buffer.prototype.toLocaleString = Buffer.prototype.toString
2381
2382Buffer.prototype.equals = function equals (b) {
2383 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
2384 if (this === b) return true
2385 return Buffer.compare(this, b) === 0
2386}
2387
2388Buffer.prototype.inspect = function inspect () {
2389 var str = ''
2390 var max = exports.INSPECT_MAX_BYTES
2391 str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
2392 if (this.length > max) str += ' ... '
2393 return '<Buffer ' + str + '>'
2394}
2395
2396Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
2397 if (isInstance(target, Uint8Array)) {
2398 target = Buffer.from(target, target.offset, target.byteLength)
2399 }
2400 if (!Buffer.isBuffer(target)) {
2401 throw new TypeError(
2402 'The "target" argument must be one of type Buffer or Uint8Array. ' +
2403 'Received type ' + (typeof target)
2404 )
2405 }
2406
2407 if (start === undefined) {
2408 start = 0
2409 }
2410 if (end === undefined) {
2411 end = target ? target.length : 0
2412 }
2413 if (thisStart === undefined) {
2414 thisStart = 0
2415 }
2416 if (thisEnd === undefined) {
2417 thisEnd = this.length
2418 }
2419
2420 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
2421 throw new RangeError('out of range index')
2422 }
2423
2424 if (thisStart >= thisEnd && start >= end) {
2425 return 0
2426 }
2427 if (thisStart >= thisEnd) {
2428 return -1
2429 }
2430 if (start >= end) {
2431 return 1
2432 }
2433
2434 start >>>= 0
2435 end >>>= 0
2436 thisStart >>>= 0
2437 thisEnd >>>= 0
2438
2439 if (this === target) return 0
2440
2441 var x = thisEnd - thisStart
2442 var y = end - start
2443 var len = Math.min(x, y)
2444
2445 var thisCopy = this.slice(thisStart, thisEnd)
2446 var targetCopy = target.slice(start, end)
2447
2448 for (var i = 0; i < len; ++i) {
2449 if (thisCopy[i] !== targetCopy[i]) {
2450 x = thisCopy[i]
2451 y = targetCopy[i]
2452 break
2453 }
2454 }
2455
2456 if (x < y) return -1
2457 if (y < x) return 1
2458 return 0
2459}
2460
2461// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
2462// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
2463//
2464// Arguments:
2465// - buffer - a Buffer to search
2466// - val - a string, Buffer, or number
2467// - byteOffset - an index into `buffer`; will be clamped to an int32
2468// - encoding - an optional encoding, relevant is val is a string
2469// - dir - true for indexOf, false for lastIndexOf
2470function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
2471 // Empty buffer means no match
2472 if (buffer.length === 0) return -1
2473
2474 // Normalize byteOffset
2475 if (typeof byteOffset === 'string') {
2476 encoding = byteOffset
2477 byteOffset = 0
2478 } else if (byteOffset > 0x7fffffff) {
2479 byteOffset = 0x7fffffff
2480 } else if (byteOffset < -0x80000000) {
2481 byteOffset = -0x80000000
2482 }
2483 byteOffset = +byteOffset // Coerce to Number.
2484 if (numberIsNaN(byteOffset)) {
2485 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
2486 byteOffset = dir ? 0 : (buffer.length - 1)
2487 }
2488
2489 // Normalize byteOffset: negative offsets start from the end of the buffer
2490 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
2491 if (byteOffset >= buffer.length) {
2492 if (dir) return -1
2493 else byteOffset = buffer.length - 1
2494 } else if (byteOffset < 0) {
2495 if (dir) byteOffset = 0
2496 else return -1
2497 }
2498
2499 // Normalize val
2500 if (typeof val === 'string') {
2501 val = Buffer.from(val, encoding)
2502 }
2503
2504 // Finally, search either indexOf (if dir is true) or lastIndexOf
2505 if (Buffer.isBuffer(val)) {
2506 // Special case: looking for empty string/buffer always fails
2507 if (val.length === 0) {
2508 return -1
2509 }
2510 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
2511 } else if (typeof val === 'number') {
2512 val = val & 0xFF // Search for a byte value [0-255]
2513 if (typeof Uint8Array.prototype.indexOf === 'function') {
2514 if (dir) {
2515 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
2516 } else {
2517 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
2518 }
2519 }
2520 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
2521 }
2522
2523 throw new TypeError('val must be string, number or Buffer')
2524}
2525
2526function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
2527 var indexSize = 1
2528 var arrLength = arr.length
2529 var valLength = val.length
2530
2531 if (encoding !== undefined) {
2532 encoding = String(encoding).toLowerCase()
2533 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
2534 encoding === 'utf16le' || encoding === 'utf-16le') {
2535 if (arr.length < 2 || val.length < 2) {
2536 return -1
2537 }
2538 indexSize = 2
2539 arrLength /= 2
2540 valLength /= 2
2541 byteOffset /= 2
2542 }
2543 }
2544
2545 function read (buf, i) {
2546 if (indexSize === 1) {
2547 return buf[i]
2548 } else {
2549 return buf.readUInt16BE(i * indexSize)
2550 }
2551 }
2552
2553 var i
2554 if (dir) {
2555 var foundIndex = -1
2556 for (i = byteOffset; i < arrLength; i++) {
2557 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
2558 if (foundIndex === -1) foundIndex = i
2559 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
2560 } else {
2561 if (foundIndex !== -1) i -= i - foundIndex
2562 foundIndex = -1
2563 }
2564 }
2565 } else {
2566 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
2567 for (i = byteOffset; i >= 0; i--) {
2568 var found = true
2569 for (var j = 0; j < valLength; j++) {
2570 if (read(arr, i + j) !== read(val, j)) {
2571 found = false
2572 break
2573 }
2574 }
2575 if (found) return i
2576 }
2577 }
2578
2579 return -1
2580}
2581
2582Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
2583 return this.indexOf(val, byteOffset, encoding) !== -1
2584}
2585
2586Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
2587 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
2588}
2589
2590Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
2591 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
2592}
2593
2594function hexWrite (buf, string, offset, length) {
2595 offset = Number(offset) || 0
2596 var remaining = buf.length - offset
2597 if (!length) {
2598 length = remaining
2599 } else {
2600 length = Number(length)
2601 if (length > remaining) {
2602 length = remaining
2603 }
2604 }
2605
2606 var strLen = string.length
2607
2608 if (length > strLen / 2) {
2609 length = strLen / 2
2610 }
2611 for (var i = 0; i < length; ++i) {
2612 var parsed = parseInt(string.substr(i * 2, 2), 16)
2613 if (numberIsNaN(parsed)) return i
2614 buf[offset + i] = parsed
2615 }
2616 return i
2617}
2618
2619function utf8Write (buf, string, offset, length) {
2620 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
2621}
2622
2623function asciiWrite (buf, string, offset, length) {
2624 return blitBuffer(asciiToBytes(string), buf, offset, length)
2625}
2626
2627function latin1Write (buf, string, offset, length) {
2628 return asciiWrite(buf, string, offset, length)
2629}
2630
2631function base64Write (buf, string, offset, length) {
2632 return blitBuffer(base64ToBytes(string), buf, offset, length)
2633}
2634
2635function ucs2Write (buf, string, offset, length) {
2636 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
2637}
2638
2639Buffer.prototype.write = function write (string, offset, length, encoding) {
2640 // Buffer#write(string)
2641 if (offset === undefined) {
2642 encoding = 'utf8'
2643 length = this.length
2644 offset = 0
2645 // Buffer#write(string, encoding)
2646 } else if (length === undefined && typeof offset === 'string') {
2647 encoding = offset
2648 length = this.length
2649 offset = 0
2650 // Buffer#write(string, offset[, length][, encoding])
2651 } else if (isFinite(offset)) {
2652 offset = offset >>> 0
2653 if (isFinite(length)) {
2654 length = length >>> 0
2655 if (encoding === undefined) encoding = 'utf8'
2656 } else {
2657 encoding = length
2658 length = undefined
2659 }
2660 } else {
2661 throw new Error(
2662 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
2663 )
2664 }
2665
2666 var remaining = this.length - offset
2667 if (length === undefined || length > remaining) length = remaining
2668
2669 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
2670 throw new RangeError('Attempt to write outside buffer bounds')
2671 }
2672
2673 if (!encoding) encoding = 'utf8'
2674
2675 var loweredCase = false
2676 for (;;) {
2677 switch (encoding) {
2678 case 'hex':
2679 return hexWrite(this, string, offset, length)
2680
2681 case 'utf8':
2682 case 'utf-8':
2683 return utf8Write(this, string, offset, length)
2684
2685 case 'ascii':
2686 return asciiWrite(this, string, offset, length)
2687
2688 case 'latin1':
2689 case 'binary':
2690 return latin1Write(this, string, offset, length)
2691
2692 case 'base64':
2693 // Warning: maxLength not taken into account in base64Write
2694 return base64Write(this, string, offset, length)
2695
2696 case 'ucs2':
2697 case 'ucs-2':
2698 case 'utf16le':
2699 case 'utf-16le':
2700 return ucs2Write(this, string, offset, length)
2701
2702 default:
2703 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
2704 encoding = ('' + encoding).toLowerCase()
2705 loweredCase = true
2706 }
2707 }
2708}
2709
2710Buffer.prototype.toJSON = function toJSON () {
2711 return {
2712 type: 'Buffer',
2713 data: Array.prototype.slice.call(this._arr || this, 0)
2714 }
2715}
2716
2717function base64Slice (buf, start, end) {
2718 if (start === 0 && end === buf.length) {
2719 return base64.fromByteArray(buf)
2720 } else {
2721 return base64.fromByteArray(buf.slice(start, end))
2722 }
2723}
2724
2725function utf8Slice (buf, start, end) {
2726 end = Math.min(buf.length, end)
2727 var res = []
2728
2729 var i = start
2730 while (i < end) {
2731 var firstByte = buf[i]
2732 var codePoint = null
2733 var bytesPerSequence = (firstByte > 0xEF) ? 4
2734 : (firstByte > 0xDF) ? 3
2735 : (firstByte > 0xBF) ? 2
2736 : 1
2737
2738 if (i + bytesPerSequence <= end) {
2739 var secondByte, thirdByte, fourthByte, tempCodePoint
2740
2741 switch (bytesPerSequence) {
2742 case 1:
2743 if (firstByte < 0x80) {
2744 codePoint = firstByte
2745 }
2746 break
2747 case 2:
2748 secondByte = buf[i + 1]
2749 if ((secondByte & 0xC0) === 0x80) {
2750 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
2751 if (tempCodePoint > 0x7F) {
2752 codePoint = tempCodePoint
2753 }
2754 }
2755 break
2756 case 3:
2757 secondByte = buf[i + 1]
2758 thirdByte = buf[i + 2]
2759 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
2760 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
2761 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
2762 codePoint = tempCodePoint
2763 }
2764 }
2765 break
2766 case 4:
2767 secondByte = buf[i + 1]
2768 thirdByte = buf[i + 2]
2769 fourthByte = buf[i + 3]
2770 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
2771 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
2772 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
2773 codePoint = tempCodePoint
2774 }
2775 }
2776 }
2777 }
2778
2779 if (codePoint === null) {
2780 // we did not generate a valid codePoint so insert a
2781 // replacement char (U+FFFD) and advance only 1 byte
2782 codePoint = 0xFFFD
2783 bytesPerSequence = 1
2784 } else if (codePoint > 0xFFFF) {
2785 // encode to utf16 (surrogate pair dance)
2786 codePoint -= 0x10000
2787 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
2788 codePoint = 0xDC00 | codePoint & 0x3FF
2789 }
2790
2791 res.push(codePoint)
2792 i += bytesPerSequence
2793 }
2794
2795 return decodeCodePointsArray(res)
2796}
2797
2798// Based on http://stackoverflow.com/a/22747272/680742, the browser with
2799// the lowest limit is Chrome, with 0x10000 args.
2800// We go 1 magnitude less, for safety
2801var MAX_ARGUMENTS_LENGTH = 0x1000
2802
2803function decodeCodePointsArray (codePoints) {
2804 var len = codePoints.length
2805 if (len <= MAX_ARGUMENTS_LENGTH) {
2806 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
2807 }
2808
2809 // Decode in chunks to avoid "call stack size exceeded".
2810 var res = ''
2811 var i = 0
2812 while (i < len) {
2813 res += String.fromCharCode.apply(
2814 String,
2815 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
2816 )
2817 }
2818 return res
2819}
2820
2821function asciiSlice (buf, start, end) {
2822 var ret = ''
2823 end = Math.min(buf.length, end)
2824
2825 for (var i = start; i < end; ++i) {
2826 ret += String.fromCharCode(buf[i] & 0x7F)
2827 }
2828 return ret
2829}
2830
2831function latin1Slice (buf, start, end) {
2832 var ret = ''
2833 end = Math.min(buf.length, end)
2834
2835 for (var i = start; i < end; ++i) {
2836 ret += String.fromCharCode(buf[i])
2837 }
2838 return ret
2839}
2840
2841function hexSlice (buf, start, end) {
2842 var len = buf.length
2843
2844 if (!start || start < 0) start = 0
2845 if (!end || end < 0 || end > len) end = len
2846
2847 var out = ''
2848 for (var i = start; i < end; ++i) {
2849 out += toHex(buf[i])
2850 }
2851 return out
2852}
2853
2854function utf16leSlice (buf, start, end) {
2855 var bytes = buf.slice(start, end)
2856 var res = ''
2857 for (var i = 0; i < bytes.length; i += 2) {
2858 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
2859 }
2860 return res
2861}
2862
2863Buffer.prototype.slice = function slice (start, end) {
2864 var len = this.length
2865 start = ~~start
2866 end = end === undefined ? len : ~~end
2867
2868 if (start < 0) {
2869 start += len
2870 if (start < 0) start = 0
2871 } else if (start > len) {
2872 start = len
2873 }
2874
2875 if (end < 0) {
2876 end += len
2877 if (end < 0) end = 0
2878 } else if (end > len) {
2879 end = len
2880 }
2881
2882 if (end < start) end = start
2883
2884 var newBuf = this.subarray(start, end)
2885 // Return an augmented `Uint8Array` instance
2886 newBuf.__proto__ = Buffer.prototype
2887 return newBuf
2888}
2889
2890/*
2891 * Need to make sure that buffer isn't trying to write out of bounds.
2892 */
2893function checkOffset (offset, ext, length) {
2894 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
2895 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
2896}
2897
2898Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
2899 offset = offset >>> 0
2900 byteLength = byteLength >>> 0
2901 if (!noAssert) checkOffset(offset, byteLength, this.length)
2902
2903 var val = this[offset]
2904 var mul = 1
2905 var i = 0
2906 while (++i < byteLength && (mul *= 0x100)) {
2907 val += this[offset + i] * mul
2908 }
2909
2910 return val
2911}
2912
2913Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
2914 offset = offset >>> 0
2915 byteLength = byteLength >>> 0
2916 if (!noAssert) {
2917 checkOffset(offset, byteLength, this.length)
2918 }
2919
2920 var val = this[offset + --byteLength]
2921 var mul = 1
2922 while (byteLength > 0 && (mul *= 0x100)) {
2923 val += this[offset + --byteLength] * mul
2924 }
2925
2926 return val
2927}
2928
2929Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
2930 offset = offset >>> 0
2931 if (!noAssert) checkOffset(offset, 1, this.length)
2932 return this[offset]
2933}
2934
2935Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
2936 offset = offset >>> 0
2937 if (!noAssert) checkOffset(offset, 2, this.length)
2938 return this[offset] | (this[offset + 1] << 8)
2939}
2940
2941Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
2942 offset = offset >>> 0
2943 if (!noAssert) checkOffset(offset, 2, this.length)
2944 return (this[offset] << 8) | this[offset + 1]
2945}
2946
2947Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
2948 offset = offset >>> 0
2949 if (!noAssert) checkOffset(offset, 4, this.length)
2950
2951 return ((this[offset]) |
2952 (this[offset + 1] << 8) |
2953 (this[offset + 2] << 16)) +
2954 (this[offset + 3] * 0x1000000)
2955}
2956
2957Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
2958 offset = offset >>> 0
2959 if (!noAssert) checkOffset(offset, 4, this.length)
2960
2961 return (this[offset] * 0x1000000) +
2962 ((this[offset + 1] << 16) |
2963 (this[offset + 2] << 8) |
2964 this[offset + 3])
2965}
2966
2967Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
2968 offset = offset >>> 0
2969 byteLength = byteLength >>> 0
2970 if (!noAssert) checkOffset(offset, byteLength, this.length)
2971
2972 var val = this[offset]
2973 var mul = 1
2974 var i = 0
2975 while (++i < byteLength && (mul *= 0x100)) {
2976 val += this[offset + i] * mul
2977 }
2978 mul *= 0x80
2979
2980 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
2981
2982 return val
2983}
2984
2985Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
2986 offset = offset >>> 0
2987 byteLength = byteLength >>> 0
2988 if (!noAssert) checkOffset(offset, byteLength, this.length)
2989
2990 var i = byteLength
2991 var mul = 1
2992 var val = this[offset + --i]
2993 while (i > 0 && (mul *= 0x100)) {
2994 val += this[offset + --i] * mul
2995 }
2996 mul *= 0x80
2997
2998 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
2999
3000 return val
3001}
3002
3003Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
3004 offset = offset >>> 0
3005 if (!noAssert) checkOffset(offset, 1, this.length)
3006 if (!(this[offset] & 0x80)) return (this[offset])
3007 return ((0xff - this[offset] + 1) * -1)
3008}
3009
3010Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
3011 offset = offset >>> 0
3012 if (!noAssert) checkOffset(offset, 2, this.length)
3013 var val = this[offset] | (this[offset + 1] << 8)
3014 return (val & 0x8000) ? val | 0xFFFF0000 : val
3015}
3016
3017Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
3018 offset = offset >>> 0
3019 if (!noAssert) checkOffset(offset, 2, this.length)
3020 var val = this[offset + 1] | (this[offset] << 8)
3021 return (val & 0x8000) ? val | 0xFFFF0000 : val
3022}
3023
3024Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
3025 offset = offset >>> 0
3026 if (!noAssert) checkOffset(offset, 4, this.length)
3027
3028 return (this[offset]) |
3029 (this[offset + 1] << 8) |
3030 (this[offset + 2] << 16) |
3031 (this[offset + 3] << 24)
3032}
3033
3034Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
3035 offset = offset >>> 0
3036 if (!noAssert) checkOffset(offset, 4, this.length)
3037
3038 return (this[offset] << 24) |
3039 (this[offset + 1] << 16) |
3040 (this[offset + 2] << 8) |
3041 (this[offset + 3])
3042}
3043
3044Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
3045 offset = offset >>> 0
3046 if (!noAssert) checkOffset(offset, 4, this.length)
3047 return ieee754.read(this, offset, true, 23, 4)
3048}
3049
3050Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
3051 offset = offset >>> 0
3052 if (!noAssert) checkOffset(offset, 4, this.length)
3053 return ieee754.read(this, offset, false, 23, 4)
3054}
3055
3056Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
3057 offset = offset >>> 0
3058 if (!noAssert) checkOffset(offset, 8, this.length)
3059 return ieee754.read(this, offset, true, 52, 8)
3060}
3061
3062Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
3063 offset = offset >>> 0
3064 if (!noAssert) checkOffset(offset, 8, this.length)
3065 return ieee754.read(this, offset, false, 52, 8)
3066}
3067
3068function checkInt (buf, value, offset, ext, max, min) {
3069 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
3070 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
3071 if (offset + ext > buf.length) throw new RangeError('Index out of range')
3072}
3073
3074Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
3075 value = +value
3076 offset = offset >>> 0
3077 byteLength = byteLength >>> 0
3078 if (!noAssert) {
3079 var maxBytes = Math.pow(2, 8 * byteLength) - 1
3080 checkInt(this, value, offset, byteLength, maxBytes, 0)
3081 }
3082
3083 var mul = 1
3084 var i = 0
3085 this[offset] = value & 0xFF
3086 while (++i < byteLength && (mul *= 0x100)) {
3087 this[offset + i] = (value / mul) & 0xFF
3088 }
3089
3090 return offset + byteLength
3091}
3092
3093Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
3094 value = +value
3095 offset = offset >>> 0
3096 byteLength = byteLength >>> 0
3097 if (!noAssert) {
3098 var maxBytes = Math.pow(2, 8 * byteLength) - 1
3099 checkInt(this, value, offset, byteLength, maxBytes, 0)
3100 }
3101
3102 var i = byteLength - 1
3103 var mul = 1
3104 this[offset + i] = value & 0xFF
3105 while (--i >= 0 && (mul *= 0x100)) {
3106 this[offset + i] = (value / mul) & 0xFF
3107 }
3108
3109 return offset + byteLength
3110}
3111
3112Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
3113 value = +value
3114 offset = offset >>> 0
3115 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
3116 this[offset] = (value & 0xff)
3117 return offset + 1
3118}
3119
3120Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
3121 value = +value
3122 offset = offset >>> 0
3123 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
3124 this[offset] = (value & 0xff)
3125 this[offset + 1] = (value >>> 8)
3126 return offset + 2
3127}
3128
3129Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
3130 value = +value
3131 offset = offset >>> 0
3132 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
3133 this[offset] = (value >>> 8)
3134 this[offset + 1] = (value & 0xff)
3135 return offset + 2
3136}
3137
3138Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
3139 value = +value
3140 offset = offset >>> 0
3141 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
3142 this[offset + 3] = (value >>> 24)
3143 this[offset + 2] = (value >>> 16)
3144 this[offset + 1] = (value >>> 8)
3145 this[offset] = (value & 0xff)
3146 return offset + 4
3147}
3148
3149Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
3150 value = +value
3151 offset = offset >>> 0
3152 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
3153 this[offset] = (value >>> 24)
3154 this[offset + 1] = (value >>> 16)
3155 this[offset + 2] = (value >>> 8)
3156 this[offset + 3] = (value & 0xff)
3157 return offset + 4
3158}
3159
3160Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
3161 value = +value
3162 offset = offset >>> 0
3163 if (!noAssert) {
3164 var limit = Math.pow(2, (8 * byteLength) - 1)
3165
3166 checkInt(this, value, offset, byteLength, limit - 1, -limit)
3167 }
3168
3169 var i = 0
3170 var mul = 1
3171 var sub = 0
3172 this[offset] = value & 0xFF
3173 while (++i < byteLength && (mul *= 0x100)) {
3174 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
3175 sub = 1
3176 }
3177 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
3178 }
3179
3180 return offset + byteLength
3181}
3182
3183Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
3184 value = +value
3185 offset = offset >>> 0
3186 if (!noAssert) {
3187 var limit = Math.pow(2, (8 * byteLength) - 1)
3188
3189 checkInt(this, value, offset, byteLength, limit - 1, -limit)
3190 }
3191
3192 var i = byteLength - 1
3193 var mul = 1
3194 var sub = 0
3195 this[offset + i] = value & 0xFF
3196 while (--i >= 0 && (mul *= 0x100)) {
3197 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
3198 sub = 1
3199 }
3200 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
3201 }
3202
3203 return offset + byteLength
3204}
3205
3206Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
3207 value = +value
3208 offset = offset >>> 0
3209 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
3210 if (value < 0) value = 0xff + value + 1
3211 this[offset] = (value & 0xff)
3212 return offset + 1
3213}
3214
3215Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
3216 value = +value
3217 offset = offset >>> 0
3218 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
3219 this[offset] = (value & 0xff)
3220 this[offset + 1] = (value >>> 8)
3221 return offset + 2
3222}
3223
3224Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
3225 value = +value
3226 offset = offset >>> 0
3227 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
3228 this[offset] = (value >>> 8)
3229 this[offset + 1] = (value & 0xff)
3230 return offset + 2
3231}
3232
3233Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
3234 value = +value
3235 offset = offset >>> 0
3236 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
3237 this[offset] = (value & 0xff)
3238 this[offset + 1] = (value >>> 8)
3239 this[offset + 2] = (value >>> 16)
3240 this[offset + 3] = (value >>> 24)
3241 return offset + 4
3242}
3243
3244Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
3245 value = +value
3246 offset = offset >>> 0
3247 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
3248 if (value < 0) value = 0xffffffff + value + 1
3249 this[offset] = (value >>> 24)
3250 this[offset + 1] = (value >>> 16)
3251 this[offset + 2] = (value >>> 8)
3252 this[offset + 3] = (value & 0xff)
3253 return offset + 4
3254}
3255
3256function checkIEEE754 (buf, value, offset, ext, max, min) {
3257 if (offset + ext > buf.length) throw new RangeError('Index out of range')
3258 if (offset < 0) throw new RangeError('Index out of range')
3259}
3260
3261function writeFloat (buf, value, offset, littleEndian, noAssert) {
3262 value = +value
3263 offset = offset >>> 0
3264 if (!noAssert) {
3265 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
3266 }
3267 ieee754.write(buf, value, offset, littleEndian, 23, 4)
3268 return offset + 4
3269}
3270
3271Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
3272 return writeFloat(this, value, offset, true, noAssert)
3273}
3274
3275Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
3276 return writeFloat(this, value, offset, false, noAssert)
3277}
3278
3279function writeDouble (buf, value, offset, littleEndian, noAssert) {
3280 value = +value
3281 offset = offset >>> 0
3282 if (!noAssert) {
3283 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
3284 }
3285 ieee754.write(buf, value, offset, littleEndian, 52, 8)
3286 return offset + 8
3287}
3288
3289Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
3290 return writeDouble(this, value, offset, true, noAssert)
3291}
3292
3293Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
3294 return writeDouble(this, value, offset, false, noAssert)
3295}
3296
3297// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
3298Buffer.prototype.copy = function copy (target, targetStart, start, end) {
3299 if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
3300 if (!start) start = 0
3301 if (!end && end !== 0) end = this.length
3302 if (targetStart >= target.length) targetStart = target.length
3303 if (!targetStart) targetStart = 0
3304 if (end > 0 && end < start) end = start
3305
3306 // Copy 0 bytes; we're done
3307 if (end === start) return 0
3308 if (target.length === 0 || this.length === 0) return 0
3309
3310 // Fatal error conditions
3311 if (targetStart < 0) {
3312 throw new RangeError('targetStart out of bounds')
3313 }
3314 if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
3315 if (end < 0) throw new RangeError('sourceEnd out of bounds')
3316
3317 // Are we oob?
3318 if (end > this.length) end = this.length
3319 if (target.length - targetStart < end - start) {
3320 end = target.length - targetStart + start
3321 }
3322
3323 var len = end - start
3324
3325 if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
3326 // Use built-in when available, missing from IE11
3327 this.copyWithin(targetStart, start, end)
3328 } else if (this === target && start < targetStart && targetStart < end) {
3329 // descending copy from end
3330 for (var i = len - 1; i >= 0; --i) {
3331 target[i + targetStart] = this[i + start]
3332 }
3333 } else {
3334 Uint8Array.prototype.set.call(
3335 target,
3336 this.subarray(start, end),
3337 targetStart
3338 )
3339 }
3340
3341 return len
3342}
3343
3344// Usage:
3345// buffer.fill(number[, offset[, end]])
3346// buffer.fill(buffer[, offset[, end]])
3347// buffer.fill(string[, offset[, end]][, encoding])
3348Buffer.prototype.fill = function fill (val, start, end, encoding) {
3349 // Handle string cases:
3350 if (typeof val === 'string') {
3351 if (typeof start === 'string') {
3352 encoding = start
3353 start = 0
3354 end = this.length
3355 } else if (typeof end === 'string') {
3356 encoding = end
3357 end = this.length
3358 }
3359 if (encoding !== undefined && typeof encoding !== 'string') {
3360 throw new TypeError('encoding must be a string')
3361 }
3362 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
3363 throw new TypeError('Unknown encoding: ' + encoding)
3364 }
3365 if (val.length === 1) {
3366 var code = val.charCodeAt(0)
3367 if ((encoding === 'utf8' && code < 128) ||
3368 encoding === 'latin1') {
3369 // Fast path: If `val` fits into a single byte, use that numeric value.
3370 val = code
3371 }
3372 }
3373 } else if (typeof val === 'number') {
3374 val = val & 255
3375 }
3376
3377 // Invalid ranges are not set to a default, so can range check early.
3378 if (start < 0 || this.length < start || this.length < end) {
3379 throw new RangeError('Out of range index')
3380 }
3381
3382 if (end <= start) {
3383 return this
3384 }
3385
3386 start = start >>> 0
3387 end = end === undefined ? this.length : end >>> 0
3388
3389 if (!val) val = 0
3390
3391 var i
3392 if (typeof val === 'number') {
3393 for (i = start; i < end; ++i) {
3394 this[i] = val
3395 }
3396 } else {
3397 var bytes = Buffer.isBuffer(val)
3398 ? val
3399 : Buffer.from(val, encoding)
3400 var len = bytes.length
3401 if (len === 0) {
3402 throw new TypeError('The value "' + val +
3403 '" is invalid for argument "value"')
3404 }
3405 for (i = 0; i < end - start; ++i) {
3406 this[i + start] = bytes[i % len]
3407 }
3408 }
3409
3410 return this
3411}
3412
3413// HELPER FUNCTIONS
3414// ================
3415
3416var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
3417
3418function base64clean (str) {
3419 // Node takes equal signs as end of the Base64 encoding
3420 str = str.split('=')[0]
3421 // Node strips out invalid characters like \n and \t from the string, base64-js does not
3422 str = str.trim().replace(INVALID_BASE64_RE, '')
3423 // Node converts strings with length < 2 to ''
3424 if (str.length < 2) return ''
3425 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
3426 while (str.length % 4 !== 0) {
3427 str = str + '='
3428 }
3429 return str
3430}
3431
3432function toHex (n) {
3433 if (n < 16) return '0' + n.toString(16)
3434 return n.toString(16)
3435}
3436
3437function utf8ToBytes (string, units) {
3438 units = units || Infinity
3439 var codePoint
3440 var length = string.length
3441 var leadSurrogate = null
3442 var bytes = []
3443
3444 for (var i = 0; i < length; ++i) {
3445 codePoint = string.charCodeAt(i)
3446
3447 // is surrogate component
3448 if (codePoint > 0xD7FF && codePoint < 0xE000) {
3449 // last char was a lead
3450 if (!leadSurrogate) {
3451 // no lead yet
3452 if (codePoint > 0xDBFF) {
3453 // unexpected trail
3454 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3455 continue
3456 } else if (i + 1 === length) {
3457 // unpaired lead
3458 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3459 continue
3460 }
3461
3462 // valid lead
3463 leadSurrogate = codePoint
3464
3465 continue
3466 }
3467
3468 // 2 leads in a row
3469 if (codePoint < 0xDC00) {
3470 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3471 leadSurrogate = codePoint
3472 continue
3473 }
3474
3475 // valid surrogate pair
3476 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
3477 } else if (leadSurrogate) {
3478 // valid bmp char, but last char was a lead
3479 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3480 }
3481
3482 leadSurrogate = null
3483
3484 // encode utf8
3485 if (codePoint < 0x80) {
3486 if ((units -= 1) < 0) break
3487 bytes.push(codePoint)
3488 } else if (codePoint < 0x800) {
3489 if ((units -= 2) < 0) break
3490 bytes.push(
3491 codePoint >> 0x6 | 0xC0,
3492 codePoint & 0x3F | 0x80
3493 )
3494 } else if (codePoint < 0x10000) {
3495 if ((units -= 3) < 0) break
3496 bytes.push(
3497 codePoint >> 0xC | 0xE0,
3498 codePoint >> 0x6 & 0x3F | 0x80,
3499 codePoint & 0x3F | 0x80
3500 )
3501 } else if (codePoint < 0x110000) {
3502 if ((units -= 4) < 0) break
3503 bytes.push(
3504 codePoint >> 0x12 | 0xF0,
3505 codePoint >> 0xC & 0x3F | 0x80,
3506 codePoint >> 0x6 & 0x3F | 0x80,
3507 codePoint & 0x3F | 0x80
3508 )
3509 } else {
3510 throw new Error('Invalid code point')
3511 }
3512 }
3513
3514 return bytes
3515}
3516
3517function asciiToBytes (str) {
3518 var byteArray = []
3519 for (var i = 0; i < str.length; ++i) {
3520 // Node's code seems to be doing this and not & 0x7F..
3521 byteArray.push(str.charCodeAt(i) & 0xFF)
3522 }
3523 return byteArray
3524}
3525
3526function utf16leToBytes (str, units) {
3527 var c, hi, lo
3528 var byteArray = []
3529 for (var i = 0; i < str.length; ++i) {
3530 if ((units -= 2) < 0) break
3531
3532 c = str.charCodeAt(i)
3533 hi = c >> 8
3534 lo = c % 256
3535 byteArray.push(lo)
3536 byteArray.push(hi)
3537 }
3538
3539 return byteArray
3540}
3541
3542function base64ToBytes (str) {
3543 return base64.toByteArray(base64clean(str))
3544}
3545
3546function blitBuffer (src, dst, offset, length) {
3547 for (var i = 0; i < length; ++i) {
3548 if ((i + offset >= dst.length) || (i >= src.length)) break
3549 dst[i + offset] = src[i]
3550 }
3551 return i
3552}
3553
3554// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
3555// the `instanceof` check but they should be treated as of that type.
3556// See: https://github.com/feross/buffer/issues/166
3557function isInstance (obj, type) {
3558 return obj instanceof type ||
3559 (obj != null && obj.constructor != null && obj.constructor.name != null &&
3560 obj.constructor.name === type.name)
3561}
3562function numberIsNaN (obj) {
3563 // For IE11 support
3564 return obj !== obj // eslint-disable-line no-self-compare
3565}
3566
3567}).call(this,_dereq_(12).Buffer)
3568},{"12":12,"29":29,"9":9}],13:[function(_dereq_,module,exports){
3569(function (Buffer){
3570// Copyright Joyent, Inc. and other Node contributors.
3571//
3572// Permission is hereby granted, free of charge, to any person obtaining a
3573// copy of this software and associated documentation files (the
3574// "Software"), to deal in the Software without restriction, including
3575// without limitation the rights to use, copy, modify, merge, publish,
3576// distribute, sublicense, and/or sell copies of the Software, and to permit
3577// persons to whom the Software is furnished to do so, subject to the
3578// following conditions:
3579//
3580// The above copyright notice and this permission notice shall be included
3581// in all copies or substantial portions of the Software.
3582//
3583// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3584// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3585// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3586// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3587// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3588// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3589// USE OR OTHER DEALINGS IN THE SOFTWARE.
3590
3591// NOTE: These type checking functions intentionally don't use `instanceof`
3592// because it is fragile and can be easily faked with `Object.create()`.
3593
3594function isArray(arg) {
3595 if (Array.isArray) {
3596 return Array.isArray(arg);
3597 }
3598 return objectToString(arg) === '[object Array]';
3599}
3600exports.isArray = isArray;
3601
3602function isBoolean(arg) {
3603 return typeof arg === 'boolean';
3604}
3605exports.isBoolean = isBoolean;
3606
3607function isNull(arg) {
3608 return arg === null;
3609}
3610exports.isNull = isNull;
3611
3612function isNullOrUndefined(arg) {
3613 return arg == null;
3614}
3615exports.isNullOrUndefined = isNullOrUndefined;
3616
3617function isNumber(arg) {
3618 return typeof arg === 'number';
3619}
3620exports.isNumber = isNumber;
3621
3622function isString(arg) {
3623 return typeof arg === 'string';
3624}
3625exports.isString = isString;
3626
3627function isSymbol(arg) {
3628 return typeof arg === 'symbol';
3629}
3630exports.isSymbol = isSymbol;
3631
3632function isUndefined(arg) {
3633 return arg === void 0;
3634}
3635exports.isUndefined = isUndefined;
3636
3637function isRegExp(re) {
3638 return objectToString(re) === '[object RegExp]';
3639}
3640exports.isRegExp = isRegExp;
3641
3642function isObject(arg) {
3643 return typeof arg === 'object' && arg !== null;
3644}
3645exports.isObject = isObject;
3646
3647function isDate(d) {
3648 return objectToString(d) === '[object Date]';
3649}
3650exports.isDate = isDate;
3651
3652function isError(e) {
3653 return (objectToString(e) === '[object Error]' || e instanceof Error);
3654}
3655exports.isError = isError;
3656
3657function isFunction(arg) {
3658 return typeof arg === 'function';
3659}
3660exports.isFunction = isFunction;
3661
3662function isPrimitive(arg) {
3663 return arg === null ||
3664 typeof arg === 'boolean' ||
3665 typeof arg === 'number' ||
3666 typeof arg === 'string' ||
3667 typeof arg === 'symbol' || // ES6 symbol
3668 typeof arg === 'undefined';
3669}
3670exports.isPrimitive = isPrimitive;
3671
3672exports.isBuffer = Buffer.isBuffer;
3673
3674function objectToString(o) {
3675 return Object.prototype.toString.call(o);
3676}
3677
3678}).call(this,{"isBuffer":_dereq_(32)})
3679},{"32":32}],14:[function(_dereq_,module,exports){
3680var Buffer = _dereq_(12).Buffer
3681
3682var CHARS = '.PYFGCRLAOEUIDHTNSQJKXBMWVZ_pyfgcrlaoeuidhtnsqjkxbmwvz1234567890'
3683 .split('').sort().join('')
3684
3685module.exports = function (chars, exports) {
3686 chars = chars || CHARS
3687 exports = exports || {}
3688 if(chars.length !== 64) throw new Error('a base 64 encoding requires 64 chars')
3689
3690 var codeToIndex = new Buffer(128)
3691 codeToIndex.fill()
3692
3693 for(var i = 0; i < 64; i++) {
3694 var code = chars.charCodeAt(i)
3695 codeToIndex[code] = i
3696 }
3697
3698 exports.encode = function (data) {
3699 var s = '', l = data.length, hang = 0
3700 for(var i = 0; i < l; i++) {
3701 var v = data[i]
3702
3703 switch (i % 3) {
3704 case 0:
3705 s += chars[v >> 2]
3706 hang = (v & 3) << 4
3707 break;
3708 case 1:
3709 s += chars[hang | v >> 4]
3710 hang = (v & 0xf) << 2
3711 break;
3712 case 2:
3713 s += chars[hang | v >> 6]
3714 s += chars[v & 0x3f]
3715 hang = 0
3716 break;
3717 }
3718
3719 }
3720 if(l%3) s += chars[hang]
3721 return s
3722 }
3723 exports.decode = function (str) {
3724 var l = str.length, j = 0
3725 var b = new Buffer(~~((l/4)*3)), hang = 0
3726
3727 for(var i = 0; i < l; i++) {
3728 var v = codeToIndex[str.charCodeAt(i)]
3729
3730 switch (i % 4) {
3731 case 0:
3732 hang = v << 2;
3733 break;
3734 case 1:
3735 b[j++] = hang | v >> 4
3736 hang = (v << 4) & 0xff
3737 break;
3738 case 2:
3739 b[j++] = hang | v >> 2
3740 hang = (v << 6) & 0xff
3741 break;
3742 case 3:
3743 b[j++] = hang | v
3744 break;
3745 }
3746
3747 }
3748 return b
3749 }
3750 return exports
3751}
3752
3753module.exports(CHARS, module.exports)
3754
3755
3756},{"12":12}],15:[function(_dereq_,module,exports){
3757var AbstractIterator = _dereq_(20).AbstractIterator
3758var inherits = _dereq_(31)
3759
3760function DeferredIterator (options) {
3761 AbstractIterator.call(this, options)
3762
3763 this._options = options
3764 this._iterator = null
3765 this._operations = []
3766}
3767
3768inherits(DeferredIterator, AbstractIterator)
3769
3770DeferredIterator.prototype.setDb = function (db) {
3771 var it = this._iterator = db.iterator(this._options)
3772 this._operations.forEach(function (op) {
3773 it[op.method].apply(it, op.args)
3774 })
3775}
3776
3777DeferredIterator.prototype._operation = function (method, args) {
3778 if (this._iterator) return this._iterator[method].apply(this._iterator, args)
3779 this._operations.push({ method: method, args: args })
3780}
3781
3782'next end'.split(' ').forEach(function (m) {
3783 DeferredIterator.prototype['_' + m] = function () {
3784 this._operation(m, arguments)
3785 }
3786})
3787
3788module.exports = DeferredIterator
3789
3790},{"20":20,"31":31}],16:[function(_dereq_,module,exports){
3791var AbstractLevelDOWN = _dereq_(20).AbstractLevelDOWN
3792var inherits = _dereq_(31)
3793var DeferredIterator = _dereq_(15)
3794var deferrables = 'put get del batch'.split(' ')
3795
3796function DeferredLevelDOWN (db) {
3797 AbstractLevelDOWN.call(this, '')
3798 this._db = db
3799 this._operations = []
3800 this._iterators = []
3801 closed(this)
3802}
3803
3804inherits(DeferredLevelDOWN, AbstractLevelDOWN)
3805
3806DeferredLevelDOWN.prototype._open = function (options, callback) {
3807 var self = this
3808
3809 this._db.open(options, function (err) {
3810 if (err) return callback(err)
3811
3812 self._operations.forEach(function (op) {
3813 self._db[op.method].apply(self._db, op.args)
3814 })
3815 self._operations = []
3816 self._iterators.forEach(function (it) {
3817 it.setDb(self._db)
3818 })
3819 self._iterators = []
3820 open(self)
3821 callback()
3822 })
3823}
3824
3825DeferredLevelDOWN.prototype._close = function (callback) {
3826 var self = this
3827
3828 this._db.close(function (err) {
3829 if (err) return callback(err)
3830 closed(self)
3831 callback()
3832 })
3833}
3834
3835function open (self) {
3836 deferrables.concat('iterator').forEach(function (m) {
3837 self['_' + m] = function () {
3838 return this._db[m].apply(this._db, arguments)
3839 }
3840 })
3841 if (self._db.approximateSize) {
3842 self.approximateSize = function () {
3843 return this._db.approximateSize.apply(this._db, arguments)
3844 }
3845 }
3846}
3847
3848function closed (self) {
3849 deferrables.forEach(function (m) {
3850 self['_' + m] = function () {
3851 this._operations.push({ method: m, args: arguments })
3852 }
3853 })
3854 if (typeof self._db.approximateSize === 'function') {
3855 self.approximateSize = function () {
3856 this._operations.push({
3857 method: 'approximateSize',
3858 args: arguments
3859 })
3860 }
3861 }
3862 self._iterator = function (options) {
3863 var it = new DeferredIterator(options)
3864 this._iterators.push(it)
3865 return it
3866 }
3867}
3868
3869DeferredLevelDOWN.prototype._serializeKey = function (key) {
3870 return key
3871}
3872
3873DeferredLevelDOWN.prototype._serializeValue = function (value) {
3874 return value
3875}
3876
3877module.exports = DeferredLevelDOWN
3878module.exports.DeferredIterator = DeferredIterator
3879
3880},{"15":15,"20":20,"31":31}],17:[function(_dereq_,module,exports){
3881function AbstractChainedBatch (db) {
3882 if (typeof db !== 'object' || db === null) {
3883 throw new TypeError('First argument must be an abstract-leveldown compliant store')
3884 }
3885
3886 this.db = db
3887 this._operations = []
3888 this._written = false
3889}
3890
3891AbstractChainedBatch.prototype._checkWritten = function () {
3892 if (this._written) {
3893 throw new Error('write() already called on this batch')
3894 }
3895}
3896
3897AbstractChainedBatch.prototype.put = function (key, value) {
3898 this._checkWritten()
3899
3900 var err = this.db._checkKey(key) || this.db._checkValue(value)
3901 if (err) throw err
3902
3903 key = this.db._serializeKey(key)
3904 value = this.db._serializeValue(value)
3905
3906 this._put(key, value)
3907
3908 return this
3909}
3910
3911AbstractChainedBatch.prototype._put = function (key, value) {
3912 this._operations.push({ type: 'put', key: key, value: value })
3913}
3914
3915AbstractChainedBatch.prototype.del = function (key) {
3916 this._checkWritten()
3917
3918 var err = this.db._checkKey(key)
3919 if (err) throw err
3920
3921 key = this.db._serializeKey(key)
3922 this._del(key)
3923
3924 return this
3925}
3926
3927AbstractChainedBatch.prototype._del = function (key) {
3928 this._operations.push({ type: 'del', key: key })
3929}
3930
3931AbstractChainedBatch.prototype.clear = function () {
3932 this._checkWritten()
3933 this._clear()
3934
3935 return this
3936}
3937
3938AbstractChainedBatch.prototype._clear = function () {
3939 this._operations = []
3940}
3941
3942AbstractChainedBatch.prototype.write = function (options, callback) {
3943 this._checkWritten()
3944
3945 if (typeof options === 'function') { callback = options }
3946 if (typeof callback !== 'function') {
3947 throw new Error('write() requires a callback argument')
3948 }
3949 if (typeof options !== 'object' || options === null) {
3950 options = {}
3951 }
3952
3953 this._written = true
3954 this._write(options, callback)
3955}
3956
3957AbstractChainedBatch.prototype._write = function (options, callback) {
3958 this.db._batch(this._operations, options, callback)
3959}
3960
3961module.exports = AbstractChainedBatch
3962
3963},{}],18:[function(_dereq_,module,exports){
3964(function (process){
3965function AbstractIterator (db) {
3966 if (typeof db !== 'object' || db === null) {
3967 throw new TypeError('First argument must be an abstract-leveldown compliant store')
3968 }
3969
3970 this.db = db
3971 this._ended = false
3972 this._nexting = false
3973}
3974
3975AbstractIterator.prototype.next = function (callback) {
3976 var self = this
3977
3978 if (typeof callback !== 'function') {
3979 throw new Error('next() requires a callback argument')
3980 }
3981
3982 if (self._ended) {
3983 process.nextTick(callback, new Error('cannot call next() after end()'))
3984 return self
3985 }
3986
3987 if (self._nexting) {
3988 process.nextTick(callback, new Error('cannot call next() before previous next() has completed'))
3989 return self
3990 }
3991
3992 self._nexting = true
3993 self._next(function () {
3994 self._nexting = false
3995 callback.apply(null, arguments)
3996 })
3997
3998 return self
3999}
4000
4001AbstractIterator.prototype._next = function (callback) {
4002 process.nextTick(callback)
4003}
4004
4005AbstractIterator.prototype.seek = function (target) {
4006 if (this._ended) {
4007 throw new Error('cannot call seek() after end()')
4008 }
4009 if (this._nexting) {
4010 throw new Error('cannot call seek() before next() has completed')
4011 }
4012
4013 target = this.db._serializeKey(target)
4014 this._seek(target)
4015}
4016
4017AbstractIterator.prototype._seek = function (target) {}
4018
4019AbstractIterator.prototype.end = function (callback) {
4020 if (typeof callback !== 'function') {
4021 throw new Error('end() requires a callback argument')
4022 }
4023
4024 if (this._ended) {
4025 return process.nextTick(callback, new Error('end() already called on iterator'))
4026 }
4027
4028 this._ended = true
4029 this._end(callback)
4030}
4031
4032AbstractIterator.prototype._end = function (callback) {
4033 process.nextTick(callback)
4034}
4035
4036module.exports = AbstractIterator
4037
4038}).call(this,_dereq_(69))
4039},{"69":69}],19:[function(_dereq_,module,exports){
4040(function (Buffer,process){
4041var xtend = _dereq_(21)
4042var AbstractIterator = _dereq_(18)
4043var AbstractChainedBatch = _dereq_(17)
4044var hasOwnProperty = Object.prototype.hasOwnProperty
4045var rangeOptions = 'start end gt gte lt lte'.split(' ')
4046
4047function AbstractLevelDOWN () {
4048 this.status = 'new'
4049}
4050
4051AbstractLevelDOWN.prototype.open = function (options, callback) {
4052 var self = this
4053 var oldStatus = this.status
4054
4055 if (typeof options === 'function') callback = options
4056
4057 if (typeof callback !== 'function') {
4058 throw new Error('open() requires a callback argument')
4059 }
4060
4061 if (typeof options !== 'object' || options === null) options = {}
4062
4063 options.createIfMissing = options.createIfMissing !== false
4064 options.errorIfExists = !!options.errorIfExists
4065
4066 this.status = 'opening'
4067 this._open(options, function (err) {
4068 if (err) {
4069 self.status = oldStatus
4070 return callback(err)
4071 }
4072 self.status = 'open'
4073 callback()
4074 })
4075}
4076
4077AbstractLevelDOWN.prototype._open = function (options, callback) {
4078 process.nextTick(callback)
4079}
4080
4081AbstractLevelDOWN.prototype.close = function (callback) {
4082 var self = this
4083 var oldStatus = this.status
4084
4085 if (typeof callback !== 'function') {
4086 throw new Error('close() requires a callback argument')
4087 }
4088
4089 this.status = 'closing'
4090 this._close(function (err) {
4091 if (err) {
4092 self.status = oldStatus
4093 return callback(err)
4094 }
4095 self.status = 'closed'
4096 callback()
4097 })
4098}
4099
4100AbstractLevelDOWN.prototype._close = function (callback) {
4101 process.nextTick(callback)
4102}
4103
4104AbstractLevelDOWN.prototype.get = function (key, options, callback) {
4105 if (typeof options === 'function') callback = options
4106
4107 if (typeof callback !== 'function') {
4108 throw new Error('get() requires a callback argument')
4109 }
4110
4111 var err = this._checkKey(key)
4112 if (err) return process.nextTick(callback, err)
4113
4114 key = this._serializeKey(key)
4115
4116 if (typeof options !== 'object' || options === null) options = {}
4117
4118 options.asBuffer = options.asBuffer !== false
4119
4120 this._get(key, options, callback)
4121}
4122
4123AbstractLevelDOWN.prototype._get = function (key, options, callback) {
4124 process.nextTick(function () { callback(new Error('NotFound')) })
4125}
4126
4127AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
4128 if (typeof options === 'function') callback = options
4129
4130 if (typeof callback !== 'function') {
4131 throw new Error('put() requires a callback argument')
4132 }
4133
4134 var err = this._checkKey(key) || this._checkValue(value)
4135 if (err) return process.nextTick(callback, err)
4136
4137 key = this._serializeKey(key)
4138 value = this._serializeValue(value)
4139
4140 if (typeof options !== 'object' || options === null) options = {}
4141
4142 this._put(key, value, options, callback)
4143}
4144
4145AbstractLevelDOWN.prototype._put = function (key, value, options, callback) {
4146 process.nextTick(callback)
4147}
4148
4149AbstractLevelDOWN.prototype.del = function (key, options, callback) {
4150 if (typeof options === 'function') callback = options
4151
4152 if (typeof callback !== 'function') {
4153 throw new Error('del() requires a callback argument')
4154 }
4155
4156 var err = this._checkKey(key)
4157 if (err) return process.nextTick(callback, err)
4158
4159 key = this._serializeKey(key)
4160
4161 if (typeof options !== 'object' || options === null) options = {}
4162
4163 this._del(key, options, callback)
4164}
4165
4166AbstractLevelDOWN.prototype._del = function (key, options, callback) {
4167 process.nextTick(callback)
4168}
4169
4170AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
4171 if (!arguments.length) return this._chainedBatch()
4172
4173 if (typeof options === 'function') callback = options
4174
4175 if (typeof array === 'function') callback = array
4176
4177 if (typeof callback !== 'function') {
4178 throw new Error('batch(array) requires a callback argument')
4179 }
4180
4181 if (!Array.isArray(array)) {
4182 return process.nextTick(callback, new Error('batch(array) requires an array argument'))
4183 }
4184
4185 if (array.length === 0) {
4186 return process.nextTick(callback)
4187 }
4188
4189 if (typeof options !== 'object' || options === null) options = {}
4190
4191 var serialized = new Array(array.length)
4192
4193 for (var i = 0; i < array.length; i++) {
4194 if (typeof array[i] !== 'object' || array[i] === null) {
4195 return process.nextTick(callback, new Error('batch(array) element must be an object and not `null`'))
4196 }
4197
4198 var e = xtend(array[i])
4199
4200 if (e.type !== 'put' && e.type !== 'del') {
4201 return process.nextTick(callback, new Error("`type` must be 'put' or 'del'"))
4202 }
4203
4204 var err = this._checkKey(e.key)
4205 if (err) return process.nextTick(callback, err)
4206
4207 e.key = this._serializeKey(e.key)
4208
4209 if (e.type === 'put') {
4210 var valueErr = this._checkValue(e.value)
4211 if (valueErr) return process.nextTick(callback, valueErr)
4212
4213 e.value = this._serializeValue(e.value)
4214 }
4215
4216 serialized[i] = e
4217 }
4218
4219 this._batch(serialized, options, callback)
4220}
4221
4222AbstractLevelDOWN.prototype._batch = function (array, options, callback) {
4223 process.nextTick(callback)
4224}
4225
4226AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
4227 options = cleanRangeOptions(this, options)
4228
4229 options.reverse = !!options.reverse
4230 options.keys = options.keys !== false
4231 options.values = options.values !== false
4232 options.limit = 'limit' in options ? options.limit : -1
4233 options.keyAsBuffer = options.keyAsBuffer !== false
4234 options.valueAsBuffer = options.valueAsBuffer !== false
4235
4236 return options
4237}
4238
4239function cleanRangeOptions (db, options) {
4240 var result = {}
4241
4242 for (var k in options) {
4243 if (!hasOwnProperty.call(options, k)) continue
4244
4245 var opt = options[k]
4246
4247 if (isRangeOption(k)) {
4248 // Note that we don't reject nullish and empty options here. While
4249 // those types are invalid as keys, they are valid as range options.
4250 opt = db._serializeKey(opt)
4251 }
4252
4253 result[k] = opt
4254 }
4255
4256 return result
4257}
4258
4259function isRangeOption (k) {
4260 return rangeOptions.indexOf(k) !== -1
4261}
4262
4263AbstractLevelDOWN.prototype.iterator = function (options) {
4264 if (typeof options !== 'object' || options === null) options = {}
4265 options = this._setupIteratorOptions(options)
4266 return this._iterator(options)
4267}
4268
4269AbstractLevelDOWN.prototype._iterator = function (options) {
4270 return new AbstractIterator(this)
4271}
4272
4273AbstractLevelDOWN.prototype._chainedBatch = function () {
4274 return new AbstractChainedBatch(this)
4275}
4276
4277AbstractLevelDOWN.prototype._serializeKey = function (key) {
4278 return key
4279}
4280
4281AbstractLevelDOWN.prototype._serializeValue = function (value) {
4282 return value
4283}
4284
4285AbstractLevelDOWN.prototype._checkKey = function (key) {
4286 if (key === null || key === undefined) {
4287 return new Error('key cannot be `null` or `undefined`')
4288 } else if (Buffer.isBuffer(key) && key.length === 0) {
4289 return new Error('key cannot be an empty Buffer')
4290 } else if (key === '') {
4291 return new Error('key cannot be an empty String')
4292 } else if (Array.isArray(key) && key.length === 0) {
4293 return new Error('key cannot be an empty Array')
4294 }
4295}
4296
4297AbstractLevelDOWN.prototype._checkValue = function (value) {
4298 if (value === null || value === undefined) {
4299 return new Error('value cannot be `null` or `undefined`')
4300 }
4301}
4302
4303module.exports = AbstractLevelDOWN
4304
4305}).call(this,{"isBuffer":_dereq_(32)},_dereq_(69))
4306},{"17":17,"18":18,"21":21,"32":32,"69":69}],20:[function(_dereq_,module,exports){
4307exports.AbstractLevelDOWN = _dereq_(19)
4308exports.AbstractIterator = _dereq_(18)
4309exports.AbstractChainedBatch = _dereq_(17)
4310
4311},{"17":17,"18":18,"19":19}],21:[function(_dereq_,module,exports){
4312module.exports = extend
4313
4314var hasOwnProperty = Object.prototype.hasOwnProperty;
4315
4316function extend() {
4317 var target = {}
4318
4319 for (var i = 0; i < arguments.length; i++) {
4320 var source = arguments[i]
4321
4322 for (var key in source) {
4323 if (hasOwnProperty.call(source, key)) {
4324 target[key] = source[key]
4325 }
4326 }
4327 }
4328
4329 return target
4330}
4331
4332},{}],22:[function(_dereq_,module,exports){
4333/**
4334 * Copyright (c) 2013 Petka Antonov
4335 *
4336 * Permission is hereby granted, free of charge, to any person obtaining a copy
4337 * of this software and associated documentation files (the "Software"), to deal
4338 * in the Software without restriction, including without limitation the rights
4339 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
4340 * copies of the Software, and to permit persons to whom the Software is
4341 * furnished to do so, subject to the following conditions:</p>
4342 *
4343 * The above copyright notice and this permission notice shall be included in
4344 * all copies or substantial portions of the Software.
4345 *
4346 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
4347 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
4348 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
4349 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
4350 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
4351 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
4352 * THE SOFTWARE.
4353 */
4354"use strict";
4355function Deque(capacity) {
4356 this._capacity = getCapacity(capacity);
4357 this._length = 0;
4358 this._front = 0;
4359 if (isArray(capacity)) {
4360 var len = capacity.length;
4361 for (var i = 0; i < len; ++i) {
4362 this[i] = capacity[i];
4363 }
4364 this._length = len;
4365 }
4366}
4367
4368Deque.prototype.toArray = function Deque$toArray() {
4369 var len = this._length;
4370 var ret = new Array(len);
4371 var front = this._front;
4372 var capacity = this._capacity;
4373 for (var j = 0; j < len; ++j) {
4374 ret[j] = this[(front + j) & (capacity - 1)];
4375 }
4376 return ret;
4377};
4378
4379Deque.prototype.push = function Deque$push(item) {
4380 var argsLength = arguments.length;
4381 var length = this._length;
4382 if (argsLength > 1) {
4383 var capacity = this._capacity;
4384 if (length + argsLength > capacity) {
4385 for (var i = 0; i < argsLength; ++i) {
4386 this._checkCapacity(length + 1);
4387 var j = (this._front + length) & (this._capacity - 1);
4388 this[j] = arguments[i];
4389 length++;
4390 this._length = length;
4391 }
4392 return length;
4393 }
4394 else {
4395 var j = this._front;
4396 for (var i = 0; i < argsLength; ++i) {
4397 this[(j + length) & (capacity - 1)] = arguments[i];
4398 j++;
4399 }
4400 this._length = length + argsLength;
4401 return length + argsLength;
4402 }
4403
4404 }
4405
4406 if (argsLength === 0) return length;
4407
4408 this._checkCapacity(length + 1);
4409 var i = (this._front + length) & (this._capacity - 1);
4410 this[i] = item;
4411 this._length = length + 1;
4412 return length + 1;
4413};
4414
4415Deque.prototype.pop = function Deque$pop() {
4416 var length = this._length;
4417 if (length === 0) {
4418 return void 0;
4419 }
4420 var i = (this._front + length - 1) & (this._capacity - 1);
4421 var ret = this[i];
4422 this[i] = void 0;
4423 this._length = length - 1;
4424 return ret;
4425};
4426
4427Deque.prototype.shift = function Deque$shift() {
4428 var length = this._length;
4429 if (length === 0) {
4430 return void 0;
4431 }
4432 var front = this._front;
4433 var ret = this[front];
4434 this[front] = void 0;
4435 this._front = (front + 1) & (this._capacity - 1);
4436 this._length = length - 1;
4437 return ret;
4438};
4439
4440Deque.prototype.unshift = function Deque$unshift(item) {
4441 var length = this._length;
4442 var argsLength = arguments.length;
4443
4444
4445 if (argsLength > 1) {
4446 var capacity = this._capacity;
4447 if (length + argsLength > capacity) {
4448 for (var i = argsLength - 1; i >= 0; i--) {
4449 this._checkCapacity(length + 1);
4450 var capacity = this._capacity;
4451 var j = (((( this._front - 1 ) &
4452 ( capacity - 1) ) ^ capacity ) - capacity );
4453 this[j] = arguments[i];
4454 length++;
4455 this._length = length;
4456 this._front = j;
4457 }
4458 return length;
4459 }
4460 else {
4461 var front = this._front;
4462 for (var i = argsLength - 1; i >= 0; i--) {
4463 var j = (((( front - 1 ) &
4464 ( capacity - 1) ) ^ capacity ) - capacity );
4465 this[j] = arguments[i];
4466 front = j;
4467 }
4468 this._front = front;
4469 this._length = length + argsLength;
4470 return length + argsLength;
4471 }
4472 }
4473
4474 if (argsLength === 0) return length;
4475
4476 this._checkCapacity(length + 1);
4477 var capacity = this._capacity;
4478 var i = (((( this._front - 1 ) &
4479 ( capacity - 1) ) ^ capacity ) - capacity );
4480 this[i] = item;
4481 this._length = length + 1;
4482 this._front = i;
4483 return length + 1;
4484};
4485
4486Deque.prototype.peekBack = function Deque$peekBack() {
4487 var length = this._length;
4488 if (length === 0) {
4489 return void 0;
4490 }
4491 var index = (this._front + length - 1) & (this._capacity - 1);
4492 return this[index];
4493};
4494
4495Deque.prototype.peekFront = function Deque$peekFront() {
4496 if (this._length === 0) {
4497 return void 0;
4498 }
4499 return this[this._front];
4500};
4501
4502Deque.prototype.get = function Deque$get(index) {
4503 var i = index;
4504 if ((i !== (i | 0))) {
4505 return void 0;
4506 }
4507 var len = this._length;
4508 if (i < 0) {
4509 i = i + len;
4510 }
4511 if (i < 0 || i >= len) {
4512 return void 0;
4513 }
4514 return this[(this._front + i) & (this._capacity - 1)];
4515};
4516
4517Deque.prototype.isEmpty = function Deque$isEmpty() {
4518 return this._length === 0;
4519};
4520
4521Deque.prototype.clear = function Deque$clear() {
4522 var len = this._length;
4523 var front = this._front;
4524 var capacity = this._capacity;
4525 for (var j = 0; j < len; ++j) {
4526 this[(front + j) & (capacity - 1)] = void 0;
4527 }
4528 this._length = 0;
4529 this._front = 0;
4530};
4531
4532Deque.prototype.toString = function Deque$toString() {
4533 return this.toArray().toString();
4534};
4535
4536Deque.prototype.valueOf = Deque.prototype.toString;
4537Deque.prototype.removeFront = Deque.prototype.shift;
4538Deque.prototype.removeBack = Deque.prototype.pop;
4539Deque.prototype.insertFront = Deque.prototype.unshift;
4540Deque.prototype.insertBack = Deque.prototype.push;
4541Deque.prototype.enqueue = Deque.prototype.push;
4542Deque.prototype.dequeue = Deque.prototype.shift;
4543Deque.prototype.toJSON = Deque.prototype.toArray;
4544
4545Object.defineProperty(Deque.prototype, "length", {
4546 get: function() {
4547 return this._length;
4548 },
4549 set: function() {
4550 throw new RangeError("");
4551 }
4552});
4553
4554Deque.prototype._checkCapacity = function Deque$_checkCapacity(size) {
4555 if (this._capacity < size) {
4556 this._resizeTo(getCapacity(this._capacity * 1.5 + 16));
4557 }
4558};
4559
4560Deque.prototype._resizeTo = function Deque$_resizeTo(capacity) {
4561 var oldCapacity = this._capacity;
4562 this._capacity = capacity;
4563 var front = this._front;
4564 var length = this._length;
4565 if (front + length > oldCapacity) {
4566 var moveItemsCount = (front + length) & (oldCapacity - 1);
4567 arrayMove(this, 0, this, oldCapacity, moveItemsCount);
4568 }
4569};
4570
4571
4572var isArray = Array.isArray;
4573
4574function arrayMove(src, srcIndex, dst, dstIndex, len) {
4575 for (var j = 0; j < len; ++j) {
4576 dst[j + dstIndex] = src[j + srcIndex];
4577 src[j + srcIndex] = void 0;
4578 }
4579}
4580
4581function pow2AtLeast(n) {
4582 n = n >>> 0;
4583 n = n - 1;
4584 n = n | (n >> 1);
4585 n = n | (n >> 2);
4586 n = n | (n >> 4);
4587 n = n | (n >> 8);
4588 n = n | (n >> 16);
4589 return n + 1;
4590}
4591
4592function getCapacity(capacity) {
4593 if (typeof capacity !== "number") {
4594 if (isArray(capacity)) {
4595 capacity = capacity.length;
4596 }
4597 else {
4598 return 16;
4599 }
4600 }
4601 return pow2AtLeast(
4602 Math.min(
4603 Math.max(16, capacity), 1073741824)
4604 );
4605}
4606
4607module.exports = Deque;
4608
4609},{}],23:[function(_dereq_,module,exports){
4610var prr = _dereq_(70)
4611
4612function init (type, message, cause) {
4613 if (!!message && typeof message != 'string') {
4614 message = message.message || message.name
4615 }
4616 prr(this, {
4617 type : type
4618 , name : type
4619 // can be passed just a 'cause'
4620 , cause : typeof message != 'string' ? message : cause
4621 , message : message
4622 }, 'ewr')
4623}
4624
4625// generic prototype, not intended to be actually used - helpful for `instanceof`
4626function CustomError (message, cause) {
4627 Error.call(this)
4628 if (Error.captureStackTrace)
4629 Error.captureStackTrace(this, this.constructor)
4630 init.call(this, 'CustomError', message, cause)
4631}
4632
4633CustomError.prototype = new Error()
4634
4635function createError (errno, type, proto) {
4636 var err = function (message, cause) {
4637 init.call(this, type, message, cause)
4638 //TODO: the specificity here is stupid, errno should be available everywhere
4639 if (type == 'FilesystemError') {
4640 this.code = this.cause.code
4641 this.path = this.cause.path
4642 this.errno = this.cause.errno
4643 this.message =
4644 (errno.errno[this.cause.errno]
4645 ? errno.errno[this.cause.errno].description
4646 : this.cause.message)
4647 + (this.cause.path ? ' [' + this.cause.path + ']' : '')
4648 }
4649 Error.call(this)
4650 if (Error.captureStackTrace)
4651 Error.captureStackTrace(this, err)
4652 }
4653 err.prototype = !!proto ? new proto() : new CustomError()
4654 return err
4655}
4656
4657module.exports = function (errno) {
4658 var ce = function (type, proto) {
4659 return createError(errno, type, proto)
4660 }
4661 return {
4662 CustomError : CustomError
4663 , FilesystemError : ce('FilesystemError')
4664 , createError : ce
4665 }
4666}
4667
4668},{"70":70}],24:[function(_dereq_,module,exports){
4669var all = module.exports.all = [
4670 {
4671 errno: -2,
4672 code: 'ENOENT',
4673 description: 'no such file or directory'
4674 },
4675 {
4676 errno: -1,
4677 code: 'UNKNOWN',
4678 description: 'unknown error'
4679 },
4680 {
4681 errno: 0,
4682 code: 'OK',
4683 description: 'success'
4684 },
4685 {
4686 errno: 1,
4687 code: 'EOF',
4688 description: 'end of file'
4689 },
4690 {
4691 errno: 2,
4692 code: 'EADDRINFO',
4693 description: 'getaddrinfo error'
4694 },
4695 {
4696 errno: 3,
4697 code: 'EACCES',
4698 description: 'permission denied'
4699 },
4700 {
4701 errno: 4,
4702 code: 'EAGAIN',
4703 description: 'resource temporarily unavailable'
4704 },
4705 {
4706 errno: 5,
4707 code: 'EADDRINUSE',
4708 description: 'address already in use'
4709 },
4710 {
4711 errno: 6,
4712 code: 'EADDRNOTAVAIL',
4713 description: 'address not available'
4714 },
4715 {
4716 errno: 7,
4717 code: 'EAFNOSUPPORT',
4718 description: 'address family not supported'
4719 },
4720 {
4721 errno: 8,
4722 code: 'EALREADY',
4723 description: 'connection already in progress'
4724 },
4725 {
4726 errno: 9,
4727 code: 'EBADF',
4728 description: 'bad file descriptor'
4729 },
4730 {
4731 errno: 10,
4732 code: 'EBUSY',
4733 description: 'resource busy or locked'
4734 },
4735 {
4736 errno: 11,
4737 code: 'ECONNABORTED',
4738 description: 'software caused connection abort'
4739 },
4740 {
4741 errno: 12,
4742 code: 'ECONNREFUSED',
4743 description: 'connection refused'
4744 },
4745 {
4746 errno: 13,
4747 code: 'ECONNRESET',
4748 description: 'connection reset by peer'
4749 },
4750 {
4751 errno: 14,
4752 code: 'EDESTADDRREQ',
4753 description: 'destination address required'
4754 },
4755 {
4756 errno: 15,
4757 code: 'EFAULT',
4758 description: 'bad address in system call argument'
4759 },
4760 {
4761 errno: 16,
4762 code: 'EHOSTUNREACH',
4763 description: 'host is unreachable'
4764 },
4765 {
4766 errno: 17,
4767 code: 'EINTR',
4768 description: 'interrupted system call'
4769 },
4770 {
4771 errno: 18,
4772 code: 'EINVAL',
4773 description: 'invalid argument'
4774 },
4775 {
4776 errno: 19,
4777 code: 'EISCONN',
4778 description: 'socket is already connected'
4779 },
4780 {
4781 errno: 20,
4782 code: 'EMFILE',
4783 description: 'too many open files'
4784 },
4785 {
4786 errno: 21,
4787 code: 'EMSGSIZE',
4788 description: 'message too long'
4789 },
4790 {
4791 errno: 22,
4792 code: 'ENETDOWN',
4793 description: 'network is down'
4794 },
4795 {
4796 errno: 23,
4797 code: 'ENETUNREACH',
4798 description: 'network is unreachable'
4799 },
4800 {
4801 errno: 24,
4802 code: 'ENFILE',
4803 description: 'file table overflow'
4804 },
4805 {
4806 errno: 25,
4807 code: 'ENOBUFS',
4808 description: 'no buffer space available'
4809 },
4810 {
4811 errno: 26,
4812 code: 'ENOMEM',
4813 description: 'not enough memory'
4814 },
4815 {
4816 errno: 27,
4817 code: 'ENOTDIR',
4818 description: 'not a directory'
4819 },
4820 {
4821 errno: 28,
4822 code: 'EISDIR',
4823 description: 'illegal operation on a directory'
4824 },
4825 {
4826 errno: 29,
4827 code: 'ENONET',
4828 description: 'machine is not on the network'
4829 },
4830 {
4831 errno: 31,
4832 code: 'ENOTCONN',
4833 description: 'socket is not connected'
4834 },
4835 {
4836 errno: 32,
4837 code: 'ENOTSOCK',
4838 description: 'socket operation on non-socket'
4839 },
4840 {
4841 errno: 33,
4842 code: 'ENOTSUP',
4843 description: 'operation not supported on socket'
4844 },
4845 {
4846 errno: 34,
4847 code: 'ENOENT',
4848 description: 'no such file or directory'
4849 },
4850 {
4851 errno: 35,
4852 code: 'ENOSYS',
4853 description: 'function not implemented'
4854 },
4855 {
4856 errno: 36,
4857 code: 'EPIPE',
4858 description: 'broken pipe'
4859 },
4860 {
4861 errno: 37,
4862 code: 'EPROTO',
4863 description: 'protocol error'
4864 },
4865 {
4866 errno: 38,
4867 code: 'EPROTONOSUPPORT',
4868 description: 'protocol not supported'
4869 },
4870 {
4871 errno: 39,
4872 code: 'EPROTOTYPE',
4873 description: 'protocol wrong type for socket'
4874 },
4875 {
4876 errno: 40,
4877 code: 'ETIMEDOUT',
4878 description: 'connection timed out'
4879 },
4880 {
4881 errno: 41,
4882 code: 'ECHARSET',
4883 description: 'invalid Unicode character'
4884 },
4885 {
4886 errno: 42,
4887 code: 'EAIFAMNOSUPPORT',
4888 description: 'address family for hostname not supported'
4889 },
4890 {
4891 errno: 44,
4892 code: 'EAISERVICE',
4893 description: 'servname not supported for ai_socktype'
4894 },
4895 {
4896 errno: 45,
4897 code: 'EAISOCKTYPE',
4898 description: 'ai_socktype not supported'
4899 },
4900 {
4901 errno: 46,
4902 code: 'ESHUTDOWN',
4903 description: 'cannot send after transport endpoint shutdown'
4904 },
4905 {
4906 errno: 47,
4907 code: 'EEXIST',
4908 description: 'file already exists'
4909 },
4910 {
4911 errno: 48,
4912 code: 'ESRCH',
4913 description: 'no such process'
4914 },
4915 {
4916 errno: 49,
4917 code: 'ENAMETOOLONG',
4918 description: 'name too long'
4919 },
4920 {
4921 errno: 50,
4922 code: 'EPERM',
4923 description: 'operation not permitted'
4924 },
4925 {
4926 errno: 51,
4927 code: 'ELOOP',
4928 description: 'too many symbolic links encountered'
4929 },
4930 {
4931 errno: 52,
4932 code: 'EXDEV',
4933 description: 'cross-device link not permitted'
4934 },
4935 {
4936 errno: 53,
4937 code: 'ENOTEMPTY',
4938 description: 'directory not empty'
4939 },
4940 {
4941 errno: 54,
4942 code: 'ENOSPC',
4943 description: 'no space left on device'
4944 },
4945 {
4946 errno: 55,
4947 code: 'EIO',
4948 description: 'i/o error'
4949 },
4950 {
4951 errno: 56,
4952 code: 'EROFS',
4953 description: 'read-only file system'
4954 },
4955 {
4956 errno: 57,
4957 code: 'ENODEV',
4958 description: 'no such device'
4959 },
4960 {
4961 errno: 58,
4962 code: 'ESPIPE',
4963 description: 'invalid seek'
4964 },
4965 {
4966 errno: 59,
4967 code: 'ECANCELED',
4968 description: 'operation canceled'
4969 }
4970]
4971
4972module.exports.errno = {}
4973module.exports.code = {}
4974
4975all.forEach(function (error) {
4976 module.exports.errno[error.errno] = error
4977 module.exports.code[error.code] = error
4978})
4979
4980module.exports.custom = _dereq_(23)(module.exports)
4981module.exports.create = module.exports.custom.createError
4982
4983},{"23":23}],25:[function(_dereq_,module,exports){
4984// Copyright Joyent, Inc. and other Node contributors.
4985//
4986// Permission is hereby granted, free of charge, to any person obtaining a
4987// copy of this software and associated documentation files (the
4988// "Software"), to deal in the Software without restriction, including
4989// without limitation the rights to use, copy, modify, merge, publish,
4990// distribute, sublicense, and/or sell copies of the Software, and to permit
4991// persons to whom the Software is furnished to do so, subject to the
4992// following conditions:
4993//
4994// The above copyright notice and this permission notice shall be included
4995// in all copies or substantial portions of the Software.
4996//
4997// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4998// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4999// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5000// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5001// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5002// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5003// USE OR OTHER DEALINGS IN THE SOFTWARE.
5004
5005var objectCreate = Object.create || objectCreatePolyfill
5006var objectKeys = Object.keys || objectKeysPolyfill
5007var bind = Function.prototype.bind || functionBindPolyfill
5008
5009function EventEmitter() {
5010 if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
5011 this._events = objectCreate(null);
5012 this._eventsCount = 0;
5013 }
5014
5015 this._maxListeners = this._maxListeners || undefined;
5016}
5017module.exports = EventEmitter;
5018
5019// Backwards-compat with node 0.10.x
5020EventEmitter.EventEmitter = EventEmitter;
5021
5022EventEmitter.prototype._events = undefined;
5023EventEmitter.prototype._maxListeners = undefined;
5024
5025// By default EventEmitters will print a warning if more than 10 listeners are
5026// added to it. This is a useful default which helps finding memory leaks.
5027var defaultMaxListeners = 10;
5028
5029var hasDefineProperty;
5030try {
5031 var o = {};
5032 if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
5033 hasDefineProperty = o.x === 0;
5034} catch (err) { hasDefineProperty = false }
5035if (hasDefineProperty) {
5036 Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
5037 enumerable: true,
5038 get: function() {
5039 return defaultMaxListeners;
5040 },
5041 set: function(arg) {
5042 // check whether the input is a positive number (whose value is zero or
5043 // greater and not a NaN).
5044 if (typeof arg !== 'number' || arg < 0 || arg !== arg)
5045 throw new TypeError('"defaultMaxListeners" must be a positive number');
5046 defaultMaxListeners = arg;
5047 }
5048 });
5049} else {
5050 EventEmitter.defaultMaxListeners = defaultMaxListeners;
5051}
5052
5053// Obviously not all Emitters should be limited to 10. This function allows
5054// that to be increased. Set to zero for unlimited.
5055EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
5056 if (typeof n !== 'number' || n < 0 || isNaN(n))
5057 throw new TypeError('"n" argument must be a positive number');
5058 this._maxListeners = n;
5059 return this;
5060};
5061
5062function $getMaxListeners(that) {
5063 if (that._maxListeners === undefined)
5064 return EventEmitter.defaultMaxListeners;
5065 return that._maxListeners;
5066}
5067
5068EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
5069 return $getMaxListeners(this);
5070};
5071
5072// These standalone emit* functions are used to optimize calling of event
5073// handlers for fast cases because emit() itself often has a variable number of
5074// arguments and can be deoptimized because of that. These functions always have
5075// the same number of arguments and thus do not get deoptimized, so the code
5076// inside them can execute faster.
5077function emitNone(handler, isFn, self) {
5078 if (isFn)
5079 handler.call(self);
5080 else {
5081 var len = handler.length;
5082 var listeners = arrayClone(handler, len);
5083 for (var i = 0; i < len; ++i)
5084 listeners[i].call(self);
5085 }
5086}
5087function emitOne(handler, isFn, self, arg1) {
5088 if (isFn)
5089 handler.call(self, arg1);
5090 else {
5091 var len = handler.length;
5092 var listeners = arrayClone(handler, len);
5093 for (var i = 0; i < len; ++i)
5094 listeners[i].call(self, arg1);
5095 }
5096}
5097function emitTwo(handler, isFn, self, arg1, arg2) {
5098 if (isFn)
5099 handler.call(self, arg1, arg2);
5100 else {
5101 var len = handler.length;
5102 var listeners = arrayClone(handler, len);
5103 for (var i = 0; i < len; ++i)
5104 listeners[i].call(self, arg1, arg2);
5105 }
5106}
5107function emitThree(handler, isFn, self, arg1, arg2, arg3) {
5108 if (isFn)
5109 handler.call(self, arg1, arg2, arg3);
5110 else {
5111 var len = handler.length;
5112 var listeners = arrayClone(handler, len);
5113 for (var i = 0; i < len; ++i)
5114 listeners[i].call(self, arg1, arg2, arg3);
5115 }
5116}
5117
5118function emitMany(handler, isFn, self, args) {
5119 if (isFn)
5120 handler.apply(self, args);
5121 else {
5122 var len = handler.length;
5123 var listeners = arrayClone(handler, len);
5124 for (var i = 0; i < len; ++i)
5125 listeners[i].apply(self, args);
5126 }
5127}
5128
5129EventEmitter.prototype.emit = function emit(type) {
5130 var er, handler, len, args, i, events;
5131 var doError = (type === 'error');
5132
5133 events = this._events;
5134 if (events)
5135 doError = (doError && events.error == null);
5136 else if (!doError)
5137 return false;
5138
5139 // If there is no 'error' event listener then throw.
5140 if (doError) {
5141 if (arguments.length > 1)
5142 er = arguments[1];
5143 if (er instanceof Error) {
5144 throw er; // Unhandled 'error' event
5145 } else {
5146 // At least give some kind of context to the user
5147 var err = new Error('Unhandled "error" event. (' + er + ')');
5148 err.context = er;
5149 throw err;
5150 }
5151 return false;
5152 }
5153
5154 handler = events[type];
5155
5156 if (!handler)
5157 return false;
5158
5159 var isFn = typeof handler === 'function';
5160 len = arguments.length;
5161 switch (len) {
5162 // fast cases
5163 case 1:
5164 emitNone(handler, isFn, this);
5165 break;
5166 case 2:
5167 emitOne(handler, isFn, this, arguments[1]);
5168 break;
5169 case 3:
5170 emitTwo(handler, isFn, this, arguments[1], arguments[2]);
5171 break;
5172 case 4:
5173 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
5174 break;
5175 // slower
5176 default:
5177 args = new Array(len - 1);
5178 for (i = 1; i < len; i++)
5179 args[i - 1] = arguments[i];
5180 emitMany(handler, isFn, this, args);
5181 }
5182
5183 return true;
5184};
5185
5186function _addListener(target, type, listener, prepend) {
5187 var m;
5188 var events;
5189 var existing;
5190
5191 if (typeof listener !== 'function')
5192 throw new TypeError('"listener" argument must be a function');
5193
5194 events = target._events;
5195 if (!events) {
5196 events = target._events = objectCreate(null);
5197 target._eventsCount = 0;
5198 } else {
5199 // To avoid recursion in the case that type === "newListener"! Before
5200 // adding it to the listeners, first emit "newListener".
5201 if (events.newListener) {
5202 target.emit('newListener', type,
5203 listener.listener ? listener.listener : listener);
5204
5205 // Re-assign `events` because a newListener handler could have caused the
5206 // this._events to be assigned to a new object
5207 events = target._events;
5208 }
5209 existing = events[type];
5210 }
5211
5212 if (!existing) {
5213 // Optimize the case of one listener. Don't need the extra array object.
5214 existing = events[type] = listener;
5215 ++target._eventsCount;
5216 } else {
5217 if (typeof existing === 'function') {
5218 // Adding the second element, need to change to array.
5219 existing = events[type] =
5220 prepend ? [listener, existing] : [existing, listener];
5221 } else {
5222 // If we've already got an array, just append.
5223 if (prepend) {
5224 existing.unshift(listener);
5225 } else {
5226 existing.push(listener);
5227 }
5228 }
5229
5230 // Check for listener leak
5231 if (!existing.warned) {
5232 m = $getMaxListeners(target);
5233 if (m && m > 0 && existing.length > m) {
5234 existing.warned = true;
5235 var w = new Error('Possible EventEmitter memory leak detected. ' +
5236 existing.length + ' "' + String(type) + '" listeners ' +
5237 'added. Use emitter.setMaxListeners() to ' +
5238 'increase limit.');
5239 w.name = 'MaxListenersExceededWarning';
5240 w.emitter = target;
5241 w.type = type;
5242 w.count = existing.length;
5243 if (typeof console === 'object' && console.warn) {
5244 console.warn('%s: %s', w.name, w.message);
5245 }
5246 }
5247 }
5248 }
5249
5250 return target;
5251}
5252
5253EventEmitter.prototype.addListener = function addListener(type, listener) {
5254 return _addListener(this, type, listener, false);
5255};
5256
5257EventEmitter.prototype.on = EventEmitter.prototype.addListener;
5258
5259EventEmitter.prototype.prependListener =
5260 function prependListener(type, listener) {
5261 return _addListener(this, type, listener, true);
5262 };
5263
5264function onceWrapper() {
5265 if (!this.fired) {
5266 this.target.removeListener(this.type, this.wrapFn);
5267 this.fired = true;
5268 switch (arguments.length) {
5269 case 0:
5270 return this.listener.call(this.target);
5271 case 1:
5272 return this.listener.call(this.target, arguments[0]);
5273 case 2:
5274 return this.listener.call(this.target, arguments[0], arguments[1]);
5275 case 3:
5276 return this.listener.call(this.target, arguments[0], arguments[1],
5277 arguments[2]);
5278 default:
5279 var args = new Array(arguments.length);
5280 for (var i = 0; i < args.length; ++i)
5281 args[i] = arguments[i];
5282 this.listener.apply(this.target, args);
5283 }
5284 }
5285}
5286
5287function _onceWrap(target, type, listener) {
5288 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
5289 var wrapped = bind.call(onceWrapper, state);
5290 wrapped.listener = listener;
5291 state.wrapFn = wrapped;
5292 return wrapped;
5293}
5294
5295EventEmitter.prototype.once = function once(type, listener) {
5296 if (typeof listener !== 'function')
5297 throw new TypeError('"listener" argument must be a function');
5298 this.on(type, _onceWrap(this, type, listener));
5299 return this;
5300};
5301
5302EventEmitter.prototype.prependOnceListener =
5303 function prependOnceListener(type, listener) {
5304 if (typeof listener !== 'function')
5305 throw new TypeError('"listener" argument must be a function');
5306 this.prependListener(type, _onceWrap(this, type, listener));
5307 return this;
5308 };
5309
5310// Emits a 'removeListener' event if and only if the listener was removed.
5311EventEmitter.prototype.removeListener =
5312 function removeListener(type, listener) {
5313 var list, events, position, i, originalListener;
5314
5315 if (typeof listener !== 'function')
5316 throw new TypeError('"listener" argument must be a function');
5317
5318 events = this._events;
5319 if (!events)
5320 return this;
5321
5322 list = events[type];
5323 if (!list)
5324 return this;
5325
5326 if (list === listener || list.listener === listener) {
5327 if (--this._eventsCount === 0)
5328 this._events = objectCreate(null);
5329 else {
5330 delete events[type];
5331 if (events.removeListener)
5332 this.emit('removeListener', type, list.listener || listener);
5333 }
5334 } else if (typeof list !== 'function') {
5335 position = -1;
5336
5337 for (i = list.length - 1; i >= 0; i--) {
5338 if (list[i] === listener || list[i].listener === listener) {
5339 originalListener = list[i].listener;
5340 position = i;
5341 break;
5342 }
5343 }
5344
5345 if (position < 0)
5346 return this;
5347
5348 if (position === 0)
5349 list.shift();
5350 else
5351 spliceOne(list, position);
5352
5353 if (list.length === 1)
5354 events[type] = list[0];
5355
5356 if (events.removeListener)
5357 this.emit('removeListener', type, originalListener || listener);
5358 }
5359
5360 return this;
5361 };
5362
5363EventEmitter.prototype.removeAllListeners =
5364 function removeAllListeners(type) {
5365 var listeners, events, i;
5366
5367 events = this._events;
5368 if (!events)
5369 return this;
5370
5371 // not listening for removeListener, no need to emit
5372 if (!events.removeListener) {
5373 if (arguments.length === 0) {
5374 this._events = objectCreate(null);
5375 this._eventsCount = 0;
5376 } else if (events[type]) {
5377 if (--this._eventsCount === 0)
5378 this._events = objectCreate(null);
5379 else
5380 delete events[type];
5381 }
5382 return this;
5383 }
5384
5385 // emit removeListener for all listeners on all events
5386 if (arguments.length === 0) {
5387 var keys = objectKeys(events);
5388 var key;
5389 for (i = 0; i < keys.length; ++i) {
5390 key = keys[i];
5391 if (key === 'removeListener') continue;
5392 this.removeAllListeners(key);
5393 }
5394 this.removeAllListeners('removeListener');
5395 this._events = objectCreate(null);
5396 this._eventsCount = 0;
5397 return this;
5398 }
5399
5400 listeners = events[type];
5401
5402 if (typeof listeners === 'function') {
5403 this.removeListener(type, listeners);
5404 } else if (listeners) {
5405 // LIFO order
5406 for (i = listeners.length - 1; i >= 0; i--) {
5407 this.removeListener(type, listeners[i]);
5408 }
5409 }
5410
5411 return this;
5412 };
5413
5414function _listeners(target, type, unwrap) {
5415 var events = target._events;
5416
5417 if (!events)
5418 return [];
5419
5420 var evlistener = events[type];
5421 if (!evlistener)
5422 return [];
5423
5424 if (typeof evlistener === 'function')
5425 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
5426
5427 return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
5428}
5429
5430EventEmitter.prototype.listeners = function listeners(type) {
5431 return _listeners(this, type, true);
5432};
5433
5434EventEmitter.prototype.rawListeners = function rawListeners(type) {
5435 return _listeners(this, type, false);
5436};
5437
5438EventEmitter.listenerCount = function(emitter, type) {
5439 if (typeof emitter.listenerCount === 'function') {
5440 return emitter.listenerCount(type);
5441 } else {
5442 return listenerCount.call(emitter, type);
5443 }
5444};
5445
5446EventEmitter.prototype.listenerCount = listenerCount;
5447function listenerCount(type) {
5448 var events = this._events;
5449
5450 if (events) {
5451 var evlistener = events[type];
5452
5453 if (typeof evlistener === 'function') {
5454 return 1;
5455 } else if (evlistener) {
5456 return evlistener.length;
5457 }
5458 }
5459
5460 return 0;
5461}
5462
5463EventEmitter.prototype.eventNames = function eventNames() {
5464 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
5465};
5466
5467// About 1.5x faster than the two-arg version of Array#splice().
5468function spliceOne(list, index) {
5469 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
5470 list[i] = list[k];
5471 list.pop();
5472}
5473
5474function arrayClone(arr, n) {
5475 var copy = new Array(n);
5476 for (var i = 0; i < n; ++i)
5477 copy[i] = arr[i];
5478 return copy;
5479}
5480
5481function unwrapListeners(arr) {
5482 var ret = new Array(arr.length);
5483 for (var i = 0; i < ret.length; ++i) {
5484 ret[i] = arr[i].listener || arr[i];
5485 }
5486 return ret;
5487}
5488
5489function objectCreatePolyfill(proto) {
5490 var F = function() {};
5491 F.prototype = proto;
5492 return new F;
5493}
5494function objectKeysPolyfill(obj) {
5495 var keys = [];
5496 for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
5497 keys.push(k);
5498 }
5499 return k;
5500}
5501function functionBindPolyfill(context) {
5502 var fn = this;
5503 return function () {
5504 return fn.apply(context, arguments);
5505 };
5506}
5507
5508},{}],26:[function(_dereq_,module,exports){
5509/**
5510 * # hasLocalStorage()
5511 *
5512 * returns `true` or `false` depending on whether localStorage is supported or not.
5513 * Beware that some browsers like Safari do not support localStorage in private mode.
5514 *
5515 * inspired by this cappuccino commit
5516 * https://github.com/cappuccino/cappuccino/commit/063b05d9643c35b303568a28809e4eb3224f71ec
5517 *
5518 * @returns {Boolean}
5519 */
5520function hasLocalStorage() {
5521 try {
5522
5523 // we've to put this in here. I've seen Firefox throwing `Security error: 1000`
5524 // when cookies have been disabled
5525 if (typeof localStorage === 'undefined') {
5526 return false;
5527 }
5528
5529 // Just because localStorage exists does not mean it works. In particular it might be disabled
5530 // as it is when Safari's private browsing mode is active.
5531 localStorage.setItem('Storage-Test', '1');
5532
5533 // that should not happen ...
5534 if (localStorage.getItem('Storage-Test') !== '1') {
5535 return false;
5536 }
5537
5538 // okay, let's clean up if we got here.
5539 localStorage.removeItem('Storage-Test');
5540 } catch (_error) {
5541
5542 // in case of an error, like Safari's Private Mode, return false
5543 return false;
5544 }
5545
5546 // we're good.
5547 return true;
5548}
5549
5550
5551if (typeof exports === 'object') {
5552 module.exports = hasLocalStorage;
5553}
5554
5555},{}],27:[function(_dereq_,module,exports){
5556(function (global){
5557var exports = module.exports = {};
5558var localStorageMemory = _dereq_(65);
5559exports.hasLocalStorage = _dereq_(26);
5560
5561/**
5562 * returns localStorage-compatible API, either backed by window.localStorage
5563 * or memory if it's not available or not persistent.
5564 *
5565 * It also adds an object API (`.getObject(key)`,
5566 * `.setObject(key, properties)`) and a `isPresistent` property
5567 *
5568 * @returns {Object}
5569 */
5570exports.create = function () {
5571 var api;
5572
5573 if (!exports.hasLocalStorage()) {
5574 api = localStorageMemory;
5575 api.isPersistent = false;
5576 } else {
5577 api = global.localStorage;
5578 api = {
5579 get length() { return global.localStorage.length; },
5580 getItem: global.localStorage.getItem.bind(global.localStorage),
5581 setItem: global.localStorage.setItem.bind(global.localStorage),
5582 removeItem: global.localStorage.removeItem.bind(global.localStorage),
5583 key: global.localStorage.key.bind(global.localStorage),
5584 clear: global.localStorage.clear.bind(global.localStorage),
5585 };
5586
5587 api.isPersistent = true;
5588 }
5589
5590 api.getObject = exports.getObject.bind(null, api);
5591 api.setObject = exports.setObject.bind(null, api);
5592
5593 return api;
5594};
5595
5596/**
5597 * sets key to passed Object.
5598 *
5599 * @returns undefined
5600 */
5601exports.setObject = function (store, key, object) {
5602 if (typeof object !== 'object') {
5603 return store.setItem(key, object);
5604 }
5605
5606 return store.setItem(key, JSON.stringify(object));
5607};
5608
5609/**
5610 * returns Object for key, or null
5611 *
5612 * @returns {Object|null}
5613 */
5614exports.getObject = function (store, key) {
5615 var item = store.getItem(key);
5616
5617 if (!item) {
5618 return null;
5619 }
5620
5621 try {
5622 return JSON.parse(item);
5623 } catch (e) {
5624 return item;
5625 }
5626};
5627
5628}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5629},{"26":26,"65":65}],28:[function(_dereq_,module,exports){
5630var api = _dereq_(27);
5631module.exports = api.create();
5632
5633},{"27":27}],29:[function(_dereq_,module,exports){
5634exports.read = function (buffer, offset, isLE, mLen, nBytes) {
5635 var e, m
5636 var eLen = (nBytes * 8) - mLen - 1
5637 var eMax = (1 << eLen) - 1
5638 var eBias = eMax >> 1
5639 var nBits = -7
5640 var i = isLE ? (nBytes - 1) : 0
5641 var d = isLE ? -1 : 1
5642 var s = buffer[offset + i]
5643
5644 i += d
5645
5646 e = s & ((1 << (-nBits)) - 1)
5647 s >>= (-nBits)
5648 nBits += eLen
5649 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
5650
5651 m = e & ((1 << (-nBits)) - 1)
5652 e >>= (-nBits)
5653 nBits += mLen
5654 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
5655
5656 if (e === 0) {
5657 e = 1 - eBias
5658 } else if (e === eMax) {
5659 return m ? NaN : ((s ? -1 : 1) * Infinity)
5660 } else {
5661 m = m + Math.pow(2, mLen)
5662 e = e - eBias
5663 }
5664 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
5665}
5666
5667exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
5668 var e, m, c
5669 var eLen = (nBytes * 8) - mLen - 1
5670 var eMax = (1 << eLen) - 1
5671 var eBias = eMax >> 1
5672 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
5673 var i = isLE ? 0 : (nBytes - 1)
5674 var d = isLE ? 1 : -1
5675 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
5676
5677 value = Math.abs(value)
5678
5679 if (isNaN(value) || value === Infinity) {
5680 m = isNaN(value) ? 1 : 0
5681 e = eMax
5682 } else {
5683 e = Math.floor(Math.log(value) / Math.LN2)
5684 if (value * (c = Math.pow(2, -e)) < 1) {
5685 e--
5686 c *= 2
5687 }
5688 if (e + eBias >= 1) {
5689 value += rt / c
5690 } else {
5691 value += rt * Math.pow(2, 1 - eBias)
5692 }
5693 if (value * c >= 2) {
5694 e++
5695 c /= 2
5696 }
5697
5698 if (e + eBias >= eMax) {
5699 m = 0
5700 e = eMax
5701 } else if (e + eBias >= 1) {
5702 m = ((value * c) - 1) * Math.pow(2, mLen)
5703 e = e + eBias
5704 } else {
5705 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
5706 e = 0
5707 }
5708 }
5709
5710 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
5711
5712 e = (e << mLen) | m
5713 eLen += mLen
5714 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
5715
5716 buffer[offset + i - d] |= s * 128
5717}
5718
5719},{}],30:[function(_dereq_,module,exports){
5720(function (global){
5721'use strict';
5722var Mutation = global.MutationObserver || global.WebKitMutationObserver;
5723
5724var scheduleDrain;
5725
5726{
5727 if (Mutation) {
5728 var called = 0;
5729 var observer = new Mutation(nextTick);
5730 var element = global.document.createTextNode('');
5731 observer.observe(element, {
5732 characterData: true
5733 });
5734 scheduleDrain = function () {
5735 element.data = (called = ++called % 2);
5736 };
5737 } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
5738 var channel = new global.MessageChannel();
5739 channel.port1.onmessage = nextTick;
5740 scheduleDrain = function () {
5741 channel.port2.postMessage(0);
5742 };
5743 } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
5744 scheduleDrain = function () {
5745
5746 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
5747 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
5748 var scriptEl = global.document.createElement('script');
5749 scriptEl.onreadystatechange = function () {
5750 nextTick();
5751
5752 scriptEl.onreadystatechange = null;
5753 scriptEl.parentNode.removeChild(scriptEl);
5754 scriptEl = null;
5755 };
5756 global.document.documentElement.appendChild(scriptEl);
5757 };
5758 } else {
5759 scheduleDrain = function () {
5760 setTimeout(nextTick, 0);
5761 };
5762 }
5763}
5764
5765var draining;
5766var queue = [];
5767//named nextTick for less confusing stack traces
5768function nextTick() {
5769 draining = true;
5770 var i, oldQueue;
5771 var len = queue.length;
5772 while (len) {
5773 oldQueue = queue;
5774 queue = [];
5775 i = -1;
5776 while (++i < len) {
5777 oldQueue[i]();
5778 }
5779 len = queue.length;
5780 }
5781 draining = false;
5782}
5783
5784module.exports = immediate;
5785function immediate(task) {
5786 if (queue.push(task) === 1 && !draining) {
5787 scheduleDrain();
5788 }
5789}
5790
5791}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5792},{}],31:[function(_dereq_,module,exports){
5793arguments[4][6][0].apply(exports,arguments)
5794},{"6":6}],32:[function(_dereq_,module,exports){
5795/*!
5796 * Determine if an object is a Buffer
5797 *
5798 * @author Feross Aboukhadijeh <https://feross.org>
5799 * @license MIT
5800 */
5801
5802// The _isBuffer check is for Safari 5-7 support, because it's missing
5803// Object.prototype.constructor. Remove this eventually
5804module.exports = function (obj) {
5805 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
5806}
5807
5808function isBuffer (obj) {
5809 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
5810}
5811
5812// For Node v0.10 support. Remove this eventually.
5813function isSlowBuffer (obj) {
5814 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
5815}
5816
5817},{}],33:[function(_dereq_,module,exports){
5818module.exports = Array.isArray || function (arr) {
5819 return Object.prototype.toString.call(arr) == '[object Array]';
5820};
5821
5822},{}],34:[function(_dereq_,module,exports){
5823var encodings = _dereq_(35)
5824
5825module.exports = Codec
5826
5827function Codec (opts) {
5828 if (!(this instanceof Codec)) {
5829 return new Codec(opts)
5830 }
5831 this.opts = opts || {}
5832 this.encodings = encodings
5833}
5834
5835Codec.prototype._encoding = function (encoding) {
5836 if (typeof encoding === 'string') encoding = encodings[encoding]
5837 if (!encoding) encoding = encodings.id
5838 return encoding
5839}
5840
5841Codec.prototype._keyEncoding = function (opts, batchOpts) {
5842 return this._encoding((batchOpts && batchOpts.keyEncoding) ||
5843 (opts && opts.keyEncoding) ||
5844 this.opts.keyEncoding)
5845}
5846
5847Codec.prototype._valueEncoding = function (opts, batchOpts) {
5848 return this._encoding((batchOpts && (batchOpts.valueEncoding || batchOpts.encoding)) ||
5849 (opts && (opts.valueEncoding || opts.encoding)) ||
5850 (this.opts.valueEncoding || this.opts.encoding))
5851}
5852
5853Codec.prototype.encodeKey = function (key, opts, batchOpts) {
5854 return this._keyEncoding(opts, batchOpts).encode(key)
5855}
5856
5857Codec.prototype.encodeValue = function (value, opts, batchOpts) {
5858 return this._valueEncoding(opts, batchOpts).encode(value)
5859}
5860
5861Codec.prototype.decodeKey = function (key, opts) {
5862 return this._keyEncoding(opts).decode(key)
5863}
5864
5865Codec.prototype.decodeValue = function (value, opts) {
5866 return this._valueEncoding(opts).decode(value)
5867}
5868
5869Codec.prototype.encodeBatch = function (ops, opts) {
5870 var self = this
5871
5872 return ops.map(function (_op) {
5873 var op = {
5874 type: _op.type,
5875 key: self.encodeKey(_op.key, opts, _op)
5876 }
5877 if (self.keyAsBuffer(opts, _op)) op.keyEncoding = 'binary'
5878 if (_op.prefix) op.prefix = _op.prefix
5879 if ('value' in _op) {
5880 op.value = self.encodeValue(_op.value, opts, _op)
5881 if (self.valueAsBuffer(opts, _op)) op.valueEncoding = 'binary'
5882 }
5883 return op
5884 })
5885}
5886
5887var ltgtKeys = ['lt', 'gt', 'lte', 'gte', 'start', 'end']
5888
5889Codec.prototype.encodeLtgt = function (ltgt) {
5890 var self = this
5891 var ret = {}
5892 Object.keys(ltgt).forEach(function (key) {
5893 ret[key] = ltgtKeys.indexOf(key) > -1
5894 ? self.encodeKey(ltgt[key], ltgt)
5895 : ltgt[key]
5896 })
5897 return ret
5898}
5899
5900Codec.prototype.createStreamDecoder = function (opts) {
5901 var self = this
5902
5903 if (opts.keys && opts.values) {
5904 return function (key, value) {
5905 return {
5906 key: self.decodeKey(key, opts),
5907 value: self.decodeValue(value, opts)
5908 }
5909 }
5910 } else if (opts.keys) {
5911 return function (key) {
5912 return self.decodeKey(key, opts)
5913 }
5914 } else if (opts.values) {
5915 return function (_, value) {
5916 return self.decodeValue(value, opts)
5917 }
5918 } else {
5919 return function () {}
5920 }
5921}
5922
5923Codec.prototype.keyAsBuffer = function (opts) {
5924 return this._keyEncoding(opts).buffer
5925}
5926
5927Codec.prototype.valueAsBuffer = function (opts) {
5928 return this._valueEncoding(opts).buffer
5929}
5930
5931},{"35":35}],35:[function(_dereq_,module,exports){
5932(function (Buffer){
5933exports.utf8 = exports['utf-8'] = {
5934 encode: function (data) {
5935 return isBinary(data) ? data : String(data)
5936 },
5937 decode: identity,
5938 buffer: false,
5939 type: 'utf8'
5940}
5941
5942exports.json = {
5943 encode: JSON.stringify,
5944 decode: JSON.parse,
5945 buffer: false,
5946 type: 'json'
5947}
5948
5949exports.binary = {
5950 encode: function (data) {
5951 return isBinary(data) ? data : Buffer.from(data)
5952 },
5953 decode: identity,
5954 buffer: true,
5955 type: 'binary'
5956}
5957
5958exports.none = {
5959 encode: identity,
5960 decode: identity,
5961 buffer: false,
5962 type: 'id'
5963}
5964
5965exports.id = exports.none
5966
5967var bufferEncodings = [
5968 'hex',
5969 'ascii',
5970 'base64',
5971 'ucs2',
5972 'ucs-2',
5973 'utf16le',
5974 'utf-16le'
5975]
5976
5977bufferEncodings.forEach(function (type) {
5978 exports[type] = {
5979 encode: function (data) {
5980 return isBinary(data) ? data : Buffer.from(data, type)
5981 },
5982 decode: function (buffer) {
5983 return buffer.toString(type)
5984 },
5985 buffer: true,
5986 type: type
5987 }
5988})
5989
5990function identity (value) {
5991 return value
5992}
5993
5994function isBinary (data) {
5995 return data === undefined || data === null || Buffer.isBuffer(data)
5996}
5997
5998}).call(this,_dereq_(12).Buffer)
5999},{"12":12}],36:[function(_dereq_,module,exports){
6000var createError = _dereq_(24).create
6001var LevelUPError = createError('LevelUPError')
6002var NotFoundError = createError('NotFoundError', LevelUPError)
6003
6004NotFoundError.prototype.notFound = true
6005NotFoundError.prototype.status = 404
6006
6007module.exports = {
6008 LevelUPError: LevelUPError,
6009 InitializationError: createError('InitializationError', LevelUPError),
6010 OpenError: createError('OpenError', LevelUPError),
6011 ReadError: createError('ReadError', LevelUPError),
6012 WriteError: createError('WriteError', LevelUPError),
6013 NotFoundError: NotFoundError,
6014 EncodingError: createError('EncodingError', LevelUPError)
6015}
6016
6017},{"24":24}],37:[function(_dereq_,module,exports){
6018var inherits = _dereq_(31)
6019var Readable = _dereq_(52).Readable
6020var extend = _dereq_(53)
6021
6022module.exports = ReadStream
6023inherits(ReadStream, Readable)
6024
6025function ReadStream (iterator, options) {
6026 if (!(this instanceof ReadStream)) return new ReadStream(iterator, options)
6027 options = options || {}
6028 Readable.call(this, extend(options, {
6029 objectMode: true
6030 }))
6031 this._iterator = iterator
6032 this._options = options
6033 this.on('end', this.destroy.bind(this, null, null))
6034}
6035
6036ReadStream.prototype._read = function () {
6037 var self = this
6038 var options = this._options
6039 if (this.destroyed) return
6040
6041 this._iterator.next(function (err, key, value) {
6042 if (self.destroyed) return
6043 if (err) return self.destroy(err)
6044
6045 if (key === undefined && value === undefined) {
6046 self.push(null)
6047 } else if (options.keys !== false && options.values === false) {
6048 self.push(key)
6049 } else if (options.keys === false && options.values !== false) {
6050 self.push(value)
6051 } else {
6052 self.push({ key: key, value: value })
6053 }
6054 })
6055}
6056
6057ReadStream.prototype._destroy = function (err, callback) {
6058 this._iterator.end(function (err2) {
6059 callback(err || err2)
6060 })
6061}
6062
6063},{"31":31,"52":52,"53":53}],38:[function(_dereq_,module,exports){
6064'use strict';
6065
6066function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
6067
6068var codes = {};
6069
6070function createErrorType(code, message, Base) {
6071 if (!Base) {
6072 Base = Error;
6073 }
6074
6075 function getMessage(arg1, arg2, arg3) {
6076 if (typeof message === 'string') {
6077 return message;
6078 } else {
6079 return message(arg1, arg2, arg3);
6080 }
6081 }
6082
6083 var NodeError =
6084 /*#__PURE__*/
6085 function (_Base) {
6086 _inheritsLoose(NodeError, _Base);
6087
6088 function NodeError(arg1, arg2, arg3) {
6089 return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
6090 }
6091
6092 return NodeError;
6093 }(Base);
6094
6095 NodeError.prototype.name = Base.name;
6096 NodeError.prototype.code = code;
6097 codes[code] = NodeError;
6098} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
6099
6100
6101function oneOf(expected, thing) {
6102 if (Array.isArray(expected)) {
6103 var len = expected.length;
6104 expected = expected.map(function (i) {
6105 return String(i);
6106 });
6107
6108 if (len > 2) {
6109 return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
6110 } else if (len === 2) {
6111 return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
6112 } else {
6113 return "of ".concat(thing, " ").concat(expected[0]);
6114 }
6115 } else {
6116 return "of ".concat(thing, " ").concat(String(expected));
6117 }
6118} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
6119
6120
6121function startsWith(str, search, pos) {
6122 return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
6123} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
6124
6125
6126function endsWith(str, search, this_len) {
6127 if (this_len === undefined || this_len > str.length) {
6128 this_len = str.length;
6129 }
6130
6131 return str.substring(this_len - search.length, this_len) === search;
6132} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
6133
6134
6135function includes(str, search, start) {
6136 if (typeof start !== 'number') {
6137 start = 0;
6138 }
6139
6140 if (start + search.length > str.length) {
6141 return false;
6142 } else {
6143 return str.indexOf(search, start) !== -1;
6144 }
6145}
6146
6147createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
6148 return 'The value "' + value + '" is invalid for option "' + name + '"';
6149}, TypeError);
6150createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
6151 // determiner: 'must be' or 'must not be'
6152 var determiner;
6153
6154 if (typeof expected === 'string' && startsWith(expected, 'not ')) {
6155 determiner = 'must not be';
6156 expected = expected.replace(/^not /, '');
6157 } else {
6158 determiner = 'must be';
6159 }
6160
6161 var msg;
6162
6163 if (endsWith(name, ' argument')) {
6164 // For cases like 'first argument'
6165 msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
6166 } else {
6167 var type = includes(name, '.') ? 'property' : 'argument';
6168 msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
6169 }
6170
6171 msg += ". Received type ".concat(typeof actual);
6172 return msg;
6173}, TypeError);
6174createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
6175createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
6176 return 'The ' + name + ' method is not implemented';
6177});
6178createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
6179createErrorType('ERR_STREAM_DESTROYED', function (name) {
6180 return 'Cannot call ' + name + ' after a stream was destroyed';
6181});
6182createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
6183createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
6184createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
6185createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
6186createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
6187 return 'Unknown encoding: ' + arg;
6188}, TypeError);
6189createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
6190module.exports.codes = codes;
6191
6192},{}],39:[function(_dereq_,module,exports){
6193(function (process){
6194'use strict'
6195
6196var experimentalWarnings = new Set();
6197
6198function emitExperimentalWarning(feature) {
6199 if (experimentalWarnings.has(feature)) return;
6200 var msg = feature + ' is an experimental feature. This feature could ' +
6201 'change at any time';
6202 experimentalWarnings.add(feature);
6203 process.emitWarning(msg, 'ExperimentalWarning');
6204}
6205
6206function noop() {}
6207
6208module.exports.emitExperimentalWarning = process.emitWarning
6209 ? emitExperimentalWarning
6210 : noop;
6211
6212}).call(this,_dereq_(69))
6213},{"69":69}],40:[function(_dereq_,module,exports){
6214(function (process){
6215// Copyright Joyent, Inc. and other Node contributors.
6216//
6217// Permission is hereby granted, free of charge, to any person obtaining a
6218// copy of this software and associated documentation files (the
6219// "Software"), to deal in the Software without restriction, including
6220// without limitation the rights to use, copy, modify, merge, publish,
6221// distribute, sublicense, and/or sell copies of the Software, and to permit
6222// persons to whom the Software is furnished to do so, subject to the
6223// following conditions:
6224//
6225// The above copyright notice and this permission notice shall be included
6226// in all copies or substantial portions of the Software.
6227//
6228// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6229// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6230// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6231// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6232// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6233// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6234// USE OR OTHER DEALINGS IN THE SOFTWARE.
6235// a duplex stream is just a stream that is both readable and writable.
6236// Since JS doesn't have multiple prototypal inheritance, this class
6237// prototypally inherits from Readable, and then parasitically from
6238// Writable.
6239'use strict';
6240/*<replacement>*/
6241
6242var objectKeys = Object.keys || function (obj) {
6243 var keys = [];
6244
6245 for (var key in obj) {
6246 keys.push(key);
6247 }
6248
6249 return keys;
6250};
6251/*</replacement>*/
6252
6253
6254module.exports = Duplex;
6255
6256var Readable = _dereq_(42);
6257
6258var Writable = _dereq_(44);
6259
6260_dereq_(31)(Duplex, Readable);
6261
6262{
6263 // Allow the keys array to be GC'ed.
6264 var keys = objectKeys(Writable.prototype);
6265
6266 for (var v = 0; v < keys.length; v++) {
6267 var method = keys[v];
6268 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
6269 }
6270}
6271
6272function Duplex(options) {
6273 if (!(this instanceof Duplex)) return new Duplex(options);
6274 Readable.call(this, options);
6275 Writable.call(this, options);
6276 this.allowHalfOpen = true;
6277
6278 if (options) {
6279 if (options.readable === false) this.readable = false;
6280 if (options.writable === false) this.writable = false;
6281
6282 if (options.allowHalfOpen === false) {
6283 this.allowHalfOpen = false;
6284 this.once('end', onend);
6285 }
6286 }
6287}
6288
6289Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
6290 // making it explicit this property is not enumerable
6291 // because otherwise some prototype manipulation in
6292 // userland will fail
6293 enumerable: false,
6294 get: function get() {
6295 return this._writableState.highWaterMark;
6296 }
6297});
6298Object.defineProperty(Duplex.prototype, 'writableBuffer', {
6299 // making it explicit this property is not enumerable
6300 // because otherwise some prototype manipulation in
6301 // userland will fail
6302 enumerable: false,
6303 get: function get() {
6304 return this._writableState && this._writableState.getBuffer();
6305 }
6306});
6307Object.defineProperty(Duplex.prototype, 'writableLength', {
6308 // making it explicit this property is not enumerable
6309 // because otherwise some prototype manipulation in
6310 // userland will fail
6311 enumerable: false,
6312 get: function get() {
6313 return this._writableState.length;
6314 }
6315}); // the no-half-open enforcer
6316
6317function onend() {
6318 // If the writable side ended, then we're ok.
6319 if (this._writableState.ended) return; // no more data can be written.
6320 // But allow more writes to happen in this tick.
6321
6322 process.nextTick(onEndNT, this);
6323}
6324
6325function onEndNT(self) {
6326 self.end();
6327}
6328
6329Object.defineProperty(Duplex.prototype, 'destroyed', {
6330 // making it explicit this property is not enumerable
6331 // because otherwise some prototype manipulation in
6332 // userland will fail
6333 enumerable: false,
6334 get: function get() {
6335 if (this._readableState === undefined || this._writableState === undefined) {
6336 return false;
6337 }
6338
6339 return this._readableState.destroyed && this._writableState.destroyed;
6340 },
6341 set: function set(value) {
6342 // we ignore the value if the stream
6343 // has not been initialized yet
6344 if (this._readableState === undefined || this._writableState === undefined) {
6345 return;
6346 } // backward compatibility, the user is explicitly
6347 // managing destroyed
6348
6349
6350 this._readableState.destroyed = value;
6351 this._writableState.destroyed = value;
6352 }
6353});
6354}).call(this,_dereq_(69))
6355},{"31":31,"42":42,"44":44,"69":69}],41:[function(_dereq_,module,exports){
6356// Copyright Joyent, Inc. and other Node contributors.
6357//
6358// Permission is hereby granted, free of charge, to any person obtaining a
6359// copy of this software and associated documentation files (the
6360// "Software"), to deal in the Software without restriction, including
6361// without limitation the rights to use, copy, modify, merge, publish,
6362// distribute, sublicense, and/or sell copies of the Software, and to permit
6363// persons to whom the Software is furnished to do so, subject to the
6364// following conditions:
6365//
6366// The above copyright notice and this permission notice shall be included
6367// in all copies or substantial portions of the Software.
6368//
6369// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6370// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6371// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6372// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6373// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6374// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6375// USE OR OTHER DEALINGS IN THE SOFTWARE.
6376// a passthrough stream.
6377// basically just the most minimal sort of Transform stream.
6378// Every written chunk gets output as-is.
6379'use strict';
6380
6381module.exports = PassThrough;
6382
6383var Transform = _dereq_(43);
6384
6385_dereq_(31)(PassThrough, Transform);
6386
6387function PassThrough(options) {
6388 if (!(this instanceof PassThrough)) return new PassThrough(options);
6389 Transform.call(this, options);
6390}
6391
6392PassThrough.prototype._transform = function (chunk, encoding, cb) {
6393 cb(null, chunk);
6394};
6395},{"31":31,"43":43}],42:[function(_dereq_,module,exports){
6396(function (process,global){
6397// Copyright Joyent, Inc. and other Node contributors.
6398//
6399// Permission is hereby granted, free of charge, to any person obtaining a
6400// copy of this software and associated documentation files (the
6401// "Software"), to deal in the Software without restriction, including
6402// without limitation the rights to use, copy, modify, merge, publish,
6403// distribute, sublicense, and/or sell copies of the Software, and to permit
6404// persons to whom the Software is furnished to do so, subject to the
6405// following conditions:
6406//
6407// The above copyright notice and this permission notice shall be included
6408// in all copies or substantial portions of the Software.
6409//
6410// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6411// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6412// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6413// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6414// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6415// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6416// USE OR OTHER DEALINGS IN THE SOFTWARE.
6417'use strict';
6418
6419module.exports = Readable;
6420/*<replacement>*/
6421
6422var Duplex;
6423/*</replacement>*/
6424
6425Readable.ReadableState = ReadableState;
6426/*<replacement>*/
6427
6428var EE = _dereq_(25).EventEmitter;
6429
6430var EElistenerCount = function EElistenerCount(emitter, type) {
6431 return emitter.listeners(type).length;
6432};
6433/*</replacement>*/
6434
6435/*<replacement>*/
6436
6437
6438var Stream = _dereq_(51);
6439/*</replacement>*/
6440
6441
6442var Buffer = _dereq_(12).Buffer;
6443
6444var OurUint8Array = global.Uint8Array || function () {};
6445
6446function _uint8ArrayToBuffer(chunk) {
6447 return Buffer.from(chunk);
6448}
6449
6450function _isUint8Array(obj) {
6451 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
6452}
6453/*<replacement>*/
6454
6455
6456var debugUtil = _dereq_(10);
6457
6458var debug;
6459
6460if (debugUtil && debugUtil.debuglog) {
6461 debug = debugUtil.debuglog('stream');
6462} else {
6463 debug = function debug() {};
6464}
6465/*</replacement>*/
6466
6467
6468var BufferList = _dereq_(46);
6469
6470var destroyImpl = _dereq_(47);
6471
6472var _require = _dereq_(50),
6473 getHighWaterMark = _require.getHighWaterMark;
6474
6475var _require$codes = _dereq_(38).codes,
6476 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
6477 ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
6478 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
6479 ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;
6480
6481var _require2 = _dereq_(39),
6482 emitExperimentalWarning = _require2.emitExperimentalWarning; // Lazy loaded to improve the startup performance.
6483
6484
6485var StringDecoder;
6486var createReadableStreamAsyncIterator;
6487
6488_dereq_(31)(Readable, Stream);
6489
6490var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
6491
6492function prependListener(emitter, event, fn) {
6493 // Sadly this is not cacheable as some libraries bundle their own
6494 // event emitter implementation with them.
6495 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
6496 // userland ones. NEVER DO THIS. This is here only because this code needs
6497 // to continue to work with older versions of Node.js that do not include
6498 // the prependListener() method. The goal is to eventually remove this hack.
6499
6500 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]];
6501}
6502
6503function ReadableState(options, stream, isDuplex) {
6504 Duplex = Duplex || _dereq_(40);
6505 options = options || {}; // Duplex streams are both readable and writable, but share
6506 // the same options object.
6507 // However, some cases require setting options to different
6508 // values for the readable and the writable sides of the duplex stream.
6509 // These options can be provided separately as readableXXX and writableXXX.
6510
6511 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to
6512 // make all the buffer merging and length checks go away
6513
6514 this.objectMode = !!options.objectMode;
6515 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
6516 // Note: 0 is a valid value, means "don't call _read preemptively ever"
6517
6518 this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the
6519 // linked list can remove elements from the beginning faster than
6520 // array.shift()
6521
6522 this.buffer = new BufferList();
6523 this.length = 0;
6524 this.pipes = null;
6525 this.pipesCount = 0;
6526 this.flowing = null;
6527 this.ended = false;
6528 this.endEmitted = false;
6529 this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted
6530 // immediately, or on a later tick. We set this to true at first, because
6531 // any actions that shouldn't happen until "later" should generally also
6532 // not happen before the first read call.
6533
6534 this.sync = true; // whenever we return null, then we set a flag to say
6535 // that we're awaiting a 'readable' event emission.
6536
6537 this.needReadable = false;
6538 this.emittedReadable = false;
6539 this.readableListening = false;
6540 this.resumeScheduled = false;
6541 this.paused = true; // Should close be emitted on destroy. Defaults to true.
6542
6543 this.emitClose = options.emitClose !== false; // has it been destroyed
6544
6545 this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string
6546 // encoding is 'binary' so we have to make this configurable.
6547 // Everything else in the universe uses 'utf8', though.
6548
6549 this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s
6550
6551 this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled
6552
6553 this.readingMore = false;
6554 this.decoder = null;
6555 this.encoding = null;
6556
6557 if (options.encoding) {
6558 if (!StringDecoder) StringDecoder = _dereq_(96).StringDecoder;
6559 this.decoder = new StringDecoder(options.encoding);
6560 this.encoding = options.encoding;
6561 }
6562}
6563
6564function Readable(options) {
6565 Duplex = Duplex || _dereq_(40);
6566 if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside
6567 // the ReadableState constructor, at least with V8 6.5
6568
6569 var isDuplex = this instanceof Duplex;
6570 this._readableState = new ReadableState(options, this, isDuplex); // legacy
6571
6572 this.readable = true;
6573
6574 if (options) {
6575 if (typeof options.read === 'function') this._read = options.read;
6576 if (typeof options.destroy === 'function') this._destroy = options.destroy;
6577 }
6578
6579 Stream.call(this);
6580}
6581
6582Object.defineProperty(Readable.prototype, 'destroyed', {
6583 // making it explicit this property is not enumerable
6584 // because otherwise some prototype manipulation in
6585 // userland will fail
6586 enumerable: false,
6587 get: function get() {
6588 if (this._readableState === undefined) {
6589 return false;
6590 }
6591
6592 return this._readableState.destroyed;
6593 },
6594 set: function set(value) {
6595 // we ignore the value if the stream
6596 // has not been initialized yet
6597 if (!this._readableState) {
6598 return;
6599 } // backward compatibility, the user is explicitly
6600 // managing destroyed
6601
6602
6603 this._readableState.destroyed = value;
6604 }
6605});
6606Readable.prototype.destroy = destroyImpl.destroy;
6607Readable.prototype._undestroy = destroyImpl.undestroy;
6608
6609Readable.prototype._destroy = function (err, cb) {
6610 cb(err);
6611}; // Manually shove something into the read() buffer.
6612// This returns true if the highWaterMark has not been hit yet,
6613// similar to how Writable.write() returns true if you should
6614// write() some more.
6615
6616
6617Readable.prototype.push = function (chunk, encoding) {
6618 var state = this._readableState;
6619 var skipChunkCheck;
6620
6621 if (!state.objectMode) {
6622 if (typeof chunk === 'string') {
6623 encoding = encoding || state.defaultEncoding;
6624
6625 if (encoding !== state.encoding) {
6626 chunk = Buffer.from(chunk, encoding);
6627 encoding = '';
6628 }
6629
6630 skipChunkCheck = true;
6631 }
6632 } else {
6633 skipChunkCheck = true;
6634 }
6635
6636 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
6637}; // Unshift should *always* be something directly out of read()
6638
6639
6640Readable.prototype.unshift = function (chunk) {
6641 return readableAddChunk(this, chunk, null, true, false);
6642};
6643
6644function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
6645 debug('readableAddChunk', chunk);
6646 var state = stream._readableState;
6647
6648 if (chunk === null) {
6649 state.reading = false;
6650 onEofChunk(stream, state);
6651 } else {
6652 var er;
6653 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
6654
6655 if (er) {
6656 stream.emit('error', er);
6657 } else if (state.objectMode || chunk && chunk.length > 0) {
6658 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
6659 chunk = _uint8ArrayToBuffer(chunk);
6660 }
6661
6662 if (addToFront) {
6663 if (state.endEmitted) stream.emit('error', new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
6664 } else if (state.ended) {
6665 stream.emit('error', new ERR_STREAM_PUSH_AFTER_EOF());
6666 } else if (state.destroyed) {
6667 return false;
6668 } else {
6669 state.reading = false;
6670
6671 if (state.decoder && !encoding) {
6672 chunk = state.decoder.write(chunk);
6673 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
6674 } else {
6675 addChunk(stream, state, chunk, false);
6676 }
6677 }
6678 } else if (!addToFront) {
6679 state.reading = false;
6680 maybeReadMore(stream, state);
6681 }
6682 } // We can push more data if we are below the highWaterMark.
6683 // Also, if we have no data yet, we can stand some more bytes.
6684 // This is to work around cases where hwm=0, such as the repl.
6685
6686
6687 return !state.ended && (state.length < state.highWaterMark || state.length === 0);
6688}
6689
6690function addChunk(stream, state, chunk, addToFront) {
6691 if (state.flowing && state.length === 0 && !state.sync) {
6692 state.awaitDrain = 0;
6693 stream.emit('data', chunk);
6694 } else {
6695 // update the buffer info.
6696 state.length += state.objectMode ? 1 : chunk.length;
6697 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
6698 if (state.needReadable) emitReadable(stream);
6699 }
6700
6701 maybeReadMore(stream, state);
6702}
6703
6704function chunkInvalid(state, chunk) {
6705 var er;
6706
6707 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
6708 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
6709 }
6710
6711 return er;
6712}
6713
6714Readable.prototype.isPaused = function () {
6715 return this._readableState.flowing === false;
6716}; // backwards compatibility.
6717
6718
6719Readable.prototype.setEncoding = function (enc) {
6720 if (!StringDecoder) StringDecoder = _dereq_(96).StringDecoder;
6721 this._readableState.decoder = new StringDecoder(enc); // if setEncoding(null), decoder.encoding equals utf8
6722
6723 this._readableState.encoding = this._readableState.decoder.encoding;
6724 return this;
6725}; // Don't raise the hwm > 8MB
6726
6727
6728var MAX_HWM = 0x800000;
6729
6730function computeNewHighWaterMark(n) {
6731 if (n >= MAX_HWM) {
6732 n = MAX_HWM;
6733 } else {
6734 // Get the next highest power of 2 to prevent increasing hwm excessively in
6735 // tiny amounts
6736 n--;
6737 n |= n >>> 1;
6738 n |= n >>> 2;
6739 n |= n >>> 4;
6740 n |= n >>> 8;
6741 n |= n >>> 16;
6742 n++;
6743 }
6744
6745 return n;
6746} // This function is designed to be inlinable, so please take care when making
6747// changes to the function body.
6748
6749
6750function howMuchToRead(n, state) {
6751 if (n <= 0 || state.length === 0 && state.ended) return 0;
6752 if (state.objectMode) return 1;
6753
6754 if (n !== n) {
6755 // Only flow one buffer at a time
6756 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
6757 } // If we're asking for more than the current hwm, then raise the hwm.
6758
6759
6760 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
6761 if (n <= state.length) return n; // Don't have enough
6762
6763 if (!state.ended) {
6764 state.needReadable = true;
6765 return 0;
6766 }
6767
6768 return state.length;
6769} // you can override either this method, or the async _read(n) below.
6770
6771
6772Readable.prototype.read = function (n) {
6773 debug('read', n);
6774 n = parseInt(n, 10);
6775 var state = this._readableState;
6776 var nOrig = n;
6777 if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we
6778 // already have a bunch of data in the buffer, then just trigger
6779 // the 'readable' event and move on.
6780
6781 if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
6782 debug('read: emitReadable', state.length, state.ended);
6783 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
6784 return null;
6785 }
6786
6787 n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.
6788
6789 if (n === 0 && state.ended) {
6790 if (state.length === 0) endReadable(this);
6791 return null;
6792 } // All the actual chunk generation logic needs to be
6793 // *below* the call to _read. The reason is that in certain
6794 // synthetic stream cases, such as passthrough streams, _read
6795 // may be a completely synchronous operation which may change
6796 // the state of the read buffer, providing enough data when
6797 // before there was *not* enough.
6798 //
6799 // So, the steps are:
6800 // 1. Figure out what the state of things will be after we do
6801 // a read from the buffer.
6802 //
6803 // 2. If that resulting state will trigger a _read, then call _read.
6804 // Note that this may be asynchronous, or synchronous. Yes, it is
6805 // deeply ugly to write APIs this way, but that still doesn't mean
6806 // that the Readable class should behave improperly, as streams are
6807 // designed to be sync/async agnostic.
6808 // Take note if the _read call is sync or async (ie, if the read call
6809 // has returned yet), so that we know whether or not it's safe to emit
6810 // 'readable' etc.
6811 //
6812 // 3. Actually pull the requested chunks out of the buffer and return.
6813 // if we need a readable event, then we need to do some reading.
6814
6815
6816 var doRead = state.needReadable;
6817 debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some
6818
6819 if (state.length === 0 || state.length - n < state.highWaterMark) {
6820 doRead = true;
6821 debug('length less than watermark', doRead);
6822 } // however, if we've ended, then there's no point, and if we're already
6823 // reading, then it's unnecessary.
6824
6825
6826 if (state.ended || state.reading) {
6827 doRead = false;
6828 debug('reading or ended', doRead);
6829 } else if (doRead) {
6830 debug('do read');
6831 state.reading = true;
6832 state.sync = true; // if the length is currently zero, then we *need* a readable event.
6833
6834 if (state.length === 0) state.needReadable = true; // call internal read method
6835
6836 this._read(state.highWaterMark);
6837
6838 state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
6839 // and we need to re-evaluate how much data we can return to the user.
6840
6841 if (!state.reading) n = howMuchToRead(nOrig, state);
6842 }
6843
6844 var ret;
6845 if (n > 0) ret = fromList(n, state);else ret = null;
6846
6847 if (ret === null) {
6848 state.needReadable = true;
6849 n = 0;
6850 } else {
6851 state.length -= n;
6852 state.awaitDrain = 0;
6853 }
6854
6855 if (state.length === 0) {
6856 // If we have nothing in the buffer, then we want to know
6857 // as soon as we *do* get something into the buffer.
6858 if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
6859
6860 if (nOrig !== n && state.ended) endReadable(this);
6861 }
6862
6863 if (ret !== null) this.emit('data', ret);
6864 return ret;
6865};
6866
6867function onEofChunk(stream, state) {
6868 if (state.ended) return;
6869
6870 if (state.decoder) {
6871 var chunk = state.decoder.end();
6872
6873 if (chunk && chunk.length) {
6874 state.buffer.push(chunk);
6875 state.length += state.objectMode ? 1 : chunk.length;
6876 }
6877 }
6878
6879 state.ended = true;
6880
6881 if (state.sync) {
6882 // if we are sync, wait until next tick to emit the data.
6883 // Otherwise we risk emitting data in the flow()
6884 // the readable code triggers during a read() call
6885 emitReadable(stream);
6886 } else {
6887 // emit 'readable' now to make sure it gets picked up.
6888 state.needReadable = false;
6889
6890 if (!state.emittedReadable) {
6891 state.emittedReadable = true;
6892 emitReadable_(stream);
6893 }
6894 }
6895} // Don't emit readable right away in sync mode, because this can trigger
6896// another read() call => stack overflow. This way, it might trigger
6897// a nextTick recursion warning, but that's not so bad.
6898
6899
6900function emitReadable(stream) {
6901 var state = stream._readableState;
6902 state.needReadable = false;
6903
6904 if (!state.emittedReadable) {
6905 debug('emitReadable', state.flowing);
6906 state.emittedReadable = true;
6907 process.nextTick(emitReadable_, stream);
6908 }
6909}
6910
6911function emitReadable_(stream) {
6912 var state = stream._readableState;
6913 debug('emitReadable_', state.destroyed, state.length, state.ended);
6914
6915 if (!state.destroyed && (state.length || state.ended)) {
6916 stream.emit('readable');
6917 } // The stream needs another readable event if
6918 // 1. It is not flowing, as the flow mechanism will take
6919 // care of it.
6920 // 2. It is not ended.
6921 // 3. It is below the highWaterMark, so we can schedule
6922 // another readable later.
6923
6924
6925 state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
6926 flow(stream);
6927} // at this point, the user has presumably seen the 'readable' event,
6928// and called read() to consume some data. that may have triggered
6929// in turn another _read(n) call, in which case reading = true if
6930// it's in progress.
6931// However, if we're not ended, or reading, and the length < hwm,
6932// then go ahead and try to read some more preemptively.
6933
6934
6935function maybeReadMore(stream, state) {
6936 if (!state.readingMore) {
6937 state.readingMore = true;
6938 process.nextTick(maybeReadMore_, stream, state);
6939 }
6940}
6941
6942function maybeReadMore_(stream, state) {
6943 // Attempt to read more data if we should.
6944 //
6945 // The conditions for reading more data are (one of):
6946 // - Not enough data buffered (state.length < state.highWaterMark). The loop
6947 // is responsible for filling the buffer with enough data if such data
6948 // is available. If highWaterMark is 0 and we are not in the flowing mode
6949 // we should _not_ attempt to buffer any extra data. We'll get more data
6950 // when the stream consumer calls read() instead.
6951 // - No data in the buffer, and the stream is in flowing mode. In this mode
6952 // the loop below is responsible for ensuring read() is called. Failing to
6953 // call read here would abort the flow and there's no other mechanism for
6954 // continuing the flow if the stream consumer has just subscribed to the
6955 // 'data' event.
6956 //
6957 // In addition to the above conditions to keep reading data, the following
6958 // conditions prevent the data from being read:
6959 // - The stream has ended (state.ended).
6960 // - There is already a pending 'read' operation (state.reading). This is a
6961 // case where the the stream has called the implementation defined _read()
6962 // method, but they are processing the call asynchronously and have _not_
6963 // called push() with new data. In this case we skip performing more
6964 // read()s. The execution ends in this method again after the _read() ends
6965 // up calling push() with more data.
6966 while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
6967 var len = state.length;
6968 debug('maybeReadMore read 0');
6969 stream.read(0);
6970 if (len === state.length) // didn't get any data, stop spinning.
6971 break;
6972 }
6973
6974 state.readingMore = false;
6975} // abstract method. to be overridden in specific implementation classes.
6976// call cb(er, data) where data is <= n in length.
6977// for virtual (non-string, non-buffer) streams, "length" is somewhat
6978// arbitrary, and perhaps not very meaningful.
6979
6980
6981Readable.prototype._read = function (n) {
6982 this.emit('error', new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
6983};
6984
6985Readable.prototype.pipe = function (dest, pipeOpts) {
6986 var src = this;
6987 var state = this._readableState;
6988
6989 switch (state.pipesCount) {
6990 case 0:
6991 state.pipes = dest;
6992 break;
6993
6994 case 1:
6995 state.pipes = [state.pipes, dest];
6996 break;
6997
6998 default:
6999 state.pipes.push(dest);
7000 break;
7001 }
7002
7003 state.pipesCount += 1;
7004 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
7005 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
7006 var endFn = doEnd ? onend : unpipe;
7007 if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
7008 dest.on('unpipe', onunpipe);
7009
7010 function onunpipe(readable, unpipeInfo) {
7011 debug('onunpipe');
7012
7013 if (readable === src) {
7014 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
7015 unpipeInfo.hasUnpiped = true;
7016 cleanup();
7017 }
7018 }
7019 }
7020
7021 function onend() {
7022 debug('onend');
7023 dest.end();
7024 } // when the dest drains, it reduces the awaitDrain counter
7025 // on the source. This would be more elegant with a .once()
7026 // handler in flow(), but adding and removing repeatedly is
7027 // too slow.
7028
7029
7030 var ondrain = pipeOnDrain(src);
7031 dest.on('drain', ondrain);
7032 var cleanedUp = false;
7033
7034 function cleanup() {
7035 debug('cleanup'); // cleanup event handlers once the pipe is broken
7036
7037 dest.removeListener('close', onclose);
7038 dest.removeListener('finish', onfinish);
7039 dest.removeListener('drain', ondrain);
7040 dest.removeListener('error', onerror);
7041 dest.removeListener('unpipe', onunpipe);
7042 src.removeListener('end', onend);
7043 src.removeListener('end', unpipe);
7044 src.removeListener('data', ondata);
7045 cleanedUp = true; // if the reader is waiting for a drain event from this
7046 // specific writer, then it would cause it to never start
7047 // flowing again.
7048 // So, if this is awaiting a drain, then we just call it now.
7049 // If we don't know, then assume that we are waiting for one.
7050
7051 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
7052 }
7053
7054 src.on('data', ondata);
7055
7056 function ondata(chunk) {
7057 debug('ondata');
7058 var ret = dest.write(chunk);
7059 debug('dest.write', ret);
7060
7061 if (ret === false) {
7062 // If the user unpiped during `dest.write()`, it is possible
7063 // to get stuck in a permanently paused state if that write
7064 // also returned false.
7065 // => Check whether `dest` is still a piping destination.
7066 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
7067 debug('false write response, pause', state.awaitDrain);
7068 state.awaitDrain++;
7069 }
7070
7071 src.pause();
7072 }
7073 } // if the dest has an error, then stop piping into it.
7074 // however, don't suppress the throwing behavior for this.
7075
7076
7077 function onerror(er) {
7078 debug('onerror', er);
7079 unpipe();
7080 dest.removeListener('error', onerror);
7081 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
7082 } // Make sure our error handler is attached before userland ones.
7083
7084
7085 prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
7086
7087 function onclose() {
7088 dest.removeListener('finish', onfinish);
7089 unpipe();
7090 }
7091
7092 dest.once('close', onclose);
7093
7094 function onfinish() {
7095 debug('onfinish');
7096 dest.removeListener('close', onclose);
7097 unpipe();
7098 }
7099
7100 dest.once('finish', onfinish);
7101
7102 function unpipe() {
7103 debug('unpipe');
7104 src.unpipe(dest);
7105 } // tell the dest that it's being piped to
7106
7107
7108 dest.emit('pipe', src); // start the flow if it hasn't been started already.
7109
7110 if (!state.flowing) {
7111 debug('pipe resume');
7112 src.resume();
7113 }
7114
7115 return dest;
7116};
7117
7118function pipeOnDrain(src) {
7119 return function pipeOnDrainFunctionResult() {
7120 var state = src._readableState;
7121 debug('pipeOnDrain', state.awaitDrain);
7122 if (state.awaitDrain) state.awaitDrain--;
7123
7124 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
7125 state.flowing = true;
7126 flow(src);
7127 }
7128 };
7129}
7130
7131Readable.prototype.unpipe = function (dest) {
7132 var state = this._readableState;
7133 var unpipeInfo = {
7134 hasUnpiped: false
7135 }; // if we're not piping anywhere, then do nothing.
7136
7137 if (state.pipesCount === 0) return this; // just one destination. most common case.
7138
7139 if (state.pipesCount === 1) {
7140 // passed in one, but it's not the right one.
7141 if (dest && dest !== state.pipes) return this;
7142 if (!dest) dest = state.pipes; // got a match.
7143
7144 state.pipes = null;
7145 state.pipesCount = 0;
7146 state.flowing = false;
7147 if (dest) dest.emit('unpipe', this, unpipeInfo);
7148 return this;
7149 } // slow case. multiple pipe destinations.
7150
7151
7152 if (!dest) {
7153 // remove all.
7154 var dests = state.pipes;
7155 var len = state.pipesCount;
7156 state.pipes = null;
7157 state.pipesCount = 0;
7158 state.flowing = false;
7159
7160 for (var i = 0; i < len; i++) {
7161 dests[i].emit('unpipe', this, {
7162 hasUnpiped: false
7163 });
7164 }
7165
7166 return this;
7167 } // try to find the right one.
7168
7169
7170 var index = indexOf(state.pipes, dest);
7171 if (index === -1) return this;
7172 state.pipes.splice(index, 1);
7173 state.pipesCount -= 1;
7174 if (state.pipesCount === 1) state.pipes = state.pipes[0];
7175 dest.emit('unpipe', this, unpipeInfo);
7176 return this;
7177}; // set up data events if they are asked for
7178// Ensure readable listeners eventually get something
7179
7180
7181Readable.prototype.on = function (ev, fn) {
7182 var res = Stream.prototype.on.call(this, ev, fn);
7183 var state = this._readableState;
7184
7185 if (ev === 'data') {
7186 // update readableListening so that resume() may be a no-op
7187 // a few lines down. This is needed to support once('readable').
7188 state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused
7189
7190 if (state.flowing !== false) this.resume();
7191 } else if (ev === 'readable') {
7192 if (!state.endEmitted && !state.readableListening) {
7193 state.readableListening = state.needReadable = true;
7194 state.flowing = false;
7195 state.emittedReadable = false;
7196 debug('on readable', state.length, state.reading);
7197
7198 if (state.length) {
7199 emitReadable(this);
7200 } else if (!state.reading) {
7201 process.nextTick(nReadingNextTick, this);
7202 }
7203 }
7204 }
7205
7206 return res;
7207};
7208
7209Readable.prototype.addListener = Readable.prototype.on;
7210
7211Readable.prototype.removeListener = function (ev, fn) {
7212 var res = Stream.prototype.removeListener.call(this, ev, fn);
7213
7214 if (ev === 'readable') {
7215 // We need to check if there is someone still listening to
7216 // readable and reset the state. However this needs to happen
7217 // after readable has been emitted but before I/O (nextTick) to
7218 // support once('readable', fn) cycles. This means that calling
7219 // resume within the same tick will have no
7220 // effect.
7221 process.nextTick(updateReadableListening, this);
7222 }
7223
7224 return res;
7225};
7226
7227Readable.prototype.removeAllListeners = function (ev) {
7228 var res = Stream.prototype.removeAllListeners.apply(this, arguments);
7229
7230 if (ev === 'readable' || ev === undefined) {
7231 // We need to check if there is someone still listening to
7232 // readable and reset the state. However this needs to happen
7233 // after readable has been emitted but before I/O (nextTick) to
7234 // support once('readable', fn) cycles. This means that calling
7235 // resume within the same tick will have no
7236 // effect.
7237 process.nextTick(updateReadableListening, this);
7238 }
7239
7240 return res;
7241};
7242
7243function updateReadableListening(self) {
7244 var state = self._readableState;
7245 state.readableListening = self.listenerCount('readable') > 0;
7246
7247 if (state.resumeScheduled && !state.paused) {
7248 // flowing needs to be set to true now, otherwise
7249 // the upcoming resume will not flow.
7250 state.flowing = true; // crude way to check if we should resume
7251 } else if (self.listenerCount('data') > 0) {
7252 self.resume();
7253 }
7254}
7255
7256function nReadingNextTick(self) {
7257 debug('readable nexttick read 0');
7258 self.read(0);
7259} // pause() and resume() are remnants of the legacy readable stream API
7260// If the user uses them, then switch into old mode.
7261
7262
7263Readable.prototype.resume = function () {
7264 var state = this._readableState;
7265
7266 if (!state.flowing) {
7267 debug('resume'); // we flow only if there is no one listening
7268 // for readable, but we still have to call
7269 // resume()
7270
7271 state.flowing = !state.readableListening;
7272 resume(this, state);
7273 }
7274
7275 state.paused = false;
7276 return this;
7277};
7278
7279function resume(stream, state) {
7280 if (!state.resumeScheduled) {
7281 state.resumeScheduled = true;
7282 process.nextTick(resume_, stream, state);
7283 }
7284}
7285
7286function resume_(stream, state) {
7287 debug('resume', state.reading);
7288
7289 if (!state.reading) {
7290 stream.read(0);
7291 }
7292
7293 state.resumeScheduled = false;
7294 stream.emit('resume');
7295 flow(stream);
7296 if (state.flowing && !state.reading) stream.read(0);
7297}
7298
7299Readable.prototype.pause = function () {
7300 debug('call pause flowing=%j', this._readableState.flowing);
7301
7302 if (this._readableState.flowing !== false) {
7303 debug('pause');
7304 this._readableState.flowing = false;
7305 this.emit('pause');
7306 }
7307
7308 this._readableState.paused = true;
7309 return this;
7310};
7311
7312function flow(stream) {
7313 var state = stream._readableState;
7314 debug('flow', state.flowing);
7315
7316 while (state.flowing && stream.read() !== null) {
7317 ;
7318 }
7319} // wrap an old-style stream as the async data source.
7320// This is *not* part of the readable stream interface.
7321// It is an ugly unfortunate mess of history.
7322
7323
7324Readable.prototype.wrap = function (stream) {
7325 var _this = this;
7326
7327 var state = this._readableState;
7328 var paused = false;
7329 stream.on('end', function () {
7330 debug('wrapped end');
7331
7332 if (state.decoder && !state.ended) {
7333 var chunk = state.decoder.end();
7334 if (chunk && chunk.length) _this.push(chunk);
7335 }
7336
7337 _this.push(null);
7338 });
7339 stream.on('data', function (chunk) {
7340 debug('wrapped data');
7341 if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
7342
7343 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
7344
7345 var ret = _this.push(chunk);
7346
7347 if (!ret) {
7348 paused = true;
7349 stream.pause();
7350 }
7351 }); // proxy all the other methods.
7352 // important when wrapping filters and duplexes.
7353
7354 for (var i in stream) {
7355 if (this[i] === undefined && typeof stream[i] === 'function') {
7356 this[i] = function methodWrap(method) {
7357 return function methodWrapReturnFunction() {
7358 return stream[method].apply(stream, arguments);
7359 };
7360 }(i);
7361 }
7362 } // proxy certain important events.
7363
7364
7365 for (var n = 0; n < kProxyEvents.length; n++) {
7366 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
7367 } // when we try to consume some more bytes, simply unpause the
7368 // underlying stream.
7369
7370
7371 this._read = function (n) {
7372 debug('wrapped _read', n);
7373
7374 if (paused) {
7375 paused = false;
7376 stream.resume();
7377 }
7378 };
7379
7380 return this;
7381};
7382
7383if (typeof Symbol === 'function') {
7384 Readable.prototype[Symbol.asyncIterator] = function () {
7385 emitExperimentalWarning('Readable[Symbol.asyncIterator]');
7386
7387 if (createReadableStreamAsyncIterator === undefined) {
7388 createReadableStreamAsyncIterator = _dereq_(45);
7389 }
7390
7391 return createReadableStreamAsyncIterator(this);
7392 };
7393}
7394
7395Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
7396 // making it explicit this property is not enumerable
7397 // because otherwise some prototype manipulation in
7398 // userland will fail
7399 enumerable: false,
7400 get: function get() {
7401 return this._readableState.highWaterMark;
7402 }
7403});
7404Object.defineProperty(Readable.prototype, 'readableBuffer', {
7405 // making it explicit this property is not enumerable
7406 // because otherwise some prototype manipulation in
7407 // userland will fail
7408 enumerable: false,
7409 get: function get() {
7410 return this._readableState && this._readableState.buffer;
7411 }
7412});
7413Object.defineProperty(Readable.prototype, 'readableFlowing', {
7414 // making it explicit this property is not enumerable
7415 // because otherwise some prototype manipulation in
7416 // userland will fail
7417 enumerable: false,
7418 get: function get() {
7419 return this._readableState.flowing;
7420 },
7421 set: function set(state) {
7422 if (this._readableState) {
7423 this._readableState.flowing = state;
7424 }
7425 }
7426}); // exposed for testing purposes only.
7427
7428Readable._fromList = fromList;
7429Object.defineProperty(Readable.prototype, 'readableLength', {
7430 // making it explicit this property is not enumerable
7431 // because otherwise some prototype manipulation in
7432 // userland will fail
7433 enumerable: false,
7434 get: function get() {
7435 return this._readableState.length;
7436 }
7437}); // Pluck off n bytes from an array of buffers.
7438// Length is the combined lengths of all the buffers in the list.
7439// This function is designed to be inlinable, so please take care when making
7440// changes to the function body.
7441
7442function fromList(n, state) {
7443 // nothing buffered
7444 if (state.length === 0) return null;
7445 var ret;
7446 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
7447 // read it all, truncate the list
7448 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
7449 state.buffer.clear();
7450 } else {
7451 // read part of list
7452 ret = state.buffer.consume(n, state.decoder);
7453 }
7454 return ret;
7455}
7456
7457function endReadable(stream) {
7458 var state = stream._readableState;
7459 debug('endReadable', state.endEmitted);
7460
7461 if (!state.endEmitted) {
7462 state.ended = true;
7463 process.nextTick(endReadableNT, state, stream);
7464 }
7465}
7466
7467function endReadableNT(state, stream) {
7468 debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.
7469
7470 if (!state.endEmitted && state.length === 0) {
7471 state.endEmitted = true;
7472 stream.readable = false;
7473 stream.emit('end');
7474 }
7475}
7476
7477function indexOf(xs, x) {
7478 for (var i = 0, l = xs.length; i < l; i++) {
7479 if (xs[i] === x) return i;
7480 }
7481
7482 return -1;
7483}
7484}).call(this,_dereq_(69),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
7485},{"10":10,"12":12,"25":25,"31":31,"38":38,"39":39,"40":40,"45":45,"46":46,"47":47,"50":50,"51":51,"69":69,"96":96}],43:[function(_dereq_,module,exports){
7486// Copyright Joyent, Inc. and other Node contributors.
7487//
7488// Permission is hereby granted, free of charge, to any person obtaining a
7489// copy of this software and associated documentation files (the
7490// "Software"), to deal in the Software without restriction, including
7491// without limitation the rights to use, copy, modify, merge, publish,
7492// distribute, sublicense, and/or sell copies of the Software, and to permit
7493// persons to whom the Software is furnished to do so, subject to the
7494// following conditions:
7495//
7496// The above copyright notice and this permission notice shall be included
7497// in all copies or substantial portions of the Software.
7498//
7499// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7500// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7501// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7502// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7503// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7504// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7505// USE OR OTHER DEALINGS IN THE SOFTWARE.
7506// a transform stream is a readable/writable stream where you do
7507// something with the data. Sometimes it's called a "filter",
7508// but that's not a great name for it, since that implies a thing where
7509// some bits pass through, and others are simply ignored. (That would
7510// be a valid example of a transform, of course.)
7511//
7512// While the output is causally related to the input, it's not a
7513// necessarily symmetric or synchronous transformation. For example,
7514// a zlib stream might take multiple plain-text writes(), and then
7515// emit a single compressed chunk some time in the future.
7516//
7517// Here's how this works:
7518//
7519// The Transform stream has all the aspects of the readable and writable
7520// stream classes. When you write(chunk), that calls _write(chunk,cb)
7521// internally, and returns false if there's a lot of pending writes
7522// buffered up. When you call read(), that calls _read(n) until
7523// there's enough pending readable data buffered up.
7524//
7525// In a transform stream, the written data is placed in a buffer. When
7526// _read(n) is called, it transforms the queued up data, calling the
7527// buffered _write cb's as it consumes chunks. If consuming a single
7528// written chunk would result in multiple output chunks, then the first
7529// outputted bit calls the readcb, and subsequent chunks just go into
7530// the read buffer, and will cause it to emit 'readable' if necessary.
7531//
7532// This way, back-pressure is actually determined by the reading side,
7533// since _read has to be called to start processing a new chunk. However,
7534// a pathological inflate type of transform can cause excessive buffering
7535// here. For example, imagine a stream where every byte of input is
7536// interpreted as an integer from 0-255, and then results in that many
7537// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
7538// 1kb of data being output. In this case, you could write a very small
7539// amount of input, and end up with a very large amount of output. In
7540// such a pathological inflating mechanism, there'd be no way to tell
7541// the system to stop doing the transform. A single 4MB write could
7542// cause the system to run out of memory.
7543//
7544// However, even in such a pathological case, only a single written chunk
7545// would be consumed, and then the rest would wait (un-transformed) until
7546// the results of the previous transformed chunk were consumed.
7547'use strict';
7548
7549module.exports = Transform;
7550
7551var _require$codes = _dereq_(38).codes,
7552 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
7553 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
7554 ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
7555 ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
7556
7557var Duplex = _dereq_(40);
7558
7559_dereq_(31)(Transform, Duplex);
7560
7561function afterTransform(er, data) {
7562 var ts = this._transformState;
7563 ts.transforming = false;
7564 var cb = ts.writecb;
7565
7566 if (cb === null) {
7567 return this.emit('error', new ERR_MULTIPLE_CALLBACK());
7568 }
7569
7570 ts.writechunk = null;
7571 ts.writecb = null;
7572 if (data != null) // single equals check for both `null` and `undefined`
7573 this.push(data);
7574 cb(er);
7575 var rs = this._readableState;
7576 rs.reading = false;
7577
7578 if (rs.needReadable || rs.length < rs.highWaterMark) {
7579 this._read(rs.highWaterMark);
7580 }
7581}
7582
7583function Transform(options) {
7584 if (!(this instanceof Transform)) return new Transform(options);
7585 Duplex.call(this, options);
7586 this._transformState = {
7587 afterTransform: afterTransform.bind(this),
7588 needTransform: false,
7589 transforming: false,
7590 writecb: null,
7591 writechunk: null,
7592 writeencoding: null
7593 }; // start out asking for a readable event once data is transformed.
7594
7595 this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
7596 // that Readable wants before the first _read call, so unset the
7597 // sync guard flag.
7598
7599 this._readableState.sync = false;
7600
7601 if (options) {
7602 if (typeof options.transform === 'function') this._transform = options.transform;
7603 if (typeof options.flush === 'function') this._flush = options.flush;
7604 } // When the writable side finishes, then flush out anything remaining.
7605
7606
7607 this.on('prefinish', prefinish);
7608}
7609
7610function prefinish() {
7611 var _this = this;
7612
7613 if (typeof this._flush === 'function' && !this._readableState.destroyed) {
7614 this._flush(function (er, data) {
7615 done(_this, er, data);
7616 });
7617 } else {
7618 done(this, null, null);
7619 }
7620}
7621
7622Transform.prototype.push = function (chunk, encoding) {
7623 this._transformState.needTransform = false;
7624 return Duplex.prototype.push.call(this, chunk, encoding);
7625}; // This is the part where you do stuff!
7626// override this function in implementation classes.
7627// 'chunk' is an input chunk.
7628//
7629// Call `push(newChunk)` to pass along transformed output
7630// to the readable side. You may call 'push' zero or more times.
7631//
7632// Call `cb(err)` when you are done with this chunk. If you pass
7633// an error, then that'll put the hurt on the whole operation. If you
7634// never call cb(), then you'll never get another chunk.
7635
7636
7637Transform.prototype._transform = function (chunk, encoding, cb) {
7638 cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
7639};
7640
7641Transform.prototype._write = function (chunk, encoding, cb) {
7642 var ts = this._transformState;
7643 ts.writecb = cb;
7644 ts.writechunk = chunk;
7645 ts.writeencoding = encoding;
7646
7647 if (!ts.transforming) {
7648 var rs = this._readableState;
7649 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
7650 }
7651}; // Doesn't matter what the args are here.
7652// _transform does all the work.
7653// That we got here means that the readable side wants more data.
7654
7655
7656Transform.prototype._read = function (n) {
7657 var ts = this._transformState;
7658
7659 if (ts.writechunk !== null && !ts.transforming) {
7660 ts.transforming = true;
7661
7662 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
7663 } else {
7664 // mark that we need a transform, so that any data that comes in
7665 // will get processed, now that we've asked for it.
7666 ts.needTransform = true;
7667 }
7668};
7669
7670Transform.prototype._destroy = function (err, cb) {
7671 Duplex.prototype._destroy.call(this, err, function (err2) {
7672 cb(err2);
7673 });
7674};
7675
7676function done(stream, er, data) {
7677 if (er) return stream.emit('error', er);
7678 if (data != null) // single equals check for both `null` and `undefined`
7679 stream.push(data); // TODO(BridgeAR): Write a test for these two error cases
7680 // if there's nothing in the write buffer, then that means
7681 // that nothing more will ever be provided
7682
7683 if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
7684 if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
7685 return stream.push(null);
7686}
7687},{"31":31,"38":38,"40":40}],44:[function(_dereq_,module,exports){
7688(function (process,global){
7689// Copyright Joyent, Inc. and other Node contributors.
7690//
7691// Permission is hereby granted, free of charge, to any person obtaining a
7692// copy of this software and associated documentation files (the
7693// "Software"), to deal in the Software without restriction, including
7694// without limitation the rights to use, copy, modify, merge, publish,
7695// distribute, sublicense, and/or sell copies of the Software, and to permit
7696// persons to whom the Software is furnished to do so, subject to the
7697// following conditions:
7698//
7699// The above copyright notice and this permission notice shall be included
7700// in all copies or substantial portions of the Software.
7701//
7702// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7703// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7704// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7705// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7706// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7707// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7708// USE OR OTHER DEALINGS IN THE SOFTWARE.
7709// A bit simpler than readable streams.
7710// Implement an async ._write(chunk, encoding, cb), and it'll handle all
7711// the drain event emission and buffering.
7712'use strict';
7713
7714module.exports = Writable;
7715/* <replacement> */
7716
7717function WriteReq(chunk, encoding, cb) {
7718 this.chunk = chunk;
7719 this.encoding = encoding;
7720 this.callback = cb;
7721 this.next = null;
7722} // It seems a linked list but it is not
7723// there will be only 2 of these for each stream
7724
7725
7726function CorkedRequest(state) {
7727 var _this = this;
7728
7729 this.next = null;
7730 this.entry = null;
7731
7732 this.finish = function () {
7733 onCorkedFinish(_this, state);
7734 };
7735}
7736/* </replacement> */
7737
7738/*<replacement>*/
7739
7740
7741var Duplex;
7742/*</replacement>*/
7743
7744Writable.WritableState = WritableState;
7745/*<replacement>*/
7746
7747var internalUtil = {
7748 deprecate: _dereq_(115)
7749};
7750/*</replacement>*/
7751
7752/*<replacement>*/
7753
7754var Stream = _dereq_(51);
7755/*</replacement>*/
7756
7757
7758var Buffer = _dereq_(12).Buffer;
7759
7760var OurUint8Array = global.Uint8Array || function () {};
7761
7762function _uint8ArrayToBuffer(chunk) {
7763 return Buffer.from(chunk);
7764}
7765
7766function _isUint8Array(obj) {
7767 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
7768}
7769
7770var destroyImpl = _dereq_(47);
7771
7772var _require = _dereq_(50),
7773 getHighWaterMark = _require.getHighWaterMark;
7774
7775var _require$codes = _dereq_(38).codes,
7776 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
7777 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
7778 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
7779 ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
7780 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
7781 ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
7782 ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
7783 ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
7784
7785_dereq_(31)(Writable, Stream);
7786
7787function nop() {}
7788
7789function WritableState(options, stream, isDuplex) {
7790 Duplex = Duplex || _dereq_(40);
7791 options = options || {}; // Duplex streams are both readable and writable, but share
7792 // the same options object.
7793 // However, some cases require setting options to different
7794 // values for the readable and the writable sides of the duplex stream,
7795 // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
7796
7797 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream
7798 // contains buffers or objects.
7799
7800 this.objectMode = !!options.objectMode;
7801 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
7802 // Note: 0 is a valid value, means that we always return false if
7803 // the entire buffer is not flushed immediately on write()
7804
7805 this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called
7806
7807 this.finalCalled = false; // drain event flag.
7808
7809 this.needDrain = false; // at the start of calling end()
7810
7811 this.ending = false; // when end() has been called, and returned
7812
7813 this.ended = false; // when 'finish' is emitted
7814
7815 this.finished = false; // has it been destroyed
7816
7817 this.destroyed = false; // should we decode strings into buffers before passing to _write?
7818 // this is here so that some node-core streams can optimize string
7819 // handling at a lower level.
7820
7821 var noDecode = options.decodeStrings === false;
7822 this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string
7823 // encoding is 'binary' so we have to make this configurable.
7824 // Everything else in the universe uses 'utf8', though.
7825
7826 this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement
7827 // of how much we're waiting to get pushed to some underlying
7828 // socket or file.
7829
7830 this.length = 0; // a flag to see when we're in the middle of a write.
7831
7832 this.writing = false; // when true all writes will be buffered until .uncork() call
7833
7834 this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,
7835 // or on a later tick. We set this to true at first, because any
7836 // actions that shouldn't happen until "later" should generally also
7837 // not happen before the first write call.
7838
7839 this.sync = true; // a flag to know if we're processing previously buffered items, which
7840 // may call the _write() callback in the same tick, so that we don't
7841 // end up in an overlapped onwrite situation.
7842
7843 this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)
7844
7845 this.onwrite = function (er) {
7846 onwrite(stream, er);
7847 }; // the callback that the user supplies to write(chunk,encoding,cb)
7848
7849
7850 this.writecb = null; // the amount that is being written when _write is called.
7851
7852 this.writelen = 0;
7853 this.bufferedRequest = null;
7854 this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
7855 // this must be 0 before 'finish' can be emitted
7856
7857 this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
7858 // This is relevant for synchronous Transform streams
7859
7860 this.prefinished = false; // True if the error was already emitted and should not be thrown again
7861
7862 this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.
7863
7864 this.emitClose = options.emitClose !== false; // count buffered requests
7865
7866 this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always
7867 // one allocated and free to use, and we maintain at most two
7868
7869 this.corkedRequestsFree = new CorkedRequest(this);
7870}
7871
7872WritableState.prototype.getBuffer = function getBuffer() {
7873 var current = this.bufferedRequest;
7874 var out = [];
7875
7876 while (current) {
7877 out.push(current);
7878 current = current.next;
7879 }
7880
7881 return out;
7882};
7883
7884(function () {
7885 try {
7886 Object.defineProperty(WritableState.prototype, 'buffer', {
7887 get: internalUtil.deprecate(function writableStateBufferGetter() {
7888 return this.getBuffer();
7889 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
7890 });
7891 } catch (_) {}
7892})(); // Test _writableState for inheritance to account for Duplex streams,
7893// whose prototype chain only points to Readable.
7894
7895
7896var realHasInstance;
7897
7898if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
7899 realHasInstance = Function.prototype[Symbol.hasInstance];
7900 Object.defineProperty(Writable, Symbol.hasInstance, {
7901 value: function value(object) {
7902 if (realHasInstance.call(this, object)) return true;
7903 if (this !== Writable) return false;
7904 return object && object._writableState instanceof WritableState;
7905 }
7906 });
7907} else {
7908 realHasInstance = function realHasInstance(object) {
7909 return object instanceof this;
7910 };
7911}
7912
7913function Writable(options) {
7914 Duplex = Duplex || _dereq_(40); // Writable ctor is applied to Duplexes, too.
7915 // `realHasInstance` is necessary because using plain `instanceof`
7916 // would return false, as no `_writableState` property is attached.
7917 // Trying to use the custom `instanceof` for Writable here will also break the
7918 // Node.js LazyTransform implementation, which has a non-trivial getter for
7919 // `_writableState` that would lead to infinite recursion.
7920 // Checking for a Stream.Duplex instance is faster here instead of inside
7921 // the WritableState constructor, at least with V8 6.5
7922
7923 var isDuplex = this instanceof Duplex;
7924 if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
7925 this._writableState = new WritableState(options, this, isDuplex); // legacy.
7926
7927 this.writable = true;
7928
7929 if (options) {
7930 if (typeof options.write === 'function') this._write = options.write;
7931 if (typeof options.writev === 'function') this._writev = options.writev;
7932 if (typeof options.destroy === 'function') this._destroy = options.destroy;
7933 if (typeof options.final === 'function') this._final = options.final;
7934 }
7935
7936 Stream.call(this);
7937} // Otherwise people can pipe Writable streams, which is just wrong.
7938
7939
7940Writable.prototype.pipe = function () {
7941 this.emit('error', new ERR_STREAM_CANNOT_PIPE());
7942};
7943
7944function writeAfterEnd(stream, cb) {
7945 var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
7946
7947 stream.emit('error', er);
7948 process.nextTick(cb, er);
7949} // Checks that a user-supplied chunk is valid, especially for the particular
7950// mode the stream is in. Currently this means that `null` is never accepted
7951// and undefined/non-string values are only allowed in object mode.
7952
7953
7954function validChunk(stream, state, chunk, cb) {
7955 var er;
7956
7957 if (chunk === null) {
7958 er = new ERR_STREAM_NULL_VALUES();
7959 } else if (typeof chunk !== 'string' && !state.objectMode) {
7960 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
7961 }
7962
7963 if (er) {
7964 stream.emit('error', er);
7965 process.nextTick(cb, er);
7966 return false;
7967 }
7968
7969 return true;
7970}
7971
7972Writable.prototype.write = function (chunk, encoding, cb) {
7973 var state = this._writableState;
7974 var ret = false;
7975
7976 var isBuf = !state.objectMode && _isUint8Array(chunk);
7977
7978 if (isBuf && !Buffer.isBuffer(chunk)) {
7979 chunk = _uint8ArrayToBuffer(chunk);
7980 }
7981
7982 if (typeof encoding === 'function') {
7983 cb = encoding;
7984 encoding = null;
7985 }
7986
7987 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
7988 if (typeof cb !== 'function') cb = nop;
7989 if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
7990 state.pendingcb++;
7991 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
7992 }
7993 return ret;
7994};
7995
7996Writable.prototype.cork = function () {
7997 this._writableState.corked++;
7998};
7999
8000Writable.prototype.uncork = function () {
8001 var state = this._writableState;
8002
8003 if (state.corked) {
8004 state.corked--;
8005 if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
8006 }
8007};
8008
8009Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
8010 // node::ParseEncoding() requires lower case.
8011 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
8012 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);
8013 this._writableState.defaultEncoding = encoding;
8014 return this;
8015};
8016
8017Object.defineProperty(Writable.prototype, 'writableBuffer', {
8018 // making it explicit this property is not enumerable
8019 // because otherwise some prototype manipulation in
8020 // userland will fail
8021 enumerable: false,
8022 get: function get() {
8023 return this._writableState && this._writableState.getBuffer();
8024 }
8025});
8026
8027function decodeChunk(state, chunk, encoding) {
8028 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
8029 chunk = Buffer.from(chunk, encoding);
8030 }
8031
8032 return chunk;
8033}
8034
8035Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
8036 // making it explicit this property is not enumerable
8037 // because otherwise some prototype manipulation in
8038 // userland will fail
8039 enumerable: false,
8040 get: function get() {
8041 return this._writableState.highWaterMark;
8042 }
8043}); // if we're already writing something, then just put this
8044// in the queue, and wait our turn. Otherwise, call _write
8045// If we return false, then we need a drain event, so set that flag.
8046
8047function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
8048 if (!isBuf) {
8049 var newChunk = decodeChunk(state, chunk, encoding);
8050
8051 if (chunk !== newChunk) {
8052 isBuf = true;
8053 encoding = 'buffer';
8054 chunk = newChunk;
8055 }
8056 }
8057
8058 var len = state.objectMode ? 1 : chunk.length;
8059 state.length += len;
8060 var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
8061
8062 if (!ret) state.needDrain = true;
8063
8064 if (state.writing || state.corked) {
8065 var last = state.lastBufferedRequest;
8066 state.lastBufferedRequest = {
8067 chunk: chunk,
8068 encoding: encoding,
8069 isBuf: isBuf,
8070 callback: cb,
8071 next: null
8072 };
8073
8074 if (last) {
8075 last.next = state.lastBufferedRequest;
8076 } else {
8077 state.bufferedRequest = state.lastBufferedRequest;
8078 }
8079
8080 state.bufferedRequestCount += 1;
8081 } else {
8082 doWrite(stream, state, false, len, chunk, encoding, cb);
8083 }
8084
8085 return ret;
8086}
8087
8088function doWrite(stream, state, writev, len, chunk, encoding, cb) {
8089 state.writelen = len;
8090 state.writecb = cb;
8091 state.writing = true;
8092 state.sync = true;
8093 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);
8094 state.sync = false;
8095}
8096
8097function onwriteError(stream, state, sync, er, cb) {
8098 --state.pendingcb;
8099
8100 if (sync) {
8101 // defer the callback if we are being called synchronously
8102 // to avoid piling up things on the stack
8103 process.nextTick(cb, er); // this can emit finish, and it will always happen
8104 // after error
8105
8106 process.nextTick(finishMaybe, stream, state);
8107 stream._writableState.errorEmitted = true;
8108 stream.emit('error', er);
8109 } else {
8110 // the caller expect this to happen before if
8111 // it is async
8112 cb(er);
8113 stream._writableState.errorEmitted = true;
8114 stream.emit('error', er); // this can emit finish, but finish must
8115 // always follow error
8116
8117 finishMaybe(stream, state);
8118 }
8119}
8120
8121function onwriteStateUpdate(state) {
8122 state.writing = false;
8123 state.writecb = null;
8124 state.length -= state.writelen;
8125 state.writelen = 0;
8126}
8127
8128function onwrite(stream, er) {
8129 var state = stream._writableState;
8130 var sync = state.sync;
8131 var cb = state.writecb;
8132 if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
8133 onwriteStateUpdate(state);
8134 if (er) onwriteError(stream, state, sync, er, cb);else {
8135 // Check if we're actually ready to finish, but don't emit yet
8136 var finished = needFinish(state) || stream.destroyed;
8137
8138 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
8139 clearBuffer(stream, state);
8140 }
8141
8142 if (sync) {
8143 process.nextTick(afterWrite, stream, state, finished, cb);
8144 } else {
8145 afterWrite(stream, state, finished, cb);
8146 }
8147 }
8148}
8149
8150function afterWrite(stream, state, finished, cb) {
8151 if (!finished) onwriteDrain(stream, state);
8152 state.pendingcb--;
8153 cb();
8154 finishMaybe(stream, state);
8155} // Must force callback to be called on nextTick, so that we don't
8156// emit 'drain' before the write() consumer gets the 'false' return
8157// value, and has a chance to attach a 'drain' listener.
8158
8159
8160function onwriteDrain(stream, state) {
8161 if (state.length === 0 && state.needDrain) {
8162 state.needDrain = false;
8163 stream.emit('drain');
8164 }
8165} // if there's something in the buffer waiting, then process it
8166
8167
8168function clearBuffer(stream, state) {
8169 state.bufferProcessing = true;
8170 var entry = state.bufferedRequest;
8171
8172 if (stream._writev && entry && entry.next) {
8173 // Fast case, write everything using _writev()
8174 var l = state.bufferedRequestCount;
8175 var buffer = new Array(l);
8176 var holder = state.corkedRequestsFree;
8177 holder.entry = entry;
8178 var count = 0;
8179 var allBuffers = true;
8180
8181 while (entry) {
8182 buffer[count] = entry;
8183 if (!entry.isBuf) allBuffers = false;
8184 entry = entry.next;
8185 count += 1;
8186 }
8187
8188 buffer.allBuffers = allBuffers;
8189 doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
8190 // as the hot path ends with doWrite
8191
8192 state.pendingcb++;
8193 state.lastBufferedRequest = null;
8194
8195 if (holder.next) {
8196 state.corkedRequestsFree = holder.next;
8197 holder.next = null;
8198 } else {
8199 state.corkedRequestsFree = new CorkedRequest(state);
8200 }
8201
8202 state.bufferedRequestCount = 0;
8203 } else {
8204 // Slow case, write chunks one-by-one
8205 while (entry) {
8206 var chunk = entry.chunk;
8207 var encoding = entry.encoding;
8208 var cb = entry.callback;
8209 var len = state.objectMode ? 1 : chunk.length;
8210 doWrite(stream, state, false, len, chunk, encoding, cb);
8211 entry = entry.next;
8212 state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then
8213 // it means that we need to wait until it does.
8214 // also, that means that the chunk and cb are currently
8215 // being processed, so move the buffer counter past them.
8216
8217 if (state.writing) {
8218 break;
8219 }
8220 }
8221
8222 if (entry === null) state.lastBufferedRequest = null;
8223 }
8224
8225 state.bufferedRequest = entry;
8226 state.bufferProcessing = false;
8227}
8228
8229Writable.prototype._write = function (chunk, encoding, cb) {
8230 cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
8231};
8232
8233Writable.prototype._writev = null;
8234
8235Writable.prototype.end = function (chunk, encoding, cb) {
8236 var state = this._writableState;
8237
8238 if (typeof chunk === 'function') {
8239 cb = chunk;
8240 chunk = null;
8241 encoding = null;
8242 } else if (typeof encoding === 'function') {
8243 cb = encoding;
8244 encoding = null;
8245 }
8246
8247 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks
8248
8249 if (state.corked) {
8250 state.corked = 1;
8251 this.uncork();
8252 } // ignore unnecessary end() calls.
8253
8254
8255 if (!state.ending) endWritable(this, state, cb);
8256 return this;
8257};
8258
8259Object.defineProperty(Writable.prototype, 'writableLength', {
8260 // making it explicit this property is not enumerable
8261 // because otherwise some prototype manipulation in
8262 // userland will fail
8263 enumerable: false,
8264 get: function get() {
8265 return this._writableState.length;
8266 }
8267});
8268
8269function needFinish(state) {
8270 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
8271}
8272
8273function callFinal(stream, state) {
8274 stream._final(function (err) {
8275 state.pendingcb--;
8276
8277 if (err) {
8278 stream.emit('error', err);
8279 }
8280
8281 state.prefinished = true;
8282 stream.emit('prefinish');
8283 finishMaybe(stream, state);
8284 });
8285}
8286
8287function prefinish(stream, state) {
8288 if (!state.prefinished && !state.finalCalled) {
8289 if (typeof stream._final === 'function' && !state.destroyed) {
8290 state.pendingcb++;
8291 state.finalCalled = true;
8292 process.nextTick(callFinal, stream, state);
8293 } else {
8294 state.prefinished = true;
8295 stream.emit('prefinish');
8296 }
8297 }
8298}
8299
8300function finishMaybe(stream, state) {
8301 var need = needFinish(state);
8302
8303 if (need) {
8304 prefinish(stream, state);
8305
8306 if (state.pendingcb === 0) {
8307 state.finished = true;
8308 stream.emit('finish');
8309 }
8310 }
8311
8312 return need;
8313}
8314
8315function endWritable(stream, state, cb) {
8316 state.ending = true;
8317 finishMaybe(stream, state);
8318
8319 if (cb) {
8320 if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
8321 }
8322
8323 state.ended = true;
8324 stream.writable = false;
8325}
8326
8327function onCorkedFinish(corkReq, state, err) {
8328 var entry = corkReq.entry;
8329 corkReq.entry = null;
8330
8331 while (entry) {
8332 var cb = entry.callback;
8333 state.pendingcb--;
8334 cb(err);
8335 entry = entry.next;
8336 } // reuse the free corkReq.
8337
8338
8339 state.corkedRequestsFree.next = corkReq;
8340}
8341
8342Object.defineProperty(Writable.prototype, 'destroyed', {
8343 // making it explicit this property is not enumerable
8344 // because otherwise some prototype manipulation in
8345 // userland will fail
8346 enumerable: false,
8347 get: function get() {
8348 if (this._writableState === undefined) {
8349 return false;
8350 }
8351
8352 return this._writableState.destroyed;
8353 },
8354 set: function set(value) {
8355 // we ignore the value if the stream
8356 // has not been initialized yet
8357 if (!this._writableState) {
8358 return;
8359 } // backward compatibility, the user is explicitly
8360 // managing destroyed
8361
8362
8363 this._writableState.destroyed = value;
8364 }
8365});
8366Writable.prototype.destroy = destroyImpl.destroy;
8367Writable.prototype._undestroy = destroyImpl.undestroy;
8368
8369Writable.prototype._destroy = function (err, cb) {
8370 cb(err);
8371};
8372}).call(this,_dereq_(69),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
8373},{"115":115,"12":12,"31":31,"38":38,"40":40,"47":47,"50":50,"51":51,"69":69}],45:[function(_dereq_,module,exports){
8374(function (process){
8375'use strict';
8376
8377var _Object$setPrototypeO;
8378
8379function _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; }
8380
8381var finished = _dereq_(48);
8382
8383var kLastResolve = Symbol('lastResolve');
8384var kLastReject = Symbol('lastReject');
8385var kError = Symbol('error');
8386var kEnded = Symbol('ended');
8387var kLastPromise = Symbol('lastPromise');
8388var kHandlePromise = Symbol('handlePromise');
8389var kStream = Symbol('stream');
8390
8391function createIterResult(value, done) {
8392 return {
8393 value: value,
8394 done: done
8395 };
8396}
8397
8398function readAndResolve(iter) {
8399 var resolve = iter[kLastResolve];
8400
8401 if (resolve !== null) {
8402 var data = iter[kStream].read(); // we defer if data is null
8403 // we can be expecting either 'end' or
8404 // 'error'
8405
8406 if (data !== null) {
8407 iter[kLastPromise] = null;
8408 iter[kLastResolve] = null;
8409 iter[kLastReject] = null;
8410 resolve(createIterResult(data, false));
8411 }
8412 }
8413}
8414
8415function onReadable(iter) {
8416 // we wait for the next tick, because it might
8417 // emit an error with process.nextTick
8418 process.nextTick(readAndResolve, iter);
8419}
8420
8421function wrapForNext(lastPromise, iter) {
8422 return function (resolve, reject) {
8423 lastPromise.then(function () {
8424 if (iter[kEnded]) {
8425 resolve(createIterResult(undefined, true));
8426 return;
8427 }
8428
8429 iter[kHandlePromise](resolve, reject);
8430 }, reject);
8431 };
8432}
8433
8434var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
8435var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
8436 get stream() {
8437 return this[kStream];
8438 },
8439
8440 next: function next() {
8441 var _this = this;
8442
8443 // if we have detected an error in the meanwhile
8444 // reject straight away
8445 var error = this[kError];
8446
8447 if (error !== null) {
8448 return Promise.reject(error);
8449 }
8450
8451 if (this[kEnded]) {
8452 return Promise.resolve(createIterResult(undefined, true));
8453 }
8454
8455 if (this[kStream].destroyed) {
8456 // We need to defer via nextTick because if .destroy(err) is
8457 // called, the error will be emitted via nextTick, and
8458 // we cannot guarantee that there is no error lingering around
8459 // waiting to be emitted.
8460 return new Promise(function (resolve, reject) {
8461 process.nextTick(function () {
8462 if (_this[kError]) {
8463 reject(_this[kError]);
8464 } else {
8465 resolve(createIterResult(undefined, true));
8466 }
8467 });
8468 });
8469 } // if we have multiple next() calls
8470 // we will wait for the previous Promise to finish
8471 // this logic is optimized to support for await loops,
8472 // where next() is only called once at a time
8473
8474
8475 var lastPromise = this[kLastPromise];
8476 var promise;
8477
8478 if (lastPromise) {
8479 promise = new Promise(wrapForNext(lastPromise, this));
8480 } else {
8481 // fast path needed to support multiple this.push()
8482 // without triggering the next() queue
8483 var data = this[kStream].read();
8484
8485 if (data !== null) {
8486 return Promise.resolve(createIterResult(data, false));
8487 }
8488
8489 promise = new Promise(this[kHandlePromise]);
8490 }
8491
8492 this[kLastPromise] = promise;
8493 return promise;
8494 }
8495}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
8496 return this;
8497}), _defineProperty(_Object$setPrototypeO, "return", function _return() {
8498 var _this2 = this;
8499
8500 // destroy(err, cb) is a private API
8501 // we can guarantee we have that here, because we control the
8502 // Readable class this is attached to
8503 return new Promise(function (resolve, reject) {
8504 _this2[kStream].destroy(null, function (err) {
8505 if (err) {
8506 reject(err);
8507 return;
8508 }
8509
8510 resolve(createIterResult(undefined, true));
8511 });
8512 });
8513}), _Object$setPrototypeO), AsyncIteratorPrototype);
8514
8515var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
8516 var _Object$create;
8517
8518 var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
8519 value: stream,
8520 writable: true
8521 }), _defineProperty(_Object$create, kLastResolve, {
8522 value: null,
8523 writable: true
8524 }), _defineProperty(_Object$create, kLastReject, {
8525 value: null,
8526 writable: true
8527 }), _defineProperty(_Object$create, kError, {
8528 value: null,
8529 writable: true
8530 }), _defineProperty(_Object$create, kEnded, {
8531 value: stream._readableState.endEmitted,
8532 writable: true
8533 }), _defineProperty(_Object$create, kHandlePromise, {
8534 value: function value(resolve, reject) {
8535 var data = iterator[kStream].read();
8536
8537 if (data) {
8538 iterator[kLastPromise] = null;
8539 iterator[kLastResolve] = null;
8540 iterator[kLastReject] = null;
8541 resolve(createIterResult(data, false));
8542 } else {
8543 iterator[kLastResolve] = resolve;
8544 iterator[kLastReject] = reject;
8545 }
8546 },
8547 writable: true
8548 }), _Object$create));
8549 iterator[kLastPromise] = null;
8550 finished(stream, function (err) {
8551 if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
8552 var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise
8553 // returned by next() and store the error
8554
8555 if (reject !== null) {
8556 iterator[kLastPromise] = null;
8557 iterator[kLastResolve] = null;
8558 iterator[kLastReject] = null;
8559 reject(err);
8560 }
8561
8562 iterator[kError] = err;
8563 return;
8564 }
8565
8566 var resolve = iterator[kLastResolve];
8567
8568 if (resolve !== null) {
8569 iterator[kLastPromise] = null;
8570 iterator[kLastResolve] = null;
8571 iterator[kLastReject] = null;
8572 resolve(createIterResult(undefined, true));
8573 }
8574
8575 iterator[kEnded] = true;
8576 });
8577 stream.on('readable', onReadable.bind(null, iterator));
8578 return iterator;
8579};
8580
8581module.exports = createReadableStreamAsyncIterator;
8582}).call(this,_dereq_(69))
8583},{"48":48,"69":69}],46:[function(_dereq_,module,exports){
8584'use strict';
8585
8586function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
8587
8588function _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; }
8589
8590var _require = _dereq_(12),
8591 Buffer = _require.Buffer;
8592
8593var _require2 = _dereq_(10),
8594 inspect = _require2.inspect;
8595
8596var custom = inspect && inspect.custom || 'inspect';
8597
8598function copyBuffer(src, target, offset) {
8599 Buffer.prototype.copy.call(src, target, offset);
8600}
8601
8602module.exports =
8603/*#__PURE__*/
8604function () {
8605 function BufferList() {
8606 this.head = null;
8607 this.tail = null;
8608 this.length = 0;
8609 }
8610
8611 var _proto = BufferList.prototype;
8612
8613 _proto.push = function push(v) {
8614 var entry = {
8615 data: v,
8616 next: null
8617 };
8618 if (this.length > 0) this.tail.next = entry;else this.head = entry;
8619 this.tail = entry;
8620 ++this.length;
8621 };
8622
8623 _proto.unshift = function unshift(v) {
8624 var entry = {
8625 data: v,
8626 next: this.head
8627 };
8628 if (this.length === 0) this.tail = entry;
8629 this.head = entry;
8630 ++this.length;
8631 };
8632
8633 _proto.shift = function shift() {
8634 if (this.length === 0) return;
8635 var ret = this.head.data;
8636 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
8637 --this.length;
8638 return ret;
8639 };
8640
8641 _proto.clear = function clear() {
8642 this.head = this.tail = null;
8643 this.length = 0;
8644 };
8645
8646 _proto.join = function join(s) {
8647 if (this.length === 0) return '';
8648 var p = this.head;
8649 var ret = '' + p.data;
8650
8651 while (p = p.next) {
8652 ret += s + p.data;
8653 }
8654
8655 return ret;
8656 };
8657
8658 _proto.concat = function concat(n) {
8659 if (this.length === 0) return Buffer.alloc(0);
8660 var ret = Buffer.allocUnsafe(n >>> 0);
8661 var p = this.head;
8662 var i = 0;
8663
8664 while (p) {
8665 copyBuffer(p.data, ret, i);
8666 i += p.data.length;
8667 p = p.next;
8668 }
8669
8670 return ret;
8671 } // Consumes a specified amount of bytes or characters from the buffered data.
8672 ;
8673
8674 _proto.consume = function consume(n, hasStrings) {
8675 var ret;
8676
8677 if (n < this.head.data.length) {
8678 // `slice` is the same for buffers and strings.
8679 ret = this.head.data.slice(0, n);
8680 this.head.data = this.head.data.slice(n);
8681 } else if (n === this.head.data.length) {
8682 // First chunk is a perfect match.
8683 ret = this.shift();
8684 } else {
8685 // Result spans more than one buffer.
8686 ret = hasStrings ? this._getString(n) : this._getBuffer(n);
8687 }
8688
8689 return ret;
8690 };
8691
8692 _proto.first = function first() {
8693 return this.head.data;
8694 } // Consumes a specified amount of characters from the buffered data.
8695 ;
8696
8697 _proto._getString = function _getString(n) {
8698 var p = this.head;
8699 var c = 1;
8700 var ret = p.data;
8701 n -= ret.length;
8702
8703 while (p = p.next) {
8704 var str = p.data;
8705 var nb = n > str.length ? str.length : n;
8706 if (nb === str.length) ret += str;else ret += str.slice(0, n);
8707 n -= nb;
8708
8709 if (n === 0) {
8710 if (nb === str.length) {
8711 ++c;
8712 if (p.next) this.head = p.next;else this.head = this.tail = null;
8713 } else {
8714 this.head = p;
8715 p.data = str.slice(nb);
8716 }
8717
8718 break;
8719 }
8720
8721 ++c;
8722 }
8723
8724 this.length -= c;
8725 return ret;
8726 } // Consumes a specified amount of bytes from the buffered data.
8727 ;
8728
8729 _proto._getBuffer = function _getBuffer(n) {
8730 var ret = Buffer.allocUnsafe(n);
8731 var p = this.head;
8732 var c = 1;
8733 p.data.copy(ret);
8734 n -= p.data.length;
8735
8736 while (p = p.next) {
8737 var buf = p.data;
8738 var nb = n > buf.length ? buf.length : n;
8739 buf.copy(ret, ret.length - n, 0, nb);
8740 n -= nb;
8741
8742 if (n === 0) {
8743 if (nb === buf.length) {
8744 ++c;
8745 if (p.next) this.head = p.next;else this.head = this.tail = null;
8746 } else {
8747 this.head = p;
8748 p.data = buf.slice(nb);
8749 }
8750
8751 break;
8752 }
8753
8754 ++c;
8755 }
8756
8757 this.length -= c;
8758 return ret;
8759 } // Make sure the linked list only shows the minimal necessary information.
8760 ;
8761
8762 _proto[custom] = function (_, options) {
8763 return inspect(this, _objectSpread({}, options, {
8764 // Only inspect one level.
8765 depth: 0,
8766 // It should not recurse.
8767 customInspect: false
8768 }));
8769 };
8770
8771 return BufferList;
8772}();
8773},{"10":10,"12":12}],47:[function(_dereq_,module,exports){
8774(function (process){
8775'use strict'; // undocumented cb() API, needed for core, not for public API
8776
8777function destroy(err, cb) {
8778 var _this = this;
8779
8780 var readableDestroyed = this._readableState && this._readableState.destroyed;
8781 var writableDestroyed = this._writableState && this._writableState.destroyed;
8782
8783 if (readableDestroyed || writableDestroyed) {
8784 if (cb) {
8785 cb(err);
8786 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
8787 process.nextTick(emitErrorNT, this, err);
8788 }
8789
8790 return this;
8791 } // we set destroyed to true before firing error callbacks in order
8792 // to make it re-entrance safe in case destroy() is called within callbacks
8793
8794
8795 if (this._readableState) {
8796 this._readableState.destroyed = true;
8797 } // if this is a duplex stream mark the writable part as destroyed as well
8798
8799
8800 if (this._writableState) {
8801 this._writableState.destroyed = true;
8802 }
8803
8804 this._destroy(err || null, function (err) {
8805 if (!cb && err) {
8806 process.nextTick(emitErrorAndCloseNT, _this, err);
8807
8808 if (_this._writableState) {
8809 _this._writableState.errorEmitted = true;
8810 }
8811 } else if (cb) {
8812 process.nextTick(emitCloseNT, _this);
8813 cb(err);
8814 } else {
8815 process.nextTick(emitCloseNT, _this);
8816 }
8817 });
8818
8819 return this;
8820}
8821
8822function emitErrorAndCloseNT(self, err) {
8823 emitErrorNT(self, err);
8824 emitCloseNT(self);
8825}
8826
8827function emitCloseNT(self) {
8828 if (self._writableState && !self._writableState.emitClose) return;
8829 if (self._readableState && !self._readableState.emitClose) return;
8830 self.emit('close');
8831}
8832
8833function undestroy() {
8834 if (this._readableState) {
8835 this._readableState.destroyed = false;
8836 this._readableState.reading = false;
8837 this._readableState.ended = false;
8838 this._readableState.endEmitted = false;
8839 }
8840
8841 if (this._writableState) {
8842 this._writableState.destroyed = false;
8843 this._writableState.ended = false;
8844 this._writableState.ending = false;
8845 this._writableState.finalCalled = false;
8846 this._writableState.prefinished = false;
8847 this._writableState.finished = false;
8848 this._writableState.errorEmitted = false;
8849 }
8850}
8851
8852function emitErrorNT(self, err) {
8853 self.emit('error', err);
8854}
8855
8856module.exports = {
8857 destroy: destroy,
8858 undestroy: undestroy
8859};
8860}).call(this,_dereq_(69))
8861},{"69":69}],48:[function(_dereq_,module,exports){
8862// Ported from https://github.com/mafintosh/end-of-stream with
8863// permission from the author, Mathias Buus (@mafintosh).
8864'use strict';
8865
8866var ERR_STREAM_PREMATURE_CLOSE = _dereq_(38).codes.ERR_STREAM_PREMATURE_CLOSE;
8867
8868function once(callback) {
8869 var called = false;
8870 return function () {
8871 if (called) return;
8872 called = true;
8873
8874 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
8875 args[_key] = arguments[_key];
8876 }
8877
8878 callback.apply(this, args);
8879 };
8880}
8881
8882function noop() {}
8883
8884function isRequest(stream) {
8885 return stream.setHeader && typeof stream.abort === 'function';
8886}
8887
8888function eos(stream, opts, callback) {
8889 if (typeof opts === 'function') return eos(stream, null, opts);
8890 if (!opts) opts = {};
8891 callback = once(callback || noop);
8892 var readable = opts.readable || opts.readable !== false && stream.readable;
8893 var writable = opts.writable || opts.writable !== false && stream.writable;
8894
8895 var onlegacyfinish = function onlegacyfinish() {
8896 if (!stream.writable) onfinish();
8897 };
8898
8899 var writableEnded = stream._writableState && stream._writableState.finished;
8900
8901 var onfinish = function onfinish() {
8902 writable = false;
8903 writableEnded = true;
8904 if (!readable) callback.call(stream);
8905 };
8906
8907 var readableEnded = stream._readableState && stream._readableState.endEmitted;
8908
8909 var onend = function onend() {
8910 readable = false;
8911 readableEnded = true;
8912 if (!writable) callback.call(stream);
8913 };
8914
8915 var onerror = function onerror(err) {
8916 callback.call(stream, err);
8917 };
8918
8919 var onclose = function onclose() {
8920 var err;
8921
8922 if (readable && !readableEnded) {
8923 if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
8924 return callback.call(stream, err);
8925 }
8926
8927 if (writable && !writableEnded) {
8928 if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
8929 return callback.call(stream, err);
8930 }
8931 };
8932
8933 var onrequest = function onrequest() {
8934 stream.req.on('finish', onfinish);
8935 };
8936
8937 if (isRequest(stream)) {
8938 stream.on('complete', onfinish);
8939 stream.on('abort', onclose);
8940 if (stream.req) onrequest();else stream.on('request', onrequest);
8941 } else if (writable && !stream._writableState) {
8942 // legacy streams
8943 stream.on('end', onlegacyfinish);
8944 stream.on('close', onlegacyfinish);
8945 }
8946
8947 stream.on('end', onend);
8948 stream.on('finish', onfinish);
8949 if (opts.error !== false) stream.on('error', onerror);
8950 stream.on('close', onclose);
8951 return function () {
8952 stream.removeListener('complete', onfinish);
8953 stream.removeListener('abort', onclose);
8954 stream.removeListener('request', onrequest);
8955 if (stream.req) stream.req.removeListener('finish', onfinish);
8956 stream.removeListener('end', onlegacyfinish);
8957 stream.removeListener('close', onlegacyfinish);
8958 stream.removeListener('finish', onfinish);
8959 stream.removeListener('end', onend);
8960 stream.removeListener('error', onerror);
8961 stream.removeListener('close', onclose);
8962 };
8963}
8964
8965module.exports = eos;
8966},{"38":38}],49:[function(_dereq_,module,exports){
8967// Ported from https://github.com/mafintosh/pump with
8968// permission from the author, Mathias Buus (@mafintosh).
8969'use strict';
8970
8971var eos;
8972
8973function once(callback) {
8974 var called = false;
8975 return function () {
8976 if (called) return;
8977 called = true;
8978 callback.apply(void 0, arguments);
8979 };
8980}
8981
8982var _require$codes = _dereq_(38).codes,
8983 ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
8984 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
8985
8986function noop(err) {
8987 // Rethrow the error if it exists to avoid swallowing it
8988 if (err) throw err;
8989}
8990
8991function isRequest(stream) {
8992 return stream.setHeader && typeof stream.abort === 'function';
8993}
8994
8995function destroyer(stream, reading, writing, callback) {
8996 callback = once(callback);
8997 var closed = false;
8998 stream.on('close', function () {
8999 closed = true;
9000 });
9001 if (eos === undefined) eos = _dereq_(48);
9002 eos(stream, {
9003 readable: reading,
9004 writable: writing
9005 }, function (err) {
9006 if (err) return callback(err);
9007 closed = true;
9008 callback();
9009 });
9010 var destroyed = false;
9011 return function (err) {
9012 if (closed) return;
9013 if (destroyed) return;
9014 destroyed = true; // request.destroy just do .end - .abort is what we want
9015
9016 if (isRequest(stream)) return stream.abort();
9017 if (typeof stream.destroy === 'function') return stream.destroy();
9018 callback(err || new ERR_STREAM_DESTROYED('pipe'));
9019 };
9020}
9021
9022function call(fn) {
9023 fn();
9024}
9025
9026function pipe(from, to) {
9027 return from.pipe(to);
9028}
9029
9030function popCallback(streams) {
9031 if (!streams.length) return noop;
9032 if (typeof streams[streams.length - 1] !== 'function') return noop;
9033 return streams.pop();
9034}
9035
9036function pipeline() {
9037 for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
9038 streams[_key] = arguments[_key];
9039 }
9040
9041 var callback = popCallback(streams);
9042 if (Array.isArray(streams[0])) streams = streams[0];
9043
9044 if (streams.length < 2) {
9045 throw new ERR_MISSING_ARGS('streams');
9046 }
9047
9048 var error;
9049 var destroys = streams.map(function (stream, i) {
9050 var reading = i < streams.length - 1;
9051 var writing = i > 0;
9052 return destroyer(stream, reading, writing, function (err) {
9053 if (!error) error = err;
9054 if (err) destroys.forEach(call);
9055 if (reading) return;
9056 destroys.forEach(call);
9057 callback(error);
9058 });
9059 });
9060 return streams.reduce(pipe);
9061}
9062
9063module.exports = pipeline;
9064},{"38":38,"48":48}],50:[function(_dereq_,module,exports){
9065'use strict';
9066
9067var ERR_INVALID_OPT_VALUE = _dereq_(38).codes.ERR_INVALID_OPT_VALUE;
9068
9069function highWaterMarkFrom(options, isDuplex, duplexKey) {
9070 return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
9071}
9072
9073function getHighWaterMark(state, options, duplexKey, isDuplex) {
9074 var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
9075
9076 if (hwm != null) {
9077 if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
9078 var name = isDuplex ? duplexKey : 'highWaterMark';
9079 throw new ERR_INVALID_OPT_VALUE(name, hwm);
9080 }
9081
9082 return Math.floor(hwm);
9083 } // Default value
9084
9085
9086 return state.objectMode ? 16 : 16 * 1024;
9087}
9088
9089module.exports = {
9090 getHighWaterMark: getHighWaterMark
9091};
9092},{"38":38}],51:[function(_dereq_,module,exports){
9093module.exports = _dereq_(25).EventEmitter;
9094
9095},{"25":25}],52:[function(_dereq_,module,exports){
9096exports = module.exports = _dereq_(42);
9097exports.Stream = exports;
9098exports.Readable = exports;
9099exports.Writable = _dereq_(44);
9100exports.Duplex = _dereq_(40);
9101exports.Transform = _dereq_(43);
9102exports.PassThrough = _dereq_(41);
9103exports.finished = _dereq_(48);
9104exports.pipeline = _dereq_(49);
9105
9106},{"40":40,"41":41,"42":42,"43":43,"44":44,"48":48,"49":49}],53:[function(_dereq_,module,exports){
9107arguments[4][21][0].apply(exports,arguments)
9108},{"21":21}],54:[function(_dereq_,module,exports){
9109var WriteError = _dereq_(36).WriteError
9110var promisify = _dereq_(57)
9111var getCallback = _dereq_(55).getCallback
9112var getOptions = _dereq_(55).getOptions
9113
9114function Batch (levelup) {
9115 this._levelup = levelup
9116 this.batch = levelup.db.batch()
9117 this.ops = []
9118 this.length = 0
9119}
9120
9121Batch.prototype.put = function (key, value) {
9122 try {
9123 this.batch.put(key, value)
9124 } catch (e) {
9125 throw new WriteError(e)
9126 }
9127
9128 this.ops.push({ type: 'put', key: key, value: value })
9129 this.length++
9130
9131 return this
9132}
9133
9134Batch.prototype.del = function (key) {
9135 try {
9136 this.batch.del(key)
9137 } catch (err) {
9138 throw new WriteError(err)
9139 }
9140
9141 this.ops.push({ type: 'del', key: key })
9142 this.length++
9143
9144 return this
9145}
9146
9147Batch.prototype.clear = function () {
9148 try {
9149 this.batch.clear()
9150 } catch (err) {
9151 throw new WriteError(err)
9152 }
9153
9154 this.ops = []
9155 this.length = 0
9156
9157 return this
9158}
9159
9160Batch.prototype.write = function (options, callback) {
9161 var levelup = this._levelup
9162 var ops = this.ops
9163 var promise
9164
9165 callback = getCallback(options, callback)
9166
9167 if (!callback) {
9168 callback = promisify()
9169 promise = callback.promise
9170 }
9171
9172 options = getOptions(options)
9173
9174 try {
9175 this.batch.write(options, function (err) {
9176 if (err) { return callback(new WriteError(err)) }
9177 levelup.emit('batch', ops)
9178 callback()
9179 })
9180 } catch (err) {
9181 throw new WriteError(err)
9182 }
9183
9184 return promise
9185}
9186
9187module.exports = Batch
9188
9189},{"36":36,"55":55,"57":57}],55:[function(_dereq_,module,exports){
9190exports.getCallback = function (options, callback) {
9191 return typeof options === 'function' ? options : callback
9192}
9193
9194exports.getOptions = function (options) {
9195 return typeof options === 'object' && options !== null ? options : {}
9196}
9197
9198},{}],56:[function(_dereq_,module,exports){
9199(function (process){
9200var EventEmitter = _dereq_(25).EventEmitter
9201var inherits = _dereq_(117).inherits
9202var extend = _dereq_(58)
9203var DeferredLevelDOWN = _dereq_(16)
9204var IteratorStream = _dereq_(37)
9205var Batch = _dereq_(54)
9206var errors = _dereq_(36)
9207var assert = _dereq_(5)
9208var promisify = _dereq_(57)
9209var getCallback = _dereq_(55).getCallback
9210var getOptions = _dereq_(55).getOptions
9211
9212var WriteError = errors.WriteError
9213var ReadError = errors.ReadError
9214var NotFoundError = errors.NotFoundError
9215var OpenError = errors.OpenError
9216var InitializationError = errors.InitializationError
9217
9218// Possible AbstractLevelDOWN#status values:
9219// - 'new' - newly created, not opened or closed
9220// - 'opening' - waiting for the database to be opened, post open()
9221// - 'open' - successfully opened the database, available for use
9222// - 'closing' - waiting for the database to be closed, post close()
9223// - 'closed' - database has been successfully closed, should not be
9224// used except for another open() operation
9225
9226function LevelUP (db, options, callback) {
9227 if (!(this instanceof LevelUP)) {
9228 return new LevelUP(db, options, callback)
9229 }
9230
9231 var error
9232
9233 EventEmitter.call(this)
9234 this.setMaxListeners(Infinity)
9235
9236 if (typeof options === 'function') {
9237 callback = options
9238 options = {}
9239 }
9240
9241 options = options || {}
9242
9243 if (!db || typeof db !== 'object') {
9244 error = new InitializationError('First argument must be an abstract-leveldown compliant store')
9245 if (typeof callback === 'function') {
9246 return process.nextTick(callback, error)
9247 }
9248 throw error
9249 }
9250
9251 assert.strictEqual(typeof db.status, 'string', '.status required, old abstract-leveldown')
9252
9253 this.options = getOptions(options)
9254 this._db = db
9255 this.db = new DeferredLevelDOWN(db)
9256 this.open(callback)
9257}
9258
9259LevelUP.prototype.emit = EventEmitter.prototype.emit
9260LevelUP.prototype.once = EventEmitter.prototype.once
9261inherits(LevelUP, EventEmitter)
9262
9263LevelUP.prototype.open = function (callback) {
9264 var self = this
9265 var promise
9266
9267 if (!callback) {
9268 callback = promisify()
9269 promise = callback.promise
9270 }
9271
9272 if (this.isOpen()) {
9273 process.nextTick(callback, null, self)
9274 return promise
9275 }
9276
9277 if (this._isOpening()) {
9278 this.once('open', function () { callback(null, self) })
9279 return promise
9280 }
9281
9282 this.emit('opening')
9283
9284 this.db.open(this.options, function (err) {
9285 if (err) {
9286 return callback(new OpenError(err))
9287 }
9288 self.db = self._db
9289 callback(null, self)
9290 self.emit('open')
9291 self.emit('ready')
9292 })
9293
9294 return promise
9295}
9296
9297LevelUP.prototype.close = function (callback) {
9298 var self = this
9299 var promise
9300
9301 if (!callback) {
9302 callback = promisify()
9303 promise = callback.promise
9304 }
9305
9306 if (this.isOpen()) {
9307 this.db.close(function () {
9308 self.emit('closed')
9309 callback.apply(null, arguments)
9310 })
9311 this.emit('closing')
9312 this.db = new DeferredLevelDOWN(this._db)
9313 } else if (this.isClosed()) {
9314 process.nextTick(callback)
9315 } else if (this.db.status === 'closing') {
9316 this.once('closed', callback)
9317 } else if (this._isOpening()) {
9318 this.once('open', function () {
9319 self.close(callback)
9320 })
9321 }
9322
9323 return promise
9324}
9325
9326LevelUP.prototype.isOpen = function () {
9327 return this.db.status === 'open'
9328}
9329
9330LevelUP.prototype._isOpening = function () {
9331 return this.db.status === 'opening'
9332}
9333
9334LevelUP.prototype.isClosed = function () {
9335 return (/^clos|new/).test(this.db.status)
9336}
9337
9338LevelUP.prototype.get = function (key, options, callback) {
9339 if (key === null || key === undefined) {
9340 throw new ReadError('get() requires a key argument')
9341 }
9342
9343 var promise
9344
9345 callback = getCallback(options, callback)
9346
9347 if (!callback) {
9348 callback = promisify()
9349 promise = callback.promise
9350 }
9351
9352 if (maybeError(this, callback)) { return promise }
9353
9354 options = getOptions(options)
9355
9356 this.db.get(key, options, function (err, value) {
9357 if (err) {
9358 if ((/notfound/i).test(err) || err.notFound) {
9359 err = new NotFoundError('Key not found in database [' + key + ']', err)
9360 } else {
9361 err = new ReadError(err)
9362 }
9363 return callback(err)
9364 }
9365 callback(null, value)
9366 })
9367
9368 return promise
9369}
9370
9371LevelUP.prototype.put = function (key, value, options, callback) {
9372 if (key === null || key === undefined) {
9373 throw new WriteError('put() requires a key argument')
9374 }
9375
9376 var self = this
9377 var promise
9378
9379 callback = getCallback(options, callback)
9380
9381 if (!callback) {
9382 callback = promisify()
9383 promise = callback.promise
9384 }
9385
9386 if (maybeError(this, callback)) { return promise }
9387
9388 options = getOptions(options)
9389
9390 this.db.put(key, value, options, function (err) {
9391 if (err) {
9392 return callback(new WriteError(err))
9393 }
9394 self.emit('put', key, value)
9395 callback()
9396 })
9397
9398 return promise
9399}
9400
9401LevelUP.prototype.del = function (key, options, callback) {
9402 if (key === null || key === undefined) {
9403 throw new WriteError('del() requires a key argument')
9404 }
9405
9406 var self = this
9407 var promise
9408
9409 callback = getCallback(options, callback)
9410
9411 if (!callback) {
9412 callback = promisify()
9413 promise = callback.promise
9414 }
9415
9416 if (maybeError(this, callback)) { return promise }
9417
9418 options = getOptions(options)
9419
9420 this.db.del(key, options, function (err) {
9421 if (err) {
9422 return callback(new WriteError(err))
9423 }
9424 self.emit('del', key)
9425 callback()
9426 })
9427
9428 return promise
9429}
9430
9431LevelUP.prototype.batch = function (arr, options, callback) {
9432 if (!arguments.length) {
9433 return new Batch(this)
9434 }
9435
9436 if (!Array.isArray(arr)) {
9437 throw new WriteError('batch() requires an array argument')
9438 }
9439
9440 var self = this
9441 var promise
9442
9443 callback = getCallback(options, callback)
9444
9445 if (!callback) {
9446 callback = promisify()
9447 promise = callback.promise
9448 }
9449
9450 if (maybeError(this, callback)) { return promise }
9451
9452 options = getOptions(options)
9453
9454 this.db.batch(arr, options, function (err) {
9455 if (err) {
9456 return callback(new WriteError(err))
9457 }
9458 self.emit('batch', arr)
9459 callback()
9460 })
9461
9462 return promise
9463}
9464
9465LevelUP.prototype.iterator = function (options) {
9466 return this.db.iterator(options)
9467}
9468
9469LevelUP.prototype.readStream =
9470LevelUP.prototype.createReadStream = function (options) {
9471 options = extend({ keys: true, values: true }, options)
9472 if (typeof options.limit !== 'number') { options.limit = -1 }
9473 return new IteratorStream(this.db.iterator(options), options)
9474}
9475
9476LevelUP.prototype.keyStream =
9477LevelUP.prototype.createKeyStream = function (options) {
9478 return this.createReadStream(extend(options, { keys: true, values: false }))
9479}
9480
9481LevelUP.prototype.valueStream =
9482LevelUP.prototype.createValueStream = function (options) {
9483 return this.createReadStream(extend(options, { keys: false, values: true }))
9484}
9485
9486LevelUP.prototype.toString = function () {
9487 return 'LevelUP'
9488}
9489
9490function maybeError (db, callback) {
9491 if (!db._isOpening() && !db.isOpen()) {
9492 process.nextTick(callback, new ReadError('Database is not open'))
9493 return true
9494 }
9495}
9496
9497LevelUP.errors = errors
9498module.exports = LevelUP.default = LevelUP
9499
9500}).call(this,_dereq_(69))
9501},{"117":117,"16":16,"25":25,"36":36,"37":37,"5":5,"54":54,"55":55,"57":57,"58":58,"69":69}],57:[function(_dereq_,module,exports){
9502function promisify () {
9503 var callback
9504 var promise = new Promise(function (resolve, reject) {
9505 callback = function callback (err, value) {
9506 if (err) reject(err)
9507 else resolve(value)
9508 }
9509 })
9510 callback.promise = promise
9511 return callback
9512}
9513
9514module.exports = promisify
9515
9516},{}],58:[function(_dereq_,module,exports){
9517arguments[4][21][0].apply(exports,arguments)
9518},{"21":21}],59:[function(_dereq_,module,exports){
9519(function (Buffer,process,global){
9520'use strict';
9521
9522var inherits = _dereq_(31);
9523var bufferFrom = _dereq_(64);
9524var AbstractLevelDOWN = _dereq_(3).AbstractLevelDOWN;
9525var AbstractIterator = _dereq_(3).AbstractIterator;
9526
9527var LocalStorage = _dereq_(61).LocalStorage;
9528var LocalStorageCore = _dereq_(60);
9529var utils = _dereq_(63);
9530
9531// see http://stackoverflow.com/a/15349865/680742
9532var nextTick = global.setImmediate || process.nextTick;
9533
9534function LDIterator(db, options) {
9535
9536 AbstractIterator.call(this, db);
9537
9538 this._reverse = !!options.reverse;
9539 this._endkey = options.end;
9540 this._startkey = options.start;
9541 this._gt = options.gt;
9542 this._gte = options.gte;
9543 this._lt = options.lt;
9544 this._lte = options.lte;
9545 this._exclusiveStart = options.exclusiveStart;
9546 this._keysOnly = options.values === false;
9547 this._limit = options.limit;
9548 this._count = 0;
9549
9550 this.onInitCompleteListeners = [];
9551}
9552
9553inherits(LDIterator, AbstractIterator);
9554
9555LDIterator.prototype._init = function (callback) {
9556 nextTick(function () {
9557 callback();
9558 });
9559};
9560
9561LDIterator.prototype._next = function (callback) {
9562 var self = this;
9563
9564 function onInitComplete() {
9565 if (self._pos === self._keys.length || self._pos < 0) { // done reading
9566 return callback();
9567 }
9568
9569 var key = self._keys[self._pos];
9570
9571 if (!!self._endkey && (self._reverse ? key < self._endkey : key > self._endkey)) {
9572 return callback();
9573 }
9574
9575 if (!!self._limit && self._limit > 0 && self._count++ >= self._limit) {
9576 return callback();
9577 }
9578
9579 if ((self._lt && key >= self._lt) ||
9580 (self._lte && key > self._lte) ||
9581 (self._gt && key <= self._gt) ||
9582 (self._gte && key < self._gte)) {
9583 return callback();
9584 }
9585
9586 self._pos += self._reverse ? -1 : 1;
9587 if (self._keysOnly) {
9588 return callback(null, key);
9589 }
9590
9591 self.db.container.getItem(key, function (err, value) {
9592 if (err) {
9593 if (err.message === 'NotFound') {
9594 return nextTick(function () {
9595 self._next(callback);
9596 });
9597 }
9598 return callback(err);
9599 }
9600 callback(null, key, value);
9601 });
9602 }
9603 if (!self.initStarted) {
9604 process.nextTick(function () {
9605 self.initStarted = true;
9606 self._init(function (err) {
9607 if (err) {
9608 return callback(err);
9609 }
9610 self.db.container.keys(function (err, keys) {
9611 if (err) {
9612 return callback(err);
9613 }
9614 self._keys = keys;
9615 if (self._startkey) {
9616 var index = utils.sortedIndexOf(self._keys, self._startkey);
9617 var startkey = (index >= self._keys.length || index < 0) ?
9618 undefined : self._keys[index];
9619 self._pos = index;
9620 if (self._reverse) {
9621 if (self._exclusiveStart || startkey !== self._startkey) {
9622 self._pos--;
9623 }
9624 } else if (self._exclusiveStart && startkey === self._startkey) {
9625 self._pos++;
9626 }
9627 } else {
9628 self._pos = self._reverse ? self._keys.length - 1 : 0;
9629 }
9630 onInitComplete();
9631
9632 self.initCompleted = true;
9633 var i = -1;
9634 while (++i < self.onInitCompleteListeners.length) {
9635 nextTick(self.onInitCompleteListeners[i]);
9636 }
9637 });
9638 });
9639 });
9640 } else if (!self.initCompleted) {
9641 self.onInitCompleteListeners.push(onInitComplete);
9642 } else {
9643 process.nextTick(onInitComplete);
9644 }
9645};
9646
9647function LD(location) {
9648 if (!(this instanceof LD)) {
9649 return new LD(location);
9650 }
9651 AbstractLevelDOWN.call(this, location);
9652 this.container = new LocalStorage(location);
9653}
9654
9655inherits(LD, AbstractLevelDOWN);
9656
9657LD.prototype._open = function (options, callback) {
9658 this.container.init(callback);
9659};
9660
9661LD.prototype._put = function (key, value, options, callback) {
9662
9663 var err = checkKeyValue(key, 'key');
9664
9665 if (err) {
9666 return nextTick(function () {
9667 callback(err);
9668 });
9669 }
9670
9671 err = checkKeyValue(value, 'value');
9672
9673 if (err) {
9674 return nextTick(function () {
9675 callback(err);
9676 });
9677 }
9678
9679 if (typeof value === 'object' && !Buffer.isBuffer(value) && value.buffer === undefined) {
9680 var obj = {};
9681 obj.storetype = "json";
9682 obj.data = value;
9683 value = JSON.stringify(obj);
9684 }
9685
9686 this.container.setItem(key, value, callback);
9687};
9688
9689LD.prototype._get = function (key, options, callback) {
9690
9691 var err = checkKeyValue(key, 'key');
9692
9693 if (err) {
9694 return nextTick(function () {
9695 callback(err);
9696 });
9697 }
9698
9699 if (!Buffer.isBuffer(key)) {
9700 key = String(key);
9701 }
9702 this.container.getItem(key, function (err, value) {
9703
9704 if (err) {
9705 return callback(err);
9706 }
9707
9708 if (options.asBuffer !== false && !Buffer.isBuffer(value)) {
9709 value = bufferFrom(value);
9710 }
9711
9712
9713 if (options.asBuffer === false) {
9714 if (value.indexOf("{\"storetype\":\"json\",\"data\"") > -1) {
9715 var res = JSON.parse(value);
9716 value = res.data;
9717 }
9718 }
9719 callback(null, value);
9720 });
9721};
9722
9723LD.prototype._del = function (key, options, callback) {
9724
9725 var err = checkKeyValue(key, 'key');
9726
9727 if (err) {
9728 return nextTick(function () {
9729 callback(err);
9730 });
9731 }
9732 if (!Buffer.isBuffer(key)) {
9733 key = String(key);
9734 }
9735
9736 this.container.removeItem(key, callback);
9737};
9738
9739LD.prototype._batch = function (array, options, callback) {
9740 var self = this;
9741 nextTick(function () {
9742 var err;
9743 var key;
9744 var value;
9745
9746 var numDone = 0;
9747 var overallErr;
9748 function checkDone() {
9749 if (++numDone === array.length) {
9750 callback(overallErr);
9751 }
9752 }
9753
9754 if (Array.isArray(array) && array.length) {
9755 for (var i = 0; i < array.length; i++) {
9756 var task = array[i];
9757 if (task) {
9758 key = Buffer.isBuffer(task.key) ? task.key : String(task.key);
9759 err = checkKeyValue(key, 'key');
9760 if (err) {
9761 overallErr = err;
9762 checkDone();
9763 } else if (task.type === 'del') {
9764 self._del(task.key, options, checkDone);
9765 } else if (task.type === 'put') {
9766 value = Buffer.isBuffer(task.value) ? task.value : String(task.value);
9767 err = checkKeyValue(value, 'value');
9768 if (err) {
9769 overallErr = err;
9770 checkDone();
9771 } else {
9772 self._put(key, value, options, checkDone);
9773 }
9774 }
9775 } else {
9776 checkDone();
9777 }
9778 }
9779 } else {
9780 callback();
9781 }
9782 });
9783};
9784
9785LD.prototype._iterator = function (options) {
9786 return new LDIterator(this, options);
9787};
9788
9789LD.destroy = function (name, callback) {
9790 LocalStorageCore.destroy(name, callback);
9791};
9792
9793function checkKeyValue(obj, type) {
9794 if (obj === null || obj === undefined) {
9795 return new Error(type + ' cannot be `null` or `undefined`');
9796 }
9797 if (obj === null || obj === undefined) {
9798 return new Error(type + ' cannot be `null` or `undefined`');
9799 }
9800
9801 if (type === 'key') {
9802
9803 if (obj instanceof Boolean) {
9804 return new Error(type + ' cannot be `null` or `undefined`');
9805 }
9806 if (obj === '') {
9807 return new Error(type + ' cannot be empty');
9808 }
9809 }
9810 if (obj.toString().indexOf("[object ArrayBuffer]") === 0) {
9811 if (obj.byteLength === 0 || obj.byteLength === undefined) {
9812 return new Error(type + ' cannot be an empty Buffer');
9813 }
9814 }
9815
9816 if (Buffer.isBuffer(obj)) {
9817 if (obj.length === 0) {
9818 return new Error(type + ' cannot be an empty Buffer');
9819 }
9820 } else if (String(obj) === '') {
9821 return new Error(type + ' cannot be an empty String');
9822 }
9823}
9824
9825module.exports = LD;
9826
9827}).call(this,{"isBuffer":_dereq_(32)},_dereq_(69),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
9828},{"3":3,"31":31,"32":32,"60":60,"61":61,"63":63,"64":64,"69":69}],60:[function(_dereq_,module,exports){
9829(function (process,global){
9830'use strict';
9831
9832//
9833// Class that should contain everything necessary to interact
9834// with localStorage as a generic key-value store.
9835// The idea is that authors who want to create an AbstractKeyValueDOWN
9836// module (e.g. on lawnchair, S3, whatever) will only have to
9837// reimplement this file.
9838//
9839
9840// see http://stackoverflow.com/a/15349865/680742
9841var nextTick = global.setImmediate || process.nextTick;
9842
9843// We use humble-localstorage as a wrapper for localStorage because
9844// it falls back to an in-memory implementation in environments without
9845// localStorage, like Node or Safari private browsing.
9846var storage = _dereq_(28);
9847
9848function callbackify(callback, fun) {
9849 var val;
9850 var err;
9851 try {
9852 val = fun();
9853 } catch (e) {
9854 err = e;
9855 }
9856 nextTick(function () {
9857 callback(err, val);
9858 });
9859}
9860
9861function createPrefix(dbname) {
9862 return dbname.replace(/!/g, '!!') + '!'; // escape bangs in dbname;
9863}
9864
9865function LocalStorageCore(dbname) {
9866 this._prefix = createPrefix(dbname);
9867}
9868
9869LocalStorageCore.prototype.getKeys = function (callback) {
9870 var self = this;
9871 callbackify(callback, function () {
9872 var keys = [];
9873 var prefixLen = self._prefix.length;
9874 var i = -1;
9875 var len = storage.length;
9876 while (++i < len) {
9877 var fullKey = storage.key(i);
9878 if (fullKey.substring(0, prefixLen) === self._prefix) {
9879 keys.push(fullKey.substring(prefixLen));
9880 }
9881 }
9882 keys.sort();
9883 return keys;
9884 });
9885};
9886
9887LocalStorageCore.prototype.put = function (key, value, callback) {
9888 var self = this;
9889 callbackify(callback, function () {
9890 storage.setItem(self._prefix + key, value);
9891 });
9892};
9893
9894LocalStorageCore.prototype.get = function (key, callback) {
9895 var self = this;
9896 callbackify(callback, function () {
9897 return storage.getItem(self._prefix + key);
9898 });
9899};
9900
9901LocalStorageCore.prototype.remove = function (key, callback) {
9902 var self = this;
9903 callbackify(callback, function () {
9904 storage.removeItem(self._prefix + key);
9905 });
9906};
9907
9908LocalStorageCore.destroy = function (dbname, callback) {
9909 var prefix = createPrefix(dbname);
9910 callbackify(callback, function () {
9911 var keysToDelete = [];
9912 var i = -1;
9913 var len = storage.length;
9914 while (++i < len) {
9915 var key = storage.key(i);
9916 if (key.substring(0, prefix.length) === prefix) {
9917 keysToDelete.push(key);
9918 }
9919 }
9920 keysToDelete.forEach(function (key) {
9921 storage.removeItem(key);
9922 });
9923 });
9924};
9925
9926module.exports = LocalStorageCore;
9927}).call(this,_dereq_(69),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
9928},{"28":28,"69":69}],61:[function(_dereq_,module,exports){
9929(function (Buffer){
9930'use strict';
9931
9932// ArrayBuffer/Uint8Array are old formats that date back to before we
9933// had a proper browserified buffer type. they may be removed later
9934var arrayBuffPrefix = 'ArrayBuffer:';
9935var arrayBuffRegex = new RegExp('^' + arrayBuffPrefix);
9936var uintPrefix = 'Uint8Array:';
9937var uintRegex = new RegExp('^' + uintPrefix);
9938
9939// this is the new encoding format used going forward
9940var bufferPrefix = 'Buff:';
9941var bufferRegex = new RegExp('^' + bufferPrefix);
9942
9943var utils = _dereq_(63);
9944var LocalStorageCore = _dereq_(60);
9945var TaskQueue = _dereq_(62);
9946var d64 = _dereq_(14);
9947
9948function LocalStorage(dbname) {
9949 this._store = new LocalStorageCore(dbname);
9950 this._queue = new TaskQueue();
9951}
9952
9953LocalStorage.prototype.sequentialize = function (callback, fun) {
9954 this._queue.add(fun, callback);
9955};
9956
9957LocalStorage.prototype.init = function (callback) {
9958 var self = this;
9959 self.sequentialize(callback, function (callback) {
9960 self._store.getKeys(function (err, keys) {
9961 if (err) {
9962 return callback(err);
9963 }
9964 self._keys = keys;
9965 return callback();
9966 });
9967 });
9968};
9969
9970LocalStorage.prototype.keys = function (callback) {
9971 var self = this;
9972 self.sequentialize(callback, function (callback) {
9973 self._store.getKeys(function (err, keys) {
9974 callback(null, keys.slice());
9975 });
9976 });
9977};
9978
9979//setItem: Saves and item at the key provided.
9980LocalStorage.prototype.setItem = function (key, value, callback) {
9981 var self = this;
9982 self.sequentialize(callback, function (callback) {
9983 if (Buffer.isBuffer(value)) {
9984 value = bufferPrefix + d64.encode(value);
9985 }
9986
9987 var idx = utils.sortedIndexOf(self._keys, key);
9988 if (self._keys[idx] !== key) {
9989 self._keys.splice(idx, 0, key);
9990 }
9991 self._store.put(key, value, callback);
9992 });
9993};
9994
9995//getItem: Returns the item identified by it's key.
9996LocalStorage.prototype.getItem = function (key, callback) {
9997 var self = this;
9998 self.sequentialize(callback, function (callback) {
9999 self._store.get(key, function (err, retval) {
10000 if (err) {
10001 return callback(err);
10002 }
10003 if (typeof retval === 'undefined' || retval === null) {
10004 // 'NotFound' error, consistent with LevelDOWN API
10005 return callback(new Error('NotFound'));
10006 }
10007 if (typeof retval !== 'undefined') {
10008 if (bufferRegex.test(retval)) {
10009 retval = d64.decode(retval.substring(bufferPrefix.length));
10010 } else if (arrayBuffRegex.test(retval)) {
10011 // this type is kept for backwards
10012 // compatibility with older databases, but may be removed
10013 // after a major version bump
10014 retval = retval.substring(arrayBuffPrefix.length);
10015 retval = new ArrayBuffer(atob(retval).split('').map(function (c) {
10016 return c.charCodeAt(0);
10017 }));
10018 } else if (uintRegex.test(retval)) {
10019 // ditto
10020 retval = retval.substring(uintPrefix.length);
10021 retval = new Uint8Array(atob(retval).split('').map(function (c) {
10022 return c.charCodeAt(0);
10023 }));
10024 }
10025 }
10026 callback(null, retval);
10027 });
10028 });
10029};
10030
10031//removeItem: Removes the item identified by it's key.
10032LocalStorage.prototype.removeItem = function (key, callback) {
10033 var self = this;
10034 self.sequentialize(callback, function (callback) {
10035 var idx = utils.sortedIndexOf(self._keys, key);
10036 if (self._keys[idx] === key) {
10037 self._keys.splice(idx, 1);
10038 self._store.remove(key, function (err) {
10039 if (err) {
10040 return callback(err);
10041 }
10042 callback();
10043 });
10044 } else {
10045 callback();
10046 }
10047 });
10048};
10049
10050LocalStorage.prototype.length = function (callback) {
10051 var self = this;
10052 self.sequentialize(callback, function (callback) {
10053 callback(null, self._keys.length);
10054 });
10055};
10056
10057exports.LocalStorage = LocalStorage;
10058
10059}).call(this,{"isBuffer":_dereq_(32)})
10060},{"14":14,"32":32,"60":60,"62":62,"63":63}],62:[function(_dereq_,module,exports){
10061(function (process,global){
10062'use strict';
10063
10064var argsarray = _dereq_(4);
10065var Queue = _dereq_(114);
10066
10067// see http://stackoverflow.com/a/15349865/680742
10068var nextTick = global.setImmediate || process.nextTick;
10069
10070function TaskQueue() {
10071 this.queue = new Queue();
10072 this.running = false;
10073}
10074
10075TaskQueue.prototype.add = function (fun, callback) {
10076 this.queue.push({fun: fun, callback: callback});
10077 this.processNext();
10078};
10079
10080TaskQueue.prototype.processNext = function () {
10081 var self = this;
10082 if (self.running || !self.queue.length) {
10083 return;
10084 }
10085 self.running = true;
10086
10087 var task = self.queue.shift();
10088 nextTick(function () {
10089 task.fun(argsarray(function (args) {
10090 task.callback.apply(null, args);
10091 self.running = false;
10092 self.processNext();
10093 }));
10094 });
10095};
10096
10097module.exports = TaskQueue;
10098
10099}).call(this,_dereq_(69),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10100},{"114":114,"4":4,"69":69}],63:[function(_dereq_,module,exports){
10101'use strict';
10102// taken from rvagg/memdown commit 2078b40
10103exports.sortedIndexOf = function(arr, item) {
10104 var low = 0;
10105 var high = arr.length;
10106 var mid;
10107 while (low < high) {
10108 mid = (low + high) >>> 1;
10109 if (arr[mid] < item) {
10110 low = mid + 1;
10111 } else {
10112 high = mid;
10113 }
10114 }
10115 return low;
10116};
10117
10118},{}],64:[function(_dereq_,module,exports){
10119arguments[4][11][0].apply(exports,arguments)
10120},{"11":11,"12":12}],65:[function(_dereq_,module,exports){
10121(function (root) {
10122 var localStorageMemory = {}
10123 var cache = {}
10124
10125 /**
10126 * number of stored items.
10127 */
10128 localStorageMemory.length = 0
10129
10130 /**
10131 * returns item for passed key, or null
10132 *
10133 * @para {String} key
10134 * name of item to be returned
10135 * @returns {String|null}
10136 */
10137 localStorageMemory.getItem = function (key) {
10138 if (key in cache) {
10139 return cache[key]
10140 }
10141
10142 return null
10143 }
10144
10145 /**
10146 * sets item for key to passed value, as String
10147 *
10148 * @para {String} key
10149 * name of item to be set
10150 * @para {String} value
10151 * value, will always be turned into a String
10152 * @returns {undefined}
10153 */
10154 localStorageMemory.setItem = function (key, value) {
10155 if (typeof value === 'undefined') {
10156 localStorageMemory.removeItem(key)
10157 } else {
10158 if (!(cache.hasOwnProperty(key))) {
10159 localStorageMemory.length++
10160 }
10161
10162 cache[key] = '' + value
10163 }
10164 }
10165
10166 /**
10167 * removes item for passed key
10168 *
10169 * @para {String} key
10170 * name of item to be removed
10171 * @returns {undefined}
10172 */
10173 localStorageMemory.removeItem = function (key) {
10174 if (cache.hasOwnProperty(key)) {
10175 delete cache[key]
10176 localStorageMemory.length--
10177 }
10178 }
10179
10180 /**
10181 * returns name of key at passed index
10182 *
10183 * @para {Number} index
10184 * Position for key to be returned (starts at 0)
10185 * @returns {String|null}
10186 */
10187 localStorageMemory.key = function (index) {
10188 return Object.keys(cache)[index] || null
10189 }
10190
10191 /**
10192 * removes all stored items and sets length to 0
10193 *
10194 * @returns {undefined}
10195 */
10196 localStorageMemory.clear = function () {
10197 cache = {}
10198 localStorageMemory.length = 0
10199 }
10200
10201 if (typeof exports === 'object') {
10202 module.exports = localStorageMemory
10203 } else {
10204 root.localStorageMemory = localStorageMemory
10205 }
10206})(this)
10207
10208},{}],66:[function(_dereq_,module,exports){
10209(function (Buffer){
10210
10211exports.compare = function (a, b) {
10212
10213 if(Buffer.isBuffer(a)) {
10214 var l = Math.min(a.length, b.length)
10215 for(var i = 0; i < l; i++) {
10216 var cmp = a[i] - b[i]
10217 if(cmp) return cmp
10218 }
10219 return a.length - b.length
10220 }
10221
10222 return a < b ? -1 : a > b ? 1 : 0
10223}
10224
10225// to be compatible with the current abstract-leveldown tests
10226// nullish or empty strings.
10227// I could use !!val but I want to permit numbers and booleans,
10228// if possible.
10229
10230function isDef (val) {
10231 return val !== undefined && val !== ''
10232}
10233
10234function has (range, name) {
10235 return Object.hasOwnProperty.call(range, name)
10236}
10237
10238function hasKey(range, name) {
10239 return Object.hasOwnProperty.call(range, name) && name
10240}
10241
10242var lowerBoundKey = exports.lowerBoundKey = function (range) {
10243 return (
10244 hasKey(range, 'gt')
10245 || hasKey(range, 'gte')
10246 || hasKey(range, 'min')
10247 || (range.reverse ? hasKey(range, 'end') : hasKey(range, 'start'))
10248 || undefined
10249 )
10250}
10251
10252var lowerBound = exports.lowerBound = function (range, def) {
10253 var k = lowerBoundKey(range)
10254 return k ? range[k] : def
10255}
10256
10257var lowerBoundInclusive = exports.lowerBoundInclusive = function (range) {
10258 return has(range, 'gt') ? false : true
10259}
10260
10261var upperBoundInclusive = exports.upperBoundInclusive =
10262 function (range) {
10263 return (has(range, 'lt') /*&& !range.maxEx*/) ? false : true
10264 }
10265
10266var lowerBoundExclusive = exports.lowerBoundExclusive =
10267 function (range) {
10268 return !lowerBoundInclusive(range)
10269 }
10270
10271var upperBoundExclusive = exports.upperBoundExclusive =
10272 function (range) {
10273 return !upperBoundInclusive(range)
10274 }
10275
10276var upperBoundKey = exports.upperBoundKey = function (range) {
10277 return (
10278 hasKey(range, 'lt')
10279 || hasKey(range, 'lte')
10280 || hasKey(range, 'max')
10281 || (range.reverse ? hasKey(range, 'start') : hasKey(range, 'end'))
10282 || undefined
10283 )
10284}
10285
10286var upperBound = exports.upperBound = function (range, def) {
10287 var k = upperBoundKey(range)
10288 return k ? range[k] : def
10289}
10290
10291exports.start = function (range, def) {
10292 return range.reverse ? upperBound(range, def) : lowerBound(range, def)
10293}
10294exports.end = function (range, def) {
10295 return range.reverse ? lowerBound(range, def) : upperBound(range, def)
10296}
10297exports.startInclusive = function (range) {
10298 return (
10299 range.reverse
10300 ? upperBoundInclusive(range)
10301 : lowerBoundInclusive(range)
10302 )
10303}
10304exports.endInclusive = function (range) {
10305 return (
10306 range.reverse
10307 ? lowerBoundInclusive(range)
10308 : upperBoundInclusive(range)
10309 )
10310}
10311
10312function id (e) { return e }
10313
10314exports.toLtgt = function (range, _range, map, lower, upper) {
10315 _range = _range || {}
10316 map = map || id
10317 var defaults = arguments.length > 3
10318 var lb = exports.lowerBoundKey(range)
10319 var ub = exports.upperBoundKey(range)
10320 if(lb) {
10321 if(lb === 'gt') _range.gt = map(range.gt, false)
10322 else _range.gte = map(range[lb], false)
10323 }
10324 else if(defaults)
10325 _range.gte = map(lower, false)
10326
10327 if(ub) {
10328 if(ub === 'lt') _range.lt = map(range.lt, true)
10329 else _range.lte = map(range[ub], true)
10330 }
10331 else if(defaults)
10332 _range.lte = map(upper, true)
10333
10334 if(range.reverse != null)
10335 _range.reverse = !!range.reverse
10336
10337 //if range was used mutably
10338 //(in level-sublevel it's part of an options object
10339 //that has more properties on it.)
10340 if(has(_range, 'max')) delete _range.max
10341 if(has(_range, 'min')) delete _range.min
10342 if(has(_range, 'start')) delete _range.start
10343 if(has(_range, 'end')) delete _range.end
10344
10345 return _range
10346}
10347
10348exports.contains = function (range, key, compare) {
10349 compare = compare || exports.compare
10350
10351 var lb = lowerBound(range)
10352 if(isDef(lb)) {
10353 var cmp = compare(key, lb)
10354 if(cmp < 0 || (cmp === 0 && lowerBoundExclusive(range)))
10355 return false
10356 }
10357
10358 var ub = upperBound(range)
10359 if(isDef(ub)) {
10360 var cmp = compare(key, ub)
10361 if(cmp > 0 || (cmp === 0) && upperBoundExclusive(range))
10362 return false
10363 }
10364
10365 return true
10366}
10367
10368exports.filter = function (range, compare) {
10369 return function (key) {
10370 return exports.contains(range, key, compare)
10371 }
10372}
10373
10374
10375
10376}).call(this,{"isBuffer":_dereq_(32)})
10377},{"32":32}],67:[function(_dereq_,module,exports){
10378/*
10379object-assign
10380(c) Sindre Sorhus
10381@license MIT
10382*/
10383
10384'use strict';
10385/* eslint-disable no-unused-vars */
10386var getOwnPropertySymbols = Object.getOwnPropertySymbols;
10387var hasOwnProperty = Object.prototype.hasOwnProperty;
10388var propIsEnumerable = Object.prototype.propertyIsEnumerable;
10389
10390function toObject(val) {
10391 if (val === null || val === undefined) {
10392 throw new TypeError('Object.assign cannot be called with null or undefined');
10393 }
10394
10395 return Object(val);
10396}
10397
10398function shouldUseNative() {
10399 try {
10400 if (!Object.assign) {
10401 return false;
10402 }
10403
10404 // Detect buggy property enumeration order in older V8 versions.
10405
10406 // https://bugs.chromium.org/p/v8/issues/detail?id=4118
10407 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
10408 test1[5] = 'de';
10409 if (Object.getOwnPropertyNames(test1)[0] === '5') {
10410 return false;
10411 }
10412
10413 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
10414 var test2 = {};
10415 for (var i = 0; i < 10; i++) {
10416 test2['_' + String.fromCharCode(i)] = i;
10417 }
10418 var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
10419 return test2[n];
10420 });
10421 if (order2.join('') !== '0123456789') {
10422 return false;
10423 }
10424
10425 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
10426 var test3 = {};
10427 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
10428 test3[letter] = letter;
10429 });
10430 if (Object.keys(Object.assign({}, test3)).join('') !==
10431 'abcdefghijklmnopqrst') {
10432 return false;
10433 }
10434
10435 return true;
10436 } catch (err) {
10437 // We don't expect any of the above to throw, but better to be safe.
10438 return false;
10439 }
10440}
10441
10442module.exports = shouldUseNative() ? Object.assign : function (target, source) {
10443 var from;
10444 var to = toObject(target);
10445 var symbols;
10446
10447 for (var s = 1; s < arguments.length; s++) {
10448 from = Object(arguments[s]);
10449
10450 for (var key in from) {
10451 if (hasOwnProperty.call(from, key)) {
10452 to[key] = from[key];
10453 }
10454 }
10455
10456 if (getOwnPropertySymbols) {
10457 symbols = getOwnPropertySymbols(from);
10458 for (var i = 0; i < symbols.length; i++) {
10459 if (propIsEnumerable.call(from, symbols[i])) {
10460 to[symbols[i]] = from[symbols[i]];
10461 }
10462 }
10463 }
10464 }
10465
10466 return to;
10467};
10468
10469},{}],68:[function(_dereq_,module,exports){
10470(function (process){
10471'use strict';
10472
10473if (!process.version ||
10474 process.version.indexOf('v0.') === 0 ||
10475 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
10476 module.exports = { nextTick: nextTick };
10477} else {
10478 module.exports = process
10479}
10480
10481function nextTick(fn, arg1, arg2, arg3) {
10482 if (typeof fn !== 'function') {
10483 throw new TypeError('"callback" argument must be a function');
10484 }
10485 var len = arguments.length;
10486 var args, i;
10487 switch (len) {
10488 case 0:
10489 case 1:
10490 return process.nextTick(fn);
10491 case 2:
10492 return process.nextTick(function afterTickOne() {
10493 fn.call(null, arg1);
10494 });
10495 case 3:
10496 return process.nextTick(function afterTickTwo() {
10497 fn.call(null, arg1, arg2);
10498 });
10499 case 4:
10500 return process.nextTick(function afterTickThree() {
10501 fn.call(null, arg1, arg2, arg3);
10502 });
10503 default:
10504 args = new Array(len - 1);
10505 i = 0;
10506 while (i < args.length) {
10507 args[i++] = arguments[i];
10508 }
10509 return process.nextTick(function afterTick() {
10510 fn.apply(null, args);
10511 });
10512 }
10513}
10514
10515
10516}).call(this,_dereq_(69))
10517},{"69":69}],69:[function(_dereq_,module,exports){
10518// shim for using process in browser
10519var process = module.exports = {};
10520
10521// cached from whatever global is present so that test runners that stub it
10522// don't break things. But we need to wrap it in a try catch in case it is
10523// wrapped in strict mode code which doesn't define any globals. It's inside a
10524// function because try/catches deoptimize in certain engines.
10525
10526var cachedSetTimeout;
10527var cachedClearTimeout;
10528
10529function defaultSetTimout() {
10530 throw new Error('setTimeout has not been defined');
10531}
10532function defaultClearTimeout () {
10533 throw new Error('clearTimeout has not been defined');
10534}
10535(function () {
10536 try {
10537 if (typeof setTimeout === 'function') {
10538 cachedSetTimeout = setTimeout;
10539 } else {
10540 cachedSetTimeout = defaultSetTimout;
10541 }
10542 } catch (e) {
10543 cachedSetTimeout = defaultSetTimout;
10544 }
10545 try {
10546 if (typeof clearTimeout === 'function') {
10547 cachedClearTimeout = clearTimeout;
10548 } else {
10549 cachedClearTimeout = defaultClearTimeout;
10550 }
10551 } catch (e) {
10552 cachedClearTimeout = defaultClearTimeout;
10553 }
10554} ())
10555function runTimeout(fun) {
10556 if (cachedSetTimeout === setTimeout) {
10557 //normal enviroments in sane situations
10558 return setTimeout(fun, 0);
10559 }
10560 // if setTimeout wasn't available but was latter defined
10561 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
10562 cachedSetTimeout = setTimeout;
10563 return setTimeout(fun, 0);
10564 }
10565 try {
10566 // when when somebody has screwed with setTimeout but no I.E. maddness
10567 return cachedSetTimeout(fun, 0);
10568 } catch(e){
10569 try {
10570 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
10571 return cachedSetTimeout.call(null, fun, 0);
10572 } catch(e){
10573 // 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
10574 return cachedSetTimeout.call(this, fun, 0);
10575 }
10576 }
10577
10578
10579}
10580function runClearTimeout(marker) {
10581 if (cachedClearTimeout === clearTimeout) {
10582 //normal enviroments in sane situations
10583 return clearTimeout(marker);
10584 }
10585 // if clearTimeout wasn't available but was latter defined
10586 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
10587 cachedClearTimeout = clearTimeout;
10588 return clearTimeout(marker);
10589 }
10590 try {
10591 // when when somebody has screwed with setTimeout but no I.E. maddness
10592 return cachedClearTimeout(marker);
10593 } catch (e){
10594 try {
10595 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
10596 return cachedClearTimeout.call(null, marker);
10597 } catch (e){
10598 // 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.
10599 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
10600 return cachedClearTimeout.call(this, marker);
10601 }
10602 }
10603
10604
10605
10606}
10607var queue = [];
10608var draining = false;
10609var currentQueue;
10610var queueIndex = -1;
10611
10612function cleanUpNextTick() {
10613 if (!draining || !currentQueue) {
10614 return;
10615 }
10616 draining = false;
10617 if (currentQueue.length) {
10618 queue = currentQueue.concat(queue);
10619 } else {
10620 queueIndex = -1;
10621 }
10622 if (queue.length) {
10623 drainQueue();
10624 }
10625}
10626
10627function drainQueue() {
10628 if (draining) {
10629 return;
10630 }
10631 var timeout = runTimeout(cleanUpNextTick);
10632 draining = true;
10633
10634 var len = queue.length;
10635 while(len) {
10636 currentQueue = queue;
10637 queue = [];
10638 while (++queueIndex < len) {
10639 if (currentQueue) {
10640 currentQueue[queueIndex].run();
10641 }
10642 }
10643 queueIndex = -1;
10644 len = queue.length;
10645 }
10646 currentQueue = null;
10647 draining = false;
10648 runClearTimeout(timeout);
10649}
10650
10651process.nextTick = function (fun) {
10652 var args = new Array(arguments.length - 1);
10653 if (arguments.length > 1) {
10654 for (var i = 1; i < arguments.length; i++) {
10655 args[i - 1] = arguments[i];
10656 }
10657 }
10658 queue.push(new Item(fun, args));
10659 if (queue.length === 1 && !draining) {
10660 runTimeout(drainQueue);
10661 }
10662};
10663
10664// v8 likes predictible objects
10665function Item(fun, array) {
10666 this.fun = fun;
10667 this.array = array;
10668}
10669Item.prototype.run = function () {
10670 this.fun.apply(null, this.array);
10671};
10672process.title = 'browser';
10673process.browser = true;
10674process.env = {};
10675process.argv = [];
10676process.version = ''; // empty string to avoid regexp issues
10677process.versions = {};
10678
10679function noop() {}
10680
10681process.on = noop;
10682process.addListener = noop;
10683process.once = noop;
10684process.off = noop;
10685process.removeListener = noop;
10686process.removeAllListeners = noop;
10687process.emit = noop;
10688process.prependListener = noop;
10689process.prependOnceListener = noop;
10690
10691process.listeners = function (name) { return [] }
10692
10693process.binding = function (name) {
10694 throw new Error('process.binding is not supported');
10695};
10696
10697process.cwd = function () { return '/' };
10698process.chdir = function (dir) {
10699 throw new Error('process.chdir is not supported');
10700};
10701process.umask = function() { return 0; };
10702
10703},{}],70:[function(_dereq_,module,exports){
10704/*!
10705 * prr
10706 * (c) 2013 Rod Vagg <rod@vagg.org>
10707 * https://github.com/rvagg/prr
10708 * License: MIT
10709 */
10710
10711(function (name, context, definition) {
10712 if (typeof module != 'undefined' && module.exports)
10713 module.exports = definition()
10714 else
10715 context[name] = definition()
10716})('prr', this, function() {
10717
10718 var setProperty = typeof Object.defineProperty == 'function'
10719 ? function (obj, key, options) {
10720 Object.defineProperty(obj, key, options)
10721 return obj
10722 }
10723 : function (obj, key, options) { // < es5
10724 obj[key] = options.value
10725 return obj
10726 }
10727
10728 , makeOptions = function (value, options) {
10729 var oo = typeof options == 'object'
10730 , os = !oo && typeof options == 'string'
10731 , op = function (p) {
10732 return oo
10733 ? !!options[p]
10734 : os
10735 ? options.indexOf(p[0]) > -1
10736 : false
10737 }
10738
10739 return {
10740 enumerable : op('enumerable')
10741 , configurable : op('configurable')
10742 , writable : op('writable')
10743 , value : value
10744 }
10745 }
10746
10747 , prr = function (obj, key, value, options) {
10748 var k
10749
10750 options = makeOptions(value, options)
10751
10752 if (typeof key == 'object') {
10753 for (k in key) {
10754 if (Object.hasOwnProperty.call(key, k)) {
10755 options.value = key[k]
10756 setProperty(obj, k, options)
10757 }
10758 }
10759 return obj
10760 }
10761
10762 return setProperty(obj, key, options)
10763 }
10764
10765 return prr
10766})
10767},{}],71:[function(_dereq_,module,exports){
10768(function (process){
10769// Copyright Joyent, Inc. and other Node contributors.
10770//
10771// Permission is hereby granted, free of charge, to any person obtaining a
10772// copy of this software and associated documentation files (the
10773// "Software"), to deal in the Software without restriction, including
10774// without limitation the rights to use, copy, modify, merge, publish,
10775// distribute, sublicense, and/or sell copies of the Software, and to permit
10776// persons to whom the Software is furnished to do so, subject to the
10777// following conditions:
10778//
10779// The above copyright notice and this permission notice shall be included
10780// in all copies or substantial portions of the Software.
10781//
10782// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
10783// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
10784// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
10785// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
10786// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
10787// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
10788// USE OR OTHER DEALINGS IN THE SOFTWARE.
10789
10790// a duplex stream is just a stream that is both readable and writable.
10791// Since JS doesn't have multiple prototypal inheritance, this class
10792// prototypally inherits from Readable, and then parasitically from
10793// Writable.
10794
10795module.exports = Duplex;
10796
10797/*<replacement>*/
10798var objectKeys = Object.keys || function (obj) {
10799 var keys = [];
10800 for (var key in obj) keys.push(key);
10801 return keys;
10802}
10803/*</replacement>*/
10804
10805
10806/*<replacement>*/
10807var util = _dereq_(13);
10808util.inherits = _dereq_(31);
10809/*</replacement>*/
10810
10811var Readable = _dereq_(73);
10812var Writable = _dereq_(75);
10813
10814util.inherits(Duplex, Readable);
10815
10816forEach(objectKeys(Writable.prototype), function(method) {
10817 if (!Duplex.prototype[method])
10818 Duplex.prototype[method] = Writable.prototype[method];
10819});
10820
10821function Duplex(options) {
10822 if (!(this instanceof Duplex))
10823 return new Duplex(options);
10824
10825 Readable.call(this, options);
10826 Writable.call(this, options);
10827
10828 if (options && options.readable === false)
10829 this.readable = false;
10830
10831 if (options && options.writable === false)
10832 this.writable = false;
10833
10834 this.allowHalfOpen = true;
10835 if (options && options.allowHalfOpen === false)
10836 this.allowHalfOpen = false;
10837
10838 this.once('end', onend);
10839}
10840
10841// the no-half-open enforcer
10842function onend() {
10843 // if we allow half-open state, or if the writable side ended,
10844 // then we're ok.
10845 if (this.allowHalfOpen || this._writableState.ended)
10846 return;
10847
10848 // no more data can be written.
10849 // But allow more writes to happen in this tick.
10850 process.nextTick(this.end.bind(this));
10851}
10852
10853function forEach (xs, f) {
10854 for (var i = 0, l = xs.length; i < l; i++) {
10855 f(xs[i], i);
10856 }
10857}
10858
10859}).call(this,_dereq_(69))
10860},{"13":13,"31":31,"69":69,"73":73,"75":75}],72:[function(_dereq_,module,exports){
10861// Copyright Joyent, Inc. and other Node contributors.
10862//
10863// Permission is hereby granted, free of charge, to any person obtaining a
10864// copy of this software and associated documentation files (the
10865// "Software"), to deal in the Software without restriction, including
10866// without limitation the rights to use, copy, modify, merge, publish,
10867// distribute, sublicense, and/or sell copies of the Software, and to permit
10868// persons to whom the Software is furnished to do so, subject to the
10869// following conditions:
10870//
10871// The above copyright notice and this permission notice shall be included
10872// in all copies or substantial portions of the Software.
10873//
10874// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
10875// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
10876// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
10877// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
10878// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
10879// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
10880// USE OR OTHER DEALINGS IN THE SOFTWARE.
10881
10882// a passthrough stream.
10883// basically just the most minimal sort of Transform stream.
10884// Every written chunk gets output as-is.
10885
10886module.exports = PassThrough;
10887
10888var Transform = _dereq_(74);
10889
10890/*<replacement>*/
10891var util = _dereq_(13);
10892util.inherits = _dereq_(31);
10893/*</replacement>*/
10894
10895util.inherits(PassThrough, Transform);
10896
10897function PassThrough(options) {
10898 if (!(this instanceof PassThrough))
10899 return new PassThrough(options);
10900
10901 Transform.call(this, options);
10902}
10903
10904PassThrough.prototype._transform = function(chunk, encoding, cb) {
10905 cb(null, chunk);
10906};
10907
10908},{"13":13,"31":31,"74":74}],73:[function(_dereq_,module,exports){
10909(function (process){
10910// Copyright Joyent, Inc. and other Node contributors.
10911//
10912// Permission is hereby granted, free of charge, to any person obtaining a
10913// copy of this software and associated documentation files (the
10914// "Software"), to deal in the Software without restriction, including
10915// without limitation the rights to use, copy, modify, merge, publish,
10916// distribute, sublicense, and/or sell copies of the Software, and to permit
10917// persons to whom the Software is furnished to do so, subject to the
10918// following conditions:
10919//
10920// The above copyright notice and this permission notice shall be included
10921// in all copies or substantial portions of the Software.
10922//
10923// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
10924// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
10925// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
10926// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
10927// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
10928// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
10929// USE OR OTHER DEALINGS IN THE SOFTWARE.
10930
10931module.exports = Readable;
10932
10933/*<replacement>*/
10934var isArray = _dereq_(33);
10935/*</replacement>*/
10936
10937
10938/*<replacement>*/
10939var Buffer = _dereq_(12).Buffer;
10940/*</replacement>*/
10941
10942Readable.ReadableState = ReadableState;
10943
10944var EE = _dereq_(25).EventEmitter;
10945
10946/*<replacement>*/
10947if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
10948 return emitter.listeners(type).length;
10949};
10950/*</replacement>*/
10951
10952var Stream = _dereq_(80);
10953
10954/*<replacement>*/
10955var util = _dereq_(13);
10956util.inherits = _dereq_(31);
10957/*</replacement>*/
10958
10959var StringDecoder;
10960
10961util.inherits(Readable, Stream);
10962
10963function ReadableState(options, stream) {
10964 options = options || {};
10965
10966 // the point at which it stops calling _read() to fill the buffer
10967 // Note: 0 is a valid value, means "don't call _read preemptively ever"
10968 var hwm = options.highWaterMark;
10969 this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
10970
10971 // cast to ints.
10972 this.highWaterMark = ~~this.highWaterMark;
10973
10974 this.buffer = [];
10975 this.length = 0;
10976 this.pipes = null;
10977 this.pipesCount = 0;
10978 this.flowing = false;
10979 this.ended = false;
10980 this.endEmitted = false;
10981 this.reading = false;
10982
10983 // In streams that never have any data, and do push(null) right away,
10984 // the consumer can miss the 'end' event if they do some I/O before
10985 // consuming the stream. So, we don't emit('end') until some reading
10986 // happens.
10987 this.calledRead = false;
10988
10989 // a flag to be able to tell if the onwrite cb is called immediately,
10990 // or on a later tick. We set this to true at first, becuase any
10991 // actions that shouldn't happen until "later" should generally also
10992 // not happen before the first write call.
10993 this.sync = true;
10994
10995 // whenever we return null, then we set a flag to say
10996 // that we're awaiting a 'readable' event emission.
10997 this.needReadable = false;
10998 this.emittedReadable = false;
10999 this.readableListening = false;
11000
11001
11002 // object stream flag. Used to make read(n) ignore n and to
11003 // make all the buffer merging and length checks go away
11004 this.objectMode = !!options.objectMode;
11005
11006 // Crypto is kind of old and crusty. Historically, its default string
11007 // encoding is 'binary' so we have to make this configurable.
11008 // Everything else in the universe uses 'utf8', though.
11009 this.defaultEncoding = options.defaultEncoding || 'utf8';
11010
11011 // when piping, we only care about 'readable' events that happen
11012 // after read()ing all the bytes and not getting any pushback.
11013 this.ranOut = false;
11014
11015 // the number of writers that are awaiting a drain event in .pipe()s
11016 this.awaitDrain = 0;
11017
11018 // if true, a maybeReadMore has been scheduled
11019 this.readingMore = false;
11020
11021 this.decoder = null;
11022 this.encoding = null;
11023 if (options.encoding) {
11024 if (!StringDecoder)
11025 StringDecoder = _dereq_(76).StringDecoder;
11026 this.decoder = new StringDecoder(options.encoding);
11027 this.encoding = options.encoding;
11028 }
11029}
11030
11031function Readable(options) {
11032 if (!(this instanceof Readable))
11033 return new Readable(options);
11034
11035 this._readableState = new ReadableState(options, this);
11036
11037 // legacy
11038 this.readable = true;
11039
11040 Stream.call(this);
11041}
11042
11043// Manually shove something into the read() buffer.
11044// This returns true if the highWaterMark has not been hit yet,
11045// similar to how Writable.write() returns true if you should
11046// write() some more.
11047Readable.prototype.push = function(chunk, encoding) {
11048 var state = this._readableState;
11049
11050 if (typeof chunk === 'string' && !state.objectMode) {
11051 encoding = encoding || state.defaultEncoding;
11052 if (encoding !== state.encoding) {
11053 chunk = new Buffer(chunk, encoding);
11054 encoding = '';
11055 }
11056 }
11057
11058 return readableAddChunk(this, state, chunk, encoding, false);
11059};
11060
11061// Unshift should *always* be something directly out of read()
11062Readable.prototype.unshift = function(chunk) {
11063 var state = this._readableState;
11064 return readableAddChunk(this, state, chunk, '', true);
11065};
11066
11067function readableAddChunk(stream, state, chunk, encoding, addToFront) {
11068 var er = chunkInvalid(state, chunk);
11069 if (er) {
11070 stream.emit('error', er);
11071 } else if (chunk === null || chunk === undefined) {
11072 state.reading = false;
11073 if (!state.ended)
11074 onEofChunk(stream, state);
11075 } else if (state.objectMode || chunk && chunk.length > 0) {
11076 if (state.ended && !addToFront) {
11077 var e = new Error('stream.push() after EOF');
11078 stream.emit('error', e);
11079 } else if (state.endEmitted && addToFront) {
11080 var e = new Error('stream.unshift() after end event');
11081 stream.emit('error', e);
11082 } else {
11083 if (state.decoder && !addToFront && !encoding)
11084 chunk = state.decoder.write(chunk);
11085
11086 // update the buffer info.
11087 state.length += state.objectMode ? 1 : chunk.length;
11088 if (addToFront) {
11089 state.buffer.unshift(chunk);
11090 } else {
11091 state.reading = false;
11092 state.buffer.push(chunk);
11093 }
11094
11095 if (state.needReadable)
11096 emitReadable(stream);
11097
11098 maybeReadMore(stream, state);
11099 }
11100 } else if (!addToFront) {
11101 state.reading = false;
11102 }
11103
11104 return needMoreData(state);
11105}
11106
11107
11108
11109// if it's past the high water mark, we can push in some more.
11110// Also, if we have no data yet, we can stand some
11111// more bytes. This is to work around cases where hwm=0,
11112// such as the repl. Also, if the push() triggered a
11113// readable event, and the user called read(largeNumber) such that
11114// needReadable was set, then we ought to push more, so that another
11115// 'readable' event will be triggered.
11116function needMoreData(state) {
11117 return !state.ended &&
11118 (state.needReadable ||
11119 state.length < state.highWaterMark ||
11120 state.length === 0);
11121}
11122
11123// backwards compatibility.
11124Readable.prototype.setEncoding = function(enc) {
11125 if (!StringDecoder)
11126 StringDecoder = _dereq_(76).StringDecoder;
11127 this._readableState.decoder = new StringDecoder(enc);
11128 this._readableState.encoding = enc;
11129};
11130
11131// Don't raise the hwm > 128MB
11132var MAX_HWM = 0x800000;
11133function roundUpToNextPowerOf2(n) {
11134 if (n >= MAX_HWM) {
11135 n = MAX_HWM;
11136 } else {
11137 // Get the next highest power of 2
11138 n--;
11139 for (var p = 1; p < 32; p <<= 1) n |= n >> p;
11140 n++;
11141 }
11142 return n;
11143}
11144
11145function howMuchToRead(n, state) {
11146 if (state.length === 0 && state.ended)
11147 return 0;
11148
11149 if (state.objectMode)
11150 return n === 0 ? 0 : 1;
11151
11152 if (n === null || isNaN(n)) {
11153 // only flow one buffer at a time
11154 if (state.flowing && state.buffer.length)
11155 return state.buffer[0].length;
11156 else
11157 return state.length;
11158 }
11159
11160 if (n <= 0)
11161 return 0;
11162
11163 // If we're asking for more than the target buffer level,
11164 // then raise the water mark. Bump up to the next highest
11165 // power of 2, to prevent increasing it excessively in tiny
11166 // amounts.
11167 if (n > state.highWaterMark)
11168 state.highWaterMark = roundUpToNextPowerOf2(n);
11169
11170 // don't have that much. return null, unless we've ended.
11171 if (n > state.length) {
11172 if (!state.ended) {
11173 state.needReadable = true;
11174 return 0;
11175 } else
11176 return state.length;
11177 }
11178
11179 return n;
11180}
11181
11182// you can override either this method, or the async _read(n) below.
11183Readable.prototype.read = function(n) {
11184 var state = this._readableState;
11185 state.calledRead = true;
11186 var nOrig = n;
11187 var ret;
11188
11189 if (typeof n !== 'number' || n > 0)
11190 state.emittedReadable = false;
11191
11192 // if we're doing read(0) to trigger a readable event, but we
11193 // already have a bunch of data in the buffer, then just trigger
11194 // the 'readable' event and move on.
11195 if (n === 0 &&
11196 state.needReadable &&
11197 (state.length >= state.highWaterMark || state.ended)) {
11198 emitReadable(this);
11199 return null;
11200 }
11201
11202 n = howMuchToRead(n, state);
11203
11204 // if we've ended, and we're now clear, then finish it up.
11205 if (n === 0 && state.ended) {
11206 ret = null;
11207
11208 // In cases where the decoder did not receive enough data
11209 // to produce a full chunk, then immediately received an
11210 // EOF, state.buffer will contain [<Buffer >, <Buffer 00 ...>].
11211 // howMuchToRead will see this and coerce the amount to
11212 // read to zero (because it's looking at the length of the
11213 // first <Buffer > in state.buffer), and we'll end up here.
11214 //
11215 // This can only happen via state.decoder -- no other venue
11216 // exists for pushing a zero-length chunk into state.buffer
11217 // and triggering this behavior. In this case, we return our
11218 // remaining data and end the stream, if appropriate.
11219 if (state.length > 0 && state.decoder) {
11220 ret = fromList(n, state);
11221 state.length -= ret.length;
11222 }
11223
11224 if (state.length === 0)
11225 endReadable(this);
11226
11227 return ret;
11228 }
11229
11230 // All the actual chunk generation logic needs to be
11231 // *below* the call to _read. The reason is that in certain
11232 // synthetic stream cases, such as passthrough streams, _read
11233 // may be a completely synchronous operation which may change
11234 // the state of the read buffer, providing enough data when
11235 // before there was *not* enough.
11236 //
11237 // So, the steps are:
11238 // 1. Figure out what the state of things will be after we do
11239 // a read from the buffer.
11240 //
11241 // 2. If that resulting state will trigger a _read, then call _read.
11242 // Note that this may be asynchronous, or synchronous. Yes, it is
11243 // deeply ugly to write APIs this way, but that still doesn't mean
11244 // that the Readable class should behave improperly, as streams are
11245 // designed to be sync/async agnostic.
11246 // Take note if the _read call is sync or async (ie, if the read call
11247 // has returned yet), so that we know whether or not it's safe to emit
11248 // 'readable' etc.
11249 //
11250 // 3. Actually pull the requested chunks out of the buffer and return.
11251
11252 // if we need a readable event, then we need to do some reading.
11253 var doRead = state.needReadable;
11254
11255 // if we currently have less than the highWaterMark, then also read some
11256 if (state.length - n <= state.highWaterMark)
11257 doRead = true;
11258
11259 // however, if we've ended, then there's no point, and if we're already
11260 // reading, then it's unnecessary.
11261 if (state.ended || state.reading)
11262 doRead = false;
11263
11264 if (doRead) {
11265 state.reading = true;
11266 state.sync = true;
11267 // if the length is currently zero, then we *need* a readable event.
11268 if (state.length === 0)
11269 state.needReadable = true;
11270 // call internal read method
11271 this._read(state.highWaterMark);
11272 state.sync = false;
11273 }
11274
11275 // If _read called its callback synchronously, then `reading`
11276 // will be false, and we need to re-evaluate how much data we
11277 // can return to the user.
11278 if (doRead && !state.reading)
11279 n = howMuchToRead(nOrig, state);
11280
11281 if (n > 0)
11282 ret = fromList(n, state);
11283 else
11284 ret = null;
11285
11286 if (ret === null) {
11287 state.needReadable = true;
11288 n = 0;
11289 }
11290
11291 state.length -= n;
11292
11293 // If we have nothing in the buffer, then we want to know
11294 // as soon as we *do* get something into the buffer.
11295 if (state.length === 0 && !state.ended)
11296 state.needReadable = true;
11297
11298 // If we happened to read() exactly the remaining amount in the
11299 // buffer, and the EOF has been seen at this point, then make sure
11300 // that we emit 'end' on the very next tick.
11301 if (state.ended && !state.endEmitted && state.length === 0)
11302 endReadable(this);
11303
11304 return ret;
11305};
11306
11307function chunkInvalid(state, chunk) {
11308 var er = null;
11309 if (!Buffer.isBuffer(chunk) &&
11310 'string' !== typeof chunk &&
11311 chunk !== null &&
11312 chunk !== undefined &&
11313 !state.objectMode) {
11314 er = new TypeError('Invalid non-string/buffer chunk');
11315 }
11316 return er;
11317}
11318
11319
11320function onEofChunk(stream, state) {
11321 if (state.decoder && !state.ended) {
11322 var chunk = state.decoder.end();
11323 if (chunk && chunk.length) {
11324 state.buffer.push(chunk);
11325 state.length += state.objectMode ? 1 : chunk.length;
11326 }
11327 }
11328 state.ended = true;
11329
11330 // if we've ended and we have some data left, then emit
11331 // 'readable' now to make sure it gets picked up.
11332 if (state.length > 0)
11333 emitReadable(stream);
11334 else
11335 endReadable(stream);
11336}
11337
11338// Don't emit readable right away in sync mode, because this can trigger
11339// another read() call => stack overflow. This way, it might trigger
11340// a nextTick recursion warning, but that's not so bad.
11341function emitReadable(stream) {
11342 var state = stream._readableState;
11343 state.needReadable = false;
11344 if (state.emittedReadable)
11345 return;
11346
11347 state.emittedReadable = true;
11348 if (state.sync)
11349 process.nextTick(function() {
11350 emitReadable_(stream);
11351 });
11352 else
11353 emitReadable_(stream);
11354}
11355
11356function emitReadable_(stream) {
11357 stream.emit('readable');
11358}
11359
11360
11361// at this point, the user has presumably seen the 'readable' event,
11362// and called read() to consume some data. that may have triggered
11363// in turn another _read(n) call, in which case reading = true if
11364// it's in progress.
11365// However, if we're not ended, or reading, and the length < hwm,
11366// then go ahead and try to read some more preemptively.
11367function maybeReadMore(stream, state) {
11368 if (!state.readingMore) {
11369 state.readingMore = true;
11370 process.nextTick(function() {
11371 maybeReadMore_(stream, state);
11372 });
11373 }
11374}
11375
11376function maybeReadMore_(stream, state) {
11377 var len = state.length;
11378 while (!state.reading && !state.flowing && !state.ended &&
11379 state.length < state.highWaterMark) {
11380 stream.read(0);
11381 if (len === state.length)
11382 // didn't get any data, stop spinning.
11383 break;
11384 else
11385 len = state.length;
11386 }
11387 state.readingMore = false;
11388}
11389
11390// abstract method. to be overridden in specific implementation classes.
11391// call cb(er, data) where data is <= n in length.
11392// for virtual (non-string, non-buffer) streams, "length" is somewhat
11393// arbitrary, and perhaps not very meaningful.
11394Readable.prototype._read = function(n) {
11395 this.emit('error', new Error('not implemented'));
11396};
11397
11398Readable.prototype.pipe = function(dest, pipeOpts) {
11399 var src = this;
11400 var state = this._readableState;
11401
11402 switch (state.pipesCount) {
11403 case 0:
11404 state.pipes = dest;
11405 break;
11406 case 1:
11407 state.pipes = [state.pipes, dest];
11408 break;
11409 default:
11410 state.pipes.push(dest);
11411 break;
11412 }
11413 state.pipesCount += 1;
11414
11415 var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
11416 dest !== process.stdout &&
11417 dest !== process.stderr;
11418
11419 var endFn = doEnd ? onend : cleanup;
11420 if (state.endEmitted)
11421 process.nextTick(endFn);
11422 else
11423 src.once('end', endFn);
11424
11425 dest.on('unpipe', onunpipe);
11426 function onunpipe(readable) {
11427 if (readable !== src) return;
11428 cleanup();
11429 }
11430
11431 function onend() {
11432 dest.end();
11433 }
11434
11435 // when the dest drains, it reduces the awaitDrain counter
11436 // on the source. This would be more elegant with a .once()
11437 // handler in flow(), but adding and removing repeatedly is
11438 // too slow.
11439 var ondrain = pipeOnDrain(src);
11440 dest.on('drain', ondrain);
11441
11442 function cleanup() {
11443 // cleanup event handlers once the pipe is broken
11444 dest.removeListener('close', onclose);
11445 dest.removeListener('finish', onfinish);
11446 dest.removeListener('drain', ondrain);
11447 dest.removeListener('error', onerror);
11448 dest.removeListener('unpipe', onunpipe);
11449 src.removeListener('end', onend);
11450 src.removeListener('end', cleanup);
11451
11452 // if the reader is waiting for a drain event from this
11453 // specific writer, then it would cause it to never start
11454 // flowing again.
11455 // So, if this is awaiting a drain, then we just call it now.
11456 // If we don't know, then assume that we are waiting for one.
11457 if (!dest._writableState || dest._writableState.needDrain)
11458 ondrain();
11459 }
11460
11461 // if the dest has an error, then stop piping into it.
11462 // however, don't suppress the throwing behavior for this.
11463 function onerror(er) {
11464 unpipe();
11465 dest.removeListener('error', onerror);
11466 if (EE.listenerCount(dest, 'error') === 0)
11467 dest.emit('error', er);
11468 }
11469 // This is a brutally ugly hack to make sure that our error handler
11470 // is attached before any userland ones. NEVER DO THIS.
11471 if (!dest._events || !dest._events.error)
11472 dest.on('error', onerror);
11473 else if (isArray(dest._events.error))
11474 dest._events.error.unshift(onerror);
11475 else
11476 dest._events.error = [onerror, dest._events.error];
11477
11478
11479
11480 // Both close and finish should trigger unpipe, but only once.
11481 function onclose() {
11482 dest.removeListener('finish', onfinish);
11483 unpipe();
11484 }
11485 dest.once('close', onclose);
11486 function onfinish() {
11487 dest.removeListener('close', onclose);
11488 unpipe();
11489 }
11490 dest.once('finish', onfinish);
11491
11492 function unpipe() {
11493 src.unpipe(dest);
11494 }
11495
11496 // tell the dest that it's being piped to
11497 dest.emit('pipe', src);
11498
11499 // start the flow if it hasn't been started already.
11500 if (!state.flowing) {
11501 // the handler that waits for readable events after all
11502 // the data gets sucked out in flow.
11503 // This would be easier to follow with a .once() handler
11504 // in flow(), but that is too slow.
11505 this.on('readable', pipeOnReadable);
11506
11507 state.flowing = true;
11508 process.nextTick(function() {
11509 flow(src);
11510 });
11511 }
11512
11513 return dest;
11514};
11515
11516function pipeOnDrain(src) {
11517 return function() {
11518 var dest = this;
11519 var state = src._readableState;
11520 state.awaitDrain--;
11521 if (state.awaitDrain === 0)
11522 flow(src);
11523 };
11524}
11525
11526function flow(src) {
11527 var state = src._readableState;
11528 var chunk;
11529 state.awaitDrain = 0;
11530
11531 function write(dest, i, list) {
11532 var written = dest.write(chunk);
11533 if (false === written) {
11534 state.awaitDrain++;
11535 }
11536 }
11537
11538 while (state.pipesCount && null !== (chunk = src.read())) {
11539
11540 if (state.pipesCount === 1)
11541 write(state.pipes, 0, null);
11542 else
11543 forEach(state.pipes, write);
11544
11545 src.emit('data', chunk);
11546
11547 // if anyone needs a drain, then we have to wait for that.
11548 if (state.awaitDrain > 0)
11549 return;
11550 }
11551
11552 // if every destination was unpiped, either before entering this
11553 // function, or in the while loop, then stop flowing.
11554 //
11555 // NB: This is a pretty rare edge case.
11556 if (state.pipesCount === 0) {
11557 state.flowing = false;
11558
11559 // if there were data event listeners added, then switch to old mode.
11560 if (EE.listenerCount(src, 'data') > 0)
11561 emitDataEvents(src);
11562 return;
11563 }
11564
11565 // at this point, no one needed a drain, so we just ran out of data
11566 // on the next readable event, start it over again.
11567 state.ranOut = true;
11568}
11569
11570function pipeOnReadable() {
11571 if (this._readableState.ranOut) {
11572 this._readableState.ranOut = false;
11573 flow(this);
11574 }
11575}
11576
11577
11578Readable.prototype.unpipe = function(dest) {
11579 var state = this._readableState;
11580
11581 // if we're not piping anywhere, then do nothing.
11582 if (state.pipesCount === 0)
11583 return this;
11584
11585 // just one destination. most common case.
11586 if (state.pipesCount === 1) {
11587 // passed in one, but it's not the right one.
11588 if (dest && dest !== state.pipes)
11589 return this;
11590
11591 if (!dest)
11592 dest = state.pipes;
11593
11594 // got a match.
11595 state.pipes = null;
11596 state.pipesCount = 0;
11597 this.removeListener('readable', pipeOnReadable);
11598 state.flowing = false;
11599 if (dest)
11600 dest.emit('unpipe', this);
11601 return this;
11602 }
11603
11604 // slow case. multiple pipe destinations.
11605
11606 if (!dest) {
11607 // remove all.
11608 var dests = state.pipes;
11609 var len = state.pipesCount;
11610 state.pipes = null;
11611 state.pipesCount = 0;
11612 this.removeListener('readable', pipeOnReadable);
11613 state.flowing = false;
11614
11615 for (var i = 0; i < len; i++)
11616 dests[i].emit('unpipe', this);
11617 return this;
11618 }
11619
11620 // try to find the right one.
11621 var i = indexOf(state.pipes, dest);
11622 if (i === -1)
11623 return this;
11624
11625 state.pipes.splice(i, 1);
11626 state.pipesCount -= 1;
11627 if (state.pipesCount === 1)
11628 state.pipes = state.pipes[0];
11629
11630 dest.emit('unpipe', this);
11631
11632 return this;
11633};
11634
11635// set up data events if they are asked for
11636// Ensure readable listeners eventually get something
11637Readable.prototype.on = function(ev, fn) {
11638 var res = Stream.prototype.on.call(this, ev, fn);
11639
11640 if (ev === 'data' && !this._readableState.flowing)
11641 emitDataEvents(this);
11642
11643 if (ev === 'readable' && this.readable) {
11644 var state = this._readableState;
11645 if (!state.readableListening) {
11646 state.readableListening = true;
11647 state.emittedReadable = false;
11648 state.needReadable = true;
11649 if (!state.reading) {
11650 this.read(0);
11651 } else if (state.length) {
11652 emitReadable(this, state);
11653 }
11654 }
11655 }
11656
11657 return res;
11658};
11659Readable.prototype.addListener = Readable.prototype.on;
11660
11661// pause() and resume() are remnants of the legacy readable stream API
11662// If the user uses them, then switch into old mode.
11663Readable.prototype.resume = function() {
11664 emitDataEvents(this);
11665 this.read(0);
11666 this.emit('resume');
11667};
11668
11669Readable.prototype.pause = function() {
11670 emitDataEvents(this, true);
11671 this.emit('pause');
11672};
11673
11674function emitDataEvents(stream, startPaused) {
11675 var state = stream._readableState;
11676
11677 if (state.flowing) {
11678 // https://github.com/isaacs/readable-stream/issues/16
11679 throw new Error('Cannot switch to old mode now.');
11680 }
11681
11682 var paused = startPaused || false;
11683 var readable = false;
11684
11685 // convert to an old-style stream.
11686 stream.readable = true;
11687 stream.pipe = Stream.prototype.pipe;
11688 stream.on = stream.addListener = Stream.prototype.on;
11689
11690 stream.on('readable', function() {
11691 readable = true;
11692
11693 var c;
11694 while (!paused && (null !== (c = stream.read())))
11695 stream.emit('data', c);
11696
11697 if (c === null) {
11698 readable = false;
11699 stream._readableState.needReadable = true;
11700 }
11701 });
11702
11703 stream.pause = function() {
11704 paused = true;
11705 this.emit('pause');
11706 };
11707
11708 stream.resume = function() {
11709 paused = false;
11710 if (readable)
11711 process.nextTick(function() {
11712 stream.emit('readable');
11713 });
11714 else
11715 this.read(0);
11716 this.emit('resume');
11717 };
11718
11719 // now make it start, just in case it hadn't already.
11720 stream.emit('readable');
11721}
11722
11723// wrap an old-style stream as the async data source.
11724// This is *not* part of the readable stream interface.
11725// It is an ugly unfortunate mess of history.
11726Readable.prototype.wrap = function(stream) {
11727 var state = this._readableState;
11728 var paused = false;
11729
11730 var self = this;
11731 stream.on('end', function() {
11732 if (state.decoder && !state.ended) {
11733 var chunk = state.decoder.end();
11734 if (chunk && chunk.length)
11735 self.push(chunk);
11736 }
11737
11738 self.push(null);
11739 });
11740
11741 stream.on('data', function(chunk) {
11742 if (state.decoder)
11743 chunk = state.decoder.write(chunk);
11744
11745 // don't skip over falsy values in objectMode
11746 //if (state.objectMode && util.isNullOrUndefined(chunk))
11747 if (state.objectMode && (chunk === null || chunk === undefined))
11748 return;
11749 else if (!state.objectMode && (!chunk || !chunk.length))
11750 return;
11751
11752 var ret = self.push(chunk);
11753 if (!ret) {
11754 paused = true;
11755 stream.pause();
11756 }
11757 });
11758
11759 // proxy all the other methods.
11760 // important when wrapping filters and duplexes.
11761 for (var i in stream) {
11762 if (typeof stream[i] === 'function' &&
11763 typeof this[i] === 'undefined') {
11764 this[i] = function(method) { return function() {
11765 return stream[method].apply(stream, arguments);
11766 }}(i);
11767 }
11768 }
11769
11770 // proxy certain important events.
11771 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
11772 forEach(events, function(ev) {
11773 stream.on(ev, self.emit.bind(self, ev));
11774 });
11775
11776 // when we try to consume some more bytes, simply unpause the
11777 // underlying stream.
11778 self._read = function(n) {
11779 if (paused) {
11780 paused = false;
11781 stream.resume();
11782 }
11783 };
11784
11785 return self;
11786};
11787
11788
11789
11790// exposed for testing purposes only.
11791Readable._fromList = fromList;
11792
11793// Pluck off n bytes from an array of buffers.
11794// Length is the combined lengths of all the buffers in the list.
11795function fromList(n, state) {
11796 var list = state.buffer;
11797 var length = state.length;
11798 var stringMode = !!state.decoder;
11799 var objectMode = !!state.objectMode;
11800 var ret;
11801
11802 // nothing in the list, definitely empty.
11803 if (list.length === 0)
11804 return null;
11805
11806 if (length === 0)
11807 ret = null;
11808 else if (objectMode)
11809 ret = list.shift();
11810 else if (!n || n >= length) {
11811 // read it all, truncate the array.
11812 if (stringMode)
11813 ret = list.join('');
11814 else
11815 ret = Buffer.concat(list, length);
11816 list.length = 0;
11817 } else {
11818 // read just some of it.
11819 if (n < list[0].length) {
11820 // just take a part of the first list item.
11821 // slice is the same for buffers and strings.
11822 var buf = list[0];
11823 ret = buf.slice(0, n);
11824 list[0] = buf.slice(n);
11825 } else if (n === list[0].length) {
11826 // first list is a perfect match
11827 ret = list.shift();
11828 } else {
11829 // complex case.
11830 // we have enough to cover it, but it spans past the first buffer.
11831 if (stringMode)
11832 ret = '';
11833 else
11834 ret = new Buffer(n);
11835
11836 var c = 0;
11837 for (var i = 0, l = list.length; i < l && c < n; i++) {
11838 var buf = list[0];
11839 var cpy = Math.min(n - c, buf.length);
11840
11841 if (stringMode)
11842 ret += buf.slice(0, cpy);
11843 else
11844 buf.copy(ret, c, 0, cpy);
11845
11846 if (cpy < buf.length)
11847 list[0] = buf.slice(cpy);
11848 else
11849 list.shift();
11850
11851 c += cpy;
11852 }
11853 }
11854 }
11855
11856 return ret;
11857}
11858
11859function endReadable(stream) {
11860 var state = stream._readableState;
11861
11862 // If we get here before consuming all the bytes, then that is a
11863 // bug in node. Should never happen.
11864 if (state.length > 0)
11865 throw new Error('endReadable called on non-empty stream');
11866
11867 if (!state.endEmitted && state.calledRead) {
11868 state.ended = true;
11869 process.nextTick(function() {
11870 // Check that we didn't get one last unshift.
11871 if (!state.endEmitted && state.length === 0) {
11872 state.endEmitted = true;
11873 stream.readable = false;
11874 stream.emit('end');
11875 }
11876 });
11877 }
11878}
11879
11880function forEach (xs, f) {
11881 for (var i = 0, l = xs.length; i < l; i++) {
11882 f(xs[i], i);
11883 }
11884}
11885
11886function indexOf (xs, x) {
11887 for (var i = 0, l = xs.length; i < l; i++) {
11888 if (xs[i] === x) return i;
11889 }
11890 return -1;
11891}
11892
11893}).call(this,_dereq_(69))
11894},{"12":12,"13":13,"25":25,"31":31,"33":33,"69":69,"76":76,"80":80}],74:[function(_dereq_,module,exports){
11895// Copyright Joyent, Inc. and other Node contributors.
11896//
11897// Permission is hereby granted, free of charge, to any person obtaining a
11898// copy of this software and associated documentation files (the
11899// "Software"), to deal in the Software without restriction, including
11900// without limitation the rights to use, copy, modify, merge, publish,
11901// distribute, sublicense, and/or sell copies of the Software, and to permit
11902// persons to whom the Software is furnished to do so, subject to the
11903// following conditions:
11904//
11905// The above copyright notice and this permission notice shall be included
11906// in all copies or substantial portions of the Software.
11907//
11908// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11909// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11910// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11911// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11912// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11913// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11914// USE OR OTHER DEALINGS IN THE SOFTWARE.
11915
11916
11917// a transform stream is a readable/writable stream where you do
11918// something with the data. Sometimes it's called a "filter",
11919// but that's not a great name for it, since that implies a thing where
11920// some bits pass through, and others are simply ignored. (That would
11921// be a valid example of a transform, of course.)
11922//
11923// While the output is causally related to the input, it's not a
11924// necessarily symmetric or synchronous transformation. For example,
11925// a zlib stream might take multiple plain-text writes(), and then
11926// emit a single compressed chunk some time in the future.
11927//
11928// Here's how this works:
11929//
11930// The Transform stream has all the aspects of the readable and writable
11931// stream classes. When you write(chunk), that calls _write(chunk,cb)
11932// internally, and returns false if there's a lot of pending writes
11933// buffered up. When you call read(), that calls _read(n) until
11934// there's enough pending readable data buffered up.
11935//
11936// In a transform stream, the written data is placed in a buffer. When
11937// _read(n) is called, it transforms the queued up data, calling the
11938// buffered _write cb's as it consumes chunks. If consuming a single
11939// written chunk would result in multiple output chunks, then the first
11940// outputted bit calls the readcb, and subsequent chunks just go into
11941// the read buffer, and will cause it to emit 'readable' if necessary.
11942//
11943// This way, back-pressure is actually determined by the reading side,
11944// since _read has to be called to start processing a new chunk. However,
11945// a pathological inflate type of transform can cause excessive buffering
11946// here. For example, imagine a stream where every byte of input is
11947// interpreted as an integer from 0-255, and then results in that many
11948// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
11949// 1kb of data being output. In this case, you could write a very small
11950// amount of input, and end up with a very large amount of output. In
11951// such a pathological inflating mechanism, there'd be no way to tell
11952// the system to stop doing the transform. A single 4MB write could
11953// cause the system to run out of memory.
11954//
11955// However, even in such a pathological case, only a single written chunk
11956// would be consumed, and then the rest would wait (un-transformed) until
11957// the results of the previous transformed chunk were consumed.
11958
11959module.exports = Transform;
11960
11961var Duplex = _dereq_(71);
11962
11963/*<replacement>*/
11964var util = _dereq_(13);
11965util.inherits = _dereq_(31);
11966/*</replacement>*/
11967
11968util.inherits(Transform, Duplex);
11969
11970
11971function TransformState(options, stream) {
11972 this.afterTransform = function(er, data) {
11973 return afterTransform(stream, er, data);
11974 };
11975
11976 this.needTransform = false;
11977 this.transforming = false;
11978 this.writecb = null;
11979 this.writechunk = null;
11980}
11981
11982function afterTransform(stream, er, data) {
11983 var ts = stream._transformState;
11984 ts.transforming = false;
11985
11986 var cb = ts.writecb;
11987
11988 if (!cb)
11989 return stream.emit('error', new Error('no writecb in Transform class'));
11990
11991 ts.writechunk = null;
11992 ts.writecb = null;
11993
11994 if (data !== null && data !== undefined)
11995 stream.push(data);
11996
11997 if (cb)
11998 cb(er);
11999
12000 var rs = stream._readableState;
12001 rs.reading = false;
12002 if (rs.needReadable || rs.length < rs.highWaterMark) {
12003 stream._read(rs.highWaterMark);
12004 }
12005}
12006
12007
12008function Transform(options) {
12009 if (!(this instanceof Transform))
12010 return new Transform(options);
12011
12012 Duplex.call(this, options);
12013
12014 var ts = this._transformState = new TransformState(options, this);
12015
12016 // when the writable side finishes, then flush out anything remaining.
12017 var stream = this;
12018
12019 // start out asking for a readable event once data is transformed.
12020 this._readableState.needReadable = true;
12021
12022 // we have implemented the _read method, and done the other things
12023 // that Readable wants before the first _read call, so unset the
12024 // sync guard flag.
12025 this._readableState.sync = false;
12026
12027 this.once('finish', function() {
12028 if ('function' === typeof this._flush)
12029 this._flush(function(er) {
12030 done(stream, er);
12031 });
12032 else
12033 done(stream);
12034 });
12035}
12036
12037Transform.prototype.push = function(chunk, encoding) {
12038 this._transformState.needTransform = false;
12039 return Duplex.prototype.push.call(this, chunk, encoding);
12040};
12041
12042// This is the part where you do stuff!
12043// override this function in implementation classes.
12044// 'chunk' is an input chunk.
12045//
12046// Call `push(newChunk)` to pass along transformed output
12047// to the readable side. You may call 'push' zero or more times.
12048//
12049// Call `cb(err)` when you are done with this chunk. If you pass
12050// an error, then that'll put the hurt on the whole operation. If you
12051// never call cb(), then you'll never get another chunk.
12052Transform.prototype._transform = function(chunk, encoding, cb) {
12053 throw new Error('not implemented');
12054};
12055
12056Transform.prototype._write = function(chunk, encoding, cb) {
12057 var ts = this._transformState;
12058 ts.writecb = cb;
12059 ts.writechunk = chunk;
12060 ts.writeencoding = encoding;
12061 if (!ts.transforming) {
12062 var rs = this._readableState;
12063 if (ts.needTransform ||
12064 rs.needReadable ||
12065 rs.length < rs.highWaterMark)
12066 this._read(rs.highWaterMark);
12067 }
12068};
12069
12070// Doesn't matter what the args are here.
12071// _transform does all the work.
12072// That we got here means that the readable side wants more data.
12073Transform.prototype._read = function(n) {
12074 var ts = this._transformState;
12075
12076 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
12077 ts.transforming = true;
12078 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
12079 } else {
12080 // mark that we need a transform, so that any data that comes in
12081 // will get processed, now that we've asked for it.
12082 ts.needTransform = true;
12083 }
12084};
12085
12086
12087function done(stream, er) {
12088 if (er)
12089 return stream.emit('error', er);
12090
12091 // if there's nothing in the write buffer, then that means
12092 // that nothing more will ever be provided
12093 var ws = stream._writableState;
12094 var rs = stream._readableState;
12095 var ts = stream._transformState;
12096
12097 if (ws.length)
12098 throw new Error('calling transform done when ws.length != 0');
12099
12100 if (ts.transforming)
12101 throw new Error('calling transform done when still transforming');
12102
12103 return stream.push(null);
12104}
12105
12106},{"13":13,"31":31,"71":71}],75:[function(_dereq_,module,exports){
12107(function (process){
12108// Copyright Joyent, Inc. and other Node contributors.
12109//
12110// Permission is hereby granted, free of charge, to any person obtaining a
12111// copy of this software and associated documentation files (the
12112// "Software"), to deal in the Software without restriction, including
12113// without limitation the rights to use, copy, modify, merge, publish,
12114// distribute, sublicense, and/or sell copies of the Software, and to permit
12115// persons to whom the Software is furnished to do so, subject to the
12116// following conditions:
12117//
12118// The above copyright notice and this permission notice shall be included
12119// in all copies or substantial portions of the Software.
12120//
12121// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12122// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12123// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12124// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12125// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12126// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12127// USE OR OTHER DEALINGS IN THE SOFTWARE.
12128
12129// A bit simpler than readable streams.
12130// Implement an async ._write(chunk, cb), and it'll handle all
12131// the drain event emission and buffering.
12132
12133module.exports = Writable;
12134
12135/*<replacement>*/
12136var Buffer = _dereq_(12).Buffer;
12137/*</replacement>*/
12138
12139Writable.WritableState = WritableState;
12140
12141
12142/*<replacement>*/
12143var util = _dereq_(13);
12144util.inherits = _dereq_(31);
12145/*</replacement>*/
12146
12147var Stream = _dereq_(80);
12148
12149util.inherits(Writable, Stream);
12150
12151function WriteReq(chunk, encoding, cb) {
12152 this.chunk = chunk;
12153 this.encoding = encoding;
12154 this.callback = cb;
12155}
12156
12157function WritableState(options, stream) {
12158 options = options || {};
12159
12160 // the point at which write() starts returning false
12161 // Note: 0 is a valid value, means that we always return false if
12162 // the entire buffer is not flushed immediately on write()
12163 var hwm = options.highWaterMark;
12164 this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
12165
12166 // object stream flag to indicate whether or not this stream
12167 // contains buffers or objects.
12168 this.objectMode = !!options.objectMode;
12169
12170 // cast to ints.
12171 this.highWaterMark = ~~this.highWaterMark;
12172
12173 this.needDrain = false;
12174 // at the start of calling end()
12175 this.ending = false;
12176 // when end() has been called, and returned
12177 this.ended = false;
12178 // when 'finish' is emitted
12179 this.finished = false;
12180
12181 // should we decode strings into buffers before passing to _write?
12182 // this is here so that some node-core streams can optimize string
12183 // handling at a lower level.
12184 var noDecode = options.decodeStrings === false;
12185 this.decodeStrings = !noDecode;
12186
12187 // Crypto is kind of old and crusty. Historically, its default string
12188 // encoding is 'binary' so we have to make this configurable.
12189 // Everything else in the universe uses 'utf8', though.
12190 this.defaultEncoding = options.defaultEncoding || 'utf8';
12191
12192 // not an actual buffer we keep track of, but a measurement
12193 // of how much we're waiting to get pushed to some underlying
12194 // socket or file.
12195 this.length = 0;
12196
12197 // a flag to see when we're in the middle of a write.
12198 this.writing = false;
12199
12200 // a flag to be able to tell if the onwrite cb is called immediately,
12201 // or on a later tick. We set this to true at first, becuase any
12202 // actions that shouldn't happen until "later" should generally also
12203 // not happen before the first write call.
12204 this.sync = true;
12205
12206 // a flag to know if we're processing previously buffered items, which
12207 // may call the _write() callback in the same tick, so that we don't
12208 // end up in an overlapped onwrite situation.
12209 this.bufferProcessing = false;
12210
12211 // the callback that's passed to _write(chunk,cb)
12212 this.onwrite = function(er) {
12213 onwrite(stream, er);
12214 };
12215
12216 // the callback that the user supplies to write(chunk,encoding,cb)
12217 this.writecb = null;
12218
12219 // the amount that is being written when _write is called.
12220 this.writelen = 0;
12221
12222 this.buffer = [];
12223
12224 // True if the error was already emitted and should not be thrown again
12225 this.errorEmitted = false;
12226}
12227
12228function Writable(options) {
12229 var Duplex = _dereq_(71);
12230
12231 // Writable ctor is applied to Duplexes, though they're not
12232 // instanceof Writable, they're instanceof Readable.
12233 if (!(this instanceof Writable) && !(this instanceof Duplex))
12234 return new Writable(options);
12235
12236 this._writableState = new WritableState(options, this);
12237
12238 // legacy.
12239 this.writable = true;
12240
12241 Stream.call(this);
12242}
12243
12244// Otherwise people can pipe Writable streams, which is just wrong.
12245Writable.prototype.pipe = function() {
12246 this.emit('error', new Error('Cannot pipe. Not readable.'));
12247};
12248
12249
12250function writeAfterEnd(stream, state, cb) {
12251 var er = new Error('write after end');
12252 // TODO: defer error events consistently everywhere, not just the cb
12253 stream.emit('error', er);
12254 process.nextTick(function() {
12255 cb(er);
12256 });
12257}
12258
12259// If we get something that is not a buffer, string, null, or undefined,
12260// and we're not in objectMode, then that's an error.
12261// Otherwise stream chunks are all considered to be of length=1, and the
12262// watermarks determine how many objects to keep in the buffer, rather than
12263// how many bytes or characters.
12264function validChunk(stream, state, chunk, cb) {
12265 var valid = true;
12266 if (!Buffer.isBuffer(chunk) &&
12267 'string' !== typeof chunk &&
12268 chunk !== null &&
12269 chunk !== undefined &&
12270 !state.objectMode) {
12271 var er = new TypeError('Invalid non-string/buffer chunk');
12272 stream.emit('error', er);
12273 process.nextTick(function() {
12274 cb(er);
12275 });
12276 valid = false;
12277 }
12278 return valid;
12279}
12280
12281Writable.prototype.write = function(chunk, encoding, cb) {
12282 var state = this._writableState;
12283 var ret = false;
12284
12285 if (typeof encoding === 'function') {
12286 cb = encoding;
12287 encoding = null;
12288 }
12289
12290 if (Buffer.isBuffer(chunk))
12291 encoding = 'buffer';
12292 else if (!encoding)
12293 encoding = state.defaultEncoding;
12294
12295 if (typeof cb !== 'function')
12296 cb = function() {};
12297
12298 if (state.ended)
12299 writeAfterEnd(this, state, cb);
12300 else if (validChunk(this, state, chunk, cb))
12301 ret = writeOrBuffer(this, state, chunk, encoding, cb);
12302
12303 return ret;
12304};
12305
12306function decodeChunk(state, chunk, encoding) {
12307 if (!state.objectMode &&
12308 state.decodeStrings !== false &&
12309 typeof chunk === 'string') {
12310 chunk = new Buffer(chunk, encoding);
12311 }
12312 return chunk;
12313}
12314
12315// if we're already writing something, then just put this
12316// in the queue, and wait our turn. Otherwise, call _write
12317// If we return false, then we need a drain event, so set that flag.
12318function writeOrBuffer(stream, state, chunk, encoding, cb) {
12319 chunk = decodeChunk(state, chunk, encoding);
12320 if (Buffer.isBuffer(chunk))
12321 encoding = 'buffer';
12322 var len = state.objectMode ? 1 : chunk.length;
12323
12324 state.length += len;
12325
12326 var ret = state.length < state.highWaterMark;
12327 // we must ensure that previous needDrain will not be reset to false.
12328 if (!ret)
12329 state.needDrain = true;
12330
12331 if (state.writing)
12332 state.buffer.push(new WriteReq(chunk, encoding, cb));
12333 else
12334 doWrite(stream, state, len, chunk, encoding, cb);
12335
12336 return ret;
12337}
12338
12339function doWrite(stream, state, len, chunk, encoding, cb) {
12340 state.writelen = len;
12341 state.writecb = cb;
12342 state.writing = true;
12343 state.sync = true;
12344 stream._write(chunk, encoding, state.onwrite);
12345 state.sync = false;
12346}
12347
12348function onwriteError(stream, state, sync, er, cb) {
12349 if (sync)
12350 process.nextTick(function() {
12351 cb(er);
12352 });
12353 else
12354 cb(er);
12355
12356 stream._writableState.errorEmitted = true;
12357 stream.emit('error', er);
12358}
12359
12360function onwriteStateUpdate(state) {
12361 state.writing = false;
12362 state.writecb = null;
12363 state.length -= state.writelen;
12364 state.writelen = 0;
12365}
12366
12367function onwrite(stream, er) {
12368 var state = stream._writableState;
12369 var sync = state.sync;
12370 var cb = state.writecb;
12371
12372 onwriteStateUpdate(state);
12373
12374 if (er)
12375 onwriteError(stream, state, sync, er, cb);
12376 else {
12377 // Check if we're actually ready to finish, but don't emit yet
12378 var finished = needFinish(stream, state);
12379
12380 if (!finished && !state.bufferProcessing && state.buffer.length)
12381 clearBuffer(stream, state);
12382
12383 if (sync) {
12384 process.nextTick(function() {
12385 afterWrite(stream, state, finished, cb);
12386 });
12387 } else {
12388 afterWrite(stream, state, finished, cb);
12389 }
12390 }
12391}
12392
12393function afterWrite(stream, state, finished, cb) {
12394 if (!finished)
12395 onwriteDrain(stream, state);
12396 cb();
12397 if (finished)
12398 finishMaybe(stream, state);
12399}
12400
12401// Must force callback to be called on nextTick, so that we don't
12402// emit 'drain' before the write() consumer gets the 'false' return
12403// value, and has a chance to attach a 'drain' listener.
12404function onwriteDrain(stream, state) {
12405 if (state.length === 0 && state.needDrain) {
12406 state.needDrain = false;
12407 stream.emit('drain');
12408 }
12409}
12410
12411
12412// if there's something in the buffer waiting, then process it
12413function clearBuffer(stream, state) {
12414 state.bufferProcessing = true;
12415
12416 for (var c = 0; c < state.buffer.length; c++) {
12417 var entry = state.buffer[c];
12418 var chunk = entry.chunk;
12419 var encoding = entry.encoding;
12420 var cb = entry.callback;
12421 var len = state.objectMode ? 1 : chunk.length;
12422
12423 doWrite(stream, state, len, chunk, encoding, cb);
12424
12425 // if we didn't call the onwrite immediately, then
12426 // it means that we need to wait until it does.
12427 // also, that means that the chunk and cb are currently
12428 // being processed, so move the buffer counter past them.
12429 if (state.writing) {
12430 c++;
12431 break;
12432 }
12433 }
12434
12435 state.bufferProcessing = false;
12436 if (c < state.buffer.length)
12437 state.buffer = state.buffer.slice(c);
12438 else
12439 state.buffer.length = 0;
12440}
12441
12442Writable.prototype._write = function(chunk, encoding, cb) {
12443 cb(new Error('not implemented'));
12444};
12445
12446Writable.prototype.end = function(chunk, encoding, cb) {
12447 var state = this._writableState;
12448
12449 if (typeof chunk === 'function') {
12450 cb = chunk;
12451 chunk = null;
12452 encoding = null;
12453 } else if (typeof encoding === 'function') {
12454 cb = encoding;
12455 encoding = null;
12456 }
12457
12458 if (typeof chunk !== 'undefined' && chunk !== null)
12459 this.write(chunk, encoding);
12460
12461 // ignore unnecessary end() calls.
12462 if (!state.ending && !state.finished)
12463 endWritable(this, state, cb);
12464};
12465
12466
12467function needFinish(stream, state) {
12468 return (state.ending &&
12469 state.length === 0 &&
12470 !state.finished &&
12471 !state.writing);
12472}
12473
12474function finishMaybe(stream, state) {
12475 var need = needFinish(stream, state);
12476 if (need) {
12477 state.finished = true;
12478 stream.emit('finish');
12479 }
12480 return need;
12481}
12482
12483function endWritable(stream, state, cb) {
12484 state.ending = true;
12485 finishMaybe(stream, state);
12486 if (cb) {
12487 if (state.finished)
12488 process.nextTick(cb);
12489 else
12490 stream.once('finish', cb);
12491 }
12492 state.ended = true;
12493}
12494
12495}).call(this,_dereq_(69))
12496},{"12":12,"13":13,"31":31,"69":69,"71":71,"80":80}],76:[function(_dereq_,module,exports){
12497// Copyright Joyent, Inc. and other Node contributors.
12498//
12499// Permission is hereby granted, free of charge, to any person obtaining a
12500// copy of this software and associated documentation files (the
12501// "Software"), to deal in the Software without restriction, including
12502// without limitation the rights to use, copy, modify, merge, publish,
12503// distribute, sublicense, and/or sell copies of the Software, and to permit
12504// persons to whom the Software is furnished to do so, subject to the
12505// following conditions:
12506//
12507// The above copyright notice and this permission notice shall be included
12508// in all copies or substantial portions of the Software.
12509//
12510// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12511// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12512// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12513// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12514// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12515// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12516// USE OR OTHER DEALINGS IN THE SOFTWARE.
12517
12518var Buffer = _dereq_(12).Buffer;
12519
12520var isBufferEncoding = Buffer.isEncoding
12521 || function(encoding) {
12522 switch (encoding && encoding.toLowerCase()) {
12523 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;
12524 default: return false;
12525 }
12526 }
12527
12528
12529function assertEncoding(encoding) {
12530 if (encoding && !isBufferEncoding(encoding)) {
12531 throw new Error('Unknown encoding: ' + encoding);
12532 }
12533}
12534
12535// StringDecoder provides an interface for efficiently splitting a series of
12536// buffers into a series of JS strings without breaking apart multi-byte
12537// characters. CESU-8 is handled as part of the UTF-8 encoding.
12538//
12539// @TODO Handling all encodings inside a single object makes it very difficult
12540// to reason about this code, so it should be split up in the future.
12541// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
12542// points as used by CESU-8.
12543var StringDecoder = exports.StringDecoder = function(encoding) {
12544 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
12545 assertEncoding(encoding);
12546 switch (this.encoding) {
12547 case 'utf8':
12548 // CESU-8 represents each of Surrogate Pair by 3-bytes
12549 this.surrogateSize = 3;
12550 break;
12551 case 'ucs2':
12552 case 'utf16le':
12553 // UTF-16 represents each of Surrogate Pair by 2-bytes
12554 this.surrogateSize = 2;
12555 this.detectIncompleteChar = utf16DetectIncompleteChar;
12556 break;
12557 case 'base64':
12558 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
12559 this.surrogateSize = 3;
12560 this.detectIncompleteChar = base64DetectIncompleteChar;
12561 break;
12562 default:
12563 this.write = passThroughWrite;
12564 return;
12565 }
12566
12567 // Enough space to store all bytes of a single character. UTF-8 needs 4
12568 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
12569 this.charBuffer = new Buffer(6);
12570 // Number of bytes received for the current incomplete multi-byte character.
12571 this.charReceived = 0;
12572 // Number of bytes expected for the current incomplete multi-byte character.
12573 this.charLength = 0;
12574};
12575
12576
12577// write decodes the given buffer and returns it as JS string that is
12578// guaranteed to not contain any partial multi-byte characters. Any partial
12579// character found at the end of the buffer is buffered up, and will be
12580// returned when calling write again with the remaining bytes.
12581//
12582// Note: Converting a Buffer containing an orphan surrogate to a String
12583// currently works, but converting a String to a Buffer (via `new Buffer`, or
12584// Buffer#write) will replace incomplete surrogates with the unicode
12585// replacement character. See https://codereview.chromium.org/121173009/ .
12586StringDecoder.prototype.write = function(buffer) {
12587 var charStr = '';
12588 // if our last write ended with an incomplete multibyte character
12589 while (this.charLength) {
12590 // determine how many remaining bytes this buffer has to offer for this char
12591 var available = (buffer.length >= this.charLength - this.charReceived) ?
12592 this.charLength - this.charReceived :
12593 buffer.length;
12594
12595 // add the new bytes to the char buffer
12596 buffer.copy(this.charBuffer, this.charReceived, 0, available);
12597 this.charReceived += available;
12598
12599 if (this.charReceived < this.charLength) {
12600 // still not enough chars in this buffer? wait for more ...
12601 return '';
12602 }
12603
12604 // remove bytes belonging to the current character from the buffer
12605 buffer = buffer.slice(available, buffer.length);
12606
12607 // get the character that was split
12608 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
12609
12610 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
12611 var charCode = charStr.charCodeAt(charStr.length - 1);
12612 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
12613 this.charLength += this.surrogateSize;
12614 charStr = '';
12615 continue;
12616 }
12617 this.charReceived = this.charLength = 0;
12618
12619 // if there are no more bytes in this buffer, just emit our char
12620 if (buffer.length === 0) {
12621 return charStr;
12622 }
12623 break;
12624 }
12625
12626 // determine and set charLength / charReceived
12627 this.detectIncompleteChar(buffer);
12628
12629 var end = buffer.length;
12630 if (this.charLength) {
12631 // buffer the incomplete character bytes we got
12632 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
12633 end -= this.charReceived;
12634 }
12635
12636 charStr += buffer.toString(this.encoding, 0, end);
12637
12638 var end = charStr.length - 1;
12639 var charCode = charStr.charCodeAt(end);
12640 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
12641 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
12642 var size = this.surrogateSize;
12643 this.charLength += size;
12644 this.charReceived += size;
12645 this.charBuffer.copy(this.charBuffer, size, 0, size);
12646 buffer.copy(this.charBuffer, 0, 0, size);
12647 return charStr.substring(0, end);
12648 }
12649
12650 // or just emit the charStr
12651 return charStr;
12652};
12653
12654// detectIncompleteChar determines if there is an incomplete UTF-8 character at
12655// the end of the given buffer. If so, it sets this.charLength to the byte
12656// length that character, and sets this.charReceived to the number of bytes
12657// that are available for this character.
12658StringDecoder.prototype.detectIncompleteChar = function(buffer) {
12659 // determine how many bytes we have to check at the end of this buffer
12660 var i = (buffer.length >= 3) ? 3 : buffer.length;
12661
12662 // Figure out if one of the last i bytes of our buffer announces an
12663 // incomplete char.
12664 for (; i > 0; i--) {
12665 var c = buffer[buffer.length - i];
12666
12667 // See http://en.wikipedia.org/wiki/UTF-8#Description
12668
12669 // 110XXXXX
12670 if (i == 1 && c >> 5 == 0x06) {
12671 this.charLength = 2;
12672 break;
12673 }
12674
12675 // 1110XXXX
12676 if (i <= 2 && c >> 4 == 0x0E) {
12677 this.charLength = 3;
12678 break;
12679 }
12680
12681 // 11110XXX
12682 if (i <= 3 && c >> 3 == 0x1E) {
12683 this.charLength = 4;
12684 break;
12685 }
12686 }
12687 this.charReceived = i;
12688};
12689
12690StringDecoder.prototype.end = function(buffer) {
12691 var res = '';
12692 if (buffer && buffer.length)
12693 res = this.write(buffer);
12694
12695 if (this.charReceived) {
12696 var cr = this.charReceived;
12697 var buf = this.charBuffer;
12698 var enc = this.encoding;
12699 res += buf.slice(0, cr).toString(enc);
12700 }
12701
12702 return res;
12703};
12704
12705function passThroughWrite(buffer) {
12706 return buffer.toString(this.encoding);
12707}
12708
12709function utf16DetectIncompleteChar(buffer) {
12710 this.charReceived = buffer.length % 2;
12711 this.charLength = this.charReceived ? 2 : 0;
12712}
12713
12714function base64DetectIncompleteChar(buffer) {
12715 this.charReceived = buffer.length % 3;
12716 this.charLength = this.charReceived ? 3 : 0;
12717}
12718
12719},{"12":12}],77:[function(_dereq_,module,exports){
12720var Stream = _dereq_(80); // hack to fix a circular dependency issue when used with browserify
12721exports = module.exports = _dereq_(73);
12722exports.Stream = Stream;
12723exports.Readable = exports;
12724exports.Writable = _dereq_(75);
12725exports.Duplex = _dereq_(71);
12726exports.Transform = _dereq_(74);
12727exports.PassThrough = _dereq_(72);
12728
12729},{"71":71,"72":72,"73":73,"74":74,"75":75,"80":80}],78:[function(_dereq_,module,exports){
12730/* eslint-disable node/no-deprecated-api */
12731var buffer = _dereq_(12)
12732var Buffer = buffer.Buffer
12733
12734// alternative to using Object.keys for old browsers
12735function copyProps (src, dst) {
12736 for (var key in src) {
12737 dst[key] = src[key]
12738 }
12739}
12740if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
12741 module.exports = buffer
12742} else {
12743 // Copy properties from require('buffer')
12744 copyProps(buffer, exports)
12745 exports.Buffer = SafeBuffer
12746}
12747
12748function SafeBuffer (arg, encodingOrOffset, length) {
12749 return Buffer(arg, encodingOrOffset, length)
12750}
12751
12752// Copy static methods from Buffer
12753copyProps(Buffer, SafeBuffer)
12754
12755SafeBuffer.from = function (arg, encodingOrOffset, length) {
12756 if (typeof arg === 'number') {
12757 throw new TypeError('Argument must not be a number')
12758 }
12759 return Buffer(arg, encodingOrOffset, length)
12760}
12761
12762SafeBuffer.alloc = function (size, fill, encoding) {
12763 if (typeof size !== 'number') {
12764 throw new TypeError('Argument must be a number')
12765 }
12766 var buf = Buffer(size)
12767 if (fill !== undefined) {
12768 if (typeof encoding === 'string') {
12769 buf.fill(fill, encoding)
12770 } else {
12771 buf.fill(fill)
12772 }
12773 } else {
12774 buf.fill(0)
12775 }
12776 return buf
12777}
12778
12779SafeBuffer.allocUnsafe = function (size) {
12780 if (typeof size !== 'number') {
12781 throw new TypeError('Argument must be a number')
12782 }
12783 return Buffer(size)
12784}
12785
12786SafeBuffer.allocUnsafeSlow = function (size) {
12787 if (typeof size !== 'number') {
12788 throw new TypeError('Argument must be a number')
12789 }
12790 return buffer.SlowBuffer(size)
12791}
12792
12793},{"12":12}],79:[function(_dereq_,module,exports){
12794(function (factory) {
12795 if (typeof exports === 'object') {
12796 // Node/CommonJS
12797 module.exports = factory();
12798 } else if (typeof define === 'function' && define.amd) {
12799 // AMD
12800 define(factory);
12801 } else {
12802 // Browser globals (with support for web workers)
12803 var glob;
12804
12805 try {
12806 glob = window;
12807 } catch (e) {
12808 glob = self;
12809 }
12810
12811 glob.SparkMD5 = factory();
12812 }
12813}(function (undefined) {
12814
12815 'use strict';
12816
12817 /*
12818 * Fastest md5 implementation around (JKM md5).
12819 * Credits: Joseph Myers
12820 *
12821 * @see http://www.myersdaily.org/joseph/javascript/md5-text.html
12822 * @see http://jsperf.com/md5-shootout/7
12823 */
12824
12825 /* this function is much faster,
12826 so if possible we use it. Some IEs
12827 are the only ones I know of that
12828 need the idiotic second function,
12829 generated by an if clause. */
12830 var add32 = function (a, b) {
12831 return (a + b) & 0xFFFFFFFF;
12832 },
12833 hex_chr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
12834
12835
12836 function cmn(q, a, b, x, s, t) {
12837 a = add32(add32(a, q), add32(x, t));
12838 return add32((a << s) | (a >>> (32 - s)), b);
12839 }
12840
12841 function md5cycle(x, k) {
12842 var a = x[0],
12843 b = x[1],
12844 c = x[2],
12845 d = x[3];
12846
12847 a += (b & c | ~b & d) + k[0] - 680876936 | 0;
12848 a = (a << 7 | a >>> 25) + b | 0;
12849 d += (a & b | ~a & c) + k[1] - 389564586 | 0;
12850 d = (d << 12 | d >>> 20) + a | 0;
12851 c += (d & a | ~d & b) + k[2] + 606105819 | 0;
12852 c = (c << 17 | c >>> 15) + d | 0;
12853 b += (c & d | ~c & a) + k[3] - 1044525330 | 0;
12854 b = (b << 22 | b >>> 10) + c | 0;
12855 a += (b & c | ~b & d) + k[4] - 176418897 | 0;
12856 a = (a << 7 | a >>> 25) + b | 0;
12857 d += (a & b | ~a & c) + k[5] + 1200080426 | 0;
12858 d = (d << 12 | d >>> 20) + a | 0;
12859 c += (d & a | ~d & b) + k[6] - 1473231341 | 0;
12860 c = (c << 17 | c >>> 15) + d | 0;
12861 b += (c & d | ~c & a) + k[7] - 45705983 | 0;
12862 b = (b << 22 | b >>> 10) + c | 0;
12863 a += (b & c | ~b & d) + k[8] + 1770035416 | 0;
12864 a = (a << 7 | a >>> 25) + b | 0;
12865 d += (a & b | ~a & c) + k[9] - 1958414417 | 0;
12866 d = (d << 12 | d >>> 20) + a | 0;
12867 c += (d & a | ~d & b) + k[10] - 42063 | 0;
12868 c = (c << 17 | c >>> 15) + d | 0;
12869 b += (c & d | ~c & a) + k[11] - 1990404162 | 0;
12870 b = (b << 22 | b >>> 10) + c | 0;
12871 a += (b & c | ~b & d) + k[12] + 1804603682 | 0;
12872 a = (a << 7 | a >>> 25) + b | 0;
12873 d += (a & b | ~a & c) + k[13] - 40341101 | 0;
12874 d = (d << 12 | d >>> 20) + a | 0;
12875 c += (d & a | ~d & b) + k[14] - 1502002290 | 0;
12876 c = (c << 17 | c >>> 15) + d | 0;
12877 b += (c & d | ~c & a) + k[15] + 1236535329 | 0;
12878 b = (b << 22 | b >>> 10) + c | 0;
12879
12880 a += (b & d | c & ~d) + k[1] - 165796510 | 0;
12881 a = (a << 5 | a >>> 27) + b | 0;
12882 d += (a & c | b & ~c) + k[6] - 1069501632 | 0;
12883 d = (d << 9 | d >>> 23) + a | 0;
12884 c += (d & b | a & ~b) + k[11] + 643717713 | 0;
12885 c = (c << 14 | c >>> 18) + d | 0;
12886 b += (c & a | d & ~a) + k[0] - 373897302 | 0;
12887 b = (b << 20 | b >>> 12) + c | 0;
12888 a += (b & d | c & ~d) + k[5] - 701558691 | 0;
12889 a = (a << 5 | a >>> 27) + b | 0;
12890 d += (a & c | b & ~c) + k[10] + 38016083 | 0;
12891 d = (d << 9 | d >>> 23) + a | 0;
12892 c += (d & b | a & ~b) + k[15] - 660478335 | 0;
12893 c = (c << 14 | c >>> 18) + d | 0;
12894 b += (c & a | d & ~a) + k[4] - 405537848 | 0;
12895 b = (b << 20 | b >>> 12) + c | 0;
12896 a += (b & d | c & ~d) + k[9] + 568446438 | 0;
12897 a = (a << 5 | a >>> 27) + b | 0;
12898 d += (a & c | b & ~c) + k[14] - 1019803690 | 0;
12899 d = (d << 9 | d >>> 23) + a | 0;
12900 c += (d & b | a & ~b) + k[3] - 187363961 | 0;
12901 c = (c << 14 | c >>> 18) + d | 0;
12902 b += (c & a | d & ~a) + k[8] + 1163531501 | 0;
12903 b = (b << 20 | b >>> 12) + c | 0;
12904 a += (b & d | c & ~d) + k[13] - 1444681467 | 0;
12905 a = (a << 5 | a >>> 27) + b | 0;
12906 d += (a & c | b & ~c) + k[2] - 51403784 | 0;
12907 d = (d << 9 | d >>> 23) + a | 0;
12908 c += (d & b | a & ~b) + k[7] + 1735328473 | 0;
12909 c = (c << 14 | c >>> 18) + d | 0;
12910 b += (c & a | d & ~a) + k[12] - 1926607734 | 0;
12911 b = (b << 20 | b >>> 12) + c | 0;
12912
12913 a += (b ^ c ^ d) + k[5] - 378558 | 0;
12914 a = (a << 4 | a >>> 28) + b | 0;
12915 d += (a ^ b ^ c) + k[8] - 2022574463 | 0;
12916 d = (d << 11 | d >>> 21) + a | 0;
12917 c += (d ^ a ^ b) + k[11] + 1839030562 | 0;
12918 c = (c << 16 | c >>> 16) + d | 0;
12919 b += (c ^ d ^ a) + k[14] - 35309556 | 0;
12920 b = (b << 23 | b >>> 9) + c | 0;
12921 a += (b ^ c ^ d) + k[1] - 1530992060 | 0;
12922 a = (a << 4 | a >>> 28) + b | 0;
12923 d += (a ^ b ^ c) + k[4] + 1272893353 | 0;
12924 d = (d << 11 | d >>> 21) + a | 0;
12925 c += (d ^ a ^ b) + k[7] - 155497632 | 0;
12926 c = (c << 16 | c >>> 16) + d | 0;
12927 b += (c ^ d ^ a) + k[10] - 1094730640 | 0;
12928 b = (b << 23 | b >>> 9) + c | 0;
12929 a += (b ^ c ^ d) + k[13] + 681279174 | 0;
12930 a = (a << 4 | a >>> 28) + b | 0;
12931 d += (a ^ b ^ c) + k[0] - 358537222 | 0;
12932 d = (d << 11 | d >>> 21) + a | 0;
12933 c += (d ^ a ^ b) + k[3] - 722521979 | 0;
12934 c = (c << 16 | c >>> 16) + d | 0;
12935 b += (c ^ d ^ a) + k[6] + 76029189 | 0;
12936 b = (b << 23 | b >>> 9) + c | 0;
12937 a += (b ^ c ^ d) + k[9] - 640364487 | 0;
12938 a = (a << 4 | a >>> 28) + b | 0;
12939 d += (a ^ b ^ c) + k[12] - 421815835 | 0;
12940 d = (d << 11 | d >>> 21) + a | 0;
12941 c += (d ^ a ^ b) + k[15] + 530742520 | 0;
12942 c = (c << 16 | c >>> 16) + d | 0;
12943 b += (c ^ d ^ a) + k[2] - 995338651 | 0;
12944 b = (b << 23 | b >>> 9) + c | 0;
12945
12946 a += (c ^ (b | ~d)) + k[0] - 198630844 | 0;
12947 a = (a << 6 | a >>> 26) + b | 0;
12948 d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0;
12949 d = (d << 10 | d >>> 22) + a | 0;
12950 c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0;
12951 c = (c << 15 | c >>> 17) + d | 0;
12952 b += (d ^ (c | ~a)) + k[5] - 57434055 | 0;
12953 b = (b << 21 |b >>> 11) + c | 0;
12954 a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0;
12955 a = (a << 6 | a >>> 26) + b | 0;
12956 d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0;
12957 d = (d << 10 | d >>> 22) + a | 0;
12958 c += (a ^ (d | ~b)) + k[10] - 1051523 | 0;
12959 c = (c << 15 | c >>> 17) + d | 0;
12960 b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0;
12961 b = (b << 21 |b >>> 11) + c | 0;
12962 a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0;
12963 a = (a << 6 | a >>> 26) + b | 0;
12964 d += (b ^ (a | ~c)) + k[15] - 30611744 | 0;
12965 d = (d << 10 | d >>> 22) + a | 0;
12966 c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0;
12967 c = (c << 15 | c >>> 17) + d | 0;
12968 b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0;
12969 b = (b << 21 |b >>> 11) + c | 0;
12970 a += (c ^ (b | ~d)) + k[4] - 145523070 | 0;
12971 a = (a << 6 | a >>> 26) + b | 0;
12972 d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0;
12973 d = (d << 10 | d >>> 22) + a | 0;
12974 c += (a ^ (d | ~b)) + k[2] + 718787259 | 0;
12975 c = (c << 15 | c >>> 17) + d | 0;
12976 b += (d ^ (c | ~a)) + k[9] - 343485551 | 0;
12977 b = (b << 21 | b >>> 11) + c | 0;
12978
12979 x[0] = a + x[0] | 0;
12980 x[1] = b + x[1] | 0;
12981 x[2] = c + x[2] | 0;
12982 x[3] = d + x[3] | 0;
12983 }
12984
12985 function md5blk(s) {
12986 var md5blks = [],
12987 i; /* Andy King said do it this way. */
12988
12989 for (i = 0; i < 64; i += 4) {
12990 md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
12991 }
12992 return md5blks;
12993 }
12994
12995 function md5blk_array(a) {
12996 var md5blks = [],
12997 i; /* Andy King said do it this way. */
12998
12999 for (i = 0; i < 64; i += 4) {
13000 md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);
13001 }
13002 return md5blks;
13003 }
13004
13005 function md51(s) {
13006 var n = s.length,
13007 state = [1732584193, -271733879, -1732584194, 271733878],
13008 i,
13009 length,
13010 tail,
13011 tmp,
13012 lo,
13013 hi;
13014
13015 for (i = 64; i <= n; i += 64) {
13016 md5cycle(state, md5blk(s.substring(i - 64, i)));
13017 }
13018 s = s.substring(i - 64);
13019 length = s.length;
13020 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
13021 for (i = 0; i < length; i += 1) {
13022 tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
13023 }
13024 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13025 if (i > 55) {
13026 md5cycle(state, tail);
13027 for (i = 0; i < 16; i += 1) {
13028 tail[i] = 0;
13029 }
13030 }
13031
13032 // Beware that the final length might not fit in 32 bits so we take care of that
13033 tmp = n * 8;
13034 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
13035 lo = parseInt(tmp[2], 16);
13036 hi = parseInt(tmp[1], 16) || 0;
13037
13038 tail[14] = lo;
13039 tail[15] = hi;
13040
13041 md5cycle(state, tail);
13042 return state;
13043 }
13044
13045 function md51_array(a) {
13046 var n = a.length,
13047 state = [1732584193, -271733879, -1732584194, 271733878],
13048 i,
13049 length,
13050 tail,
13051 tmp,
13052 lo,
13053 hi;
13054
13055 for (i = 64; i <= n; i += 64) {
13056 md5cycle(state, md5blk_array(a.subarray(i - 64, i)));
13057 }
13058
13059 // Not sure if it is a bug, however IE10 will always produce a sub array of length 1
13060 // containing the last element of the parent array if the sub array specified starts
13061 // beyond the length of the parent array - weird.
13062 // https://connect.microsoft.com/IE/feedback/details/771452/typed-array-subarray-issue
13063 a = (i - 64) < n ? a.subarray(i - 64) : new Uint8Array(0);
13064
13065 length = a.length;
13066 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
13067 for (i = 0; i < length; i += 1) {
13068 tail[i >> 2] |= a[i] << ((i % 4) << 3);
13069 }
13070
13071 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13072 if (i > 55) {
13073 md5cycle(state, tail);
13074 for (i = 0; i < 16; i += 1) {
13075 tail[i] = 0;
13076 }
13077 }
13078
13079 // Beware that the final length might not fit in 32 bits so we take care of that
13080 tmp = n * 8;
13081 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
13082 lo = parseInt(tmp[2], 16);
13083 hi = parseInt(tmp[1], 16) || 0;
13084
13085 tail[14] = lo;
13086 tail[15] = hi;
13087
13088 md5cycle(state, tail);
13089
13090 return state;
13091 }
13092
13093 function rhex(n) {
13094 var s = '',
13095 j;
13096 for (j = 0; j < 4; j += 1) {
13097 s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
13098 }
13099 return s;
13100 }
13101
13102 function hex(x) {
13103 var i;
13104 for (i = 0; i < x.length; i += 1) {
13105 x[i] = rhex(x[i]);
13106 }
13107 return x.join('');
13108 }
13109
13110 // In some cases the fast add32 function cannot be used..
13111 if (hex(md51('hello')) !== '5d41402abc4b2a76b9719d911017c592') {
13112 add32 = function (x, y) {
13113 var lsw = (x & 0xFFFF) + (y & 0xFFFF),
13114 msw = (x >> 16) + (y >> 16) + (lsw >> 16);
13115 return (msw << 16) | (lsw & 0xFFFF);
13116 };
13117 }
13118
13119 // ---------------------------------------------------
13120
13121 /**
13122 * ArrayBuffer slice polyfill.
13123 *
13124 * @see https://github.com/ttaubert/node-arraybuffer-slice
13125 */
13126
13127 if (typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.prototype.slice) {
13128 (function () {
13129 function clamp(val, length) {
13130 val = (val | 0) || 0;
13131
13132 if (val < 0) {
13133 return Math.max(val + length, 0);
13134 }
13135
13136 return Math.min(val, length);
13137 }
13138
13139 ArrayBuffer.prototype.slice = function (from, to) {
13140 var length = this.byteLength,
13141 begin = clamp(from, length),
13142 end = length,
13143 num,
13144 target,
13145 targetArray,
13146 sourceArray;
13147
13148 if (to !== undefined) {
13149 end = clamp(to, length);
13150 }
13151
13152 if (begin > end) {
13153 return new ArrayBuffer(0);
13154 }
13155
13156 num = end - begin;
13157 target = new ArrayBuffer(num);
13158 targetArray = new Uint8Array(target);
13159
13160 sourceArray = new Uint8Array(this, begin, num);
13161 targetArray.set(sourceArray);
13162
13163 return target;
13164 };
13165 })();
13166 }
13167
13168 // ---------------------------------------------------
13169
13170 /**
13171 * Helpers.
13172 */
13173
13174 function toUtf8(str) {
13175 if (/[\u0080-\uFFFF]/.test(str)) {
13176 str = unescape(encodeURIComponent(str));
13177 }
13178
13179 return str;
13180 }
13181
13182 function utf8Str2ArrayBuffer(str, returnUInt8Array) {
13183 var length = str.length,
13184 buff = new ArrayBuffer(length),
13185 arr = new Uint8Array(buff),
13186 i;
13187
13188 for (i = 0; i < length; i += 1) {
13189 arr[i] = str.charCodeAt(i);
13190 }
13191
13192 return returnUInt8Array ? arr : buff;
13193 }
13194
13195 function arrayBuffer2Utf8Str(buff) {
13196 return String.fromCharCode.apply(null, new Uint8Array(buff));
13197 }
13198
13199 function concatenateArrayBuffers(first, second, returnUInt8Array) {
13200 var result = new Uint8Array(first.byteLength + second.byteLength);
13201
13202 result.set(new Uint8Array(first));
13203 result.set(new Uint8Array(second), first.byteLength);
13204
13205 return returnUInt8Array ? result : result.buffer;
13206 }
13207
13208 function hexToBinaryString(hex) {
13209 var bytes = [],
13210 length = hex.length,
13211 x;
13212
13213 for (x = 0; x < length - 1; x += 2) {
13214 bytes.push(parseInt(hex.substr(x, 2), 16));
13215 }
13216
13217 return String.fromCharCode.apply(String, bytes);
13218 }
13219
13220 // ---------------------------------------------------
13221
13222 /**
13223 * SparkMD5 OOP implementation.
13224 *
13225 * Use this class to perform an incremental md5, otherwise use the
13226 * static methods instead.
13227 */
13228
13229 function SparkMD5() {
13230 // call reset to init the instance
13231 this.reset();
13232 }
13233
13234 /**
13235 * Appends a string.
13236 * A conversion will be applied if an utf8 string is detected.
13237 *
13238 * @param {String} str The string to be appended
13239 *
13240 * @return {SparkMD5} The instance itself
13241 */
13242 SparkMD5.prototype.append = function (str) {
13243 // Converts the string to utf8 bytes if necessary
13244 // Then append as binary
13245 this.appendBinary(toUtf8(str));
13246
13247 return this;
13248 };
13249
13250 /**
13251 * Appends a binary string.
13252 *
13253 * @param {String} contents The binary string to be appended
13254 *
13255 * @return {SparkMD5} The instance itself
13256 */
13257 SparkMD5.prototype.appendBinary = function (contents) {
13258 this._buff += contents;
13259 this._length += contents.length;
13260
13261 var length = this._buff.length,
13262 i;
13263
13264 for (i = 64; i <= length; i += 64) {
13265 md5cycle(this._hash, md5blk(this._buff.substring(i - 64, i)));
13266 }
13267
13268 this._buff = this._buff.substring(i - 64);
13269
13270 return this;
13271 };
13272
13273 /**
13274 * Finishes the incremental computation, reseting the internal state and
13275 * returning the result.
13276 *
13277 * @param {Boolean} raw True to get the raw string, false to get the hex string
13278 *
13279 * @return {String} The result
13280 */
13281 SparkMD5.prototype.end = function (raw) {
13282 var buff = this._buff,
13283 length = buff.length,
13284 i,
13285 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
13286 ret;
13287
13288 for (i = 0; i < length; i += 1) {
13289 tail[i >> 2] |= buff.charCodeAt(i) << ((i % 4) << 3);
13290 }
13291
13292 this._finish(tail, length);
13293 ret = hex(this._hash);
13294
13295 if (raw) {
13296 ret = hexToBinaryString(ret);
13297 }
13298
13299 this.reset();
13300
13301 return ret;
13302 };
13303
13304 /**
13305 * Resets the internal state of the computation.
13306 *
13307 * @return {SparkMD5} The instance itself
13308 */
13309 SparkMD5.prototype.reset = function () {
13310 this._buff = '';
13311 this._length = 0;
13312 this._hash = [1732584193, -271733879, -1732584194, 271733878];
13313
13314 return this;
13315 };
13316
13317 /**
13318 * Gets the internal state of the computation.
13319 *
13320 * @return {Object} The state
13321 */
13322 SparkMD5.prototype.getState = function () {
13323 return {
13324 buff: this._buff,
13325 length: this._length,
13326 hash: this._hash
13327 };
13328 };
13329
13330 /**
13331 * Gets the internal state of the computation.
13332 *
13333 * @param {Object} state The state
13334 *
13335 * @return {SparkMD5} The instance itself
13336 */
13337 SparkMD5.prototype.setState = function (state) {
13338 this._buff = state.buff;
13339 this._length = state.length;
13340 this._hash = state.hash;
13341
13342 return this;
13343 };
13344
13345 /**
13346 * Releases memory used by the incremental buffer and other additional
13347 * resources. If you plan to use the instance again, use reset instead.
13348 */
13349 SparkMD5.prototype.destroy = function () {
13350 delete this._hash;
13351 delete this._buff;
13352 delete this._length;
13353 };
13354
13355 /**
13356 * Finish the final calculation based on the tail.
13357 *
13358 * @param {Array} tail The tail (will be modified)
13359 * @param {Number} length The length of the remaining buffer
13360 */
13361 SparkMD5.prototype._finish = function (tail, length) {
13362 var i = length,
13363 tmp,
13364 lo,
13365 hi;
13366
13367 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13368 if (i > 55) {
13369 md5cycle(this._hash, tail);
13370 for (i = 0; i < 16; i += 1) {
13371 tail[i] = 0;
13372 }
13373 }
13374
13375 // Do the final computation based on the tail and length
13376 // Beware that the final length may not fit in 32 bits so we take care of that
13377 tmp = this._length * 8;
13378 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
13379 lo = parseInt(tmp[2], 16);
13380 hi = parseInt(tmp[1], 16) || 0;
13381
13382 tail[14] = lo;
13383 tail[15] = hi;
13384 md5cycle(this._hash, tail);
13385 };
13386
13387 /**
13388 * Performs the md5 hash on a string.
13389 * A conversion will be applied if utf8 string is detected.
13390 *
13391 * @param {String} str The string
13392 * @param {Boolean} raw True to get the raw string, false to get the hex string
13393 *
13394 * @return {String} The result
13395 */
13396 SparkMD5.hash = function (str, raw) {
13397 // Converts the string to utf8 bytes if necessary
13398 // Then compute it using the binary function
13399 return SparkMD5.hashBinary(toUtf8(str), raw);
13400 };
13401
13402 /**
13403 * Performs the md5 hash on a binary string.
13404 *
13405 * @param {String} content The binary string
13406 * @param {Boolean} raw True to get the raw string, false to get the hex string
13407 *
13408 * @return {String} The result
13409 */
13410 SparkMD5.hashBinary = function (content, raw) {
13411 var hash = md51(content),
13412 ret = hex(hash);
13413
13414 return raw ? hexToBinaryString(ret) : ret;
13415 };
13416
13417 // ---------------------------------------------------
13418
13419 /**
13420 * SparkMD5 OOP implementation for array buffers.
13421 *
13422 * Use this class to perform an incremental md5 ONLY for array buffers.
13423 */
13424 SparkMD5.ArrayBuffer = function () {
13425 // call reset to init the instance
13426 this.reset();
13427 };
13428
13429 /**
13430 * Appends an array buffer.
13431 *
13432 * @param {ArrayBuffer} arr The array to be appended
13433 *
13434 * @return {SparkMD5.ArrayBuffer} The instance itself
13435 */
13436 SparkMD5.ArrayBuffer.prototype.append = function (arr) {
13437 var buff = concatenateArrayBuffers(this._buff.buffer, arr, true),
13438 length = buff.length,
13439 i;
13440
13441 this._length += arr.byteLength;
13442
13443 for (i = 64; i <= length; i += 64) {
13444 md5cycle(this._hash, md5blk_array(buff.subarray(i - 64, i)));
13445 }
13446
13447 this._buff = (i - 64) < length ? new Uint8Array(buff.buffer.slice(i - 64)) : new Uint8Array(0);
13448
13449 return this;
13450 };
13451
13452 /**
13453 * Finishes the incremental computation, reseting the internal state and
13454 * returning the result.
13455 *
13456 * @param {Boolean} raw True to get the raw string, false to get the hex string
13457 *
13458 * @return {String} The result
13459 */
13460 SparkMD5.ArrayBuffer.prototype.end = function (raw) {
13461 var buff = this._buff,
13462 length = buff.length,
13463 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
13464 i,
13465 ret;
13466
13467 for (i = 0; i < length; i += 1) {
13468 tail[i >> 2] |= buff[i] << ((i % 4) << 3);
13469 }
13470
13471 this._finish(tail, length);
13472 ret = hex(this._hash);
13473
13474 if (raw) {
13475 ret = hexToBinaryString(ret);
13476 }
13477
13478 this.reset();
13479
13480 return ret;
13481 };
13482
13483 /**
13484 * Resets the internal state of the computation.
13485 *
13486 * @return {SparkMD5.ArrayBuffer} The instance itself
13487 */
13488 SparkMD5.ArrayBuffer.prototype.reset = function () {
13489 this._buff = new Uint8Array(0);
13490 this._length = 0;
13491 this._hash = [1732584193, -271733879, -1732584194, 271733878];
13492
13493 return this;
13494 };
13495
13496 /**
13497 * Gets the internal state of the computation.
13498 *
13499 * @return {Object} The state
13500 */
13501 SparkMD5.ArrayBuffer.prototype.getState = function () {
13502 var state = SparkMD5.prototype.getState.call(this);
13503
13504 // Convert buffer to a string
13505 state.buff = arrayBuffer2Utf8Str(state.buff);
13506
13507 return state;
13508 };
13509
13510 /**
13511 * Gets the internal state of the computation.
13512 *
13513 * @param {Object} state The state
13514 *
13515 * @return {SparkMD5.ArrayBuffer} The instance itself
13516 */
13517 SparkMD5.ArrayBuffer.prototype.setState = function (state) {
13518 // Convert string to buffer
13519 state.buff = utf8Str2ArrayBuffer(state.buff, true);
13520
13521 return SparkMD5.prototype.setState.call(this, state);
13522 };
13523
13524 SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
13525
13526 SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
13527
13528 /**
13529 * Performs the md5 hash on an array buffer.
13530 *
13531 * @param {ArrayBuffer} arr The array buffer
13532 * @param {Boolean} raw True to get the raw string, false to get the hex one
13533 *
13534 * @return {String} The result
13535 */
13536 SparkMD5.ArrayBuffer.hash = function (arr, raw) {
13537 var hash = md51_array(new Uint8Array(arr)),
13538 ret = hex(hash);
13539
13540 return raw ? hexToBinaryString(ret) : ret;
13541 };
13542
13543 return SparkMD5;
13544}));
13545
13546},{}],80:[function(_dereq_,module,exports){
13547// Copyright Joyent, Inc. and other Node contributors.
13548//
13549// Permission is hereby granted, free of charge, to any person obtaining a
13550// copy of this software and associated documentation files (the
13551// "Software"), to deal in the Software without restriction, including
13552// without limitation the rights to use, copy, modify, merge, publish,
13553// distribute, sublicense, and/or sell copies of the Software, and to permit
13554// persons to whom the Software is furnished to do so, subject to the
13555// following conditions:
13556//
13557// The above copyright notice and this permission notice shall be included
13558// in all copies or substantial portions of the Software.
13559//
13560// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13561// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13562// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13563// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13564// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13565// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13566// USE OR OTHER DEALINGS IN THE SOFTWARE.
13567
13568module.exports = Stream;
13569
13570var EE = _dereq_(25).EventEmitter;
13571var inherits = _dereq_(31);
13572
13573inherits(Stream, EE);
13574Stream.Readable = _dereq_(92);
13575Stream.Writable = _dereq_(94);
13576Stream.Duplex = _dereq_(82);
13577Stream.Transform = _dereq_(93);
13578Stream.PassThrough = _dereq_(91);
13579
13580// Backwards-compat with node 0.4.x
13581Stream.Stream = Stream;
13582
13583
13584
13585// old-style streams. Note that the pipe method (the only relevant
13586// part of this class) is overridden in the Readable class.
13587
13588function Stream() {
13589 EE.call(this);
13590}
13591
13592Stream.prototype.pipe = function(dest, options) {
13593 var source = this;
13594
13595 function ondata(chunk) {
13596 if (dest.writable) {
13597 if (false === dest.write(chunk) && source.pause) {
13598 source.pause();
13599 }
13600 }
13601 }
13602
13603 source.on('data', ondata);
13604
13605 function ondrain() {
13606 if (source.readable && source.resume) {
13607 source.resume();
13608 }
13609 }
13610
13611 dest.on('drain', ondrain);
13612
13613 // If the 'end' option is not supplied, dest.end() will be called when
13614 // source gets the 'end' or 'close' events. Only dest.end() once.
13615 if (!dest._isStdio && (!options || options.end !== false)) {
13616 source.on('end', onend);
13617 source.on('close', onclose);
13618 }
13619
13620 var didOnEnd = false;
13621 function onend() {
13622 if (didOnEnd) return;
13623 didOnEnd = true;
13624
13625 dest.end();
13626 }
13627
13628
13629 function onclose() {
13630 if (didOnEnd) return;
13631 didOnEnd = true;
13632
13633 if (typeof dest.destroy === 'function') dest.destroy();
13634 }
13635
13636 // don't leave dangling pipes when there are errors.
13637 function onerror(er) {
13638 cleanup();
13639 if (EE.listenerCount(this, 'error') === 0) {
13640 throw er; // Unhandled stream error in pipe.
13641 }
13642 }
13643
13644 source.on('error', onerror);
13645 dest.on('error', onerror);
13646
13647 // remove all the event listeners that were added.
13648 function cleanup() {
13649 source.removeListener('data', ondata);
13650 dest.removeListener('drain', ondrain);
13651
13652 source.removeListener('end', onend);
13653 source.removeListener('close', onclose);
13654
13655 source.removeListener('error', onerror);
13656 dest.removeListener('error', onerror);
13657
13658 source.removeListener('end', cleanup);
13659 source.removeListener('close', cleanup);
13660
13661 dest.removeListener('close', cleanup);
13662 }
13663
13664 source.on('end', cleanup);
13665 source.on('close', cleanup);
13666
13667 dest.on('close', cleanup);
13668
13669 dest.emit('pipe', source);
13670
13671 // Allow for unix-like usage: A.pipe(B).pipe(C)
13672 return dest;
13673};
13674
13675},{"25":25,"31":31,"82":82,"91":91,"92":92,"93":93,"94":94}],81:[function(_dereq_,module,exports){
13676var toString = {}.toString;
13677
13678module.exports = Array.isArray || function (arr) {
13679 return toString.call(arr) == '[object Array]';
13680};
13681
13682},{}],82:[function(_dereq_,module,exports){
13683module.exports = _dereq_(83);
13684
13685},{"83":83}],83:[function(_dereq_,module,exports){
13686// Copyright Joyent, Inc. and other Node contributors.
13687//
13688// Permission is hereby granted, free of charge, to any person obtaining a
13689// copy of this software and associated documentation files (the
13690// "Software"), to deal in the Software without restriction, including
13691// without limitation the rights to use, copy, modify, merge, publish,
13692// distribute, sublicense, and/or sell copies of the Software, and to permit
13693// persons to whom the Software is furnished to do so, subject to the
13694// following conditions:
13695//
13696// The above copyright notice and this permission notice shall be included
13697// in all copies or substantial portions of the Software.
13698//
13699// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13700// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13701// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13702// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13703// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13704// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13705// USE OR OTHER DEALINGS IN THE SOFTWARE.
13706
13707// a duplex stream is just a stream that is both readable and writable.
13708// Since JS doesn't have multiple prototypal inheritance, this class
13709// prototypally inherits from Readable, and then parasitically from
13710// Writable.
13711
13712'use strict';
13713
13714/*<replacement>*/
13715
13716var pna = _dereq_(68);
13717/*</replacement>*/
13718
13719/*<replacement>*/
13720var objectKeys = Object.keys || function (obj) {
13721 var keys = [];
13722 for (var key in obj) {
13723 keys.push(key);
13724 }return keys;
13725};
13726/*</replacement>*/
13727
13728module.exports = Duplex;
13729
13730/*<replacement>*/
13731var util = _dereq_(13);
13732util.inherits = _dereq_(31);
13733/*</replacement>*/
13734
13735var Readable = _dereq_(85);
13736var Writable = _dereq_(87);
13737
13738util.inherits(Duplex, Readable);
13739
13740{
13741 // avoid scope creep, the keys array can then be collected
13742 var keys = objectKeys(Writable.prototype);
13743 for (var v = 0; v < keys.length; v++) {
13744 var method = keys[v];
13745 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
13746 }
13747}
13748
13749function Duplex(options) {
13750 if (!(this instanceof Duplex)) return new Duplex(options);
13751
13752 Readable.call(this, options);
13753 Writable.call(this, options);
13754
13755 if (options && options.readable === false) this.readable = false;
13756
13757 if (options && options.writable === false) this.writable = false;
13758
13759 this.allowHalfOpen = true;
13760 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
13761
13762 this.once('end', onend);
13763}
13764
13765Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
13766 // making it explicit this property is not enumerable
13767 // because otherwise some prototype manipulation in
13768 // userland will fail
13769 enumerable: false,
13770 get: function () {
13771 return this._writableState.highWaterMark;
13772 }
13773});
13774
13775// the no-half-open enforcer
13776function onend() {
13777 // if we allow half-open state, or if the writable side ended,
13778 // then we're ok.
13779 if (this.allowHalfOpen || this._writableState.ended) return;
13780
13781 // no more data can be written.
13782 // But allow more writes to happen in this tick.
13783 pna.nextTick(onEndNT, this);
13784}
13785
13786function onEndNT(self) {
13787 self.end();
13788}
13789
13790Object.defineProperty(Duplex.prototype, 'destroyed', {
13791 get: function () {
13792 if (this._readableState === undefined || this._writableState === undefined) {
13793 return false;
13794 }
13795 return this._readableState.destroyed && this._writableState.destroyed;
13796 },
13797 set: function (value) {
13798 // we ignore the value if the stream
13799 // has not been initialized yet
13800 if (this._readableState === undefined || this._writableState === undefined) {
13801 return;
13802 }
13803
13804 // backward compatibility, the user is explicitly
13805 // managing destroyed
13806 this._readableState.destroyed = value;
13807 this._writableState.destroyed = value;
13808 }
13809});
13810
13811Duplex.prototype._destroy = function (err, cb) {
13812 this.push(null);
13813 this.end();
13814
13815 pna.nextTick(cb, err);
13816};
13817},{"13":13,"31":31,"68":68,"85":85,"87":87}],84:[function(_dereq_,module,exports){
13818// Copyright Joyent, Inc. and other Node contributors.
13819//
13820// Permission is hereby granted, free of charge, to any person obtaining a
13821// copy of this software and associated documentation files (the
13822// "Software"), to deal in the Software without restriction, including
13823// without limitation the rights to use, copy, modify, merge, publish,
13824// distribute, sublicense, and/or sell copies of the Software, and to permit
13825// persons to whom the Software is furnished to do so, subject to the
13826// following conditions:
13827//
13828// The above copyright notice and this permission notice shall be included
13829// in all copies or substantial portions of the Software.
13830//
13831// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13832// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13833// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13834// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13835// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13836// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13837// USE OR OTHER DEALINGS IN THE SOFTWARE.
13838
13839// a passthrough stream.
13840// basically just the most minimal sort of Transform stream.
13841// Every written chunk gets output as-is.
13842
13843'use strict';
13844
13845module.exports = PassThrough;
13846
13847var Transform = _dereq_(86);
13848
13849/*<replacement>*/
13850var util = _dereq_(13);
13851util.inherits = _dereq_(31);
13852/*</replacement>*/
13853
13854util.inherits(PassThrough, Transform);
13855
13856function PassThrough(options) {
13857 if (!(this instanceof PassThrough)) return new PassThrough(options);
13858
13859 Transform.call(this, options);
13860}
13861
13862PassThrough.prototype._transform = function (chunk, encoding, cb) {
13863 cb(null, chunk);
13864};
13865},{"13":13,"31":31,"86":86}],85:[function(_dereq_,module,exports){
13866(function (process,global){
13867// Copyright Joyent, Inc. and other Node contributors.
13868//
13869// Permission is hereby granted, free of charge, to any person obtaining a
13870// copy of this software and associated documentation files (the
13871// "Software"), to deal in the Software without restriction, including
13872// without limitation the rights to use, copy, modify, merge, publish,
13873// distribute, sublicense, and/or sell copies of the Software, and to permit
13874// persons to whom the Software is furnished to do so, subject to the
13875// following conditions:
13876//
13877// The above copyright notice and this permission notice shall be included
13878// in all copies or substantial portions of the Software.
13879//
13880// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13881// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13882// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13883// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13884// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13885// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13886// USE OR OTHER DEALINGS IN THE SOFTWARE.
13887
13888'use strict';
13889
13890/*<replacement>*/
13891
13892var pna = _dereq_(68);
13893/*</replacement>*/
13894
13895module.exports = Readable;
13896
13897/*<replacement>*/
13898var isArray = _dereq_(81);
13899/*</replacement>*/
13900
13901/*<replacement>*/
13902var Duplex;
13903/*</replacement>*/
13904
13905Readable.ReadableState = ReadableState;
13906
13907/*<replacement>*/
13908var EE = _dereq_(25).EventEmitter;
13909
13910var EElistenerCount = function (emitter, type) {
13911 return emitter.listeners(type).length;
13912};
13913/*</replacement>*/
13914
13915/*<replacement>*/
13916var Stream = _dereq_(90);
13917/*</replacement>*/
13918
13919/*<replacement>*/
13920
13921var Buffer = _dereq_(78).Buffer;
13922var OurUint8Array = global.Uint8Array || function () {};
13923function _uint8ArrayToBuffer(chunk) {
13924 return Buffer.from(chunk);
13925}
13926function _isUint8Array(obj) {
13927 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
13928}
13929
13930/*</replacement>*/
13931
13932/*<replacement>*/
13933var util = _dereq_(13);
13934util.inherits = _dereq_(31);
13935/*</replacement>*/
13936
13937/*<replacement>*/
13938var debugUtil = _dereq_(10);
13939var debug = void 0;
13940if (debugUtil && debugUtil.debuglog) {
13941 debug = debugUtil.debuglog('stream');
13942} else {
13943 debug = function () {};
13944}
13945/*</replacement>*/
13946
13947var BufferList = _dereq_(88);
13948var destroyImpl = _dereq_(89);
13949var StringDecoder;
13950
13951util.inherits(Readable, Stream);
13952
13953var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
13954
13955function prependListener(emitter, event, fn) {
13956 // Sadly this is not cacheable as some libraries bundle their own
13957 // event emitter implementation with them.
13958 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
13959
13960 // This is a hack to make sure that our error handler is attached before any
13961 // userland ones. NEVER DO THIS. This is here only because this code needs
13962 // to continue to work with older versions of Node.js that do not include
13963 // the prependListener() method. The goal is to eventually remove this hack.
13964 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]];
13965}
13966
13967function ReadableState(options, stream) {
13968 Duplex = Duplex || _dereq_(83);
13969
13970 options = options || {};
13971
13972 // Duplex streams are both readable and writable, but share
13973 // the same options object.
13974 // However, some cases require setting options to different
13975 // values for the readable and the writable sides of the duplex stream.
13976 // These options can be provided separately as readableXXX and writableXXX.
13977 var isDuplex = stream instanceof Duplex;
13978
13979 // object stream flag. Used to make read(n) ignore n and to
13980 // make all the buffer merging and length checks go away
13981 this.objectMode = !!options.objectMode;
13982
13983 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
13984
13985 // the point at which it stops calling _read() to fill the buffer
13986 // Note: 0 is a valid value, means "don't call _read preemptively ever"
13987 var hwm = options.highWaterMark;
13988 var readableHwm = options.readableHighWaterMark;
13989 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
13990
13991 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
13992
13993 // cast to ints.
13994 this.highWaterMark = Math.floor(this.highWaterMark);
13995
13996 // A linked list is used to store data chunks instead of an array because the
13997 // linked list can remove elements from the beginning faster than
13998 // array.shift()
13999 this.buffer = new BufferList();
14000 this.length = 0;
14001 this.pipes = null;
14002 this.pipesCount = 0;
14003 this.flowing = null;
14004 this.ended = false;
14005 this.endEmitted = false;
14006 this.reading = false;
14007
14008 // a flag to be able to tell if the event 'readable'/'data' is emitted
14009 // immediately, or on a later tick. We set this to true at first, because
14010 // any actions that shouldn't happen until "later" should generally also
14011 // not happen before the first read call.
14012 this.sync = true;
14013
14014 // whenever we return null, then we set a flag to say
14015 // that we're awaiting a 'readable' event emission.
14016 this.needReadable = false;
14017 this.emittedReadable = false;
14018 this.readableListening = false;
14019 this.resumeScheduled = false;
14020
14021 // has it been destroyed
14022 this.destroyed = false;
14023
14024 // Crypto is kind of old and crusty. Historically, its default string
14025 // encoding is 'binary' so we have to make this configurable.
14026 // Everything else in the universe uses 'utf8', though.
14027 this.defaultEncoding = options.defaultEncoding || 'utf8';
14028
14029 // the number of writers that are awaiting a drain event in .pipe()s
14030 this.awaitDrain = 0;
14031
14032 // if true, a maybeReadMore has been scheduled
14033 this.readingMore = false;
14034
14035 this.decoder = null;
14036 this.encoding = null;
14037 if (options.encoding) {
14038 if (!StringDecoder) StringDecoder = _dereq_(95).StringDecoder;
14039 this.decoder = new StringDecoder(options.encoding);
14040 this.encoding = options.encoding;
14041 }
14042}
14043
14044function Readable(options) {
14045 Duplex = Duplex || _dereq_(83);
14046
14047 if (!(this instanceof Readable)) return new Readable(options);
14048
14049 this._readableState = new ReadableState(options, this);
14050
14051 // legacy
14052 this.readable = true;
14053
14054 if (options) {
14055 if (typeof options.read === 'function') this._read = options.read;
14056
14057 if (typeof options.destroy === 'function') this._destroy = options.destroy;
14058 }
14059
14060 Stream.call(this);
14061}
14062
14063Object.defineProperty(Readable.prototype, 'destroyed', {
14064 get: function () {
14065 if (this._readableState === undefined) {
14066 return false;
14067 }
14068 return this._readableState.destroyed;
14069 },
14070 set: function (value) {
14071 // we ignore the value if the stream
14072 // has not been initialized yet
14073 if (!this._readableState) {
14074 return;
14075 }
14076
14077 // backward compatibility, the user is explicitly
14078 // managing destroyed
14079 this._readableState.destroyed = value;
14080 }
14081});
14082
14083Readable.prototype.destroy = destroyImpl.destroy;
14084Readable.prototype._undestroy = destroyImpl.undestroy;
14085Readable.prototype._destroy = function (err, cb) {
14086 this.push(null);
14087 cb(err);
14088};
14089
14090// Manually shove something into the read() buffer.
14091// This returns true if the highWaterMark has not been hit yet,
14092// similar to how Writable.write() returns true if you should
14093// write() some more.
14094Readable.prototype.push = function (chunk, encoding) {
14095 var state = this._readableState;
14096 var skipChunkCheck;
14097
14098 if (!state.objectMode) {
14099 if (typeof chunk === 'string') {
14100 encoding = encoding || state.defaultEncoding;
14101 if (encoding !== state.encoding) {
14102 chunk = Buffer.from(chunk, encoding);
14103 encoding = '';
14104 }
14105 skipChunkCheck = true;
14106 }
14107 } else {
14108 skipChunkCheck = true;
14109 }
14110
14111 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
14112};
14113
14114// Unshift should *always* be something directly out of read()
14115Readable.prototype.unshift = function (chunk) {
14116 return readableAddChunk(this, chunk, null, true, false);
14117};
14118
14119function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
14120 var state = stream._readableState;
14121 if (chunk === null) {
14122 state.reading = false;
14123 onEofChunk(stream, state);
14124 } else {
14125 var er;
14126 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
14127 if (er) {
14128 stream.emit('error', er);
14129 } else if (state.objectMode || chunk && chunk.length > 0) {
14130 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
14131 chunk = _uint8ArrayToBuffer(chunk);
14132 }
14133
14134 if (addToFront) {
14135 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
14136 } else if (state.ended) {
14137 stream.emit('error', new Error('stream.push() after EOF'));
14138 } else {
14139 state.reading = false;
14140 if (state.decoder && !encoding) {
14141 chunk = state.decoder.write(chunk);
14142 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
14143 } else {
14144 addChunk(stream, state, chunk, false);
14145 }
14146 }
14147 } else if (!addToFront) {
14148 state.reading = false;
14149 }
14150 }
14151
14152 return needMoreData(state);
14153}
14154
14155function addChunk(stream, state, chunk, addToFront) {
14156 if (state.flowing && state.length === 0 && !state.sync) {
14157 stream.emit('data', chunk);
14158 stream.read(0);
14159 } else {
14160 // update the buffer info.
14161 state.length += state.objectMode ? 1 : chunk.length;
14162 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
14163
14164 if (state.needReadable) emitReadable(stream);
14165 }
14166 maybeReadMore(stream, state);
14167}
14168
14169function chunkInvalid(state, chunk) {
14170 var er;
14171 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
14172 er = new TypeError('Invalid non-string/buffer chunk');
14173 }
14174 return er;
14175}
14176
14177// if it's past the high water mark, we can push in some more.
14178// Also, if we have no data yet, we can stand some
14179// more bytes. This is to work around cases where hwm=0,
14180// such as the repl. Also, if the push() triggered a
14181// readable event, and the user called read(largeNumber) such that
14182// needReadable was set, then we ought to push more, so that another
14183// 'readable' event will be triggered.
14184function needMoreData(state) {
14185 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
14186}
14187
14188Readable.prototype.isPaused = function () {
14189 return this._readableState.flowing === false;
14190};
14191
14192// backwards compatibility.
14193Readable.prototype.setEncoding = function (enc) {
14194 if (!StringDecoder) StringDecoder = _dereq_(95).StringDecoder;
14195 this._readableState.decoder = new StringDecoder(enc);
14196 this._readableState.encoding = enc;
14197 return this;
14198};
14199
14200// Don't raise the hwm > 8MB
14201var MAX_HWM = 0x800000;
14202function computeNewHighWaterMark(n) {
14203 if (n >= MAX_HWM) {
14204 n = MAX_HWM;
14205 } else {
14206 // Get the next highest power of 2 to prevent increasing hwm excessively in
14207 // tiny amounts
14208 n--;
14209 n |= n >>> 1;
14210 n |= n >>> 2;
14211 n |= n >>> 4;
14212 n |= n >>> 8;
14213 n |= n >>> 16;
14214 n++;
14215 }
14216 return n;
14217}
14218
14219// This function is designed to be inlinable, so please take care when making
14220// changes to the function body.
14221function howMuchToRead(n, state) {
14222 if (n <= 0 || state.length === 0 && state.ended) return 0;
14223 if (state.objectMode) return 1;
14224 if (n !== n) {
14225 // Only flow one buffer at a time
14226 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
14227 }
14228 // If we're asking for more than the current hwm, then raise the hwm.
14229 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
14230 if (n <= state.length) return n;
14231 // Don't have enough
14232 if (!state.ended) {
14233 state.needReadable = true;
14234 return 0;
14235 }
14236 return state.length;
14237}
14238
14239// you can override either this method, or the async _read(n) below.
14240Readable.prototype.read = function (n) {
14241 debug('read', n);
14242 n = parseInt(n, 10);
14243 var state = this._readableState;
14244 var nOrig = n;
14245
14246 if (n !== 0) state.emittedReadable = false;
14247
14248 // if we're doing read(0) to trigger a readable event, but we
14249 // already have a bunch of data in the buffer, then just trigger
14250 // the 'readable' event and move on.
14251 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
14252 debug('read: emitReadable', state.length, state.ended);
14253 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
14254 return null;
14255 }
14256
14257 n = howMuchToRead(n, state);
14258
14259 // if we've ended, and we're now clear, then finish it up.
14260 if (n === 0 && state.ended) {
14261 if (state.length === 0) endReadable(this);
14262 return null;
14263 }
14264
14265 // All the actual chunk generation logic needs to be
14266 // *below* the call to _read. The reason is that in certain
14267 // synthetic stream cases, such as passthrough streams, _read
14268 // may be a completely synchronous operation which may change
14269 // the state of the read buffer, providing enough data when
14270 // before there was *not* enough.
14271 //
14272 // So, the steps are:
14273 // 1. Figure out what the state of things will be after we do
14274 // a read from the buffer.
14275 //
14276 // 2. If that resulting state will trigger a _read, then call _read.
14277 // Note that this may be asynchronous, or synchronous. Yes, it is
14278 // deeply ugly to write APIs this way, but that still doesn't mean
14279 // that the Readable class should behave improperly, as streams are
14280 // designed to be sync/async agnostic.
14281 // Take note if the _read call is sync or async (ie, if the read call
14282 // has returned yet), so that we know whether or not it's safe to emit
14283 // 'readable' etc.
14284 //
14285 // 3. Actually pull the requested chunks out of the buffer and return.
14286
14287 // if we need a readable event, then we need to do some reading.
14288 var doRead = state.needReadable;
14289 debug('need readable', doRead);
14290
14291 // if we currently have less than the highWaterMark, then also read some
14292 if (state.length === 0 || state.length - n < state.highWaterMark) {
14293 doRead = true;
14294 debug('length less than watermark', doRead);
14295 }
14296
14297 // however, if we've ended, then there's no point, and if we're already
14298 // reading, then it's unnecessary.
14299 if (state.ended || state.reading) {
14300 doRead = false;
14301 debug('reading or ended', doRead);
14302 } else if (doRead) {
14303 debug('do read');
14304 state.reading = true;
14305 state.sync = true;
14306 // if the length is currently zero, then we *need* a readable event.
14307 if (state.length === 0) state.needReadable = true;
14308 // call internal read method
14309 this._read(state.highWaterMark);
14310 state.sync = false;
14311 // If _read pushed data synchronously, then `reading` will be false,
14312 // and we need to re-evaluate how much data we can return to the user.
14313 if (!state.reading) n = howMuchToRead(nOrig, state);
14314 }
14315
14316 var ret;
14317 if (n > 0) ret = fromList(n, state);else ret = null;
14318
14319 if (ret === null) {
14320 state.needReadable = true;
14321 n = 0;
14322 } else {
14323 state.length -= n;
14324 }
14325
14326 if (state.length === 0) {
14327 // If we have nothing in the buffer, then we want to know
14328 // as soon as we *do* get something into the buffer.
14329 if (!state.ended) state.needReadable = true;
14330
14331 // If we tried to read() past the EOF, then emit end on the next tick.
14332 if (nOrig !== n && state.ended) endReadable(this);
14333 }
14334
14335 if (ret !== null) this.emit('data', ret);
14336
14337 return ret;
14338};
14339
14340function onEofChunk(stream, state) {
14341 if (state.ended) return;
14342 if (state.decoder) {
14343 var chunk = state.decoder.end();
14344 if (chunk && chunk.length) {
14345 state.buffer.push(chunk);
14346 state.length += state.objectMode ? 1 : chunk.length;
14347 }
14348 }
14349 state.ended = true;
14350
14351 // emit 'readable' now to make sure it gets picked up.
14352 emitReadable(stream);
14353}
14354
14355// Don't emit readable right away in sync mode, because this can trigger
14356// another read() call => stack overflow. This way, it might trigger
14357// a nextTick recursion warning, but that's not so bad.
14358function emitReadable(stream) {
14359 var state = stream._readableState;
14360 state.needReadable = false;
14361 if (!state.emittedReadable) {
14362 debug('emitReadable', state.flowing);
14363 state.emittedReadable = true;
14364 if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
14365 }
14366}
14367
14368function emitReadable_(stream) {
14369 debug('emit readable');
14370 stream.emit('readable');
14371 flow(stream);
14372}
14373
14374// at this point, the user has presumably seen the 'readable' event,
14375// and called read() to consume some data. that may have triggered
14376// in turn another _read(n) call, in which case reading = true if
14377// it's in progress.
14378// However, if we're not ended, or reading, and the length < hwm,
14379// then go ahead and try to read some more preemptively.
14380function maybeReadMore(stream, state) {
14381 if (!state.readingMore) {
14382 state.readingMore = true;
14383 pna.nextTick(maybeReadMore_, stream, state);
14384 }
14385}
14386
14387function maybeReadMore_(stream, state) {
14388 var len = state.length;
14389 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
14390 debug('maybeReadMore read 0');
14391 stream.read(0);
14392 if (len === state.length)
14393 // didn't get any data, stop spinning.
14394 break;else len = state.length;
14395 }
14396 state.readingMore = false;
14397}
14398
14399// abstract method. to be overridden in specific implementation classes.
14400// call cb(er, data) where data is <= n in length.
14401// for virtual (non-string, non-buffer) streams, "length" is somewhat
14402// arbitrary, and perhaps not very meaningful.
14403Readable.prototype._read = function (n) {
14404 this.emit('error', new Error('_read() is not implemented'));
14405};
14406
14407Readable.prototype.pipe = function (dest, pipeOpts) {
14408 var src = this;
14409 var state = this._readableState;
14410
14411 switch (state.pipesCount) {
14412 case 0:
14413 state.pipes = dest;
14414 break;
14415 case 1:
14416 state.pipes = [state.pipes, dest];
14417 break;
14418 default:
14419 state.pipes.push(dest);
14420 break;
14421 }
14422 state.pipesCount += 1;
14423 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
14424
14425 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
14426
14427 var endFn = doEnd ? onend : unpipe;
14428 if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
14429
14430 dest.on('unpipe', onunpipe);
14431 function onunpipe(readable, unpipeInfo) {
14432 debug('onunpipe');
14433 if (readable === src) {
14434 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
14435 unpipeInfo.hasUnpiped = true;
14436 cleanup();
14437 }
14438 }
14439 }
14440
14441 function onend() {
14442 debug('onend');
14443 dest.end();
14444 }
14445
14446 // when the dest drains, it reduces the awaitDrain counter
14447 // on the source. This would be more elegant with a .once()
14448 // handler in flow(), but adding and removing repeatedly is
14449 // too slow.
14450 var ondrain = pipeOnDrain(src);
14451 dest.on('drain', ondrain);
14452
14453 var cleanedUp = false;
14454 function cleanup() {
14455 debug('cleanup');
14456 // cleanup event handlers once the pipe is broken
14457 dest.removeListener('close', onclose);
14458 dest.removeListener('finish', onfinish);
14459 dest.removeListener('drain', ondrain);
14460 dest.removeListener('error', onerror);
14461 dest.removeListener('unpipe', onunpipe);
14462 src.removeListener('end', onend);
14463 src.removeListener('end', unpipe);
14464 src.removeListener('data', ondata);
14465
14466 cleanedUp = true;
14467
14468 // if the reader is waiting for a drain event from this
14469 // specific writer, then it would cause it to never start
14470 // flowing again.
14471 // So, if this is awaiting a drain, then we just call it now.
14472 // If we don't know, then assume that we are waiting for one.
14473 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
14474 }
14475
14476 // If the user pushes more data while we're writing to dest then we'll end up
14477 // in ondata again. However, we only want to increase awaitDrain once because
14478 // dest will only emit one 'drain' event for the multiple writes.
14479 // => Introduce a guard on increasing awaitDrain.
14480 var increasedAwaitDrain = false;
14481 src.on('data', ondata);
14482 function ondata(chunk) {
14483 debug('ondata');
14484 increasedAwaitDrain = false;
14485 var ret = dest.write(chunk);
14486 if (false === ret && !increasedAwaitDrain) {
14487 // If the user unpiped during `dest.write()`, it is possible
14488 // to get stuck in a permanently paused state if that write
14489 // also returned false.
14490 // => Check whether `dest` is still a piping destination.
14491 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
14492 debug('false write response, pause', src._readableState.awaitDrain);
14493 src._readableState.awaitDrain++;
14494 increasedAwaitDrain = true;
14495 }
14496 src.pause();
14497 }
14498 }
14499
14500 // if the dest has an error, then stop piping into it.
14501 // however, don't suppress the throwing behavior for this.
14502 function onerror(er) {
14503 debug('onerror', er);
14504 unpipe();
14505 dest.removeListener('error', onerror);
14506 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
14507 }
14508
14509 // Make sure our error handler is attached before userland ones.
14510 prependListener(dest, 'error', onerror);
14511
14512 // Both close and finish should trigger unpipe, but only once.
14513 function onclose() {
14514 dest.removeListener('finish', onfinish);
14515 unpipe();
14516 }
14517 dest.once('close', onclose);
14518 function onfinish() {
14519 debug('onfinish');
14520 dest.removeListener('close', onclose);
14521 unpipe();
14522 }
14523 dest.once('finish', onfinish);
14524
14525 function unpipe() {
14526 debug('unpipe');
14527 src.unpipe(dest);
14528 }
14529
14530 // tell the dest that it's being piped to
14531 dest.emit('pipe', src);
14532
14533 // start the flow if it hasn't been started already.
14534 if (!state.flowing) {
14535 debug('pipe resume');
14536 src.resume();
14537 }
14538
14539 return dest;
14540};
14541
14542function pipeOnDrain(src) {
14543 return function () {
14544 var state = src._readableState;
14545 debug('pipeOnDrain', state.awaitDrain);
14546 if (state.awaitDrain) state.awaitDrain--;
14547 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
14548 state.flowing = true;
14549 flow(src);
14550 }
14551 };
14552}
14553
14554Readable.prototype.unpipe = function (dest) {
14555 var state = this._readableState;
14556 var unpipeInfo = { hasUnpiped: false };
14557
14558 // if we're not piping anywhere, then do nothing.
14559 if (state.pipesCount === 0) return this;
14560
14561 // just one destination. most common case.
14562 if (state.pipesCount === 1) {
14563 // passed in one, but it's not the right one.
14564 if (dest && dest !== state.pipes) return this;
14565
14566 if (!dest) dest = state.pipes;
14567
14568 // got a match.
14569 state.pipes = null;
14570 state.pipesCount = 0;
14571 state.flowing = false;
14572 if (dest) dest.emit('unpipe', this, unpipeInfo);
14573 return this;
14574 }
14575
14576 // slow case. multiple pipe destinations.
14577
14578 if (!dest) {
14579 // remove all.
14580 var dests = state.pipes;
14581 var len = state.pipesCount;
14582 state.pipes = null;
14583 state.pipesCount = 0;
14584 state.flowing = false;
14585
14586 for (var i = 0; i < len; i++) {
14587 dests[i].emit('unpipe', this, unpipeInfo);
14588 }return this;
14589 }
14590
14591 // try to find the right one.
14592 var index = indexOf(state.pipes, dest);
14593 if (index === -1) return this;
14594
14595 state.pipes.splice(index, 1);
14596 state.pipesCount -= 1;
14597 if (state.pipesCount === 1) state.pipes = state.pipes[0];
14598
14599 dest.emit('unpipe', this, unpipeInfo);
14600
14601 return this;
14602};
14603
14604// set up data events if they are asked for
14605// Ensure readable listeners eventually get something
14606Readable.prototype.on = function (ev, fn) {
14607 var res = Stream.prototype.on.call(this, ev, fn);
14608
14609 if (ev === 'data') {
14610 // Start flowing on next tick if stream isn't explicitly paused
14611 if (this._readableState.flowing !== false) this.resume();
14612 } else if (ev === 'readable') {
14613 var state = this._readableState;
14614 if (!state.endEmitted && !state.readableListening) {
14615 state.readableListening = state.needReadable = true;
14616 state.emittedReadable = false;
14617 if (!state.reading) {
14618 pna.nextTick(nReadingNextTick, this);
14619 } else if (state.length) {
14620 emitReadable(this);
14621 }
14622 }
14623 }
14624
14625 return res;
14626};
14627Readable.prototype.addListener = Readable.prototype.on;
14628
14629function nReadingNextTick(self) {
14630 debug('readable nexttick read 0');
14631 self.read(0);
14632}
14633
14634// pause() and resume() are remnants of the legacy readable stream API
14635// If the user uses them, then switch into old mode.
14636Readable.prototype.resume = function () {
14637 var state = this._readableState;
14638 if (!state.flowing) {
14639 debug('resume');
14640 state.flowing = true;
14641 resume(this, state);
14642 }
14643 return this;
14644};
14645
14646function resume(stream, state) {
14647 if (!state.resumeScheduled) {
14648 state.resumeScheduled = true;
14649 pna.nextTick(resume_, stream, state);
14650 }
14651}
14652
14653function resume_(stream, state) {
14654 if (!state.reading) {
14655 debug('resume read 0');
14656 stream.read(0);
14657 }
14658
14659 state.resumeScheduled = false;
14660 state.awaitDrain = 0;
14661 stream.emit('resume');
14662 flow(stream);
14663 if (state.flowing && !state.reading) stream.read(0);
14664}
14665
14666Readable.prototype.pause = function () {
14667 debug('call pause flowing=%j', this._readableState.flowing);
14668 if (false !== this._readableState.flowing) {
14669 debug('pause');
14670 this._readableState.flowing = false;
14671 this.emit('pause');
14672 }
14673 return this;
14674};
14675
14676function flow(stream) {
14677 var state = stream._readableState;
14678 debug('flow', state.flowing);
14679 while (state.flowing && stream.read() !== null) {}
14680}
14681
14682// wrap an old-style stream as the async data source.
14683// This is *not* part of the readable stream interface.
14684// It is an ugly unfortunate mess of history.
14685Readable.prototype.wrap = function (stream) {
14686 var _this = this;
14687
14688 var state = this._readableState;
14689 var paused = false;
14690
14691 stream.on('end', function () {
14692 debug('wrapped end');
14693 if (state.decoder && !state.ended) {
14694 var chunk = state.decoder.end();
14695 if (chunk && chunk.length) _this.push(chunk);
14696 }
14697
14698 _this.push(null);
14699 });
14700
14701 stream.on('data', function (chunk) {
14702 debug('wrapped data');
14703 if (state.decoder) chunk = state.decoder.write(chunk);
14704
14705 // don't skip over falsy values in objectMode
14706 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
14707
14708 var ret = _this.push(chunk);
14709 if (!ret) {
14710 paused = true;
14711 stream.pause();
14712 }
14713 });
14714
14715 // proxy all the other methods.
14716 // important when wrapping filters and duplexes.
14717 for (var i in stream) {
14718 if (this[i] === undefined && typeof stream[i] === 'function') {
14719 this[i] = function (method) {
14720 return function () {
14721 return stream[method].apply(stream, arguments);
14722 };
14723 }(i);
14724 }
14725 }
14726
14727 // proxy certain important events.
14728 for (var n = 0; n < kProxyEvents.length; n++) {
14729 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
14730 }
14731
14732 // when we try to consume some more bytes, simply unpause the
14733 // underlying stream.
14734 this._read = function (n) {
14735 debug('wrapped _read', n);
14736 if (paused) {
14737 paused = false;
14738 stream.resume();
14739 }
14740 };
14741
14742 return this;
14743};
14744
14745Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
14746 // making it explicit this property is not enumerable
14747 // because otherwise some prototype manipulation in
14748 // userland will fail
14749 enumerable: false,
14750 get: function () {
14751 return this._readableState.highWaterMark;
14752 }
14753});
14754
14755// exposed for testing purposes only.
14756Readable._fromList = fromList;
14757
14758// Pluck off n bytes from an array of buffers.
14759// Length is the combined lengths of all the buffers in the list.
14760// This function is designed to be inlinable, so please take care when making
14761// changes to the function body.
14762function fromList(n, state) {
14763 // nothing buffered
14764 if (state.length === 0) return null;
14765
14766 var ret;
14767 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
14768 // read it all, truncate the list
14769 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);
14770 state.buffer.clear();
14771 } else {
14772 // read part of list
14773 ret = fromListPartial(n, state.buffer, state.decoder);
14774 }
14775
14776 return ret;
14777}
14778
14779// Extracts only enough buffered data to satisfy the amount requested.
14780// This function is designed to be inlinable, so please take care when making
14781// changes to the function body.
14782function fromListPartial(n, list, hasStrings) {
14783 var ret;
14784 if (n < list.head.data.length) {
14785 // slice is the same for buffers and strings
14786 ret = list.head.data.slice(0, n);
14787 list.head.data = list.head.data.slice(n);
14788 } else if (n === list.head.data.length) {
14789 // first chunk is a perfect match
14790 ret = list.shift();
14791 } else {
14792 // result spans more than one buffer
14793 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
14794 }
14795 return ret;
14796}
14797
14798// Copies a specified amount of characters from the list of buffered data
14799// chunks.
14800// This function is designed to be inlinable, so please take care when making
14801// changes to the function body.
14802function copyFromBufferString(n, list) {
14803 var p = list.head;
14804 var c = 1;
14805 var ret = p.data;
14806 n -= ret.length;
14807 while (p = p.next) {
14808 var str = p.data;
14809 var nb = n > str.length ? str.length : n;
14810 if (nb === str.length) ret += str;else ret += str.slice(0, n);
14811 n -= nb;
14812 if (n === 0) {
14813 if (nb === str.length) {
14814 ++c;
14815 if (p.next) list.head = p.next;else list.head = list.tail = null;
14816 } else {
14817 list.head = p;
14818 p.data = str.slice(nb);
14819 }
14820 break;
14821 }
14822 ++c;
14823 }
14824 list.length -= c;
14825 return ret;
14826}
14827
14828// Copies a specified amount of bytes from the list of buffered data chunks.
14829// This function is designed to be inlinable, so please take care when making
14830// changes to the function body.
14831function copyFromBuffer(n, list) {
14832 var ret = Buffer.allocUnsafe(n);
14833 var p = list.head;
14834 var c = 1;
14835 p.data.copy(ret);
14836 n -= p.data.length;
14837 while (p = p.next) {
14838 var buf = p.data;
14839 var nb = n > buf.length ? buf.length : n;
14840 buf.copy(ret, ret.length - n, 0, nb);
14841 n -= nb;
14842 if (n === 0) {
14843 if (nb === buf.length) {
14844 ++c;
14845 if (p.next) list.head = p.next;else list.head = list.tail = null;
14846 } else {
14847 list.head = p;
14848 p.data = buf.slice(nb);
14849 }
14850 break;
14851 }
14852 ++c;
14853 }
14854 list.length -= c;
14855 return ret;
14856}
14857
14858function endReadable(stream) {
14859 var state = stream._readableState;
14860
14861 // If we get here before consuming all the bytes, then that is a
14862 // bug in node. Should never happen.
14863 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
14864
14865 if (!state.endEmitted) {
14866 state.ended = true;
14867 pna.nextTick(endReadableNT, state, stream);
14868 }
14869}
14870
14871function endReadableNT(state, stream) {
14872 // Check that we didn't get one last unshift.
14873 if (!state.endEmitted && state.length === 0) {
14874 state.endEmitted = true;
14875 stream.readable = false;
14876 stream.emit('end');
14877 }
14878}
14879
14880function indexOf(xs, x) {
14881 for (var i = 0, l = xs.length; i < l; i++) {
14882 if (xs[i] === x) return i;
14883 }
14884 return -1;
14885}
14886}).call(this,_dereq_(69),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
14887},{"10":10,"13":13,"25":25,"31":31,"68":68,"69":69,"78":78,"81":81,"83":83,"88":88,"89":89,"90":90,"95":95}],86:[function(_dereq_,module,exports){
14888// Copyright Joyent, Inc. and other Node contributors.
14889//
14890// Permission is hereby granted, free of charge, to any person obtaining a
14891// copy of this software and associated documentation files (the
14892// "Software"), to deal in the Software without restriction, including
14893// without limitation the rights to use, copy, modify, merge, publish,
14894// distribute, sublicense, and/or sell copies of the Software, and to permit
14895// persons to whom the Software is furnished to do so, subject to the
14896// following conditions:
14897//
14898// The above copyright notice and this permission notice shall be included
14899// in all copies or substantial portions of the Software.
14900//
14901// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14902// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14903// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14904// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14905// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14906// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14907// USE OR OTHER DEALINGS IN THE SOFTWARE.
14908
14909// a transform stream is a readable/writable stream where you do
14910// something with the data. Sometimes it's called a "filter",
14911// but that's not a great name for it, since that implies a thing where
14912// some bits pass through, and others are simply ignored. (That would
14913// be a valid example of a transform, of course.)
14914//
14915// While the output is causally related to the input, it's not a
14916// necessarily symmetric or synchronous transformation. For example,
14917// a zlib stream might take multiple plain-text writes(), and then
14918// emit a single compressed chunk some time in the future.
14919//
14920// Here's how this works:
14921//
14922// The Transform stream has all the aspects of the readable and writable
14923// stream classes. When you write(chunk), that calls _write(chunk,cb)
14924// internally, and returns false if there's a lot of pending writes
14925// buffered up. When you call read(), that calls _read(n) until
14926// there's enough pending readable data buffered up.
14927//
14928// In a transform stream, the written data is placed in a buffer. When
14929// _read(n) is called, it transforms the queued up data, calling the
14930// buffered _write cb's as it consumes chunks. If consuming a single
14931// written chunk would result in multiple output chunks, then the first
14932// outputted bit calls the readcb, and subsequent chunks just go into
14933// the read buffer, and will cause it to emit 'readable' if necessary.
14934//
14935// This way, back-pressure is actually determined by the reading side,
14936// since _read has to be called to start processing a new chunk. However,
14937// a pathological inflate type of transform can cause excessive buffering
14938// here. For example, imagine a stream where every byte of input is
14939// interpreted as an integer from 0-255, and then results in that many
14940// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
14941// 1kb of data being output. In this case, you could write a very small
14942// amount of input, and end up with a very large amount of output. In
14943// such a pathological inflating mechanism, there'd be no way to tell
14944// the system to stop doing the transform. A single 4MB write could
14945// cause the system to run out of memory.
14946//
14947// However, even in such a pathological case, only a single written chunk
14948// would be consumed, and then the rest would wait (un-transformed) until
14949// the results of the previous transformed chunk were consumed.
14950
14951'use strict';
14952
14953module.exports = Transform;
14954
14955var Duplex = _dereq_(83);
14956
14957/*<replacement>*/
14958var util = _dereq_(13);
14959util.inherits = _dereq_(31);
14960/*</replacement>*/
14961
14962util.inherits(Transform, Duplex);
14963
14964function afterTransform(er, data) {
14965 var ts = this._transformState;
14966 ts.transforming = false;
14967
14968 var cb = ts.writecb;
14969
14970 if (!cb) {
14971 return this.emit('error', new Error('write callback called multiple times'));
14972 }
14973
14974 ts.writechunk = null;
14975 ts.writecb = null;
14976
14977 if (data != null) // single equals check for both `null` and `undefined`
14978 this.push(data);
14979
14980 cb(er);
14981
14982 var rs = this._readableState;
14983 rs.reading = false;
14984 if (rs.needReadable || rs.length < rs.highWaterMark) {
14985 this._read(rs.highWaterMark);
14986 }
14987}
14988
14989function Transform(options) {
14990 if (!(this instanceof Transform)) return new Transform(options);
14991
14992 Duplex.call(this, options);
14993
14994 this._transformState = {
14995 afterTransform: afterTransform.bind(this),
14996 needTransform: false,
14997 transforming: false,
14998 writecb: null,
14999 writechunk: null,
15000 writeencoding: null
15001 };
15002
15003 // start out asking for a readable event once data is transformed.
15004 this._readableState.needReadable = true;
15005
15006 // we have implemented the _read method, and done the other things
15007 // that Readable wants before the first _read call, so unset the
15008 // sync guard flag.
15009 this._readableState.sync = false;
15010
15011 if (options) {
15012 if (typeof options.transform === 'function') this._transform = options.transform;
15013
15014 if (typeof options.flush === 'function') this._flush = options.flush;
15015 }
15016
15017 // When the writable side finishes, then flush out anything remaining.
15018 this.on('prefinish', prefinish);
15019}
15020
15021function prefinish() {
15022 var _this = this;
15023
15024 if (typeof this._flush === 'function') {
15025 this._flush(function (er, data) {
15026 done(_this, er, data);
15027 });
15028 } else {
15029 done(this, null, null);
15030 }
15031}
15032
15033Transform.prototype.push = function (chunk, encoding) {
15034 this._transformState.needTransform = false;
15035 return Duplex.prototype.push.call(this, chunk, encoding);
15036};
15037
15038// This is the part where you do stuff!
15039// override this function in implementation classes.
15040// 'chunk' is an input chunk.
15041//
15042// Call `push(newChunk)` to pass along transformed output
15043// to the readable side. You may call 'push' zero or more times.
15044//
15045// Call `cb(err)` when you are done with this chunk. If you pass
15046// an error, then that'll put the hurt on the whole operation. If you
15047// never call cb(), then you'll never get another chunk.
15048Transform.prototype._transform = function (chunk, encoding, cb) {
15049 throw new Error('_transform() is not implemented');
15050};
15051
15052Transform.prototype._write = function (chunk, encoding, cb) {
15053 var ts = this._transformState;
15054 ts.writecb = cb;
15055 ts.writechunk = chunk;
15056 ts.writeencoding = encoding;
15057 if (!ts.transforming) {
15058 var rs = this._readableState;
15059 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
15060 }
15061};
15062
15063// Doesn't matter what the args are here.
15064// _transform does all the work.
15065// That we got here means that the readable side wants more data.
15066Transform.prototype._read = function (n) {
15067 var ts = this._transformState;
15068
15069 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
15070 ts.transforming = true;
15071 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
15072 } else {
15073 // mark that we need a transform, so that any data that comes in
15074 // will get processed, now that we've asked for it.
15075 ts.needTransform = true;
15076 }
15077};
15078
15079Transform.prototype._destroy = function (err, cb) {
15080 var _this2 = this;
15081
15082 Duplex.prototype._destroy.call(this, err, function (err2) {
15083 cb(err2);
15084 _this2.emit('close');
15085 });
15086};
15087
15088function done(stream, er, data) {
15089 if (er) return stream.emit('error', er);
15090
15091 if (data != null) // single equals check for both `null` and `undefined`
15092 stream.push(data);
15093
15094 // if there's nothing in the write buffer, then that means
15095 // that nothing more will ever be provided
15096 if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
15097
15098 if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
15099
15100 return stream.push(null);
15101}
15102},{"13":13,"31":31,"83":83}],87:[function(_dereq_,module,exports){
15103(function (process,global,setImmediate){
15104// Copyright Joyent, Inc. and other Node contributors.
15105//
15106// Permission is hereby granted, free of charge, to any person obtaining a
15107// copy of this software and associated documentation files (the
15108// "Software"), to deal in the Software without restriction, including
15109// without limitation the rights to use, copy, modify, merge, publish,
15110// distribute, sublicense, and/or sell copies of the Software, and to permit
15111// persons to whom the Software is furnished to do so, subject to the
15112// following conditions:
15113//
15114// The above copyright notice and this permission notice shall be included
15115// in all copies or substantial portions of the Software.
15116//
15117// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15118// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15119// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15120// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15121// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15122// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15123// USE OR OTHER DEALINGS IN THE SOFTWARE.
15124
15125// A bit simpler than readable streams.
15126// Implement an async ._write(chunk, encoding, cb), and it'll handle all
15127// the drain event emission and buffering.
15128
15129'use strict';
15130
15131/*<replacement>*/
15132
15133var pna = _dereq_(68);
15134/*</replacement>*/
15135
15136module.exports = Writable;
15137
15138/* <replacement> */
15139function WriteReq(chunk, encoding, cb) {
15140 this.chunk = chunk;
15141 this.encoding = encoding;
15142 this.callback = cb;
15143 this.next = null;
15144}
15145
15146// It seems a linked list but it is not
15147// there will be only 2 of these for each stream
15148function CorkedRequest(state) {
15149 var _this = this;
15150
15151 this.next = null;
15152 this.entry = null;
15153 this.finish = function () {
15154 onCorkedFinish(_this, state);
15155 };
15156}
15157/* </replacement> */
15158
15159/*<replacement>*/
15160var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
15161/*</replacement>*/
15162
15163/*<replacement>*/
15164var Duplex;
15165/*</replacement>*/
15166
15167Writable.WritableState = WritableState;
15168
15169/*<replacement>*/
15170var util = _dereq_(13);
15171util.inherits = _dereq_(31);
15172/*</replacement>*/
15173
15174/*<replacement>*/
15175var internalUtil = {
15176 deprecate: _dereq_(115)
15177};
15178/*</replacement>*/
15179
15180/*<replacement>*/
15181var Stream = _dereq_(90);
15182/*</replacement>*/
15183
15184/*<replacement>*/
15185
15186var Buffer = _dereq_(78).Buffer;
15187var OurUint8Array = global.Uint8Array || function () {};
15188function _uint8ArrayToBuffer(chunk) {
15189 return Buffer.from(chunk);
15190}
15191function _isUint8Array(obj) {
15192 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
15193}
15194
15195/*</replacement>*/
15196
15197var destroyImpl = _dereq_(89);
15198
15199util.inherits(Writable, Stream);
15200
15201function nop() {}
15202
15203function WritableState(options, stream) {
15204 Duplex = Duplex || _dereq_(83);
15205
15206 options = options || {};
15207
15208 // Duplex streams are both readable and writable, but share
15209 // the same options object.
15210 // However, some cases require setting options to different
15211 // values for the readable and the writable sides of the duplex stream.
15212 // These options can be provided separately as readableXXX and writableXXX.
15213 var isDuplex = stream instanceof Duplex;
15214
15215 // object stream flag to indicate whether or not this stream
15216 // contains buffers or objects.
15217 this.objectMode = !!options.objectMode;
15218
15219 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
15220
15221 // the point at which write() starts returning false
15222 // Note: 0 is a valid value, means that we always return false if
15223 // the entire buffer is not flushed immediately on write()
15224 var hwm = options.highWaterMark;
15225 var writableHwm = options.writableHighWaterMark;
15226 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
15227
15228 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
15229
15230 // cast to ints.
15231 this.highWaterMark = Math.floor(this.highWaterMark);
15232
15233 // if _final has been called
15234 this.finalCalled = false;
15235
15236 // drain event flag.
15237 this.needDrain = false;
15238 // at the start of calling end()
15239 this.ending = false;
15240 // when end() has been called, and returned
15241 this.ended = false;
15242 // when 'finish' is emitted
15243 this.finished = false;
15244
15245 // has it been destroyed
15246 this.destroyed = false;
15247
15248 // should we decode strings into buffers before passing to _write?
15249 // this is here so that some node-core streams can optimize string
15250 // handling at a lower level.
15251 var noDecode = options.decodeStrings === false;
15252 this.decodeStrings = !noDecode;
15253
15254 // Crypto is kind of old and crusty. Historically, its default string
15255 // encoding is 'binary' so we have to make this configurable.
15256 // Everything else in the universe uses 'utf8', though.
15257 this.defaultEncoding = options.defaultEncoding || 'utf8';
15258
15259 // not an actual buffer we keep track of, but a measurement
15260 // of how much we're waiting to get pushed to some underlying
15261 // socket or file.
15262 this.length = 0;
15263
15264 // a flag to see when we're in the middle of a write.
15265 this.writing = false;
15266
15267 // when true all writes will be buffered until .uncork() call
15268 this.corked = 0;
15269
15270 // a flag to be able to tell if the onwrite cb is called immediately,
15271 // or on a later tick. We set this to true at first, because any
15272 // actions that shouldn't happen until "later" should generally also
15273 // not happen before the first write call.
15274 this.sync = true;
15275
15276 // a flag to know if we're processing previously buffered items, which
15277 // may call the _write() callback in the same tick, so that we don't
15278 // end up in an overlapped onwrite situation.
15279 this.bufferProcessing = false;
15280
15281 // the callback that's passed to _write(chunk,cb)
15282 this.onwrite = function (er) {
15283 onwrite(stream, er);
15284 };
15285
15286 // the callback that the user supplies to write(chunk,encoding,cb)
15287 this.writecb = null;
15288
15289 // the amount that is being written when _write is called.
15290 this.writelen = 0;
15291
15292 this.bufferedRequest = null;
15293 this.lastBufferedRequest = null;
15294
15295 // number of pending user-supplied write callbacks
15296 // this must be 0 before 'finish' can be emitted
15297 this.pendingcb = 0;
15298
15299 // emit prefinish if the only thing we're waiting for is _write cbs
15300 // This is relevant for synchronous Transform streams
15301 this.prefinished = false;
15302
15303 // True if the error was already emitted and should not be thrown again
15304 this.errorEmitted = false;
15305
15306 // count buffered requests
15307 this.bufferedRequestCount = 0;
15308
15309 // allocate the first CorkedRequest, there is always
15310 // one allocated and free to use, and we maintain at most two
15311 this.corkedRequestsFree = new CorkedRequest(this);
15312}
15313
15314WritableState.prototype.getBuffer = function getBuffer() {
15315 var current = this.bufferedRequest;
15316 var out = [];
15317 while (current) {
15318 out.push(current);
15319 current = current.next;
15320 }
15321 return out;
15322};
15323
15324(function () {
15325 try {
15326 Object.defineProperty(WritableState.prototype, 'buffer', {
15327 get: internalUtil.deprecate(function () {
15328 return this.getBuffer();
15329 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
15330 });
15331 } catch (_) {}
15332})();
15333
15334// Test _writableState for inheritance to account for Duplex streams,
15335// whose prototype chain only points to Readable.
15336var realHasInstance;
15337if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
15338 realHasInstance = Function.prototype[Symbol.hasInstance];
15339 Object.defineProperty(Writable, Symbol.hasInstance, {
15340 value: function (object) {
15341 if (realHasInstance.call(this, object)) return true;
15342 if (this !== Writable) return false;
15343
15344 return object && object._writableState instanceof WritableState;
15345 }
15346 });
15347} else {
15348 realHasInstance = function (object) {
15349 return object instanceof this;
15350 };
15351}
15352
15353function Writable(options) {
15354 Duplex = Duplex || _dereq_(83);
15355
15356 // Writable ctor is applied to Duplexes, too.
15357 // `realHasInstance` is necessary because using plain `instanceof`
15358 // would return false, as no `_writableState` property is attached.
15359
15360 // Trying to use the custom `instanceof` for Writable here will also break the
15361 // Node.js LazyTransform implementation, which has a non-trivial getter for
15362 // `_writableState` that would lead to infinite recursion.
15363 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
15364 return new Writable(options);
15365 }
15366
15367 this._writableState = new WritableState(options, this);
15368
15369 // legacy.
15370 this.writable = true;
15371
15372 if (options) {
15373 if (typeof options.write === 'function') this._write = options.write;
15374
15375 if (typeof options.writev === 'function') this._writev = options.writev;
15376
15377 if (typeof options.destroy === 'function') this._destroy = options.destroy;
15378
15379 if (typeof options.final === 'function') this._final = options.final;
15380 }
15381
15382 Stream.call(this);
15383}
15384
15385// Otherwise people can pipe Writable streams, which is just wrong.
15386Writable.prototype.pipe = function () {
15387 this.emit('error', new Error('Cannot pipe, not readable'));
15388};
15389
15390function writeAfterEnd(stream, cb) {
15391 var er = new Error('write after end');
15392 // TODO: defer error events consistently everywhere, not just the cb
15393 stream.emit('error', er);
15394 pna.nextTick(cb, er);
15395}
15396
15397// Checks that a user-supplied chunk is valid, especially for the particular
15398// mode the stream is in. Currently this means that `null` is never accepted
15399// and undefined/non-string values are only allowed in object mode.
15400function validChunk(stream, state, chunk, cb) {
15401 var valid = true;
15402 var er = false;
15403
15404 if (chunk === null) {
15405 er = new TypeError('May not write null values to stream');
15406 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
15407 er = new TypeError('Invalid non-string/buffer chunk');
15408 }
15409 if (er) {
15410 stream.emit('error', er);
15411 pna.nextTick(cb, er);
15412 valid = false;
15413 }
15414 return valid;
15415}
15416
15417Writable.prototype.write = function (chunk, encoding, cb) {
15418 var state = this._writableState;
15419 var ret = false;
15420 var isBuf = !state.objectMode && _isUint8Array(chunk);
15421
15422 if (isBuf && !Buffer.isBuffer(chunk)) {
15423 chunk = _uint8ArrayToBuffer(chunk);
15424 }
15425
15426 if (typeof encoding === 'function') {
15427 cb = encoding;
15428 encoding = null;
15429 }
15430
15431 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
15432
15433 if (typeof cb !== 'function') cb = nop;
15434
15435 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
15436 state.pendingcb++;
15437 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
15438 }
15439
15440 return ret;
15441};
15442
15443Writable.prototype.cork = function () {
15444 var state = this._writableState;
15445
15446 state.corked++;
15447};
15448
15449Writable.prototype.uncork = function () {
15450 var state = this._writableState;
15451
15452 if (state.corked) {
15453 state.corked--;
15454
15455 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
15456 }
15457};
15458
15459Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
15460 // node::ParseEncoding() requires lower case.
15461 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
15462 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);
15463 this._writableState.defaultEncoding = encoding;
15464 return this;
15465};
15466
15467function decodeChunk(state, chunk, encoding) {
15468 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
15469 chunk = Buffer.from(chunk, encoding);
15470 }
15471 return chunk;
15472}
15473
15474Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
15475 // making it explicit this property is not enumerable
15476 // because otherwise some prototype manipulation in
15477 // userland will fail
15478 enumerable: false,
15479 get: function () {
15480 return this._writableState.highWaterMark;
15481 }
15482});
15483
15484// if we're already writing something, then just put this
15485// in the queue, and wait our turn. Otherwise, call _write
15486// If we return false, then we need a drain event, so set that flag.
15487function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
15488 if (!isBuf) {
15489 var newChunk = decodeChunk(state, chunk, encoding);
15490 if (chunk !== newChunk) {
15491 isBuf = true;
15492 encoding = 'buffer';
15493 chunk = newChunk;
15494 }
15495 }
15496 var len = state.objectMode ? 1 : chunk.length;
15497
15498 state.length += len;
15499
15500 var ret = state.length < state.highWaterMark;
15501 // we must ensure that previous needDrain will not be reset to false.
15502 if (!ret) state.needDrain = true;
15503
15504 if (state.writing || state.corked) {
15505 var last = state.lastBufferedRequest;
15506 state.lastBufferedRequest = {
15507 chunk: chunk,
15508 encoding: encoding,
15509 isBuf: isBuf,
15510 callback: cb,
15511 next: null
15512 };
15513 if (last) {
15514 last.next = state.lastBufferedRequest;
15515 } else {
15516 state.bufferedRequest = state.lastBufferedRequest;
15517 }
15518 state.bufferedRequestCount += 1;
15519 } else {
15520 doWrite(stream, state, false, len, chunk, encoding, cb);
15521 }
15522
15523 return ret;
15524}
15525
15526function doWrite(stream, state, writev, len, chunk, encoding, cb) {
15527 state.writelen = len;
15528 state.writecb = cb;
15529 state.writing = true;
15530 state.sync = true;
15531 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
15532 state.sync = false;
15533}
15534
15535function onwriteError(stream, state, sync, er, cb) {
15536 --state.pendingcb;
15537
15538 if (sync) {
15539 // defer the callback if we are being called synchronously
15540 // to avoid piling up things on the stack
15541 pna.nextTick(cb, er);
15542 // this can emit finish, and it will always happen
15543 // after error
15544 pna.nextTick(finishMaybe, stream, state);
15545 stream._writableState.errorEmitted = true;
15546 stream.emit('error', er);
15547 } else {
15548 // the caller expect this to happen before if
15549 // it is async
15550 cb(er);
15551 stream._writableState.errorEmitted = true;
15552 stream.emit('error', er);
15553 // this can emit finish, but finish must
15554 // always follow error
15555 finishMaybe(stream, state);
15556 }
15557}
15558
15559function onwriteStateUpdate(state) {
15560 state.writing = false;
15561 state.writecb = null;
15562 state.length -= state.writelen;
15563 state.writelen = 0;
15564}
15565
15566function onwrite(stream, er) {
15567 var state = stream._writableState;
15568 var sync = state.sync;
15569 var cb = state.writecb;
15570
15571 onwriteStateUpdate(state);
15572
15573 if (er) onwriteError(stream, state, sync, er, cb);else {
15574 // Check if we're actually ready to finish, but don't emit yet
15575 var finished = needFinish(state);
15576
15577 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
15578 clearBuffer(stream, state);
15579 }
15580
15581 if (sync) {
15582 /*<replacement>*/
15583 asyncWrite(afterWrite, stream, state, finished, cb);
15584 /*</replacement>*/
15585 } else {
15586 afterWrite(stream, state, finished, cb);
15587 }
15588 }
15589}
15590
15591function afterWrite(stream, state, finished, cb) {
15592 if (!finished) onwriteDrain(stream, state);
15593 state.pendingcb--;
15594 cb();
15595 finishMaybe(stream, state);
15596}
15597
15598// Must force callback to be called on nextTick, so that we don't
15599// emit 'drain' before the write() consumer gets the 'false' return
15600// value, and has a chance to attach a 'drain' listener.
15601function onwriteDrain(stream, state) {
15602 if (state.length === 0 && state.needDrain) {
15603 state.needDrain = false;
15604 stream.emit('drain');
15605 }
15606}
15607
15608// if there's something in the buffer waiting, then process it
15609function clearBuffer(stream, state) {
15610 state.bufferProcessing = true;
15611 var entry = state.bufferedRequest;
15612
15613 if (stream._writev && entry && entry.next) {
15614 // Fast case, write everything using _writev()
15615 var l = state.bufferedRequestCount;
15616 var buffer = new Array(l);
15617 var holder = state.corkedRequestsFree;
15618 holder.entry = entry;
15619
15620 var count = 0;
15621 var allBuffers = true;
15622 while (entry) {
15623 buffer[count] = entry;
15624 if (!entry.isBuf) allBuffers = false;
15625 entry = entry.next;
15626 count += 1;
15627 }
15628 buffer.allBuffers = allBuffers;
15629
15630 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
15631
15632 // doWrite is almost always async, defer these to save a bit of time
15633 // as the hot path ends with doWrite
15634 state.pendingcb++;
15635 state.lastBufferedRequest = null;
15636 if (holder.next) {
15637 state.corkedRequestsFree = holder.next;
15638 holder.next = null;
15639 } else {
15640 state.corkedRequestsFree = new CorkedRequest(state);
15641 }
15642 state.bufferedRequestCount = 0;
15643 } else {
15644 // Slow case, write chunks one-by-one
15645 while (entry) {
15646 var chunk = entry.chunk;
15647 var encoding = entry.encoding;
15648 var cb = entry.callback;
15649 var len = state.objectMode ? 1 : chunk.length;
15650
15651 doWrite(stream, state, false, len, chunk, encoding, cb);
15652 entry = entry.next;
15653 state.bufferedRequestCount--;
15654 // if we didn't call the onwrite immediately, then
15655 // it means that we need to wait until it does.
15656 // also, that means that the chunk and cb are currently
15657 // being processed, so move the buffer counter past them.
15658 if (state.writing) {
15659 break;
15660 }
15661 }
15662
15663 if (entry === null) state.lastBufferedRequest = null;
15664 }
15665
15666 state.bufferedRequest = entry;
15667 state.bufferProcessing = false;
15668}
15669
15670Writable.prototype._write = function (chunk, encoding, cb) {
15671 cb(new Error('_write() is not implemented'));
15672};
15673
15674Writable.prototype._writev = null;
15675
15676Writable.prototype.end = function (chunk, encoding, cb) {
15677 var state = this._writableState;
15678
15679 if (typeof chunk === 'function') {
15680 cb = chunk;
15681 chunk = null;
15682 encoding = null;
15683 } else if (typeof encoding === 'function') {
15684 cb = encoding;
15685 encoding = null;
15686 }
15687
15688 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
15689
15690 // .end() fully uncorks
15691 if (state.corked) {
15692 state.corked = 1;
15693 this.uncork();
15694 }
15695
15696 // ignore unnecessary end() calls.
15697 if (!state.ending && !state.finished) endWritable(this, state, cb);
15698};
15699
15700function needFinish(state) {
15701 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
15702}
15703function callFinal(stream, state) {
15704 stream._final(function (err) {
15705 state.pendingcb--;
15706 if (err) {
15707 stream.emit('error', err);
15708 }
15709 state.prefinished = true;
15710 stream.emit('prefinish');
15711 finishMaybe(stream, state);
15712 });
15713}
15714function prefinish(stream, state) {
15715 if (!state.prefinished && !state.finalCalled) {
15716 if (typeof stream._final === 'function') {
15717 state.pendingcb++;
15718 state.finalCalled = true;
15719 pna.nextTick(callFinal, stream, state);
15720 } else {
15721 state.prefinished = true;
15722 stream.emit('prefinish');
15723 }
15724 }
15725}
15726
15727function finishMaybe(stream, state) {
15728 var need = needFinish(state);
15729 if (need) {
15730 prefinish(stream, state);
15731 if (state.pendingcb === 0) {
15732 state.finished = true;
15733 stream.emit('finish');
15734 }
15735 }
15736 return need;
15737}
15738
15739function endWritable(stream, state, cb) {
15740 state.ending = true;
15741 finishMaybe(stream, state);
15742 if (cb) {
15743 if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
15744 }
15745 state.ended = true;
15746 stream.writable = false;
15747}
15748
15749function onCorkedFinish(corkReq, state, err) {
15750 var entry = corkReq.entry;
15751 corkReq.entry = null;
15752 while (entry) {
15753 var cb = entry.callback;
15754 state.pendingcb--;
15755 cb(err);
15756 entry = entry.next;
15757 }
15758 if (state.corkedRequestsFree) {
15759 state.corkedRequestsFree.next = corkReq;
15760 } else {
15761 state.corkedRequestsFree = corkReq;
15762 }
15763}
15764
15765Object.defineProperty(Writable.prototype, 'destroyed', {
15766 get: function () {
15767 if (this._writableState === undefined) {
15768 return false;
15769 }
15770 return this._writableState.destroyed;
15771 },
15772 set: function (value) {
15773 // we ignore the value if the stream
15774 // has not been initialized yet
15775 if (!this._writableState) {
15776 return;
15777 }
15778
15779 // backward compatibility, the user is explicitly
15780 // managing destroyed
15781 this._writableState.destroyed = value;
15782 }
15783});
15784
15785Writable.prototype.destroy = destroyImpl.destroy;
15786Writable.prototype._undestroy = destroyImpl.undestroy;
15787Writable.prototype._destroy = function (err, cb) {
15788 this.end();
15789 cb(err);
15790};
15791}).call(this,_dereq_(69),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_(113).setImmediate)
15792},{"113":113,"115":115,"13":13,"31":31,"68":68,"69":69,"78":78,"83":83,"89":89,"90":90}],88:[function(_dereq_,module,exports){
15793'use strict';
15794
15795function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
15796
15797var Buffer = _dereq_(78).Buffer;
15798var util = _dereq_(10);
15799
15800function copyBuffer(src, target, offset) {
15801 src.copy(target, offset);
15802}
15803
15804module.exports = function () {
15805 function BufferList() {
15806 _classCallCheck(this, BufferList);
15807
15808 this.head = null;
15809 this.tail = null;
15810 this.length = 0;
15811 }
15812
15813 BufferList.prototype.push = function push(v) {
15814 var entry = { data: v, next: null };
15815 if (this.length > 0) this.tail.next = entry;else this.head = entry;
15816 this.tail = entry;
15817 ++this.length;
15818 };
15819
15820 BufferList.prototype.unshift = function unshift(v) {
15821 var entry = { data: v, next: this.head };
15822 if (this.length === 0) this.tail = entry;
15823 this.head = entry;
15824 ++this.length;
15825 };
15826
15827 BufferList.prototype.shift = function shift() {
15828 if (this.length === 0) return;
15829 var ret = this.head.data;
15830 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
15831 --this.length;
15832 return ret;
15833 };
15834
15835 BufferList.prototype.clear = function clear() {
15836 this.head = this.tail = null;
15837 this.length = 0;
15838 };
15839
15840 BufferList.prototype.join = function join(s) {
15841 if (this.length === 0) return '';
15842 var p = this.head;
15843 var ret = '' + p.data;
15844 while (p = p.next) {
15845 ret += s + p.data;
15846 }return ret;
15847 };
15848
15849 BufferList.prototype.concat = function concat(n) {
15850 if (this.length === 0) return Buffer.alloc(0);
15851 if (this.length === 1) return this.head.data;
15852 var ret = Buffer.allocUnsafe(n >>> 0);
15853 var p = this.head;
15854 var i = 0;
15855 while (p) {
15856 copyBuffer(p.data, ret, i);
15857 i += p.data.length;
15858 p = p.next;
15859 }
15860 return ret;
15861 };
15862
15863 return BufferList;
15864}();
15865
15866if (util && util.inspect && util.inspect.custom) {
15867 module.exports.prototype[util.inspect.custom] = function () {
15868 var obj = util.inspect({ length: this.length });
15869 return this.constructor.name + ' ' + obj;
15870 };
15871}
15872},{"10":10,"78":78}],89:[function(_dereq_,module,exports){
15873'use strict';
15874
15875/*<replacement>*/
15876
15877var pna = _dereq_(68);
15878/*</replacement>*/
15879
15880// undocumented cb() API, needed for core, not for public API
15881function destroy(err, cb) {
15882 var _this = this;
15883
15884 var readableDestroyed = this._readableState && this._readableState.destroyed;
15885 var writableDestroyed = this._writableState && this._writableState.destroyed;
15886
15887 if (readableDestroyed || writableDestroyed) {
15888 if (cb) {
15889 cb(err);
15890 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
15891 pna.nextTick(emitErrorNT, this, err);
15892 }
15893 return this;
15894 }
15895
15896 // we set destroyed to true before firing error callbacks in order
15897 // to make it re-entrance safe in case destroy() is called within callbacks
15898
15899 if (this._readableState) {
15900 this._readableState.destroyed = true;
15901 }
15902
15903 // if this is a duplex stream mark the writable part as destroyed as well
15904 if (this._writableState) {
15905 this._writableState.destroyed = true;
15906 }
15907
15908 this._destroy(err || null, function (err) {
15909 if (!cb && err) {
15910 pna.nextTick(emitErrorNT, _this, err);
15911 if (_this._writableState) {
15912 _this._writableState.errorEmitted = true;
15913 }
15914 } else if (cb) {
15915 cb(err);
15916 }
15917 });
15918
15919 return this;
15920}
15921
15922function undestroy() {
15923 if (this._readableState) {
15924 this._readableState.destroyed = false;
15925 this._readableState.reading = false;
15926 this._readableState.ended = false;
15927 this._readableState.endEmitted = false;
15928 }
15929
15930 if (this._writableState) {
15931 this._writableState.destroyed = false;
15932 this._writableState.ended = false;
15933 this._writableState.ending = false;
15934 this._writableState.finished = false;
15935 this._writableState.errorEmitted = false;
15936 }
15937}
15938
15939function emitErrorNT(self, err) {
15940 self.emit('error', err);
15941}
15942
15943module.exports = {
15944 destroy: destroy,
15945 undestroy: undestroy
15946};
15947},{"68":68}],90:[function(_dereq_,module,exports){
15948arguments[4][51][0].apply(exports,arguments)
15949},{"25":25,"51":51}],91:[function(_dereq_,module,exports){
15950module.exports = _dereq_(92).PassThrough
15951
15952},{"92":92}],92:[function(_dereq_,module,exports){
15953exports = module.exports = _dereq_(85);
15954exports.Stream = exports;
15955exports.Readable = exports;
15956exports.Writable = _dereq_(87);
15957exports.Duplex = _dereq_(83);
15958exports.Transform = _dereq_(86);
15959exports.PassThrough = _dereq_(84);
15960
15961},{"83":83,"84":84,"85":85,"86":86,"87":87}],93:[function(_dereq_,module,exports){
15962module.exports = _dereq_(92).Transform
15963
15964},{"92":92}],94:[function(_dereq_,module,exports){
15965module.exports = _dereq_(87);
15966
15967},{"87":87}],95:[function(_dereq_,module,exports){
15968// Copyright Joyent, Inc. and other Node contributors.
15969//
15970// Permission is hereby granted, free of charge, to any person obtaining a
15971// copy of this software and associated documentation files (the
15972// "Software"), to deal in the Software without restriction, including
15973// without limitation the rights to use, copy, modify, merge, publish,
15974// distribute, sublicense, and/or sell copies of the Software, and to permit
15975// persons to whom the Software is furnished to do so, subject to the
15976// following conditions:
15977//
15978// The above copyright notice and this permission notice shall be included
15979// in all copies or substantial portions of the Software.
15980//
15981// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15982// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15983// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15984// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15985// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15986// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15987// USE OR OTHER DEALINGS IN THE SOFTWARE.
15988
15989'use strict';
15990
15991/*<replacement>*/
15992
15993var Buffer = _dereq_(78).Buffer;
15994/*</replacement>*/
15995
15996var isEncoding = Buffer.isEncoding || function (encoding) {
15997 encoding = '' + encoding;
15998 switch (encoding && encoding.toLowerCase()) {
15999 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':
16000 return true;
16001 default:
16002 return false;
16003 }
16004};
16005
16006function _normalizeEncoding(enc) {
16007 if (!enc) return 'utf8';
16008 var retried;
16009 while (true) {
16010 switch (enc) {
16011 case 'utf8':
16012 case 'utf-8':
16013 return 'utf8';
16014 case 'ucs2':
16015 case 'ucs-2':
16016 case 'utf16le':
16017 case 'utf-16le':
16018 return 'utf16le';
16019 case 'latin1':
16020 case 'binary':
16021 return 'latin1';
16022 case 'base64':
16023 case 'ascii':
16024 case 'hex':
16025 return enc;
16026 default:
16027 if (retried) return; // undefined
16028 enc = ('' + enc).toLowerCase();
16029 retried = true;
16030 }
16031 }
16032};
16033
16034// Do not cache `Buffer.isEncoding` when checking encoding names as some
16035// modules monkey-patch it to support additional encodings
16036function normalizeEncoding(enc) {
16037 var nenc = _normalizeEncoding(enc);
16038 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
16039 return nenc || enc;
16040}
16041
16042// StringDecoder provides an interface for efficiently splitting a series of
16043// buffers into a series of JS strings without breaking apart multi-byte
16044// characters.
16045exports.StringDecoder = StringDecoder;
16046function StringDecoder(encoding) {
16047 this.encoding = normalizeEncoding(encoding);
16048 var nb;
16049 switch (this.encoding) {
16050 case 'utf16le':
16051 this.text = utf16Text;
16052 this.end = utf16End;
16053 nb = 4;
16054 break;
16055 case 'utf8':
16056 this.fillLast = utf8FillLast;
16057 nb = 4;
16058 break;
16059 case 'base64':
16060 this.text = base64Text;
16061 this.end = base64End;
16062 nb = 3;
16063 break;
16064 default:
16065 this.write = simpleWrite;
16066 this.end = simpleEnd;
16067 return;
16068 }
16069 this.lastNeed = 0;
16070 this.lastTotal = 0;
16071 this.lastChar = Buffer.allocUnsafe(nb);
16072}
16073
16074StringDecoder.prototype.write = function (buf) {
16075 if (buf.length === 0) return '';
16076 var r;
16077 var i;
16078 if (this.lastNeed) {
16079 r = this.fillLast(buf);
16080 if (r === undefined) return '';
16081 i = this.lastNeed;
16082 this.lastNeed = 0;
16083 } else {
16084 i = 0;
16085 }
16086 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
16087 return r || '';
16088};
16089
16090StringDecoder.prototype.end = utf8End;
16091
16092// Returns only complete characters in a Buffer
16093StringDecoder.prototype.text = utf8Text;
16094
16095// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
16096StringDecoder.prototype.fillLast = function (buf) {
16097 if (this.lastNeed <= buf.length) {
16098 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
16099 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
16100 }
16101 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
16102 this.lastNeed -= buf.length;
16103};
16104
16105// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
16106// continuation byte. If an invalid byte is detected, -2 is returned.
16107function utf8CheckByte(byte) {
16108 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;
16109 return byte >> 6 === 0x02 ? -1 : -2;
16110}
16111
16112// Checks at most 3 bytes at the end of a Buffer in order to detect an
16113// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
16114// needed to complete the UTF-8 character (if applicable) are returned.
16115function utf8CheckIncomplete(self, buf, i) {
16116 var j = buf.length - 1;
16117 if (j < i) return 0;
16118 var nb = utf8CheckByte(buf[j]);
16119 if (nb >= 0) {
16120 if (nb > 0) self.lastNeed = nb - 1;
16121 return nb;
16122 }
16123 if (--j < i || nb === -2) return 0;
16124 nb = utf8CheckByte(buf[j]);
16125 if (nb >= 0) {
16126 if (nb > 0) self.lastNeed = nb - 2;
16127 return nb;
16128 }
16129 if (--j < i || nb === -2) return 0;
16130 nb = utf8CheckByte(buf[j]);
16131 if (nb >= 0) {
16132 if (nb > 0) {
16133 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
16134 }
16135 return nb;
16136 }
16137 return 0;
16138}
16139
16140// Validates as many continuation bytes for a multi-byte UTF-8 character as
16141// needed or are available. If we see a non-continuation byte where we expect
16142// one, we "replace" the validated continuation bytes we've seen so far with
16143// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
16144// behavior. The continuation byte check is included three times in the case
16145// where all of the continuation bytes for a character exist in the same buffer.
16146// It is also done this way as a slight performance increase instead of using a
16147// loop.
16148function utf8CheckExtraBytes(self, buf, p) {
16149 if ((buf[0] & 0xC0) !== 0x80) {
16150 self.lastNeed = 0;
16151 return '\ufffd';
16152 }
16153 if (self.lastNeed > 1 && buf.length > 1) {
16154 if ((buf[1] & 0xC0) !== 0x80) {
16155 self.lastNeed = 1;
16156 return '\ufffd';
16157 }
16158 if (self.lastNeed > 2 && buf.length > 2) {
16159 if ((buf[2] & 0xC0) !== 0x80) {
16160 self.lastNeed = 2;
16161 return '\ufffd';
16162 }
16163 }
16164 }
16165}
16166
16167// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
16168function utf8FillLast(buf) {
16169 var p = this.lastTotal - this.lastNeed;
16170 var r = utf8CheckExtraBytes(this, buf, p);
16171 if (r !== undefined) return r;
16172 if (this.lastNeed <= buf.length) {
16173 buf.copy(this.lastChar, p, 0, this.lastNeed);
16174 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
16175 }
16176 buf.copy(this.lastChar, p, 0, buf.length);
16177 this.lastNeed -= buf.length;
16178}
16179
16180// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
16181// partial character, the character's bytes are buffered until the required
16182// number of bytes are available.
16183function utf8Text(buf, i) {
16184 var total = utf8CheckIncomplete(this, buf, i);
16185 if (!this.lastNeed) return buf.toString('utf8', i);
16186 this.lastTotal = total;
16187 var end = buf.length - (total - this.lastNeed);
16188 buf.copy(this.lastChar, 0, end);
16189 return buf.toString('utf8', i, end);
16190}
16191
16192// For UTF-8, a replacement character is added when ending on a partial
16193// character.
16194function utf8End(buf) {
16195 var r = buf && buf.length ? this.write(buf) : '';
16196 if (this.lastNeed) return r + '\ufffd';
16197 return r;
16198}
16199
16200// UTF-16LE typically needs two bytes per character, but even if we have an even
16201// number of bytes available, we need to check if we end on a leading/high
16202// surrogate. In that case, we need to wait for the next two bytes in order to
16203// decode the last character properly.
16204function utf16Text(buf, i) {
16205 if ((buf.length - i) % 2 === 0) {
16206 var r = buf.toString('utf16le', i);
16207 if (r) {
16208 var c = r.charCodeAt(r.length - 1);
16209 if (c >= 0xD800 && c <= 0xDBFF) {
16210 this.lastNeed = 2;
16211 this.lastTotal = 4;
16212 this.lastChar[0] = buf[buf.length - 2];
16213 this.lastChar[1] = buf[buf.length - 1];
16214 return r.slice(0, -1);
16215 }
16216 }
16217 return r;
16218 }
16219 this.lastNeed = 1;
16220 this.lastTotal = 2;
16221 this.lastChar[0] = buf[buf.length - 1];
16222 return buf.toString('utf16le', i, buf.length - 1);
16223}
16224
16225// For UTF-16LE we do not explicitly append special replacement characters if we
16226// end on a partial character, we simply let v8 handle that.
16227function utf16End(buf) {
16228 var r = buf && buf.length ? this.write(buf) : '';
16229 if (this.lastNeed) {
16230 var end = this.lastTotal - this.lastNeed;
16231 return r + this.lastChar.toString('utf16le', 0, end);
16232 }
16233 return r;
16234}
16235
16236function base64Text(buf, i) {
16237 var n = (buf.length - i) % 3;
16238 if (n === 0) return buf.toString('base64', i);
16239 this.lastNeed = 3 - n;
16240 this.lastTotal = 3;
16241 if (n === 1) {
16242 this.lastChar[0] = buf[buf.length - 1];
16243 } else {
16244 this.lastChar[0] = buf[buf.length - 2];
16245 this.lastChar[1] = buf[buf.length - 1];
16246 }
16247 return buf.toString('base64', i, buf.length - n);
16248}
16249
16250function base64End(buf) {
16251 var r = buf && buf.length ? this.write(buf) : '';
16252 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
16253 return r;
16254}
16255
16256// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
16257function simpleWrite(buf) {
16258 return buf.toString(this.encoding);
16259}
16260
16261function simpleEnd(buf) {
16262 return buf && buf.length ? this.write(buf) : '';
16263}
16264},{"78":78}],96:[function(_dereq_,module,exports){
16265arguments[4][95][0].apply(exports,arguments)
16266},{"78":78,"95":95}],97:[function(_dereq_,module,exports){
16267arguments[4][38][0].apply(exports,arguments)
16268},{"38":38}],98:[function(_dereq_,module,exports){
16269arguments[4][39][0].apply(exports,arguments)
16270},{"39":39,"69":69}],99:[function(_dereq_,module,exports){
16271arguments[4][40][0].apply(exports,arguments)
16272},{"101":101,"103":103,"31":31,"40":40,"69":69}],100:[function(_dereq_,module,exports){
16273arguments[4][41][0].apply(exports,arguments)
16274},{"102":102,"31":31,"41":41}],101:[function(_dereq_,module,exports){
16275arguments[4][42][0].apply(exports,arguments)
16276},{"10":10,"104":104,"105":105,"106":106,"109":109,"110":110,"12":12,"25":25,"31":31,"42":42,"69":69,"96":96,"97":97,"98":98,"99":99}],102:[function(_dereq_,module,exports){
16277arguments[4][43][0].apply(exports,arguments)
16278},{"31":31,"43":43,"97":97,"99":99}],103:[function(_dereq_,module,exports){
16279arguments[4][44][0].apply(exports,arguments)
16280},{"106":106,"109":109,"110":110,"115":115,"12":12,"31":31,"44":44,"69":69,"97":97,"99":99}],104:[function(_dereq_,module,exports){
16281arguments[4][45][0].apply(exports,arguments)
16282},{"107":107,"45":45,"69":69}],105:[function(_dereq_,module,exports){
16283arguments[4][46][0].apply(exports,arguments)
16284},{"10":10,"12":12,"46":46}],106:[function(_dereq_,module,exports){
16285arguments[4][47][0].apply(exports,arguments)
16286},{"47":47,"69":69}],107:[function(_dereq_,module,exports){
16287arguments[4][48][0].apply(exports,arguments)
16288},{"48":48,"97":97}],108:[function(_dereq_,module,exports){
16289arguments[4][49][0].apply(exports,arguments)
16290},{"107":107,"49":49,"97":97}],109:[function(_dereq_,module,exports){
16291arguments[4][50][0].apply(exports,arguments)
16292},{"50":50,"97":97}],110:[function(_dereq_,module,exports){
16293arguments[4][51][0].apply(exports,arguments)
16294},{"25":25,"51":51}],111:[function(_dereq_,module,exports){
16295arguments[4][52][0].apply(exports,arguments)
16296},{"100":100,"101":101,"102":102,"103":103,"107":107,"108":108,"52":52,"99":99}],112:[function(_dereq_,module,exports){
16297(function (process){
16298var Transform = _dereq_(111).Transform
16299 , inherits = _dereq_(117).inherits
16300
16301function DestroyableTransform(opts) {
16302 Transform.call(this, opts)
16303 this._destroyed = false
16304}
16305
16306inherits(DestroyableTransform, Transform)
16307
16308DestroyableTransform.prototype.destroy = function(err) {
16309 if (this._destroyed) return
16310 this._destroyed = true
16311
16312 var self = this
16313 process.nextTick(function() {
16314 if (err)
16315 self.emit('error', err)
16316 self.emit('close')
16317 })
16318}
16319
16320// a noop _transform function
16321function noop (chunk, enc, callback) {
16322 callback(null, chunk)
16323}
16324
16325
16326// create a new export function, used by both the main export and
16327// the .ctor export, contains common logic for dealing with arguments
16328function through2 (construct) {
16329 return function (options, transform, flush) {
16330 if (typeof options == 'function') {
16331 flush = transform
16332 transform = options
16333 options = {}
16334 }
16335
16336 if (typeof transform != 'function')
16337 transform = noop
16338
16339 if (typeof flush != 'function')
16340 flush = null
16341
16342 return construct(options, transform, flush)
16343 }
16344}
16345
16346
16347// main export, just make me a transform stream!
16348module.exports = through2(function (options, transform, flush) {
16349 var t2 = new DestroyableTransform(options)
16350
16351 t2._transform = transform
16352
16353 if (flush)
16354 t2._flush = flush
16355
16356 return t2
16357})
16358
16359
16360// make me a reusable prototype that I can `new`, or implicitly `new`
16361// with a constructor call
16362module.exports.ctor = through2(function (options, transform, flush) {
16363 function Through2 (override) {
16364 if (!(this instanceof Through2))
16365 return new Through2(override)
16366
16367 this.options = Object.assign({}, options, override)
16368
16369 DestroyableTransform.call(this, this.options)
16370 }
16371
16372 inherits(Through2, DestroyableTransform)
16373
16374 Through2.prototype._transform = transform
16375
16376 if (flush)
16377 Through2.prototype._flush = flush
16378
16379 return Through2
16380})
16381
16382
16383module.exports.obj = through2(function (options, transform, flush) {
16384 var t2 = new DestroyableTransform(Object.assign({ objectMode: true, highWaterMark: 16 }, options))
16385
16386 t2._transform = transform
16387
16388 if (flush)
16389 t2._flush = flush
16390
16391 return t2
16392})
16393
16394}).call(this,_dereq_(69))
16395},{"111":111,"117":117,"69":69}],113:[function(_dereq_,module,exports){
16396(function (setImmediate,clearImmediate){
16397var nextTick = _dereq_(69).nextTick;
16398var apply = Function.prototype.apply;
16399var slice = Array.prototype.slice;
16400var immediateIds = {};
16401var nextImmediateId = 0;
16402
16403// DOM APIs, for completeness
16404
16405exports.setTimeout = function() {
16406 return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
16407};
16408exports.setInterval = function() {
16409 return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
16410};
16411exports.clearTimeout =
16412exports.clearInterval = function(timeout) { timeout.close(); };
16413
16414function Timeout(id, clearFn) {
16415 this._id = id;
16416 this._clearFn = clearFn;
16417}
16418Timeout.prototype.unref = Timeout.prototype.ref = function() {};
16419Timeout.prototype.close = function() {
16420 this._clearFn.call(window, this._id);
16421};
16422
16423// Does not start the time, just sets up the members needed.
16424exports.enroll = function(item, msecs) {
16425 clearTimeout(item._idleTimeoutId);
16426 item._idleTimeout = msecs;
16427};
16428
16429exports.unenroll = function(item) {
16430 clearTimeout(item._idleTimeoutId);
16431 item._idleTimeout = -1;
16432};
16433
16434exports._unrefActive = exports.active = function(item) {
16435 clearTimeout(item._idleTimeoutId);
16436
16437 var msecs = item._idleTimeout;
16438 if (msecs >= 0) {
16439 item._idleTimeoutId = setTimeout(function onTimeout() {
16440 if (item._onTimeout)
16441 item._onTimeout();
16442 }, msecs);
16443 }
16444};
16445
16446// That's not how node.js implements it but the exposed api is the same.
16447exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
16448 var id = nextImmediateId++;
16449 var args = arguments.length < 2 ? false : slice.call(arguments, 1);
16450
16451 immediateIds[id] = true;
16452
16453 nextTick(function onNextTick() {
16454 if (immediateIds[id]) {
16455 // fn.call() is faster so we optimize for the common use-case
16456 // @see http://jsperf.com/call-apply-segu
16457 if (args) {
16458 fn.apply(null, args);
16459 } else {
16460 fn.call(null);
16461 }
16462 // Prevent ids from leaking
16463 exports.clearImmediate(id);
16464 }
16465 });
16466
16467 return id;
16468};
16469
16470exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
16471 delete immediateIds[id];
16472};
16473}).call(this,_dereq_(113).setImmediate,_dereq_(113).clearImmediate)
16474},{"113":113,"69":69}],114:[function(_dereq_,module,exports){
16475'use strict';
16476
16477// Simple FIFO queue implementation to avoid having to do shift()
16478// on an array, which is slow.
16479
16480function Queue() {
16481 this.length = 0;
16482}
16483
16484Queue.prototype.push = function (item) {
16485 var node = {item: item};
16486 if (this.last) {
16487 this.last = this.last.next = node;
16488 } else {
16489 this.last = this.first = node;
16490 }
16491 this.length++;
16492};
16493
16494Queue.prototype.shift = function () {
16495 var node = this.first;
16496 if (node) {
16497 this.first = node.next;
16498 if (!(--this.length)) {
16499 this.last = undefined;
16500 }
16501 return node.item;
16502 }
16503};
16504
16505Queue.prototype.slice = function (start, end) {
16506 start = typeof start === 'undefined' ? 0 : start;
16507 end = typeof end === 'undefined' ? Infinity : end;
16508
16509 var output = [];
16510
16511 var i = 0;
16512 for (var node = this.first; node; node = node.next) {
16513 if (--end < 0) {
16514 break;
16515 } else if (++i > start) {
16516 output.push(node.item);
16517 }
16518 }
16519 return output;
16520}
16521
16522module.exports = Queue;
16523
16524},{}],115:[function(_dereq_,module,exports){
16525(function (global){
16526
16527/**
16528 * Module exports.
16529 */
16530
16531module.exports = deprecate;
16532
16533/**
16534 * Mark that a method should not be used.
16535 * Returns a modified function which warns once by default.
16536 *
16537 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
16538 *
16539 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
16540 * will throw an Error when invoked.
16541 *
16542 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
16543 * will invoke `console.trace()` instead of `console.error()`.
16544 *
16545 * @param {Function} fn - the function to deprecate
16546 * @param {String} msg - the string to print to the console when `fn` is invoked
16547 * @returns {Function} a new "deprecated" version of `fn`
16548 * @api public
16549 */
16550
16551function deprecate (fn, msg) {
16552 if (config('noDeprecation')) {
16553 return fn;
16554 }
16555
16556 var warned = false;
16557 function deprecated() {
16558 if (!warned) {
16559 if (config('throwDeprecation')) {
16560 throw new Error(msg);
16561 } else if (config('traceDeprecation')) {
16562 console.trace(msg);
16563 } else {
16564 console.warn(msg);
16565 }
16566 warned = true;
16567 }
16568 return fn.apply(this, arguments);
16569 }
16570
16571 return deprecated;
16572}
16573
16574/**
16575 * Checks `localStorage` for boolean values for the given `name`.
16576 *
16577 * @param {String} name
16578 * @returns {Boolean}
16579 * @api private
16580 */
16581
16582function config (name) {
16583 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
16584 try {
16585 if (!global.localStorage) return false;
16586 } catch (_) {
16587 return false;
16588 }
16589 var val = global.localStorage[name];
16590 if (null == val) return false;
16591 return String(val).toLowerCase() === 'true';
16592}
16593
16594}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
16595},{}],116:[function(_dereq_,module,exports){
16596arguments[4][7][0].apply(exports,arguments)
16597},{"7":7}],117:[function(_dereq_,module,exports){
16598arguments[4][8][0].apply(exports,arguments)
16599},{"116":116,"31":31,"69":69,"8":8}],118:[function(_dereq_,module,exports){
16600var v1 = _dereq_(121);
16601var v4 = _dereq_(122);
16602
16603var uuid = v4;
16604uuid.v1 = v1;
16605uuid.v4 = v4;
16606
16607module.exports = uuid;
16608
16609},{"121":121,"122":122}],119:[function(_dereq_,module,exports){
16610/**
16611 * Convert array of 16 byte values to UUID string format of the form:
16612 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
16613 */
16614var byteToHex = [];
16615for (var i = 0; i < 256; ++i) {
16616 byteToHex[i] = (i + 0x100).toString(16).substr(1);
16617}
16618
16619function bytesToUuid(buf, offset) {
16620 var i = offset || 0;
16621 var bth = byteToHex;
16622 return bth[buf[i++]] + bth[buf[i++]] +
16623 bth[buf[i++]] + bth[buf[i++]] + '-' +
16624 bth[buf[i++]] + bth[buf[i++]] + '-' +
16625 bth[buf[i++]] + bth[buf[i++]] + '-' +
16626 bth[buf[i++]] + bth[buf[i++]] + '-' +
16627 bth[buf[i++]] + bth[buf[i++]] +
16628 bth[buf[i++]] + bth[buf[i++]] +
16629 bth[buf[i++]] + bth[buf[i++]];
16630}
16631
16632module.exports = bytesToUuid;
16633
16634},{}],120:[function(_dereq_,module,exports){
16635// Unique ID creation requires a high quality random # generator. In the
16636// browser this is a little complicated due to unknown quality of Math.random()
16637// and inconsistent support for the `crypto` API. We do the best we can via
16638// feature-detection
16639
16640// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
16641var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues.bind(crypto)) ||
16642 (typeof(msCrypto) != 'undefined' && msCrypto.getRandomValues.bind(msCrypto));
16643if (getRandomValues) {
16644 // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
16645 var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
16646
16647 module.exports = function whatwgRNG() {
16648 getRandomValues(rnds8);
16649 return rnds8;
16650 };
16651} else {
16652 // Math.random()-based (RNG)
16653 //
16654 // If all else fails, use Math.random(). It's fast, but is of unspecified
16655 // quality.
16656 var rnds = new Array(16);
16657
16658 module.exports = function mathRNG() {
16659 for (var i = 0, r; i < 16; i++) {
16660 if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
16661 rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
16662 }
16663
16664 return rnds;
16665 };
16666}
16667
16668},{}],121:[function(_dereq_,module,exports){
16669var rng = _dereq_(120);
16670var bytesToUuid = _dereq_(119);
16671
16672// **`v1()` - Generate time-based UUID**
16673//
16674// Inspired by https://github.com/LiosK/UUID.js
16675// and http://docs.python.org/library/uuid.html
16676
16677var _nodeId;
16678var _clockseq;
16679
16680// Previous uuid creation time
16681var _lastMSecs = 0;
16682var _lastNSecs = 0;
16683
16684// See https://github.com/broofa/node-uuid for API details
16685function v1(options, buf, offset) {
16686 var i = buf && offset || 0;
16687 var b = buf || [];
16688
16689 options = options || {};
16690 var node = options.node || _nodeId;
16691 var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
16692
16693 // node and clockseq need to be initialized to random values if they're not
16694 // specified. We do this lazily to minimize issues related to insufficient
16695 // system entropy. See #189
16696 if (node == null || clockseq == null) {
16697 var seedBytes = rng();
16698 if (node == null) {
16699 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
16700 node = _nodeId = [
16701 seedBytes[0] | 0x01,
16702 seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]
16703 ];
16704 }
16705 if (clockseq == null) {
16706 // Per 4.2.2, randomize (14 bit) clockseq
16707 clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
16708 }
16709 }
16710
16711 // UUID timestamps are 100 nano-second units since the Gregorian epoch,
16712 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
16713 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
16714 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
16715 var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
16716
16717 // Per 4.2.1.2, use count of uuid's generated during the current clock
16718 // cycle to simulate higher resolution clock
16719 var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
16720
16721 // Time since last uuid creation (in msecs)
16722 var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
16723
16724 // Per 4.2.1.2, Bump clockseq on clock regression
16725 if (dt < 0 && options.clockseq === undefined) {
16726 clockseq = clockseq + 1 & 0x3fff;
16727 }
16728
16729 // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
16730 // time interval
16731 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
16732 nsecs = 0;
16733 }
16734
16735 // Per 4.2.1.2 Throw error if too many uuids are requested
16736 if (nsecs >= 10000) {
16737 throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
16738 }
16739
16740 _lastMSecs = msecs;
16741 _lastNSecs = nsecs;
16742 _clockseq = clockseq;
16743
16744 // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
16745 msecs += 12219292800000;
16746
16747 // `time_low`
16748 var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
16749 b[i++] = tl >>> 24 & 0xff;
16750 b[i++] = tl >>> 16 & 0xff;
16751 b[i++] = tl >>> 8 & 0xff;
16752 b[i++] = tl & 0xff;
16753
16754 // `time_mid`
16755 var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
16756 b[i++] = tmh >>> 8 & 0xff;
16757 b[i++] = tmh & 0xff;
16758
16759 // `time_high_and_version`
16760 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
16761 b[i++] = tmh >>> 16 & 0xff;
16762
16763 // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
16764 b[i++] = clockseq >>> 8 | 0x80;
16765
16766 // `clock_seq_low`
16767 b[i++] = clockseq & 0xff;
16768
16769 // `node`
16770 for (var n = 0; n < 6; ++n) {
16771 b[i + n] = node[n];
16772 }
16773
16774 return buf ? buf : bytesToUuid(b);
16775}
16776
16777module.exports = v1;
16778
16779},{"119":119,"120":120}],122:[function(_dereq_,module,exports){
16780var rng = _dereq_(120);
16781var bytesToUuid = _dereq_(119);
16782
16783function v4(options, buf, offset) {
16784 var i = buf && offset || 0;
16785
16786 if (typeof(options) == 'string') {
16787 buf = options === 'binary' ? new Array(16) : null;
16788 options = null;
16789 }
16790 options = options || {};
16791
16792 var rnds = options.random || (options.rng || rng)();
16793
16794 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
16795 rnds[6] = (rnds[6] & 0x0f) | 0x40;
16796 rnds[8] = (rnds[8] & 0x3f) | 0x80;
16797
16798 // Copy bytes to buffer, if provided
16799 if (buf) {
16800 for (var ii = 0; ii < 16; ++ii) {
16801 buf[i + ii] = rnds[ii];
16802 }
16803 }
16804
16805 return buf || bytesToUuid(rnds);
16806}
16807
16808module.exports = v4;
16809
16810},{"119":119,"120":120}],123:[function(_dereq_,module,exports){
16811'use strict';
16812
16813/**
16814 * Stringify/parse functions that don't operate
16815 * recursively, so they avoid call stack exceeded
16816 * errors.
16817 */
16818exports.stringify = function stringify(input) {
16819 var queue = [];
16820 queue.push({obj: input});
16821
16822 var res = '';
16823 var next, obj, prefix, val, i, arrayPrefix, keys, k, key, value, objPrefix;
16824 while ((next = queue.pop())) {
16825 obj = next.obj;
16826 prefix = next.prefix || '';
16827 val = next.val || '';
16828 res += prefix;
16829 if (val) {
16830 res += val;
16831 } else if (typeof obj !== 'object') {
16832 res += typeof obj === 'undefined' ? null : JSON.stringify(obj);
16833 } else if (obj === null) {
16834 res += 'null';
16835 } else if (Array.isArray(obj)) {
16836 queue.push({val: ']'});
16837 for (i = obj.length - 1; i >= 0; i--) {
16838 arrayPrefix = i === 0 ? '' : ',';
16839 queue.push({obj: obj[i], prefix: arrayPrefix});
16840 }
16841 queue.push({val: '['});
16842 } else { // object
16843 keys = [];
16844 for (k in obj) {
16845 if (obj.hasOwnProperty(k)) {
16846 keys.push(k);
16847 }
16848 }
16849 queue.push({val: '}'});
16850 for (i = keys.length - 1; i >= 0; i--) {
16851 key = keys[i];
16852 value = obj[key];
16853 objPrefix = (i > 0 ? ',' : '');
16854 objPrefix += JSON.stringify(key) + ':';
16855 queue.push({obj: value, prefix: objPrefix});
16856 }
16857 queue.push({val: '{'});
16858 }
16859 }
16860 return res;
16861};
16862
16863// Convenience function for the parse function.
16864// This pop function is basically copied from
16865// pouchCollate.parseIndexableString
16866function pop(obj, stack, metaStack) {
16867 var lastMetaElement = metaStack[metaStack.length - 1];
16868 if (obj === lastMetaElement.element) {
16869 // popping a meta-element, e.g. an object whose value is another object
16870 metaStack.pop();
16871 lastMetaElement = metaStack[metaStack.length - 1];
16872 }
16873 var element = lastMetaElement.element;
16874 var lastElementIndex = lastMetaElement.index;
16875 if (Array.isArray(element)) {
16876 element.push(obj);
16877 } else if (lastElementIndex === stack.length - 2) { // obj with key+value
16878 var key = stack.pop();
16879 element[key] = obj;
16880 } else {
16881 stack.push(obj); // obj with key only
16882 }
16883}
16884
16885exports.parse = function (str) {
16886 var stack = [];
16887 var metaStack = []; // stack for arrays and objects
16888 var i = 0;
16889 var collationIndex,parsedNum,numChar;
16890 var parsedString,lastCh,numConsecutiveSlashes,ch;
16891 var arrayElement, objElement;
16892 while (true) {
16893 collationIndex = str[i++];
16894 if (collationIndex === '}' ||
16895 collationIndex === ']' ||
16896 typeof collationIndex === 'undefined') {
16897 if (stack.length === 1) {
16898 return stack.pop();
16899 } else {
16900 pop(stack.pop(), stack, metaStack);
16901 continue;
16902 }
16903 }
16904 switch (collationIndex) {
16905 case ' ':
16906 case '\t':
16907 case '\n':
16908 case ':':
16909 case ',':
16910 break;
16911 case 'n':
16912 i += 3; // 'ull'
16913 pop(null, stack, metaStack);
16914 break;
16915 case 't':
16916 i += 3; // 'rue'
16917 pop(true, stack, metaStack);
16918 break;
16919 case 'f':
16920 i += 4; // 'alse'
16921 pop(false, stack, metaStack);
16922 break;
16923 case '0':
16924 case '1':
16925 case '2':
16926 case '3':
16927 case '4':
16928 case '5':
16929 case '6':
16930 case '7':
16931 case '8':
16932 case '9':
16933 case '-':
16934 parsedNum = '';
16935 i--;
16936 while (true) {
16937 numChar = str[i++];
16938 if (/[\d\.\-e\+]/.test(numChar)) {
16939 parsedNum += numChar;
16940 } else {
16941 i--;
16942 break;
16943 }
16944 }
16945 pop(parseFloat(parsedNum), stack, metaStack);
16946 break;
16947 case '"':
16948 parsedString = '';
16949 lastCh = void 0;
16950 numConsecutiveSlashes = 0;
16951 while (true) {
16952 ch = str[i++];
16953 if (ch !== '"' || (lastCh === '\\' &&
16954 numConsecutiveSlashes % 2 === 1)) {
16955 parsedString += ch;
16956 lastCh = ch;
16957 if (lastCh === '\\') {
16958 numConsecutiveSlashes++;
16959 } else {
16960 numConsecutiveSlashes = 0;
16961 }
16962 } else {
16963 break;
16964 }
16965 }
16966 pop(JSON.parse('"' + parsedString + '"'), stack, metaStack);
16967 break;
16968 case '[':
16969 arrayElement = { element: [], index: stack.length };
16970 stack.push(arrayElement.element);
16971 metaStack.push(arrayElement);
16972 break;
16973 case '{':
16974 objElement = { element: {}, index: stack.length };
16975 stack.push(objElement.element);
16976 metaStack.push(objElement);
16977 break;
16978 default:
16979 throw new Error(
16980 'unexpectedly reached end of input: ' + collationIndex);
16981 }
16982 }
16983};
16984
16985},{}],124:[function(_dereq_,module,exports){
16986module.exports = extend
16987
16988function extend() {
16989 var target = {}
16990
16991 for (var i = 0; i < arguments.length; i++) {
16992 var source = arguments[i]
16993
16994 for (var key in source) {
16995 if (source.hasOwnProperty(key)) {
16996 target[key] = source[key]
16997 }
16998 }
16999 }
17000
17001 return target
17002}
17003
17004},{}],125:[function(_dereq_,module,exports){
17005(function (global){
17006'use strict';
17007
17008function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
17009
17010var immediate = _interopDefault(_dereq_(30));
17011var uuidV4 = _interopDefault(_dereq_(118));
17012var Md5 = _interopDefault(_dereq_(79));
17013var levelup = _interopDefault(_dereq_(56));
17014var ltgt = _interopDefault(_dereq_(66));
17015var events = _dereq_(25);
17016var events__default = _interopDefault(events);
17017var Codec = _interopDefault(_dereq_(34));
17018var ReadableStreamCore = _interopDefault(_dereq_(77));
17019var inherits = _interopDefault(_dereq_(31));
17020var through2 = _dereq_(112);
17021var getArguments = _interopDefault(_dereq_(4));
17022var Deque = _interopDefault(_dereq_(22));
17023var bufferFrom = _interopDefault(_dereq_(11));
17024var vuvuzela = _interopDefault(_dereq_(123));
17025var localstoragedown = _interopDefault(_dereq_(59));
17026
17027function isBinaryObject(object) {
17028 return (typeof ArrayBuffer !== 'undefined' && object instanceof ArrayBuffer) ||
17029 (typeof Blob !== 'undefined' && object instanceof Blob);
17030}
17031
17032function cloneArrayBuffer(buff) {
17033 if (typeof buff.slice === 'function') {
17034 return buff.slice(0);
17035 }
17036 // IE10-11 slice() polyfill
17037 var target = new ArrayBuffer(buff.byteLength);
17038 var targetArray = new Uint8Array(target);
17039 var sourceArray = new Uint8Array(buff);
17040 targetArray.set(sourceArray);
17041 return target;
17042}
17043
17044function cloneBinaryObject(object) {
17045 if (object instanceof ArrayBuffer) {
17046 return cloneArrayBuffer(object);
17047 }
17048 var size = object.size;
17049 var type = object.type;
17050 // Blob
17051 if (typeof object.slice === 'function') {
17052 return object.slice(0, size, type);
17053 }
17054 // PhantomJS slice() replacement
17055 return object.webkitSlice(0, size, type);
17056}
17057
17058// most of this is borrowed from lodash.isPlainObject:
17059// https://github.com/fis-components/lodash.isplainobject/
17060// blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js
17061
17062var funcToString = Function.prototype.toString;
17063var objectCtorString = funcToString.call(Object);
17064
17065function isPlainObject(value) {
17066 var proto = Object.getPrototypeOf(value);
17067 /* istanbul ignore if */
17068 if (proto === null) { // not sure when this happens, but I guess it can
17069 return true;
17070 }
17071 var Ctor = proto.constructor;
17072 return (typeof Ctor == 'function' &&
17073 Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
17074}
17075
17076function clone(object) {
17077 var newObject;
17078 var i;
17079 var len;
17080
17081 if (!object || typeof object !== 'object') {
17082 return object;
17083 }
17084
17085 if (Array.isArray(object)) {
17086 newObject = [];
17087 for (i = 0, len = object.length; i < len; i++) {
17088 newObject[i] = clone(object[i]);
17089 }
17090 return newObject;
17091 }
17092
17093 // special case: to avoid inconsistencies between IndexedDB
17094 // and other backends, we automatically stringify Dates
17095 if (object instanceof Date) {
17096 return object.toISOString();
17097 }
17098
17099 if (isBinaryObject(object)) {
17100 return cloneBinaryObject(object);
17101 }
17102
17103 if (!isPlainObject(object)) {
17104 return object; // don't clone objects like Workers
17105 }
17106
17107 newObject = {};
17108 for (i in object) {
17109 /* istanbul ignore else */
17110 if (Object.prototype.hasOwnProperty.call(object, i)) {
17111 var value = clone(object[i]);
17112 if (typeof value !== 'undefined') {
17113 newObject[i] = value;
17114 }
17115 }
17116 }
17117 return newObject;
17118}
17119
17120function mangle(key) {
17121 return '$' + key;
17122}
17123function unmangle(key) {
17124 return key.substring(1);
17125}
17126function Map$1() {
17127 this._store = {};
17128}
17129Map$1.prototype.get = function (key) {
17130 var mangled = mangle(key);
17131 return this._store[mangled];
17132};
17133Map$1.prototype.set = function (key, value) {
17134 var mangled = mangle(key);
17135 this._store[mangled] = value;
17136 return true;
17137};
17138Map$1.prototype.has = function (key) {
17139 var mangled = mangle(key);
17140 return mangled in this._store;
17141};
17142Map$1.prototype["delete"] = function (key) {
17143 var mangled = mangle(key);
17144 var res = mangled in this._store;
17145 delete this._store[mangled];
17146 return res;
17147};
17148Map$1.prototype.forEach = function (cb) {
17149 var keys = Object.keys(this._store);
17150 for (var i = 0, len = keys.length; i < len; i++) {
17151 var key = keys[i];
17152 var value = this._store[key];
17153 key = unmangle(key);
17154 cb(value, key);
17155 }
17156};
17157Object.defineProperty(Map$1.prototype, 'size', {
17158 get: function () {
17159 return Object.keys(this._store).length;
17160 }
17161});
17162
17163function Set$1(array) {
17164 this._store = new Map$1();
17165
17166 // init with an array
17167 if (array && Array.isArray(array)) {
17168 for (var i = 0, len = array.length; i < len; i++) {
17169 this.add(array[i]);
17170 }
17171 }
17172}
17173Set$1.prototype.add = function (key) {
17174 return this._store.set(key, true);
17175};
17176Set$1.prototype.has = function (key) {
17177 return this._store.has(key);
17178};
17179Set$1.prototype.forEach = function (cb) {
17180 this._store.forEach(function (value, key) {
17181 cb(key);
17182 });
17183};
17184Object.defineProperty(Set$1.prototype, 'size', {
17185 get: function () {
17186 return this._store.size;
17187 }
17188});
17189
17190/* global Map,Set,Symbol */
17191// Based on https://kangax.github.io/compat-table/es6/ we can sniff out
17192// incomplete Map/Set implementations which would otherwise cause our tests to fail.
17193// Notably they fail in IE11 and iOS 8.4, which this prevents.
17194function supportsMapAndSet() {
17195 if (typeof Symbol === 'undefined' || typeof Map === 'undefined' || typeof Set === 'undefined') {
17196 return false;
17197 }
17198 var prop = Object.getOwnPropertyDescriptor(Map, Symbol.species);
17199 return prop && 'get' in prop && Map[Symbol.species] === Map;
17200}
17201
17202// based on https://github.com/montagejs/collections
17203
17204var ExportedSet;
17205var ExportedMap;
17206
17207{
17208 if (supportsMapAndSet()) { // prefer built-in Map/Set
17209 ExportedSet = Set;
17210 ExportedMap = Map;
17211 } else { // fall back to our polyfill
17212 ExportedSet = Set$1;
17213 ExportedMap = Map$1;
17214 }
17215}
17216
17217// like underscore/lodash _.pick()
17218function pick(obj, arr) {
17219 var res = {};
17220 for (var i = 0, len = arr.length; i < len; i++) {
17221 var prop = arr[i];
17222 if (prop in obj) {
17223 res[prop] = obj[prop];
17224 }
17225 }
17226 return res;
17227}
17228
17229var hasLocal;
17230
17231try {
17232 localStorage.setItem('_pouch_check_localstorage', 1);
17233 hasLocal = !!localStorage.getItem('_pouch_check_localstorage');
17234} catch (e) {
17235 hasLocal = false;
17236}
17237
17238function hasLocalStorage() {
17239 return hasLocal;
17240}
17241
17242// Custom nextTick() shim for browsers. In node, this will just be process.nextTick(). We
17243
17244inherits(Changes, events.EventEmitter);
17245
17246/* istanbul ignore next */
17247function attachBrowserEvents(self) {
17248 if (hasLocalStorage()) {
17249 addEventListener("storage", function (e) {
17250 self.emit(e.key);
17251 });
17252 }
17253}
17254
17255function Changes() {
17256 events.EventEmitter.call(this);
17257 this._listeners = {};
17258
17259 attachBrowserEvents(this);
17260}
17261Changes.prototype.addListener = function (dbName, id, db, opts) {
17262 /* istanbul ignore if */
17263 if (this._listeners[id]) {
17264 return;
17265 }
17266 var self = this;
17267 var inprogress = false;
17268 function eventFunction() {
17269 /* istanbul ignore if */
17270 if (!self._listeners[id]) {
17271 return;
17272 }
17273 if (inprogress) {
17274 inprogress = 'waiting';
17275 return;
17276 }
17277 inprogress = true;
17278 var changesOpts = pick(opts, [
17279 'style', 'include_docs', 'attachments', 'conflicts', 'filter',
17280 'doc_ids', 'view', 'since', 'query_params', 'binary', 'return_docs'
17281 ]);
17282
17283 /* istanbul ignore next */
17284 function onError() {
17285 inprogress = false;
17286 }
17287
17288 db.changes(changesOpts).on('change', function (c) {
17289 if (c.seq > opts.since && !opts.cancelled) {
17290 opts.since = c.seq;
17291 opts.onChange(c);
17292 }
17293 }).on('complete', function () {
17294 if (inprogress === 'waiting') {
17295 immediate(eventFunction);
17296 }
17297 inprogress = false;
17298 }).on('error', onError);
17299 }
17300 this._listeners[id] = eventFunction;
17301 this.on(dbName, eventFunction);
17302};
17303
17304Changes.prototype.removeListener = function (dbName, id) {
17305 /* istanbul ignore if */
17306 if (!(id in this._listeners)) {
17307 return;
17308 }
17309 events.EventEmitter.prototype.removeListener.call(this, dbName,
17310 this._listeners[id]);
17311 delete this._listeners[id];
17312};
17313
17314
17315/* istanbul ignore next */
17316Changes.prototype.notifyLocalWindows = function (dbName) {
17317 //do a useless change on a storage thing
17318 //in order to get other windows's listeners to activate
17319 if (hasLocalStorage()) {
17320 localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a";
17321 }
17322};
17323
17324Changes.prototype.notify = function (dbName) {
17325 this.emit(dbName);
17326 this.notifyLocalWindows(dbName);
17327};
17328
17329function guardedConsole(method) {
17330 /* istanbul ignore else */
17331 if (typeof console !== 'undefined' && typeof console[method] === 'function') {
17332 var args = Array.prototype.slice.call(arguments, 1);
17333 console[method].apply(console, args);
17334 }
17335}
17336
17337var assign;
17338{
17339 if (typeof Object.assign === 'function') {
17340 assign = Object.assign;
17341 } else {
17342 // lite Object.assign polyfill based on
17343 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
17344 assign = function (target) {
17345 var to = Object(target);
17346
17347 for (var index = 1; index < arguments.length; index++) {
17348 var nextSource = arguments[index];
17349
17350 if (nextSource != null) { // Skip over if undefined or null
17351 for (var nextKey in nextSource) {
17352 // Avoid bugs when hasOwnProperty is shadowed
17353 if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
17354 to[nextKey] = nextSource[nextKey];
17355 }
17356 }
17357 }
17358 }
17359 return to;
17360 };
17361 }
17362}
17363
17364var $inject_Object_assign = assign;
17365
17366inherits(PouchError, Error);
17367
17368function PouchError(status, error, reason) {
17369 Error.call(this, reason);
17370 this.status = status;
17371 this.name = error;
17372 this.message = reason;
17373 this.error = true;
17374}
17375
17376PouchError.prototype.toString = function () {
17377 return JSON.stringify({
17378 status: this.status,
17379 name: this.name,
17380 message: this.message,
17381 reason: this.reason
17382 });
17383};
17384
17385var UNAUTHORIZED = new PouchError(401, 'unauthorized', "Name or password is incorrect.");
17386var MISSING_BULK_DOCS = new PouchError(400, 'bad_request', "Missing JSON list of 'docs'");
17387var MISSING_DOC = new PouchError(404, 'not_found', 'missing');
17388var REV_CONFLICT = new PouchError(409, 'conflict', 'Document update conflict');
17389var INVALID_ID = new PouchError(400, 'bad_request', '_id field must contain a string');
17390var MISSING_ID = new PouchError(412, 'missing_id', '_id is required for puts');
17391var RESERVED_ID = new PouchError(400, 'bad_request', 'Only reserved document ids may start with underscore.');
17392var NOT_OPEN = new PouchError(412, 'precondition_failed', 'Database not open');
17393var UNKNOWN_ERROR = new PouchError(500, 'unknown_error', 'Database encountered an unknown error');
17394var BAD_ARG = new PouchError(500, 'badarg', 'Some query argument is invalid');
17395var INVALID_REQUEST = new PouchError(400, 'invalid_request', 'Request was invalid');
17396var QUERY_PARSE_ERROR = new PouchError(400, 'query_parse_error', 'Some query parameter is invalid');
17397var DOC_VALIDATION = new PouchError(500, 'doc_validation', 'Bad special document member');
17398var BAD_REQUEST = new PouchError(400, 'bad_request', 'Something wrong with the request');
17399var NOT_AN_OBJECT = new PouchError(400, 'bad_request', 'Document must be a JSON object');
17400var DB_MISSING = new PouchError(404, 'not_found', 'Database not found');
17401var IDB_ERROR = new PouchError(500, 'indexed_db_went_bad', 'unknown');
17402var WSQ_ERROR = new PouchError(500, 'web_sql_went_bad', 'unknown');
17403var LDB_ERROR = new PouchError(500, 'levelDB_went_went_bad', 'unknown');
17404var FORBIDDEN = new PouchError(403, 'forbidden', 'Forbidden by design doc validate_doc_update function');
17405var INVALID_REV = new PouchError(400, 'bad_request', 'Invalid rev format');
17406var FILE_EXISTS = new PouchError(412, 'file_exists', 'The database could not be created, the file already exists.');
17407var MISSING_STUB = new PouchError(412, 'missing_stub', 'A pre-existing attachment stub wasn\'t found');
17408var INVALID_URL = new PouchError(413, 'invalid_url', 'Provided URL is invalid');
17409
17410function createError(error, reason) {
17411 function CustomPouchError(reason) {
17412 // inherit error properties from our parent error manually
17413 // so as to allow proper JSON parsing.
17414 /* jshint ignore:start */
17415 for (var p in error) {
17416 if (typeof error[p] !== 'function') {
17417 this[p] = error[p];
17418 }
17419 }
17420 /* jshint ignore:end */
17421 if (reason !== undefined) {
17422 this.reason = reason;
17423 }
17424 }
17425 CustomPouchError.prototype = PouchError.prototype;
17426 return new CustomPouchError(reason);
17427}
17428
17429function tryFilter(filter, doc, req) {
17430 try {
17431 return !filter(doc, req);
17432 } catch (err) {
17433 var msg = 'Filter function threw: ' + err.toString();
17434 return createError(BAD_REQUEST, msg);
17435 }
17436}
17437
17438function filterChange(opts) {
17439 var req = {};
17440 var hasFilter = opts.filter && typeof opts.filter === 'function';
17441 req.query = opts.query_params;
17442
17443 return function filter(change) {
17444 if (!change.doc) {
17445 // CSG sends events on the changes feed that don't have documents,
17446 // this hack makes a whole lot of existing code robust.
17447 change.doc = {};
17448 }
17449
17450 var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req);
17451
17452 if (typeof filterReturn === 'object') {
17453 return filterReturn;
17454 }
17455
17456 if (filterReturn) {
17457 return false;
17458 }
17459
17460 if (!opts.include_docs) {
17461 delete change.doc;
17462 } else if (!opts.attachments) {
17463 for (var att in change.doc._attachments) {
17464 /* istanbul ignore else */
17465 if (change.doc._attachments.hasOwnProperty(att)) {
17466 change.doc._attachments[att].stub = true;
17467 }
17468 }
17469 }
17470 return true;
17471 };
17472}
17473
17474// shim for Function.prototype.name,
17475// for browsers that don't support it like IE
17476
17477/* istanbul ignore next */
17478function f() {}
17479
17480var hasName = f.name;
17481var res;
17482
17483// We dont run coverage in IE
17484/* istanbul ignore else */
17485if (hasName) {
17486 res = function (fun) {
17487 return fun.name;
17488 };
17489} else {
17490 res = function (fun) {
17491 var match = fun.toString().match(/^\s*function\s*(?:(\S+)\s*)?\(/);
17492 if (match && match[1]) {
17493 return match[1];
17494 }
17495 else {
17496 return '';
17497 }
17498 };
17499}
17500
17501var functionName = res;
17502
17503// Determine id an ID is valid
17504// - invalid IDs begin with an underescore that does not begin '_design' or
17505// '_local'
17506// - any other string value is a valid id
17507// Returns the specific error object for each case
17508function invalidIdError(id) {
17509 var err;
17510 if (!id) {
17511 err = createError(MISSING_ID);
17512 } else if (typeof id !== 'string') {
17513 err = createError(INVALID_ID);
17514 } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {
17515 err = createError(RESERVED_ID);
17516 }
17517 if (err) {
17518 throw err;
17519 }
17520}
17521
17522// Checks if a PouchDB object is "remote" or not. This is
17523
17524// originally parseUri 1.2.2, now patched by us
17525
17526// Based on https://github.com/alexdavid/scope-eval v0.0.3
17527
17528var thisAtob = function (str) {
17529 return atob(str);
17530};
17531
17532var thisBtoa = function (str) {
17533 return btoa(str);
17534};
17535
17536// Abstracts constructing a Blob object, so it also works in older
17537// browsers that don't support the native Blob constructor (e.g.
17538// old QtWebKit versions, Android < 4.4).
17539function createBlob(parts, properties) {
17540 /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
17541 parts = parts || [];
17542 properties = properties || {};
17543 try {
17544 return new Blob(parts, properties);
17545 } catch (e) {
17546 if (e.name !== "TypeError") {
17547 throw e;
17548 }
17549 var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
17550 typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
17551 typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
17552 WebKitBlobBuilder;
17553 var builder = new Builder();
17554 for (var i = 0; i < parts.length; i += 1) {
17555 builder.append(parts[i]);
17556 }
17557 return builder.getBlob(properties.type);
17558 }
17559}
17560
17561// From http://stackoverflow.com/questions/14967647/ (continues on next line)
17562// encode-decode-image-with-base64-breaks-image (2013-04-21)
17563function binaryStringToArrayBuffer(bin) {
17564 var length = bin.length;
17565 var buf = new ArrayBuffer(length);
17566 var arr = new Uint8Array(buf);
17567 for (var i = 0; i < length; i++) {
17568 arr[i] = bin.charCodeAt(i);
17569 }
17570 return buf;
17571}
17572
17573function binStringToBluffer(binString, type) {
17574 return createBlob([binaryStringToArrayBuffer(binString)], {type: type});
17575}
17576
17577//Can't find original post, but this is close
17578//http://stackoverflow.com/questions/6965107/ (continues on next line)
17579//converting-between-strings-and-arraybuffers
17580function arrayBufferToBinaryString(buffer) {
17581 var binary = '';
17582 var bytes = new Uint8Array(buffer);
17583 var length = bytes.byteLength;
17584 for (var i = 0; i < length; i++) {
17585 binary += String.fromCharCode(bytes[i]);
17586 }
17587 return binary;
17588}
17589
17590// shim for browsers that don't support it
17591function readAsBinaryString(blob, callback) {
17592 var reader = new FileReader();
17593 var hasBinaryString = typeof reader.readAsBinaryString === 'function';
17594 reader.onloadend = function (e) {
17595 var result = e.target.result || '';
17596 if (hasBinaryString) {
17597 return callback(result);
17598 }
17599 callback(arrayBufferToBinaryString(result));
17600 };
17601 if (hasBinaryString) {
17602 reader.readAsBinaryString(blob);
17603 } else {
17604 reader.readAsArrayBuffer(blob);
17605 }
17606}
17607
17608// simplified API. universal browser support is assumed
17609function readAsArrayBuffer(blob, callback) {
17610 var reader = new FileReader();
17611 reader.onloadend = function (e) {
17612 var result = e.target.result || new ArrayBuffer(0);
17613 callback(result);
17614 };
17615 reader.readAsArrayBuffer(blob);
17616}
17617
17618// this is not used in the browser
17619
17620var setImmediateShim = global.setImmediate || global.setTimeout;
17621var MD5_CHUNK_SIZE = 32768;
17622
17623function rawToBase64(raw) {
17624 return thisBtoa(raw);
17625}
17626
17627function sliceBlob(blob, start, end) {
17628 if (blob.webkitSlice) {
17629 return blob.webkitSlice(start, end);
17630 }
17631 return blob.slice(start, end);
17632}
17633
17634function appendBlob(buffer, blob, start, end, callback) {
17635 if (start > 0 || end < blob.size) {
17636 // only slice blob if we really need to
17637 blob = sliceBlob(blob, start, end);
17638 }
17639 readAsArrayBuffer(blob, function (arrayBuffer) {
17640 buffer.append(arrayBuffer);
17641 callback();
17642 });
17643}
17644
17645function appendString(buffer, string, start, end, callback) {
17646 if (start > 0 || end < string.length) {
17647 // only create a substring if we really need to
17648 string = string.substring(start, end);
17649 }
17650 buffer.appendBinary(string);
17651 callback();
17652}
17653
17654function binaryMd5(data, callback) {
17655 var inputIsString = typeof data === 'string';
17656 var len = inputIsString ? data.length : data.size;
17657 var chunkSize = Math.min(MD5_CHUNK_SIZE, len);
17658 var chunks = Math.ceil(len / chunkSize);
17659 var currentChunk = 0;
17660 var buffer = inputIsString ? new Md5() : new Md5.ArrayBuffer();
17661
17662 var append = inputIsString ? appendString : appendBlob;
17663
17664 function next() {
17665 setImmediateShim(loadNextChunk);
17666 }
17667
17668 function done() {
17669 var raw = buffer.end(true);
17670 var base64 = rawToBase64(raw);
17671 callback(base64);
17672 buffer.destroy();
17673 }
17674
17675 function loadNextChunk() {
17676 var start = currentChunk * chunkSize;
17677 var end = start + chunkSize;
17678 currentChunk++;
17679 if (currentChunk < chunks) {
17680 append(buffer, data, start, end, next);
17681 } else {
17682 append(buffer, data, start, end, done);
17683 }
17684 }
17685 loadNextChunk();
17686}
17687
17688function stringMd5(string) {
17689 return Md5.hash(string);
17690}
17691
17692function rev(doc, deterministic_revs) {
17693 var clonedDoc = clone(doc);
17694 if (!deterministic_revs) {
17695 return uuidV4.v4().replace(/-/g, '').toLowerCase();
17696 }
17697
17698 delete clonedDoc._rev_tree;
17699 return stringMd5(JSON.stringify(clonedDoc));
17700}
17701
17702var uuid = uuidV4.v4;
17703
17704function isFunction(f) {
17705 return 'function' === typeof f;
17706}
17707
17708function getPrefix(db) {
17709 if (isFunction(db.prefix)) {
17710 return db.prefix();
17711 }
17712 return db;
17713}
17714
17715function clone$1(_obj) {
17716 var obj = {};
17717 for (var k in _obj) {
17718 obj[k] = _obj[k];
17719 }
17720 return obj;
17721}
17722
17723function nut(db, precodec, codec) {
17724 function encodePrefix(prefix, key, opts1, opts2) {
17725 return precodec.encode([ prefix, codec.encodeKey(key, opts1, opts2 ) ]);
17726 }
17727
17728 function addEncodings(op, prefix) {
17729 if (prefix && prefix.options) {
17730 op.keyEncoding =
17731 op.keyEncoding || prefix.options.keyEncoding;
17732 op.valueEncoding =
17733 op.valueEncoding || prefix.options.valueEncoding;
17734 }
17735 return op;
17736 }
17737
17738 db.open(function () { /* no-op */});
17739
17740 return {
17741 apply: function (ops, opts, cb) {
17742 opts = opts || {};
17743
17744 var batch = [];
17745 var i = -1;
17746 var len = ops.length;
17747
17748 while (++i < len) {
17749 var op = ops[i];
17750 addEncodings(op, op.prefix);
17751 op.prefix = getPrefix(op.prefix);
17752 batch.push({
17753 key: encodePrefix(op.prefix, op.key, opts, op),
17754 value: op.type !== 'del' && codec.encodeValue(op.value, opts, op),
17755 type: op.type
17756 });
17757 }
17758 db.db.batch(batch, opts, cb);
17759 },
17760 get: function (key, prefix, opts, cb) {
17761 opts.asBuffer = codec.valueAsBuffer(opts);
17762 return db.db.get(
17763 encodePrefix(prefix, key, opts),
17764 opts,
17765 function (err, value) {
17766 if (err) {
17767 cb(err);
17768 } else {
17769 cb(null, codec.decodeValue(value, opts));
17770 }
17771 }
17772 );
17773 },
17774 createDecoder: function (opts) {
17775 return function (key, value) {
17776 return {
17777 key: codec.decodeKey(precodec.decode(key)[1], opts),
17778 value: codec.decodeValue(value, opts)
17779 };
17780 };
17781 },
17782 isClosed: function isClosed() {
17783 return db.isClosed();
17784 },
17785 close: function close(cb) {
17786 return db.close(cb);
17787 },
17788 iterator: function (_opts) {
17789 var opts = clone$1(_opts || {});
17790 var prefix = _opts.prefix || [];
17791
17792 function encodeKey(key) {
17793 return encodePrefix(prefix, key, opts, {});
17794 }
17795
17796 ltgt.toLtgt(_opts, opts, encodeKey, precodec.lowerBound, precodec.upperBound);
17797
17798 // if these legacy values are in the options, remove them
17799
17800 opts.prefix = null;
17801
17802 //************************************************
17803 //hard coded defaults, for now...
17804 //TODO: pull defaults and encoding out of levelup.
17805 opts.keyAsBuffer = opts.valueAsBuffer = false;
17806 //************************************************
17807
17808
17809 //this is vital, otherwise limit: undefined will
17810 //create an empty stream.
17811 /* istanbul ignore next */
17812 if ('number' !== typeof opts.limit) {
17813 opts.limit = -1;
17814 }
17815
17816 opts.keyAsBuffer = precodec.buffer;
17817 opts.valueAsBuffer = codec.valueAsBuffer(opts);
17818
17819 function wrapIterator(iterator) {
17820 return {
17821 next: function (cb) {
17822 return iterator.next(cb);
17823 },
17824 end: function (cb) {
17825 iterator.end(cb);
17826 }
17827 };
17828 }
17829
17830 return wrapIterator(db.db.iterator(opts));
17831 }
17832 };
17833}
17834
17835function NotFoundError() {
17836 Error.call(this);
17837}
17838
17839inherits(NotFoundError, Error);
17840
17841NotFoundError.prototype.name = 'NotFoundError';
17842
17843var EventEmitter = events__default.EventEmitter;
17844var version = "6.5.4";
17845
17846var NOT_FOUND_ERROR = new NotFoundError();
17847
17848var sublevel = function (nut, prefix, createStream, options) {
17849 var emitter = new EventEmitter();
17850 emitter.sublevels = {};
17851 emitter.options = options;
17852
17853 emitter.version = version;
17854
17855 emitter.methods = {};
17856 prefix = prefix || [];
17857
17858 function mergeOpts(opts) {
17859 var o = {};
17860 var k;
17861 if (options) {
17862 for (k in options) {
17863 if (typeof options[k] !== 'undefined') {
17864 o[k] = options[k];
17865 }
17866 }
17867 }
17868 if (opts) {
17869 for (k in opts) {
17870 if (typeof opts[k] !== 'undefined') {
17871 o[k] = opts[k];
17872 }
17873 }
17874 }
17875 return o;
17876 }
17877
17878 emitter.put = function (key, value, opts, cb) {
17879 if ('function' === typeof opts) {
17880 cb = opts;
17881 opts = {};
17882 }
17883
17884 nut.apply([{
17885 key: key, value: value,
17886 prefix: prefix.slice(), type: 'put'
17887 }], mergeOpts(opts), function (err) {
17888 /* istanbul ignore next */
17889 if (err) {
17890 return cb(err);
17891 }
17892 emitter.emit('put', key, value);
17893 cb(null);
17894 });
17895 };
17896
17897 emitter.prefix = function () {
17898 return prefix.slice();
17899 };
17900
17901 emitter.batch = function (ops, opts, cb) {
17902 if ('function' === typeof opts) {
17903 cb = opts;
17904 opts = {};
17905 }
17906
17907 ops = ops.map(function (op) {
17908 return {
17909 key: op.key,
17910 value: op.value,
17911 prefix: op.prefix || prefix,
17912 keyEncoding: op.keyEncoding, // *
17913 valueEncoding: op.valueEncoding, // * (TODO: encodings on sublevel)
17914 type: op.type
17915 };
17916 });
17917
17918 nut.apply(ops, mergeOpts(opts), function (err) {
17919 /* istanbul ignore next */
17920 if (err) {
17921 return cb(err);
17922 }
17923 emitter.emit('batch', ops);
17924 cb(null);
17925 });
17926 };
17927
17928 emitter.get = function (key, opts, cb) {
17929 /* istanbul ignore else */
17930 if ('function' === typeof opts) {
17931 cb = opts;
17932 opts = {};
17933 }
17934 nut.get(key, prefix, mergeOpts(opts), function (err, value) {
17935 if (err) {
17936 cb(NOT_FOUND_ERROR);
17937 } else {
17938 cb(null, value);
17939 }
17940 });
17941 };
17942
17943 emitter.sublevel = function (name, opts) {
17944 return emitter.sublevels[name] =
17945 emitter.sublevels[name] || sublevel(nut, prefix.concat(name), createStream, mergeOpts(opts));
17946 };
17947
17948 emitter.readStream = emitter.createReadStream = function (opts) {
17949 opts = mergeOpts(opts);
17950 opts.prefix = prefix;
17951 var stream;
17952 var it = nut.iterator(opts);
17953
17954 stream = createStream(opts, nut.createDecoder(opts));
17955 stream.setIterator(it);
17956
17957 return stream;
17958 };
17959
17960 emitter.close = function (cb) {
17961 nut.close(cb);
17962 };
17963
17964 emitter.isOpen = nut.isOpen;
17965 emitter.isClosed = nut.isClosed;
17966
17967 return emitter;
17968};
17969
17970/* Copyright (c) 2012-2014 LevelUP contributors
17971 * See list at <https://github.com/rvagg/node-levelup#contributing>
17972 * MIT License <https://github.com/rvagg/node-levelup/blob/master/LICENSE.md>
17973 */
17974
17975var Readable = ReadableStreamCore.Readable;
17976
17977function ReadStream(options, makeData) {
17978 if (!(this instanceof ReadStream)) {
17979 return new ReadStream(options, makeData);
17980 }
17981
17982 Readable.call(this, { objectMode: true, highWaterMark: options.highWaterMark });
17983
17984 // purely to keep `db` around until we're done so it's not GCed if the user doesn't keep a ref
17985
17986 this._waiting = false;
17987 this._options = options;
17988 this._makeData = makeData;
17989}
17990
17991inherits(ReadStream, Readable);
17992
17993ReadStream.prototype.setIterator = function (it) {
17994 this._iterator = it;
17995 /* istanbul ignore if */
17996 if (this._destroyed) {
17997 return it.end(function () {});
17998 }
17999 /* istanbul ignore if */
18000 if (this._waiting) {
18001 this._waiting = false;
18002 return this._read();
18003 }
18004 return this;
18005};
18006
18007ReadStream.prototype._read = function read() {
18008 var self = this;
18009 /* istanbul ignore if */
18010 if (self._destroyed) {
18011 return;
18012 }
18013 /* istanbul ignore if */
18014 if (!self._iterator) {
18015 return this._waiting = true;
18016 }
18017
18018 self._iterator.next(function (err, key, value) {
18019 if (err || (key === undefined && value === undefined)) {
18020 if (!err && !self._destroyed) {
18021 self.push(null);
18022 }
18023 return self._cleanup(err);
18024 }
18025
18026
18027 value = self._makeData(key, value);
18028 if (!self._destroyed) {
18029 self.push(value);
18030 }
18031 });
18032};
18033
18034ReadStream.prototype._cleanup = function (err) {
18035 if (this._destroyed) {
18036 return;
18037 }
18038
18039 this._destroyed = true;
18040
18041 var self = this;
18042 /* istanbul ignore if */
18043 if (err && err.message !== 'iterator has ended') {
18044 self.emit('error', err);
18045 }
18046
18047 /* istanbul ignore else */
18048 if (self._iterator) {
18049 self._iterator.end(function () {
18050 self._iterator = null;
18051 self.emit('close');
18052 });
18053 } else {
18054 self.emit('close');
18055 }
18056};
18057
18058ReadStream.prototype.destroy = function () {
18059 this._cleanup();
18060};
18061
18062var precodec = {
18063 encode: function (decodedKey) {
18064 return '\xff' + decodedKey[0] + '\xff' + decodedKey[1];
18065 },
18066 decode: function (encodedKeyAsBuffer) {
18067 var str = encodedKeyAsBuffer.toString();
18068 var idx = str.indexOf('\xff', 1);
18069 return [str.substring(1, idx), str.substring(idx + 1)];
18070 },
18071 lowerBound: '\x00',
18072 upperBound: '\xff'
18073};
18074
18075var codec = new Codec();
18076
18077function sublevelPouch(db) {
18078 return sublevel(nut(db, precodec, codec), [], ReadStream, db.options);
18079}
18080
18081function allDocsKeysQuery(api, opts) {
18082 var keys = opts.keys;
18083 var finalResults = {
18084 offset: opts.skip
18085 };
18086 return Promise.all(keys.map(function (key) {
18087 var subOpts = $inject_Object_assign({key: key, deleted: 'ok'}, opts);
18088 ['limit', 'skip', 'keys'].forEach(function (optKey) {
18089 delete subOpts[optKey];
18090 });
18091 return new Promise(function (resolve, reject) {
18092 api._allDocs(subOpts, function (err, res) {
18093 /* istanbul ignore if */
18094 if (err) {
18095 return reject(err);
18096 }
18097 /* istanbul ignore if */
18098 if (opts.update_seq && res.update_seq !== undefined) {
18099 finalResults.update_seq = res.update_seq;
18100 }
18101 finalResults.total_rows = res.total_rows;
18102 resolve(res.rows[0] || {key: key, error: 'not_found'});
18103 });
18104 });
18105 })).then(function (results) {
18106 finalResults.rows = results;
18107 return finalResults;
18108 });
18109}
18110
18111function toObject(array) {
18112 return array.reduce(function (obj, item) {
18113 obj[item] = true;
18114 return obj;
18115 }, {});
18116}
18117// List of top level reserved words for doc
18118var reservedWords = toObject([
18119 '_id',
18120 '_rev',
18121 '_attachments',
18122 '_deleted',
18123 '_revisions',
18124 '_revs_info',
18125 '_conflicts',
18126 '_deleted_conflicts',
18127 '_local_seq',
18128 '_rev_tree',
18129 //replication documents
18130 '_replication_id',
18131 '_replication_state',
18132 '_replication_state_time',
18133 '_replication_state_reason',
18134 '_replication_stats',
18135 // Specific to Couchbase Sync Gateway
18136 '_removed'
18137]);
18138
18139// List of reserved words that should end up the document
18140var dataWords = toObject([
18141 '_attachments',
18142 //replication documents
18143 '_replication_id',
18144 '_replication_state',
18145 '_replication_state_time',
18146 '_replication_state_reason',
18147 '_replication_stats'
18148]);
18149
18150function parseRevisionInfo(rev$$1) {
18151 if (!/^\d+-./.test(rev$$1)) {
18152 return createError(INVALID_REV);
18153 }
18154 var idx = rev$$1.indexOf('-');
18155 var left = rev$$1.substring(0, idx);
18156 var right = rev$$1.substring(idx + 1);
18157 return {
18158 prefix: parseInt(left, 10),
18159 id: right
18160 };
18161}
18162
18163function makeRevTreeFromRevisions(revisions, opts) {
18164 var pos = revisions.start - revisions.ids.length + 1;
18165
18166 var revisionIds = revisions.ids;
18167 var ids = [revisionIds[0], opts, []];
18168
18169 for (var i = 1, len = revisionIds.length; i < len; i++) {
18170 ids = [revisionIds[i], {status: 'missing'}, [ids]];
18171 }
18172
18173 return [{
18174 pos: pos,
18175 ids: ids
18176 }];
18177}
18178
18179// Preprocess documents, parse their revisions, assign an id and a
18180// revision for new writes that are missing them, etc
18181function parseDoc(doc, newEdits, dbOpts) {
18182 if (!dbOpts) {
18183 dbOpts = {
18184 deterministic_revs: true
18185 };
18186 }
18187
18188 var nRevNum;
18189 var newRevId;
18190 var revInfo;
18191 var opts = {status: 'available'};
18192 if (doc._deleted) {
18193 opts.deleted = true;
18194 }
18195
18196 if (newEdits) {
18197 if (!doc._id) {
18198 doc._id = uuid();
18199 }
18200 newRevId = rev(doc, dbOpts.deterministic_revs);
18201 if (doc._rev) {
18202 revInfo = parseRevisionInfo(doc._rev);
18203 if (revInfo.error) {
18204 return revInfo;
18205 }
18206 doc._rev_tree = [{
18207 pos: revInfo.prefix,
18208 ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]]
18209 }];
18210 nRevNum = revInfo.prefix + 1;
18211 } else {
18212 doc._rev_tree = [{
18213 pos: 1,
18214 ids : [newRevId, opts, []]
18215 }];
18216 nRevNum = 1;
18217 }
18218 } else {
18219 if (doc._revisions) {
18220 doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts);
18221 nRevNum = doc._revisions.start;
18222 newRevId = doc._revisions.ids[0];
18223 }
18224 if (!doc._rev_tree) {
18225 revInfo = parseRevisionInfo(doc._rev);
18226 if (revInfo.error) {
18227 return revInfo;
18228 }
18229 nRevNum = revInfo.prefix;
18230 newRevId = revInfo.id;
18231 doc._rev_tree = [{
18232 pos: nRevNum,
18233 ids: [newRevId, opts, []]
18234 }];
18235 }
18236 }
18237
18238 invalidIdError(doc._id);
18239
18240 doc._rev = nRevNum + '-' + newRevId;
18241
18242 var result = {metadata : {}, data : {}};
18243 for (var key in doc) {
18244 /* istanbul ignore else */
18245 if (Object.prototype.hasOwnProperty.call(doc, key)) {
18246 var specialKey = key[0] === '_';
18247 if (specialKey && !reservedWords[key]) {
18248 var error = createError(DOC_VALIDATION, key);
18249 error.message = DOC_VALIDATION.message + ': ' + key;
18250 throw error;
18251 } else if (specialKey && !dataWords[key]) {
18252 result.metadata[key.slice(1)] = doc[key];
18253 } else {
18254 result.data[key] = doc[key];
18255 }
18256 }
18257 }
18258 return result;
18259}
18260
18261// We fetch all leafs of the revision tree, and sort them based on tree length
18262// and whether they were deleted, undeleted documents with the longest revision
18263// tree (most edits) win
18264// The final sort algorithm is slightly documented in a sidebar here:
18265// http://guide.couchdb.org/draft/conflicts.html
18266function winningRev(metadata) {
18267 var winningId;
18268 var winningPos;
18269 var winningDeleted;
18270 var toVisit = metadata.rev_tree.slice();
18271 var node;
18272 while ((node = toVisit.pop())) {
18273 var tree = node.ids;
18274 var branches = tree[2];
18275 var pos = node.pos;
18276 if (branches.length) { // non-leaf
18277 for (var i = 0, len = branches.length; i < len; i++) {
18278 toVisit.push({pos: pos + 1, ids: branches[i]});
18279 }
18280 continue;
18281 }
18282 var deleted = !!tree[1].deleted;
18283 var id = tree[0];
18284 // sort by deleted, then pos, then id
18285 if (!winningId || (winningDeleted !== deleted ? winningDeleted :
18286 winningPos !== pos ? winningPos < pos : winningId < id)) {
18287 winningId = id;
18288 winningPos = pos;
18289 winningDeleted = deleted;
18290 }
18291 }
18292
18293 return winningPos + '-' + winningId;
18294}
18295
18296// Pretty much all below can be combined into a higher order function to
18297// traverse revisions
18298// The return value from the callback will be passed as context to all
18299// children of that node
18300function traverseRevTree(revs, callback) {
18301 var toVisit = revs.slice();
18302
18303 var node;
18304 while ((node = toVisit.pop())) {
18305 var pos = node.pos;
18306 var tree = node.ids;
18307 var branches = tree[2];
18308 var newCtx =
18309 callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]);
18310 for (var i = 0, len = branches.length; i < len; i++) {
18311 toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx});
18312 }
18313 }
18314}
18315
18316function sortByPos(a, b) {
18317 return a.pos - b.pos;
18318}
18319
18320function collectLeaves(revs) {
18321 var leaves = [];
18322 traverseRevTree(revs, function (isLeaf, pos, id, acc, opts) {
18323 if (isLeaf) {
18324 leaves.push({rev: pos + "-" + id, pos: pos, opts: opts});
18325 }
18326 });
18327 leaves.sort(sortByPos).reverse();
18328 for (var i = 0, len = leaves.length; i < len; i++) {
18329 delete leaves[i].pos;
18330 }
18331 return leaves;
18332}
18333
18334// returns revs of all conflicts that is leaves such that
18335// 1. are not deleted and
18336// 2. are different than winning revision
18337function collectConflicts(metadata) {
18338 var win = winningRev(metadata);
18339 var leaves = collectLeaves(metadata.rev_tree);
18340 var conflicts = [];
18341 for (var i = 0, len = leaves.length; i < len; i++) {
18342 var leaf = leaves[i];
18343 if (leaf.rev !== win && !leaf.opts.deleted) {
18344 conflicts.push(leaf.rev);
18345 }
18346 }
18347 return conflicts;
18348}
18349
18350// compact a tree by marking its non-leafs as missing,
18351// and return a list of revs to delete
18352function compactTree(metadata) {
18353 var revs = [];
18354 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
18355 revHash, ctx, opts) {
18356 if (opts.status === 'available' && !isLeaf) {
18357 revs.push(pos + '-' + revHash);
18358 opts.status = 'missing';
18359 }
18360 });
18361 return revs;
18362}
18363
18364// build up a list of all the paths to the leafs in this revision tree
18365function rootToLeaf(revs) {
18366 var paths = [];
18367 var toVisit = revs.slice();
18368 var node;
18369 while ((node = toVisit.pop())) {
18370 var pos = node.pos;
18371 var tree = node.ids;
18372 var id = tree[0];
18373 var opts = tree[1];
18374 var branches = tree[2];
18375 var isLeaf = branches.length === 0;
18376
18377 var history = node.history ? node.history.slice() : [];
18378 history.push({id: id, opts: opts});
18379 if (isLeaf) {
18380 paths.push({pos: (pos + 1 - history.length), ids: history});
18381 }
18382 for (var i = 0, len = branches.length; i < len; i++) {
18383 toVisit.push({pos: pos + 1, ids: branches[i], history: history});
18384 }
18385 }
18386 return paths.reverse();
18387}
18388
18389// for a better overview of what this is doing, read:
18390
18391function sortByPos$1(a, b) {
18392 return a.pos - b.pos;
18393}
18394
18395// classic binary search
18396function binarySearch(arr, item, comparator) {
18397 var low = 0;
18398 var high = arr.length;
18399 var mid;
18400 while (low < high) {
18401 mid = (low + high) >>> 1;
18402 if (comparator(arr[mid], item) < 0) {
18403 low = mid + 1;
18404 } else {
18405 high = mid;
18406 }
18407 }
18408 return low;
18409}
18410
18411// assuming the arr is sorted, insert the item in the proper place
18412function insertSorted(arr, item, comparator) {
18413 var idx = binarySearch(arr, item, comparator);
18414 arr.splice(idx, 0, item);
18415}
18416
18417// Turn a path as a flat array into a tree with a single branch.
18418// If any should be stemmed from the beginning of the array, that's passed
18419// in as the second argument
18420function pathToTree(path, numStemmed) {
18421 var root;
18422 var leaf;
18423 for (var i = numStemmed, len = path.length; i < len; i++) {
18424 var node = path[i];
18425 var currentLeaf = [node.id, node.opts, []];
18426 if (leaf) {
18427 leaf[2].push(currentLeaf);
18428 leaf = currentLeaf;
18429 } else {
18430 root = leaf = currentLeaf;
18431 }
18432 }
18433 return root;
18434}
18435
18436// compare the IDs of two trees
18437function compareTree(a, b) {
18438 return a[0] < b[0] ? -1 : 1;
18439}
18440
18441// Merge two trees together
18442// The roots of tree1 and tree2 must be the same revision
18443function mergeTree(in_tree1, in_tree2) {
18444 var queue = [{tree1: in_tree1, tree2: in_tree2}];
18445 var conflicts = false;
18446 while (queue.length > 0) {
18447 var item = queue.pop();
18448 var tree1 = item.tree1;
18449 var tree2 = item.tree2;
18450
18451 if (tree1[1].status || tree2[1].status) {
18452 tree1[1].status =
18453 (tree1[1].status === 'available' ||
18454 tree2[1].status === 'available') ? 'available' : 'missing';
18455 }
18456
18457 for (var i = 0; i < tree2[2].length; i++) {
18458 if (!tree1[2][0]) {
18459 conflicts = 'new_leaf';
18460 tree1[2][0] = tree2[2][i];
18461 continue;
18462 }
18463
18464 var merged = false;
18465 for (var j = 0; j < tree1[2].length; j++) {
18466 if (tree1[2][j][0] === tree2[2][i][0]) {
18467 queue.push({tree1: tree1[2][j], tree2: tree2[2][i]});
18468 merged = true;
18469 }
18470 }
18471 if (!merged) {
18472 conflicts = 'new_branch';
18473 insertSorted(tree1[2], tree2[2][i], compareTree);
18474 }
18475 }
18476 }
18477 return {conflicts: conflicts, tree: in_tree1};
18478}
18479
18480function doMerge(tree, path, dontExpand) {
18481 var restree = [];
18482 var conflicts = false;
18483 var merged = false;
18484 var res;
18485
18486 if (!tree.length) {
18487 return {tree: [path], conflicts: 'new_leaf'};
18488 }
18489
18490 for (var i = 0, len = tree.length; i < len; i++) {
18491 var branch = tree[i];
18492 if (branch.pos === path.pos && branch.ids[0] === path.ids[0]) {
18493 // Paths start at the same position and have the same root, so they need
18494 // merged
18495 res = mergeTree(branch.ids, path.ids);
18496 restree.push({pos: branch.pos, ids: res.tree});
18497 conflicts = conflicts || res.conflicts;
18498 merged = true;
18499 } else if (dontExpand !== true) {
18500 // The paths start at a different position, take the earliest path and
18501 // traverse up until it as at the same point from root as the path we
18502 // want to merge. If the keys match we return the longer path with the
18503 // other merged After stemming we dont want to expand the trees
18504
18505 var t1 = branch.pos < path.pos ? branch : path;
18506 var t2 = branch.pos < path.pos ? path : branch;
18507 var diff = t2.pos - t1.pos;
18508
18509 var candidateParents = [];
18510
18511 var trees = [];
18512 trees.push({ids: t1.ids, diff: diff, parent: null, parentIdx: null});
18513 while (trees.length > 0) {
18514 var item = trees.pop();
18515 if (item.diff === 0) {
18516 if (item.ids[0] === t2.ids[0]) {
18517 candidateParents.push(item);
18518 }
18519 continue;
18520 }
18521 var elements = item.ids[2];
18522 for (var j = 0, elementsLen = elements.length; j < elementsLen; j++) {
18523 trees.push({
18524 ids: elements[j],
18525 diff: item.diff - 1,
18526 parent: item.ids,
18527 parentIdx: j
18528 });
18529 }
18530 }
18531
18532 var el = candidateParents[0];
18533
18534 if (!el) {
18535 restree.push(branch);
18536 } else {
18537 res = mergeTree(el.ids, t2.ids);
18538 el.parent[2][el.parentIdx] = res.tree;
18539 restree.push({pos: t1.pos, ids: t1.ids});
18540 conflicts = conflicts || res.conflicts;
18541 merged = true;
18542 }
18543 } else {
18544 restree.push(branch);
18545 }
18546 }
18547
18548 // We didnt find
18549 if (!merged) {
18550 restree.push(path);
18551 }
18552
18553 restree.sort(sortByPos$1);
18554
18555 return {
18556 tree: restree,
18557 conflicts: conflicts || 'internal_node'
18558 };
18559}
18560
18561// To ensure we dont grow the revision tree infinitely, we stem old revisions
18562function stem(tree, depth) {
18563 // First we break out the tree into a complete list of root to leaf paths
18564 var paths = rootToLeaf(tree);
18565 var stemmedRevs;
18566
18567 var result;
18568 for (var i = 0, len = paths.length; i < len; i++) {
18569 // Then for each path, we cut off the start of the path based on the
18570 // `depth` to stem to, and generate a new set of flat trees
18571 var path = paths[i];
18572 var stemmed = path.ids;
18573 var node;
18574 if (stemmed.length > depth) {
18575 // only do the stemming work if we actually need to stem
18576 if (!stemmedRevs) {
18577 stemmedRevs = {}; // avoid allocating this object unnecessarily
18578 }
18579 var numStemmed = stemmed.length - depth;
18580 node = {
18581 pos: path.pos + numStemmed,
18582 ids: pathToTree(stemmed, numStemmed)
18583 };
18584
18585 for (var s = 0; s < numStemmed; s++) {
18586 var rev = (path.pos + s) + '-' + stemmed[s].id;
18587 stemmedRevs[rev] = true;
18588 }
18589 } else { // no need to actually stem
18590 node = {
18591 pos: path.pos,
18592 ids: pathToTree(stemmed, 0)
18593 };
18594 }
18595
18596 // Then we remerge all those flat trees together, ensuring that we dont
18597 // connect trees that would go beyond the depth limit
18598 if (result) {
18599 result = doMerge(result, node, true).tree;
18600 } else {
18601 result = [node];
18602 }
18603 }
18604
18605 // this is memory-heavy per Chrome profiler, avoid unless we actually stemmed
18606 if (stemmedRevs) {
18607 traverseRevTree(result, function (isLeaf, pos, revHash) {
18608 // some revisions may have been removed in a branch but not in another
18609 delete stemmedRevs[pos + '-' + revHash];
18610 });
18611 }
18612
18613 return {
18614 tree: result,
18615 revs: stemmedRevs ? Object.keys(stemmedRevs) : []
18616 };
18617}
18618
18619function merge(tree, path, depth) {
18620 var newTree = doMerge(tree, path);
18621 var stemmed = stem(newTree.tree, depth);
18622 return {
18623 tree: stemmed.tree,
18624 stemmedRevs: stemmed.revs,
18625 conflicts: newTree.conflicts
18626 };
18627}
18628
18629// return true if a rev exists in the rev tree, false otherwise
18630function revExists(revs, rev) {
18631 var toVisit = revs.slice();
18632 var splitRev = rev.split('-');
18633 var targetPos = parseInt(splitRev[0], 10);
18634 var targetId = splitRev[1];
18635
18636 var node;
18637 while ((node = toVisit.pop())) {
18638 if (node.pos === targetPos && node.ids[0] === targetId) {
18639 return true;
18640 }
18641 var branches = node.ids[2];
18642 for (var i = 0, len = branches.length; i < len; i++) {
18643 toVisit.push({pos: node.pos + 1, ids: branches[i]});
18644 }
18645 }
18646 return false;
18647}
18648
18649function getTrees(node) {
18650 return node.ids;
18651}
18652
18653// check if a specific revision of a doc has been deleted
18654// - metadata: the metadata object from the doc store
18655// - rev: (optional) the revision to check. defaults to winning revision
18656function isDeleted(metadata, rev) {
18657 if (!rev) {
18658 rev = winningRev(metadata);
18659 }
18660 var id = rev.substring(rev.indexOf('-') + 1);
18661 var toVisit = metadata.rev_tree.map(getTrees);
18662
18663 var tree;
18664 while ((tree = toVisit.pop())) {
18665 if (tree[0] === id) {
18666 return !!tree[1].deleted;
18667 }
18668 toVisit = toVisit.concat(tree[2]);
18669 }
18670}
18671
18672function isLocalId(id) {
18673 return (/^_local/).test(id);
18674}
18675
18676// returns the current leaf node for a given revision
18677function latest(rev, metadata) {
18678 var toVisit = metadata.rev_tree.slice();
18679 var node;
18680 while ((node = toVisit.pop())) {
18681 var pos = node.pos;
18682 var tree = node.ids;
18683 var id = tree[0];
18684 var opts = tree[1];
18685 var branches = tree[2];
18686 var isLeaf = branches.length === 0;
18687
18688 var history = node.history ? node.history.slice() : [];
18689 history.push({id: id, pos: pos, opts: opts});
18690
18691 if (isLeaf) {
18692 for (var i = 0, len = history.length; i < len; i++) {
18693 var historyNode = history[i];
18694 var historyRev = historyNode.pos + '-' + historyNode.id;
18695
18696 if (historyRev === rev) {
18697 // return the rev of this leaf
18698 return pos + '-' + id;
18699 }
18700 }
18701 }
18702
18703 for (var j = 0, l = branches.length; j < l; j++) {
18704 toVisit.push({pos: pos + 1, ids: branches[j], history: history});
18705 }
18706 }
18707
18708 /* istanbul ignore next */
18709 throw new Error('Unable to resolve latest revision for id ' + metadata.id + ', rev ' + rev);
18710}
18711
18712function updateDoc(revLimit, prev, docInfo, results,
18713 i, cb, writeDoc, newEdits) {
18714
18715 if (revExists(prev.rev_tree, docInfo.metadata.rev) && !newEdits) {
18716 results[i] = docInfo;
18717 return cb();
18718 }
18719
18720 // sometimes this is pre-calculated. historically not always
18721 var previousWinningRev = prev.winningRev || winningRev(prev);
18722 var previouslyDeleted = 'deleted' in prev ? prev.deleted :
18723 isDeleted(prev, previousWinningRev);
18724 var deleted = 'deleted' in docInfo.metadata ? docInfo.metadata.deleted :
18725 isDeleted(docInfo.metadata);
18726 var isRoot = /^1-/.test(docInfo.metadata.rev);
18727
18728 if (previouslyDeleted && !deleted && newEdits && isRoot) {
18729 var newDoc = docInfo.data;
18730 newDoc._rev = previousWinningRev;
18731 newDoc._id = docInfo.metadata.id;
18732 docInfo = parseDoc(newDoc, newEdits);
18733 }
18734
18735 var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit);
18736
18737 var inConflict = newEdits && ((
18738 (previouslyDeleted && deleted && merged.conflicts !== 'new_leaf') ||
18739 (!previouslyDeleted && merged.conflicts !== 'new_leaf') ||
18740 (previouslyDeleted && !deleted && merged.conflicts === 'new_branch')));
18741
18742 if (inConflict) {
18743 var err = createError(REV_CONFLICT);
18744 results[i] = err;
18745 return cb();
18746 }
18747
18748 var newRev = docInfo.metadata.rev;
18749 docInfo.metadata.rev_tree = merged.tree;
18750 docInfo.stemmedRevs = merged.stemmedRevs || [];
18751 /* istanbul ignore else */
18752 if (prev.rev_map) {
18753 docInfo.metadata.rev_map = prev.rev_map; // used only by leveldb
18754 }
18755
18756 // recalculate
18757 var winningRev$$1 = winningRev(docInfo.metadata);
18758 var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev$$1);
18759
18760 // calculate the total number of documents that were added/removed,
18761 // from the perspective of total_rows/doc_count
18762 var delta = (previouslyDeleted === winningRevIsDeleted) ? 0 :
18763 previouslyDeleted < winningRevIsDeleted ? -1 : 1;
18764
18765 var newRevIsDeleted;
18766 if (newRev === winningRev$$1) {
18767 // if the new rev is the same as the winning rev, we can reuse that value
18768 newRevIsDeleted = winningRevIsDeleted;
18769 } else {
18770 // if they're not the same, then we need to recalculate
18771 newRevIsDeleted = isDeleted(docInfo.metadata, newRev);
18772 }
18773
18774 writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
18775 true, delta, i, cb);
18776}
18777
18778function rootIsMissing(docInfo) {
18779 return docInfo.metadata.rev_tree[0].ids[1].status === 'missing';
18780}
18781
18782function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results,
18783 writeDoc, opts, overallCallback) {
18784
18785 // Default to 1000 locally
18786 revLimit = revLimit || 1000;
18787
18788 function insertDoc(docInfo, resultsIdx, callback) {
18789 // Cant insert new deleted documents
18790 var winningRev$$1 = winningRev(docInfo.metadata);
18791 var deleted = isDeleted(docInfo.metadata, winningRev$$1);
18792 if ('was_delete' in opts && deleted) {
18793 results[resultsIdx] = createError(MISSING_DOC, 'deleted');
18794 return callback();
18795 }
18796
18797 // 4712 - detect whether a new document was inserted with a _rev
18798 var inConflict = newEdits && rootIsMissing(docInfo);
18799
18800 if (inConflict) {
18801 var err = createError(REV_CONFLICT);
18802 results[resultsIdx] = err;
18803 return callback();
18804 }
18805
18806 var delta = deleted ? 0 : 1;
18807
18808 writeDoc(docInfo, winningRev$$1, deleted, deleted, false,
18809 delta, resultsIdx, callback);
18810 }
18811
18812 var newEdits = opts.new_edits;
18813 var idsToDocs = new ExportedMap();
18814
18815 var docsDone = 0;
18816 var docsToDo = docInfos.length;
18817
18818 function checkAllDocsDone() {
18819 if (++docsDone === docsToDo && overallCallback) {
18820 overallCallback();
18821 }
18822 }
18823
18824 docInfos.forEach(function (currentDoc, resultsIdx) {
18825
18826 if (currentDoc._id && isLocalId(currentDoc._id)) {
18827 var fun = currentDoc._deleted ? '_removeLocal' : '_putLocal';
18828 api[fun](currentDoc, {ctx: tx}, function (err, res) {
18829 results[resultsIdx] = err || res;
18830 checkAllDocsDone();
18831 });
18832 return;
18833 }
18834
18835 var id = currentDoc.metadata.id;
18836 if (idsToDocs.has(id)) {
18837 docsToDo--; // duplicate
18838 idsToDocs.get(id).push([currentDoc, resultsIdx]);
18839 } else {
18840 idsToDocs.set(id, [[currentDoc, resultsIdx]]);
18841 }
18842 });
18843
18844 // in the case of new_edits, the user can provide multiple docs
18845 // with the same id. these need to be processed sequentially
18846 idsToDocs.forEach(function (docs, id) {
18847 var numDone = 0;
18848
18849 function docWritten() {
18850 if (++numDone < docs.length) {
18851 nextDoc();
18852 } else {
18853 checkAllDocsDone();
18854 }
18855 }
18856 function nextDoc() {
18857 var value = docs[numDone];
18858 var currentDoc = value[0];
18859 var resultsIdx = value[1];
18860
18861 if (fetchedDocs.has(id)) {
18862 updateDoc(revLimit, fetchedDocs.get(id), currentDoc, results,
18863 resultsIdx, docWritten, writeDoc, newEdits);
18864 } else {
18865 // Ensure stemming applies to new writes as well
18866 var merged = merge([], currentDoc.metadata.rev_tree[0], revLimit);
18867 currentDoc.metadata.rev_tree = merged.tree;
18868 currentDoc.stemmedRevs = merged.stemmedRevs || [];
18869 insertDoc(currentDoc, resultsIdx, docWritten);
18870 }
18871 }
18872 nextDoc();
18873 });
18874}
18875
18876function safeJsonParse(str) {
18877 // This try/catch guards against stack overflow errors.
18878 // JSON.parse() is faster than vuvuzela.parse() but vuvuzela
18879 // cannot overflow.
18880 try {
18881 return JSON.parse(str);
18882 } catch (e) {
18883 /* istanbul ignore next */
18884 return vuvuzela.parse(str);
18885 }
18886}
18887
18888function safeJsonStringify(json) {
18889 try {
18890 return JSON.stringify(json);
18891 } catch (e) {
18892 /* istanbul ignore next */
18893 return vuvuzela.stringify(json);
18894 }
18895}
18896
18897function readAsBlobOrBuffer(storedObject, type) {
18898 // In the browser, we've stored a binary string. This now comes back as a
18899 // browserified Node-style Buffer (implemented as a typed array),
18900 // but we want a Blob instead.
18901 var byteArray = new Uint8Array(storedObject);
18902 return createBlob([byteArray], {type: type});
18903}
18904
18905// In the browser, we store a binary string
18906function prepareAttachmentForStorage(attData, cb) {
18907 readAsBinaryString(attData, cb);
18908}
18909
18910function createEmptyBlobOrBuffer(type) {
18911 return createBlob([''], {type: type});
18912}
18913
18914function getCacheFor(transaction, store) {
18915 var prefix = store.prefix()[0];
18916 var cache = transaction._cache;
18917 var subCache = cache.get(prefix);
18918 if (!subCache) {
18919 subCache = new ExportedMap();
18920 cache.set(prefix, subCache);
18921 }
18922 return subCache;
18923}
18924
18925function LevelTransaction() {
18926 this._batch = [];
18927 this._cache = new ExportedMap();
18928}
18929
18930LevelTransaction.prototype.get = function (store, key, callback) {
18931 var cache = getCacheFor(this, store);
18932 var exists = cache.get(key);
18933 if (exists) {
18934 return immediate(function () {
18935 callback(null, exists);
18936 });
18937 } else if (exists === null) { // deleted marker
18938 /* istanbul ignore next */
18939 return immediate(function () {
18940 callback({name: 'NotFoundError'});
18941 });
18942 }
18943 store.get(key, function (err, res) {
18944 if (err) {
18945 /* istanbul ignore else */
18946 if (err.name === 'NotFoundError') {
18947 cache.set(key, null);
18948 }
18949 return callback(err);
18950 }
18951 cache.set(key, res);
18952 callback(null, res);
18953 });
18954};
18955
18956LevelTransaction.prototype.batch = function (batch) {
18957 for (var i = 0, len = batch.length; i < len; i++) {
18958 var operation = batch[i];
18959
18960 var cache = getCacheFor(this, operation.prefix);
18961
18962 if (operation.type === 'put') {
18963 cache.set(operation.key, operation.value);
18964 } else {
18965 cache.set(operation.key, null);
18966 }
18967 }
18968 this._batch = this._batch.concat(batch);
18969};
18970
18971LevelTransaction.prototype.execute = function (db, callback) {
18972
18973 var keys = new ExportedSet();
18974 var uniqBatches = [];
18975
18976 // remove duplicates; last one wins
18977 for (var i = this._batch.length - 1; i >= 0; i--) {
18978 var operation = this._batch[i];
18979 var lookupKey = operation.prefix.prefix()[0] + '\xff' + operation.key;
18980 if (keys.has(lookupKey)) {
18981 continue;
18982 }
18983 keys.add(lookupKey);
18984 uniqBatches.push(operation);
18985 }
18986
18987 db.batch(uniqBatches, callback);
18988};
18989
18990var DOC_STORE = 'document-store';
18991var BY_SEQ_STORE = 'by-sequence';
18992var ATTACHMENT_STORE = 'attach-store';
18993var BINARY_STORE = 'attach-binary-store';
18994var LOCAL_STORE = 'local-store';
18995var META_STORE = 'meta-store';
18996
18997// leveldb barks if we try to open a db multiple times
18998// so we cache opened connections here for initstore()
18999var dbStores = new ExportedMap();
19000
19001// store the value of update_seq in the by-sequence store the key name will
19002// never conflict, since the keys in the by-sequence store are integers
19003var UPDATE_SEQ_KEY = '_local_last_update_seq';
19004var DOC_COUNT_KEY = '_local_doc_count';
19005var UUID_KEY = '_local_uuid';
19006
19007var MD5_PREFIX = 'md5-';
19008
19009var safeJsonEncoding = {
19010 encode: safeJsonStringify,
19011 decode: safeJsonParse,
19012 buffer: false,
19013 type: 'cheap-json'
19014};
19015
19016var levelChanges = new Changes();
19017
19018// winningRev and deleted are performance-killers, but
19019// in newer versions of PouchDB, they are cached on the metadata
19020function getWinningRev(metadata) {
19021 return 'winningRev' in metadata ?
19022 metadata.winningRev : winningRev(metadata);
19023}
19024
19025function getIsDeleted(metadata, winningRev$$1) {
19026 return 'deleted' in metadata ?
19027 metadata.deleted : isDeleted(metadata, winningRev$$1);
19028}
19029
19030function fetchAttachment(att, stores, opts) {
19031 var type = att.content_type;
19032 return new Promise(function (resolve, reject) {
19033 stores.binaryStore.get(att.digest, function (err, buffer) {
19034 var data;
19035 if (err) {
19036 /* istanbul ignore if */
19037 if (err.name !== 'NotFoundError') {
19038 return reject(err);
19039 } else {
19040 // empty
19041 if (!opts.binary) {
19042 data = '';
19043 } else {
19044 data = binStringToBluffer('', type);
19045 }
19046 }
19047 } else { // non-empty
19048 if (opts.binary) {
19049 data = readAsBlobOrBuffer(buffer, type);
19050 } else {
19051 data = buffer.toString('base64');
19052 }
19053 }
19054 delete att.stub;
19055 delete att.length;
19056 att.data = data;
19057 resolve();
19058 });
19059 });
19060}
19061
19062function fetchAttachments(results, stores, opts) {
19063 var atts = [];
19064 results.forEach(function (row) {
19065 if (!(row.doc && row.doc._attachments)) {
19066 return;
19067 }
19068 var attNames = Object.keys(row.doc._attachments);
19069 attNames.forEach(function (attName) {
19070 var att = row.doc._attachments[attName];
19071 if (!('data' in att)) {
19072 atts.push(att);
19073 }
19074 });
19075 });
19076
19077 return Promise.all(atts.map(function (att) {
19078 return fetchAttachment(att, stores, opts);
19079 }));
19080}
19081
19082function LevelPouch(opts, callback) {
19083 opts = clone(opts);
19084 var api = this;
19085 var instanceId;
19086 var stores = {};
19087 var revLimit = opts.revs_limit;
19088 var db;
19089 var name = opts.name;
19090 // TODO: this is undocumented and unused probably
19091 /* istanbul ignore else */
19092 if (typeof opts.createIfMissing === 'undefined') {
19093 opts.createIfMissing = true;
19094 }
19095
19096 var leveldown = opts.db;
19097
19098 var dbStore;
19099 var leveldownName = functionName(leveldown);
19100 if (dbStores.has(leveldownName)) {
19101 dbStore = dbStores.get(leveldownName);
19102 } else {
19103 dbStore = new ExportedMap();
19104 dbStores.set(leveldownName, dbStore);
19105 }
19106 if (dbStore.has(name)) {
19107 db = dbStore.get(name);
19108 afterDBCreated();
19109 } else {
19110 dbStore.set(name, sublevelPouch(levelup(leveldown(name), opts, function (err) {
19111 /* istanbul ignore if */
19112 if (err) {
19113 dbStore["delete"](name);
19114 return callback(err);
19115 }
19116 db = dbStore.get(name);
19117 db._docCount = -1;
19118 db._queue = new Deque();
19119 /* istanbul ignore else */
19120 if (typeof opts.migrate === 'object') { // migration for leveldown
19121 opts.migrate.doMigrationOne(name, db, afterDBCreated);
19122 } else {
19123 afterDBCreated();
19124 }
19125 })));
19126 }
19127
19128 function afterDBCreated() {
19129 stores.docStore = db.sublevel(DOC_STORE, {valueEncoding: safeJsonEncoding});
19130 stores.bySeqStore = db.sublevel(BY_SEQ_STORE, {valueEncoding: 'json'});
19131 stores.attachmentStore =
19132 db.sublevel(ATTACHMENT_STORE, {valueEncoding: 'json'});
19133 stores.binaryStore = db.sublevel(BINARY_STORE, {valueEncoding: 'binary'});
19134 stores.localStore = db.sublevel(LOCAL_STORE, {valueEncoding: 'json'});
19135 stores.metaStore = db.sublevel(META_STORE, {valueEncoding: 'json'});
19136 /* istanbul ignore else */
19137 if (typeof opts.migrate === 'object') { // migration for leveldown
19138 opts.migrate.doMigrationTwo(db, stores, afterLastMigration);
19139 } else {
19140 afterLastMigration();
19141 }
19142 }
19143
19144 function afterLastMigration() {
19145 stores.metaStore.get(UPDATE_SEQ_KEY, function (err, value) {
19146 if (typeof db._updateSeq === 'undefined') {
19147 db._updateSeq = value || 0;
19148 }
19149 stores.metaStore.get(DOC_COUNT_KEY, function (err, value) {
19150 db._docCount = !err ? value : 0;
19151 stores.metaStore.get(UUID_KEY, function (err, value) {
19152 instanceId = !err ? value : uuid();
19153 stores.metaStore.put(UUID_KEY, instanceId, function () {
19154 immediate(function () {
19155 callback(null, api);
19156 });
19157 });
19158 });
19159 });
19160 });
19161 }
19162
19163 function countDocs(callback) {
19164 /* istanbul ignore if */
19165 if (db.isClosed()) {
19166 return callback(new Error('database is closed'));
19167 }
19168 return callback(null, db._docCount); // use cached value
19169 }
19170
19171 api._remote = false;
19172 /* istanbul ignore next */
19173 api.type = function () {
19174 return 'leveldb';
19175 };
19176
19177 api._id = function (callback) {
19178 callback(null, instanceId);
19179 };
19180
19181 api._info = function (callback) {
19182 var res = {
19183 doc_count: db._docCount,
19184 update_seq: db._updateSeq,
19185 backend_adapter: functionName(leveldown)
19186 };
19187 return immediate(function () {
19188 callback(null, res);
19189 });
19190 };
19191
19192 function tryCode(fun, args) {
19193 try {
19194 fun.apply(null, args);
19195 } catch (err) {
19196 args[args.length - 1](err);
19197 }
19198 }
19199
19200 function executeNext() {
19201 var firstTask = db._queue.peekFront();
19202
19203 if (firstTask.type === 'read') {
19204 runReadOperation(firstTask);
19205 } else { // write, only do one at a time
19206 runWriteOperation(firstTask);
19207 }
19208 }
19209
19210 function runReadOperation(firstTask) {
19211 // do multiple reads at once simultaneously, because it's safe
19212
19213 var readTasks = [firstTask];
19214 var i = 1;
19215 var nextTask = db._queue.get(i);
19216 while (typeof nextTask !== 'undefined' && nextTask.type === 'read') {
19217 readTasks.push(nextTask);
19218 i++;
19219 nextTask = db._queue.get(i);
19220 }
19221
19222 var numDone = 0;
19223
19224 readTasks.forEach(function (readTask) {
19225 var args = readTask.args;
19226 var callback = args[args.length - 1];
19227 args[args.length - 1] = getArguments(function (cbArgs) {
19228 callback.apply(null, cbArgs);
19229 if (++numDone === readTasks.length) {
19230 immediate(function () {
19231 // all read tasks have finished
19232 readTasks.forEach(function () {
19233 db._queue.shift();
19234 });
19235 if (db._queue.length) {
19236 executeNext();
19237 }
19238 });
19239 }
19240 });
19241 tryCode(readTask.fun, args);
19242 });
19243 }
19244
19245 function runWriteOperation(firstTask) {
19246 var args = firstTask.args;
19247 var callback = args[args.length - 1];
19248 args[args.length - 1] = getArguments(function (cbArgs) {
19249 callback.apply(null, cbArgs);
19250 immediate(function () {
19251 db._queue.shift();
19252 if (db._queue.length) {
19253 executeNext();
19254 }
19255 });
19256 });
19257 tryCode(firstTask.fun, args);
19258 }
19259
19260 // all read/write operations to the database are done in a queue,
19261 // similar to how websql/idb works. this avoids problems such
19262 // as e.g. compaction needing to have a lock on the database while
19263 // it updates stuff. in the future we can revisit this.
19264 function writeLock(fun) {
19265 return getArguments(function (args) {
19266 db._queue.push({
19267 fun: fun,
19268 args: args,
19269 type: 'write'
19270 });
19271
19272 if (db._queue.length === 1) {
19273 immediate(executeNext);
19274 }
19275 });
19276 }
19277
19278 // same as the writelock, but multiple can run at once
19279 function readLock(fun) {
19280 return getArguments(function (args) {
19281 db._queue.push({
19282 fun: fun,
19283 args: args,
19284 type: 'read'
19285 });
19286
19287 if (db._queue.length === 1) {
19288 immediate(executeNext);
19289 }
19290 });
19291 }
19292
19293 function formatSeq(n) {
19294 return ('0000000000000000' + n).slice(-16);
19295 }
19296
19297 function parseSeq(s) {
19298 return parseInt(s, 10);
19299 }
19300
19301 api._get = readLock(function (id, opts, callback) {
19302 opts = clone(opts);
19303
19304 stores.docStore.get(id, function (err, metadata) {
19305
19306 if (err || !metadata) {
19307 return callback(createError(MISSING_DOC, 'missing'));
19308 }
19309
19310 var rev$$1;
19311 if (!opts.rev) {
19312 rev$$1 = getWinningRev(metadata);
19313 var deleted = getIsDeleted(metadata, rev$$1);
19314 if (deleted) {
19315 return callback(createError(MISSING_DOC, "deleted"));
19316 }
19317 } else {
19318 rev$$1 = opts.latest ? latest(opts.rev, metadata) : opts.rev;
19319 }
19320
19321 var seq = metadata.rev_map[rev$$1];
19322
19323 stores.bySeqStore.get(formatSeq(seq), function (err, doc) {
19324 if (!doc) {
19325 return callback(createError(MISSING_DOC));
19326 }
19327 /* istanbul ignore if */
19328 if ('_id' in doc && doc._id !== metadata.id) {
19329 // this failing implies something very wrong
19330 return callback(new Error('wrong doc returned'));
19331 }
19332 doc._id = metadata.id;
19333 if ('_rev' in doc) {
19334 /* istanbul ignore if */
19335 if (doc._rev !== rev$$1) {
19336 // this failing implies something very wrong
19337 return callback(new Error('wrong doc returned'));
19338 }
19339 } else {
19340 // we didn't always store this
19341 doc._rev = rev$$1;
19342 }
19343 return callback(null, {doc: doc, metadata: metadata});
19344 });
19345 });
19346 });
19347
19348 // not technically part of the spec, but if putAttachment has its own
19349 // method...
19350 api._getAttachment = function (docId, attachId, attachment, opts, callback) {
19351 var digest = attachment.digest;
19352 var type = attachment.content_type;
19353
19354 stores.binaryStore.get(digest, function (err, attach) {
19355 if (err) {
19356 /* istanbul ignore if */
19357 if (err.name !== 'NotFoundError') {
19358 return callback(err);
19359 }
19360 // Empty attachment
19361 return callback(null, opts.binary ? createEmptyBlobOrBuffer(type) : '');
19362 }
19363
19364 if (opts.binary) {
19365 callback(null, readAsBlobOrBuffer(attach, type));
19366 } else {
19367 callback(null, attach.toString('base64'));
19368 }
19369 });
19370 };
19371
19372 api._bulkDocs = writeLock(function (req, opts, callback) {
19373 var newEdits = opts.new_edits;
19374 var results = new Array(req.docs.length);
19375 var fetchedDocs = new ExportedMap();
19376 var stemmedRevs = new ExportedMap();
19377
19378 var txn = new LevelTransaction();
19379 var docCountDelta = 0;
19380 var newUpdateSeq = db._updateSeq;
19381
19382 // parse the docs and give each a sequence number
19383 var userDocs = req.docs;
19384 var docInfos = userDocs.map(function (doc) {
19385 if (doc._id && isLocalId(doc._id)) {
19386 return doc;
19387 }
19388 var newDoc = parseDoc(doc, newEdits, api.__opts);
19389
19390 if (newDoc.metadata && !newDoc.metadata.rev_map) {
19391 newDoc.metadata.rev_map = {};
19392 }
19393
19394 return newDoc;
19395 });
19396 var infoErrors = docInfos.filter(function (doc) {
19397 return doc.error;
19398 });
19399
19400 if (infoErrors.length) {
19401 return callback(infoErrors[0]);
19402 }
19403
19404 // verify any stub attachments as a precondition test
19405
19406 function verifyAttachment(digest, callback) {
19407 txn.get(stores.attachmentStore, digest, function (levelErr) {
19408 if (levelErr) {
19409 var err = createError(MISSING_STUB,
19410 'unknown stub attachment with digest ' +
19411 digest);
19412 callback(err);
19413 } else {
19414 callback();
19415 }
19416 });
19417 }
19418
19419 function verifyAttachments(finish) {
19420 var digests = [];
19421 userDocs.forEach(function (doc) {
19422 if (doc && doc._attachments) {
19423 Object.keys(doc._attachments).forEach(function (filename) {
19424 var att = doc._attachments[filename];
19425 if (att.stub) {
19426 digests.push(att.digest);
19427 }
19428 });
19429 }
19430 });
19431 if (!digests.length) {
19432 return finish();
19433 }
19434 var numDone = 0;
19435 var err;
19436
19437 digests.forEach(function (digest) {
19438 verifyAttachment(digest, function (attErr) {
19439 if (attErr && !err) {
19440 err = attErr;
19441 }
19442
19443 if (++numDone === digests.length) {
19444 finish(err);
19445 }
19446 });
19447 });
19448 }
19449
19450 function fetchExistingDocs(finish) {
19451 var numDone = 0;
19452 var overallErr;
19453 function checkDone() {
19454 if (++numDone === userDocs.length) {
19455 return finish(overallErr);
19456 }
19457 }
19458
19459 userDocs.forEach(function (doc) {
19460 if (doc._id && isLocalId(doc._id)) {
19461 // skip local docs
19462 return checkDone();
19463 }
19464 txn.get(stores.docStore, doc._id, function (err, info) {
19465 if (err) {
19466 /* istanbul ignore if */
19467 if (err.name !== 'NotFoundError') {
19468 overallErr = err;
19469 }
19470 } else {
19471 fetchedDocs.set(doc._id, info);
19472 }
19473 checkDone();
19474 });
19475 });
19476 }
19477
19478 function compact(revsMap, callback) {
19479 var promise = Promise.resolve();
19480 revsMap.forEach(function (revs, docId) {
19481 // TODO: parallelize, for now need to be sequential to
19482 // pass orphaned attachment tests
19483 promise = promise.then(function () {
19484 return new Promise(function (resolve, reject) {
19485 api._doCompactionNoLock(docId, revs, {ctx: txn}, function (err) {
19486 /* istanbul ignore if */
19487 if (err) {
19488 return reject(err);
19489 }
19490 resolve();
19491 });
19492 });
19493 });
19494 });
19495
19496 promise.then(function () {
19497 callback();
19498 }, callback);
19499 }
19500
19501 function autoCompact(callback) {
19502 var revsMap = new ExportedMap();
19503 fetchedDocs.forEach(function (metadata, docId) {
19504 revsMap.set(docId, compactTree(metadata));
19505 });
19506 compact(revsMap, callback);
19507 }
19508
19509 function finish() {
19510 compact(stemmedRevs, function (error) {
19511 /* istanbul ignore if */
19512 if (error) {
19513 complete(error);
19514 }
19515 if (api.auto_compaction) {
19516 return autoCompact(complete);
19517 }
19518 complete();
19519 });
19520 }
19521
19522 function writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
19523 isUpdate, delta, resultsIdx, callback2) {
19524 docCountDelta += delta;
19525
19526 var err = null;
19527 var recv = 0;
19528
19529 docInfo.metadata.winningRev = winningRev$$1;
19530 docInfo.metadata.deleted = winningRevIsDeleted;
19531
19532 docInfo.data._id = docInfo.metadata.id;
19533 docInfo.data._rev = docInfo.metadata.rev;
19534
19535 if (newRevIsDeleted) {
19536 docInfo.data._deleted = true;
19537 }
19538
19539 if (docInfo.stemmedRevs.length) {
19540 stemmedRevs.set(docInfo.metadata.id, docInfo.stemmedRevs);
19541 }
19542
19543 var attachments = docInfo.data._attachments ?
19544 Object.keys(docInfo.data._attachments) :
19545 [];
19546
19547 function attachmentSaved(attachmentErr) {
19548 recv++;
19549 if (!err) {
19550 /* istanbul ignore if */
19551 if (attachmentErr) {
19552 err = attachmentErr;
19553 callback2(err);
19554 } else if (recv === attachments.length) {
19555 finish();
19556 }
19557 }
19558 }
19559
19560 function onMD5Load(doc, key, data, attachmentSaved) {
19561 return function (result) {
19562 saveAttachment(doc, MD5_PREFIX + result, key, data, attachmentSaved);
19563 };
19564 }
19565
19566 function doMD5(doc, key, attachmentSaved) {
19567 return function (data) {
19568 binaryMd5(data, onMD5Load(doc, key, data, attachmentSaved));
19569 };
19570 }
19571
19572 for (var i = 0; i < attachments.length; i++) {
19573 var key = attachments[i];
19574 var att = docInfo.data._attachments[key];
19575
19576 if (att.stub) {
19577 // still need to update the refs mapping
19578 var id = docInfo.data._id;
19579 var rev$$1 = docInfo.data._rev;
19580 saveAttachmentRefs(id, rev$$1, att.digest, attachmentSaved);
19581 continue;
19582 }
19583 var data;
19584 if (typeof att.data === 'string') {
19585 // input is assumed to be a base64 string
19586 try {
19587 data = thisAtob(att.data);
19588 } catch (e) {
19589 callback(createError(BAD_ARG,
19590 'Attachment is not a valid base64 string'));
19591 return;
19592 }
19593 doMD5(docInfo, key, attachmentSaved)(data);
19594 } else {
19595 prepareAttachmentForStorage(att.data,
19596 doMD5(docInfo, key, attachmentSaved));
19597 }
19598 }
19599
19600 function finish() {
19601 var seq = docInfo.metadata.rev_map[docInfo.metadata.rev];
19602 /* istanbul ignore if */
19603 if (seq) {
19604 // check that there aren't any existing revisions with the same
19605 // revision id, else we shouldn't do anything
19606 return callback2();
19607 }
19608 seq = ++newUpdateSeq;
19609 docInfo.metadata.rev_map[docInfo.metadata.rev] =
19610 docInfo.metadata.seq = seq;
19611 var seqKey = formatSeq(seq);
19612 var batch = [{
19613 key: seqKey,
19614 value: docInfo.data,
19615 prefix: stores.bySeqStore,
19616 type: 'put'
19617 }, {
19618 key: docInfo.metadata.id,
19619 value: docInfo.metadata,
19620 prefix: stores.docStore,
19621 type: 'put'
19622 }];
19623 txn.batch(batch);
19624 results[resultsIdx] = {
19625 ok: true,
19626 id: docInfo.metadata.id,
19627 rev: docInfo.metadata.rev
19628 };
19629 fetchedDocs.set(docInfo.metadata.id, docInfo.metadata);
19630 callback2();
19631 }
19632
19633 if (!attachments.length) {
19634 finish();
19635 }
19636 }
19637
19638 // attachments are queued per-digest, otherwise the refs could be
19639 // overwritten by concurrent writes in the same bulkDocs session
19640 var attachmentQueues = {};
19641
19642 function saveAttachmentRefs(id, rev$$1, digest, callback) {
19643
19644 function fetchAtt() {
19645 return new Promise(function (resolve, reject) {
19646 txn.get(stores.attachmentStore, digest, function (err, oldAtt) {
19647 /* istanbul ignore if */
19648 if (err && err.name !== 'NotFoundError') {
19649 return reject(err);
19650 }
19651 resolve(oldAtt);
19652 });
19653 });
19654 }
19655
19656 function saveAtt(oldAtt) {
19657 var ref = [id, rev$$1].join('@');
19658 var newAtt = {};
19659
19660 if (oldAtt) {
19661 if (oldAtt.refs) {
19662 // only update references if this attachment already has them
19663 // since we cannot migrate old style attachments here without
19664 // doing a full db scan for references
19665 newAtt.refs = oldAtt.refs;
19666 newAtt.refs[ref] = true;
19667 }
19668 } else {
19669 newAtt.refs = {};
19670 newAtt.refs[ref] = true;
19671 }
19672
19673 return new Promise(function (resolve) {
19674 txn.batch([{
19675 type: 'put',
19676 prefix: stores.attachmentStore,
19677 key: digest,
19678 value: newAtt
19679 }]);
19680 resolve(!oldAtt);
19681 });
19682 }
19683
19684 // put attachments in a per-digest queue, to avoid two docs with the same
19685 // attachment overwriting each other
19686 var queue = attachmentQueues[digest] || Promise.resolve();
19687 attachmentQueues[digest] = queue.then(function () {
19688 return fetchAtt().then(saveAtt).then(function (isNewAttachment) {
19689 callback(null, isNewAttachment);
19690 }, callback);
19691 });
19692 }
19693
19694 function saveAttachment(docInfo, digest, key, data, callback) {
19695 var att = docInfo.data._attachments[key];
19696 delete att.data;
19697 att.digest = digest;
19698 att.length = data.length;
19699 var id = docInfo.metadata.id;
19700 var rev$$1 = docInfo.metadata.rev;
19701 att.revpos = parseInt(rev$$1, 10);
19702
19703 saveAttachmentRefs(id, rev$$1, digest, function (err, isNewAttachment) {
19704 /* istanbul ignore if */
19705 if (err) {
19706 return callback(err);
19707 }
19708 // do not try to store empty attachments
19709 if (data.length === 0) {
19710 return callback(err);
19711 }
19712 if (!isNewAttachment) {
19713 // small optimization - don't bother writing it again
19714 return callback(err);
19715 }
19716 txn.batch([{
19717 type: 'put',
19718 prefix: stores.binaryStore,
19719 key: digest,
19720 value: bufferFrom(data, 'binary')
19721 }]);
19722 callback();
19723 });
19724 }
19725
19726 function complete(err) {
19727 /* istanbul ignore if */
19728 if (err) {
19729 return immediate(function () {
19730 callback(err);
19731 });
19732 }
19733 txn.batch([
19734 {
19735 prefix: stores.metaStore,
19736 type: 'put',
19737 key: UPDATE_SEQ_KEY,
19738 value: newUpdateSeq
19739 },
19740 {
19741 prefix: stores.metaStore,
19742 type: 'put',
19743 key: DOC_COUNT_KEY,
19744 value: db._docCount + docCountDelta
19745 }
19746 ]);
19747 txn.execute(db, function (err) {
19748 /* istanbul ignore if */
19749 if (err) {
19750 return callback(err);
19751 }
19752 db._docCount += docCountDelta;
19753 db._updateSeq = newUpdateSeq;
19754 levelChanges.notify(name);
19755 immediate(function () {
19756 callback(null, results);
19757 });
19758 });
19759 }
19760
19761 if (!docInfos.length) {
19762 return callback(null, []);
19763 }
19764
19765 verifyAttachments(function (err) {
19766 if (err) {
19767 return callback(err);
19768 }
19769 fetchExistingDocs(function (err) {
19770 /* istanbul ignore if */
19771 if (err) {
19772 return callback(err);
19773 }
19774 processDocs(revLimit, docInfos, api, fetchedDocs, txn, results,
19775 writeDoc, opts, finish);
19776 });
19777 });
19778 });
19779 api._allDocs = function (opts, callback) {
19780 if ('keys' in opts) {
19781 return allDocsKeysQuery(this, opts);
19782 }
19783 return readLock(function (opts, callback) {
19784 opts = clone(opts);
19785 countDocs(function (err, docCount) {
19786 /* istanbul ignore if */
19787 if (err) {
19788 return callback(err);
19789 }
19790 var readstreamOpts = {};
19791 var skip = opts.skip || 0;
19792 if (opts.startkey) {
19793 readstreamOpts.gte = opts.startkey;
19794 }
19795 if (opts.endkey) {
19796 readstreamOpts.lte = opts.endkey;
19797 }
19798 if (opts.key) {
19799 readstreamOpts.gte = readstreamOpts.lte = opts.key;
19800 }
19801 if (opts.descending) {
19802 readstreamOpts.reverse = true;
19803 // switch start and ends
19804 var tmp = readstreamOpts.lte;
19805 readstreamOpts.lte = readstreamOpts.gte;
19806 readstreamOpts.gte = tmp;
19807 }
19808 var limit;
19809 if (typeof opts.limit === 'number') {
19810 limit = opts.limit;
19811 }
19812 if (limit === 0 ||
19813 ('gte' in readstreamOpts && 'lte' in readstreamOpts &&
19814 readstreamOpts.gte > readstreamOpts.lte)) {
19815 // should return 0 results when start is greater than end.
19816 // normally level would "fix" this for us by reversing the order,
19817 // so short-circuit instead
19818 var returnVal = {
19819 total_rows: docCount,
19820 offset: opts.skip,
19821 rows: []
19822 };
19823 /* istanbul ignore if */
19824 if (opts.update_seq) {
19825 returnVal.update_seq = db._updateSeq;
19826 }
19827 return callback(null, returnVal);
19828 }
19829 var results = [];
19830 var docstream = stores.docStore.readStream(readstreamOpts);
19831
19832 var throughStream = through2.obj(function (entry, _, next) {
19833 var metadata = entry.value;
19834 // winningRev and deleted are performance-killers, but
19835 // in newer versions of PouchDB, they are cached on the metadata
19836 var winningRev$$1 = getWinningRev(metadata);
19837 var deleted = getIsDeleted(metadata, winningRev$$1);
19838 if (!deleted) {
19839 if (skip-- > 0) {
19840 next();
19841 return;
19842 } else if (typeof limit === 'number' && limit-- <= 0) {
19843 docstream.unpipe();
19844 docstream.destroy();
19845 next();
19846 return;
19847 }
19848 } else if (opts.deleted !== 'ok') {
19849 next();
19850 return;
19851 }
19852 function allDocsInner(data) {
19853 var doc = {
19854 id: metadata.id,
19855 key: metadata.id,
19856 value: {
19857 rev: winningRev$$1
19858 }
19859 };
19860 if (opts.include_docs) {
19861 doc.doc = data;
19862 doc.doc._rev = doc.value.rev;
19863 if (opts.conflicts) {
19864 var conflicts = collectConflicts(metadata);
19865 if (conflicts.length) {
19866 doc.doc._conflicts = conflicts;
19867 }
19868 }
19869 for (var att in doc.doc._attachments) {
19870 if (doc.doc._attachments.hasOwnProperty(att)) {
19871 doc.doc._attachments[att].stub = true;
19872 }
19873 }
19874 }
19875 if (opts.inclusive_end === false && metadata.id === opts.endkey) {
19876 return next();
19877 } else if (deleted) {
19878 if (opts.deleted === 'ok') {
19879 doc.value.deleted = true;
19880 doc.doc = null;
19881 } else {
19882 /* istanbul ignore next */
19883 return next();
19884 }
19885 }
19886 results.push(doc);
19887 next();
19888 }
19889 if (opts.include_docs) {
19890 var seq = metadata.rev_map[winningRev$$1];
19891 stores.bySeqStore.get(formatSeq(seq), function (err, data) {
19892 allDocsInner(data);
19893 });
19894 }
19895 else {
19896 allDocsInner();
19897 }
19898 }, function (next) {
19899 Promise.resolve().then(function () {
19900 if (opts.include_docs && opts.attachments) {
19901 return fetchAttachments(results, stores, opts);
19902 }
19903 }).then(function () {
19904 var returnVal = {
19905 total_rows: docCount,
19906 offset: opts.skip,
19907 rows: results
19908 };
19909
19910 /* istanbul ignore if */
19911 if (opts.update_seq) {
19912 returnVal.update_seq = db._updateSeq;
19913 }
19914 callback(null, returnVal);
19915 }, callback);
19916 next();
19917 }).on('unpipe', function () {
19918 throughStream.end();
19919 });
19920
19921 docstream.on('error', callback);
19922
19923 docstream.pipe(throughStream);
19924 });
19925 })(opts, callback);
19926 };
19927
19928 api._changes = function (opts) {
19929 opts = clone(opts);
19930
19931 if (opts.continuous) {
19932 var id = name + ':' + uuid();
19933 levelChanges.addListener(name, id, api, opts);
19934 levelChanges.notify(name);
19935 return {
19936 cancel: function () {
19937 levelChanges.removeListener(name, id);
19938 }
19939 };
19940 }
19941
19942 var descending = opts.descending;
19943 var results = [];
19944 var lastSeq = opts.since || 0;
19945 var called = 0;
19946 var streamOpts = {
19947 reverse: descending
19948 };
19949 var limit;
19950 if ('limit' in opts && opts.limit > 0) {
19951 limit = opts.limit;
19952 }
19953 if (!streamOpts.reverse) {
19954 streamOpts.start = formatSeq(opts.since || 0);
19955 }
19956
19957 var docIds = opts.doc_ids && new ExportedSet(opts.doc_ids);
19958 var filter = filterChange(opts);
19959 var docIdsToMetadata = new ExportedMap();
19960
19961 function complete() {
19962 opts.done = true;
19963 if (opts.return_docs && opts.limit) {
19964 /* istanbul ignore if */
19965 if (opts.limit < results.length) {
19966 results.length = opts.limit;
19967 }
19968 }
19969 changeStream.unpipe(throughStream);
19970 changeStream.destroy();
19971 if (!opts.continuous && !opts.cancelled) {
19972 if (opts.include_docs && opts.attachments && opts.return_docs) {
19973 fetchAttachments(results, stores, opts).then(function () {
19974 opts.complete(null, {results: results, last_seq: lastSeq});
19975 });
19976 } else {
19977 opts.complete(null, {results: results, last_seq: lastSeq});
19978 }
19979 }
19980 }
19981 var changeStream = stores.bySeqStore.readStream(streamOpts);
19982 var throughStream = through2.obj(function (data, _, next) {
19983 if (limit && called >= limit) {
19984 complete();
19985 return next();
19986 }
19987 if (opts.cancelled || opts.done) {
19988 return next();
19989 }
19990
19991 var seq = parseSeq(data.key);
19992 var doc = data.value;
19993
19994 if (seq === opts.since && !descending) {
19995 // couchdb ignores `since` if descending=true
19996 return next();
19997 }
19998
19999 if (docIds && !docIds.has(doc._id)) {
20000 return next();
20001 }
20002
20003 var metadata;
20004
20005 function onGetMetadata(metadata) {
20006 var winningRev$$1 = getWinningRev(metadata);
20007
20008 function onGetWinningDoc(winningDoc) {
20009
20010 var change = opts.processChange(winningDoc, metadata, opts);
20011 change.seq = metadata.seq;
20012
20013 var filtered = filter(change);
20014 if (typeof filtered === 'object') {
20015 return opts.complete(filtered);
20016 }
20017
20018 if (filtered) {
20019 called++;
20020
20021 if (opts.attachments && opts.include_docs) {
20022 // fetch attachment immediately for the benefit
20023 // of live listeners
20024 fetchAttachments([change], stores, opts).then(function () {
20025 opts.onChange(change);
20026 });
20027 } else {
20028 opts.onChange(change);
20029 }
20030
20031 if (opts.return_docs) {
20032 results.push(change);
20033 }
20034 }
20035 next();
20036 }
20037
20038 if (metadata.seq !== seq) {
20039 // some other seq is later
20040 return next();
20041 }
20042
20043 lastSeq = seq;
20044
20045 if (winningRev$$1 === doc._rev) {
20046 return onGetWinningDoc(doc);
20047 }
20048
20049 // fetch the winner
20050
20051 var winningSeq = metadata.rev_map[winningRev$$1];
20052
20053 stores.bySeqStore.get(formatSeq(winningSeq), function (err, doc) {
20054 onGetWinningDoc(doc);
20055 });
20056 }
20057
20058 metadata = docIdsToMetadata.get(doc._id);
20059 if (metadata) { // cached
20060 return onGetMetadata(metadata);
20061 }
20062 // metadata not cached, have to go fetch it
20063 stores.docStore.get(doc._id, function (err, metadata) {
20064 /* istanbul ignore if */
20065 if (opts.cancelled || opts.done || db.isClosed() ||
20066 isLocalId(metadata.id)) {
20067 return next();
20068 }
20069 docIdsToMetadata.set(doc._id, metadata);
20070 onGetMetadata(metadata);
20071 });
20072 }, function (next) {
20073 if (opts.cancelled) {
20074 return next();
20075 }
20076 if (opts.return_docs && opts.limit) {
20077 /* istanbul ignore if */
20078 if (opts.limit < results.length) {
20079 results.length = opts.limit;
20080 }
20081 }
20082
20083 next();
20084 }).on('unpipe', function () {
20085 throughStream.end();
20086 complete();
20087 });
20088 changeStream.pipe(throughStream);
20089 return {
20090 cancel: function () {
20091 opts.cancelled = true;
20092 complete();
20093 }
20094 };
20095 };
20096
20097 api._close = function (callback) {
20098 /* istanbul ignore if */
20099 if (db.isClosed()) {
20100 return callback(createError(NOT_OPEN));
20101 }
20102 db.close(function (err) {
20103 /* istanbul ignore if */
20104 if (err) {
20105 callback(err);
20106 } else {
20107 dbStore["delete"](name);
20108 callback();
20109 }
20110 });
20111 };
20112
20113 api._getRevisionTree = function (docId, callback) {
20114 stores.docStore.get(docId, function (err, metadata) {
20115 if (err) {
20116 callback(createError(MISSING_DOC));
20117 } else {
20118 callback(null, metadata.rev_tree);
20119 }
20120 });
20121 };
20122
20123 api._doCompaction = writeLock(function (docId, revs, opts, callback) {
20124 api._doCompactionNoLock(docId, revs, opts, callback);
20125 });
20126
20127 // the NoLock version is for use by bulkDocs
20128 api._doCompactionNoLock = function (docId, revs, opts, callback) {
20129 if (typeof opts === 'function') {
20130 callback = opts;
20131 opts = {};
20132 }
20133
20134 if (!revs.length) {
20135 return callback();
20136 }
20137 var txn = opts.ctx || new LevelTransaction();
20138
20139 txn.get(stores.docStore, docId, function (err, metadata) {
20140 /* istanbul ignore if */
20141 if (err) {
20142 return callback(err);
20143 }
20144 var seqs = revs.map(function (rev$$1) {
20145 var seq = metadata.rev_map[rev$$1];
20146 delete metadata.rev_map[rev$$1];
20147 return seq;
20148 });
20149 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
20150 revHash, ctx, opts) {
20151 var rev$$1 = pos + '-' + revHash;
20152 if (revs.indexOf(rev$$1) !== -1) {
20153 opts.status = 'missing';
20154 }
20155 });
20156
20157 var batch = [];
20158 batch.push({
20159 key: metadata.id,
20160 value: metadata,
20161 type: 'put',
20162 prefix: stores.docStore
20163 });
20164
20165 var digestMap = {};
20166 var numDone = 0;
20167 var overallErr;
20168 function checkDone(err) {
20169 /* istanbul ignore if */
20170 if (err) {
20171 overallErr = err;
20172 }
20173 if (++numDone === revs.length) { // done
20174 /* istanbul ignore if */
20175 if (overallErr) {
20176 return callback(overallErr);
20177 }
20178 deleteOrphanedAttachments();
20179 }
20180 }
20181
20182 function finish(err) {
20183 /* istanbul ignore if */
20184 if (err) {
20185 return callback(err);
20186 }
20187 txn.batch(batch);
20188 if (opts.ctx) {
20189 // don't execute immediately
20190 return callback();
20191 }
20192 txn.execute(db, callback);
20193 }
20194
20195 function deleteOrphanedAttachments() {
20196 var possiblyOrphanedAttachments = Object.keys(digestMap);
20197 if (!possiblyOrphanedAttachments.length) {
20198 return finish();
20199 }
20200 var numDone = 0;
20201 var overallErr;
20202 function checkDone(err) {
20203 /* istanbul ignore if */
20204 if (err) {
20205 overallErr = err;
20206 }
20207 if (++numDone === possiblyOrphanedAttachments.length) {
20208 finish(overallErr);
20209 }
20210 }
20211 var refsToDelete = new ExportedMap();
20212 revs.forEach(function (rev$$1) {
20213 refsToDelete.set(docId + '@' + rev$$1, true);
20214 });
20215 possiblyOrphanedAttachments.forEach(function (digest) {
20216 txn.get(stores.attachmentStore, digest, function (err, attData) {
20217 /* istanbul ignore if */
20218 if (err) {
20219 if (err.name === 'NotFoundError') {
20220 return checkDone();
20221 } else {
20222 return checkDone(err);
20223 }
20224 }
20225 var refs = Object.keys(attData.refs || {}).filter(function (ref) {
20226 return !refsToDelete.has(ref);
20227 });
20228 var newRefs = {};
20229 refs.forEach(function (ref) {
20230 newRefs[ref] = true;
20231 });
20232 if (refs.length) { // not orphaned
20233 batch.push({
20234 key: digest,
20235 type: 'put',
20236 value: {refs: newRefs},
20237 prefix: stores.attachmentStore
20238 });
20239 } else { // orphaned, can safely delete
20240 batch = batch.concat([{
20241 key: digest,
20242 type: 'del',
20243 prefix: stores.attachmentStore
20244 }, {
20245 key: digest,
20246 type: 'del',
20247 prefix: stores.binaryStore
20248 }]);
20249 }
20250 checkDone();
20251 });
20252 });
20253 }
20254
20255 seqs.forEach(function (seq) {
20256 batch.push({
20257 key: formatSeq(seq),
20258 type: 'del',
20259 prefix: stores.bySeqStore
20260 });
20261 txn.get(stores.bySeqStore, formatSeq(seq), function (err, doc) {
20262 /* istanbul ignore if */
20263 if (err) {
20264 if (err.name === 'NotFoundError') {
20265 return checkDone();
20266 } else {
20267 return checkDone(err);
20268 }
20269 }
20270 var atts = Object.keys(doc._attachments || {});
20271 atts.forEach(function (attName) {
20272 var digest = doc._attachments[attName].digest;
20273 digestMap[digest] = true;
20274 });
20275 checkDone();
20276 });
20277 });
20278 });
20279 };
20280
20281 api._getLocal = function (id, callback) {
20282 stores.localStore.get(id, function (err, doc) {
20283 if (err) {
20284 callback(createError(MISSING_DOC));
20285 } else {
20286 callback(null, doc);
20287 }
20288 });
20289 };
20290
20291 api._putLocal = function (doc, opts, callback) {
20292 if (typeof opts === 'function') {
20293 callback = opts;
20294 opts = {};
20295 }
20296 if (opts.ctx) {
20297 api._putLocalNoLock(doc, opts, callback);
20298 } else {
20299 api._putLocalWithLock(doc, opts, callback);
20300 }
20301 };
20302
20303 api._putLocalWithLock = writeLock(function (doc, opts, callback) {
20304 api._putLocalNoLock(doc, opts, callback);
20305 });
20306
20307 // the NoLock version is for use by bulkDocs
20308 api._putLocalNoLock = function (doc, opts, callback) {
20309 delete doc._revisions; // ignore this, trust the rev
20310 var oldRev = doc._rev;
20311 var id = doc._id;
20312
20313 var txn = opts.ctx || new LevelTransaction();
20314
20315 txn.get(stores.localStore, id, function (err, resp) {
20316 if (err && oldRev) {
20317 return callback(createError(REV_CONFLICT));
20318 }
20319 if (resp && resp._rev !== oldRev) {
20320 return callback(createError(REV_CONFLICT));
20321 }
20322 doc._rev =
20323 oldRev ? '0-' + (parseInt(oldRev.split('-')[1], 10) + 1) : '0-1';
20324 var batch = [
20325 {
20326 type: 'put',
20327 prefix: stores.localStore,
20328 key: id,
20329 value: doc
20330 }
20331 ];
20332
20333 txn.batch(batch);
20334 var ret = {ok: true, id: doc._id, rev: doc._rev};
20335
20336 if (opts.ctx) {
20337 // don't execute immediately
20338 return callback(null, ret);
20339 }
20340 txn.execute(db, function (err) {
20341 /* istanbul ignore if */
20342 if (err) {
20343 return callback(err);
20344 }
20345 callback(null, ret);
20346 });
20347 });
20348 };
20349
20350 api._removeLocal = function (doc, opts, callback) {
20351 if (typeof opts === 'function') {
20352 callback = opts;
20353 opts = {};
20354 }
20355 if (opts.ctx) {
20356 api._removeLocalNoLock(doc, opts, callback);
20357 } else {
20358 api._removeLocalWithLock(doc, opts, callback);
20359 }
20360 };
20361
20362 api._removeLocalWithLock = writeLock(function (doc, opts, callback) {
20363 api._removeLocalNoLock(doc, opts, callback);
20364 });
20365
20366 // the NoLock version is for use by bulkDocs
20367 api._removeLocalNoLock = function (doc, opts, callback) {
20368 var txn = opts.ctx || new LevelTransaction();
20369 txn.get(stores.localStore, doc._id, function (err, resp) {
20370 if (err) {
20371 /* istanbul ignore if */
20372 if (err.name !== 'NotFoundError') {
20373 return callback(err);
20374 } else {
20375 return callback(createError(MISSING_DOC));
20376 }
20377 }
20378 if (resp._rev !== doc._rev) {
20379 return callback(createError(REV_CONFLICT));
20380 }
20381 txn.batch([{
20382 prefix: stores.localStore,
20383 type: 'del',
20384 key: doc._id
20385 }]);
20386 var ret = {ok: true, id: doc._id, rev: '0-0'};
20387 if (opts.ctx) {
20388 // don't execute immediately
20389 return callback(null, ret);
20390 }
20391 txn.execute(db, function (err) {
20392 /* istanbul ignore if */
20393 if (err) {
20394 return callback(err);
20395 }
20396 callback(null, ret);
20397 });
20398 });
20399 };
20400
20401 // close and delete open leveldb stores
20402 api._destroy = function (opts, callback) {
20403 var dbStore;
20404 var leveldownName = functionName(leveldown);
20405 /* istanbul ignore else */
20406 if (dbStores.has(leveldownName)) {
20407 dbStore = dbStores.get(leveldownName);
20408 } else {
20409 return callDestroy(name, callback);
20410 }
20411
20412 /* istanbul ignore else */
20413 if (dbStore.has(name)) {
20414 levelChanges.removeAllListeners(name);
20415
20416 dbStore.get(name).close(function () {
20417 dbStore["delete"](name);
20418 callDestroy(name, callback);
20419 });
20420 } else {
20421 callDestroy(name, callback);
20422 }
20423 };
20424 function callDestroy(name, cb) {
20425 // May not exist if leveldown is backed by memory adapter
20426 /* istanbul ignore else */
20427 if ('destroy' in leveldown) {
20428 leveldown.destroy(name, cb);
20429 } else {
20430 cb(null);
20431 }
20432 }
20433}
20434
20435function LocalStoragePouch(opts, callback) {
20436 var _opts = $inject_Object_assign({
20437 db: localstoragedown
20438 }, opts);
20439
20440 LevelPouch.call(this, _opts, callback);
20441}
20442
20443// overrides for normal LevelDB behavior on Node
20444LocalStoragePouch.valid = function () {
20445 return typeof localStorage !== 'undefined';
20446};
20447LocalStoragePouch.use_prefix = true;
20448
20449function LocalStoragePouchPlugin (PouchDB) {
20450 PouchDB.adapter('localstorage', LocalStoragePouch, true);
20451}
20452
20453/* global PouchDB */
20454
20455if (typeof PouchDB === 'undefined') {
20456 guardedConsole('error', 'localstorage adapter plugin error: ' +
20457 'Cannot find global "PouchDB" object! ' +
20458 'Did you remember to include pouchdb.js?');
20459} else {
20460 PouchDB.plugin(LocalStoragePouchPlugin);
20461}
20462
20463}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
20464},{"11":11,"112":112,"118":118,"123":123,"22":22,"25":25,"30":30,"31":31,"34":34,"4":4,"56":56,"59":59,"66":66,"77":77,"79":79}]},{},[125]);
20465
\No newline at end of file