UNPKG

621 kBJavaScriptView Raw
1// PouchDB localStorage plugin 7.3.0
2// Based on localstorage-down: https://github.com/No9/localstorage-down
3//
4// (c) 2012-2022 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){(function (){
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)}).call(this,_dereq_(73))
92},{"73":73}],2:[function(_dereq_,module,exports){
93(function (process){(function (){
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)}).call(this,_dereq_(73))
145},{"73":73}],3:[function(_dereq_,module,exports){
146(function (Buffer,process){(function (){
147/* Copyright (c) 2013 Rod Vagg, MIT License */
148
149var xtend = _dereq_(4)
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)}).call(this,{"isBuffer":_dereq_(38)},_dereq_(73))
407},{"1":1,"2":2,"38":38,"4":4,"73":73}],4:[function(_dereq_,module,exports){
408module.exports = extend
409
410function extend() {
411 var target = {}
412
413 for (var i = 0; i < arguments.length; i++) {
414 var source = arguments[i]
415
416 for (var key in source) {
417 if (source.hasOwnProperty(key)) {
418 target[key] = source[key]
419 }
420 }
421 }
422
423 return target
424}
425
426},{}],5:[function(_dereq_,module,exports){
427'use strict';
428
429module.exports = argsArray;
430
431function argsArray(fun) {
432 return function () {
433 var len = arguments.length;
434 if (len) {
435 var args = [];
436 var i = -1;
437 while (++i < len) {
438 args[i] = arguments[i];
439 }
440 return fun.call(this, args);
441 } else {
442 return fun.call(this, []);
443 }
444 };
445}
446},{}],6:[function(_dereq_,module,exports){
447(function (global){(function (){
448'use strict';
449
450var objectAssign = _dereq_(71);
451
452// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
453// original notice:
454
455/*!
456 * The buffer module from node.js, for the browser.
457 *
458 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
459 * @license MIT
460 */
461function compare(a, b) {
462 if (a === b) {
463 return 0;
464 }
465
466 var x = a.length;
467 var y = b.length;
468
469 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
470 if (a[i] !== b[i]) {
471 x = a[i];
472 y = b[i];
473 break;
474 }
475 }
476
477 if (x < y) {
478 return -1;
479 }
480 if (y < x) {
481 return 1;
482 }
483 return 0;
484}
485function isBuffer(b) {
486 if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
487 return global.Buffer.isBuffer(b);
488 }
489 return !!(b != null && b._isBuffer);
490}
491
492// based on node assert, original notice:
493// NB: The URL to the CommonJS spec is kept just for tradition.
494// node-assert has evolved a lot since then, both in API and behavior.
495
496// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
497//
498// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
499//
500// Originally from narwhal.js (http://narwhaljs.org)
501// Copyright (c) 2009 Thomas Robinson <280north.com>
502//
503// Permission is hereby granted, free of charge, to any person obtaining a copy
504// of this software and associated documentation files (the 'Software'), to
505// deal in the Software without restriction, including without limitation the
506// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
507// sell copies of the Software, and to permit persons to whom the Software is
508// furnished to do so, subject to the following conditions:
509//
510// The above copyright notice and this permission notice shall be included in
511// all copies or substantial portions of the Software.
512//
513// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
514// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
515// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
516// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
517// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
518// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
519
520var util = _dereq_(9);
521var hasOwn = Object.prototype.hasOwnProperty;
522var pSlice = Array.prototype.slice;
523var functionsHaveNames = (function () {
524 return function foo() {}.name === 'foo';
525}());
526function pToString (obj) {
527 return Object.prototype.toString.call(obj);
528}
529function isView(arrbuf) {
530 if (isBuffer(arrbuf)) {
531 return false;
532 }
533 if (typeof global.ArrayBuffer !== 'function') {
534 return false;
535 }
536 if (typeof ArrayBuffer.isView === 'function') {
537 return ArrayBuffer.isView(arrbuf);
538 }
539 if (!arrbuf) {
540 return false;
541 }
542 if (arrbuf instanceof DataView) {
543 return true;
544 }
545 if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
546 return true;
547 }
548 return false;
549}
550// 1. The assert module provides functions that throw
551// AssertionError's when particular conditions are not met. The
552// assert module must conform to the following interface.
553
554var assert = module.exports = ok;
555
556// 2. The AssertionError is defined in assert.
557// new assert.AssertionError({ message: message,
558// actual: actual,
559// expected: expected })
560
561var regex = /\s*function\s+([^\(\s]*)\s*/;
562// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
563function getName(func) {
564 if (!util.isFunction(func)) {
565 return;
566 }
567 if (functionsHaveNames) {
568 return func.name;
569 }
570 var str = func.toString();
571 var match = str.match(regex);
572 return match && match[1];
573}
574assert.AssertionError = function AssertionError(options) {
575 this.name = 'AssertionError';
576 this.actual = options.actual;
577 this.expected = options.expected;
578 this.operator = options.operator;
579 if (options.message) {
580 this.message = options.message;
581 this.generatedMessage = false;
582 } else {
583 this.message = getMessage(this);
584 this.generatedMessage = true;
585 }
586 var stackStartFunction = options.stackStartFunction || fail;
587 if (Error.captureStackTrace) {
588 Error.captureStackTrace(this, stackStartFunction);
589 } else {
590 // non v8 browsers so we can have a stacktrace
591 var err = new Error();
592 if (err.stack) {
593 var out = err.stack;
594
595 // try to strip useless frames
596 var fn_name = getName(stackStartFunction);
597 var idx = out.indexOf('\n' + fn_name);
598 if (idx >= 0) {
599 // once we have located the function frame
600 // we need to strip out everything before it (and its line)
601 var next_line = out.indexOf('\n', idx + 1);
602 out = out.substring(next_line + 1);
603 }
604
605 this.stack = out;
606 }
607 }
608};
609
610// assert.AssertionError instanceof Error
611util.inherits(assert.AssertionError, Error);
612
613function truncate(s, n) {
614 if (typeof s === 'string') {
615 return s.length < n ? s : s.slice(0, n);
616 } else {
617 return s;
618 }
619}
620function inspect(something) {
621 if (functionsHaveNames || !util.isFunction(something)) {
622 return util.inspect(something);
623 }
624 var rawname = getName(something);
625 var name = rawname ? ': ' + rawname : '';
626 return '[Function' + name + ']';
627}
628function getMessage(self) {
629 return truncate(inspect(self.actual), 128) + ' ' +
630 self.operator + ' ' +
631 truncate(inspect(self.expected), 128);
632}
633
634// At present only the three keys mentioned above are used and
635// understood by the spec. Implementations or sub modules can pass
636// other keys to the AssertionError's constructor - they will be
637// ignored.
638
639// 3. All of the following functions must throw an AssertionError
640// when a corresponding condition is not met, with a message that
641// may be undefined if not provided. All assertion methods provide
642// both the actual and expected values to the assertion error for
643// display purposes.
644
645function fail(actual, expected, message, operator, stackStartFunction) {
646 throw new assert.AssertionError({
647 message: message,
648 actual: actual,
649 expected: expected,
650 operator: operator,
651 stackStartFunction: stackStartFunction
652 });
653}
654
655// EXTENSION! allows for well behaved errors defined elsewhere.
656assert.fail = fail;
657
658// 4. Pure assertion tests whether a value is truthy, as determined
659// by !!guard.
660// assert.ok(guard, message_opt);
661// This statement is equivalent to assert.equal(true, !!guard,
662// message_opt);. To test strictly for the value true, use
663// assert.strictEqual(true, guard, message_opt);.
664
665function ok(value, message) {
666 if (!value) fail(value, true, message, '==', assert.ok);
667}
668assert.ok = ok;
669
670// 5. The equality assertion tests shallow, coercive equality with
671// ==.
672// assert.equal(actual, expected, message_opt);
673
674assert.equal = function equal(actual, expected, message) {
675 if (actual != expected) fail(actual, expected, message, '==', assert.equal);
676};
677
678// 6. The non-equality assertion tests for whether two objects are not equal
679// with != assert.notEqual(actual, expected, message_opt);
680
681assert.notEqual = function notEqual(actual, expected, message) {
682 if (actual == expected) {
683 fail(actual, expected, message, '!=', assert.notEqual);
684 }
685};
686
687// 7. The equivalence assertion tests a deep equality relation.
688// assert.deepEqual(actual, expected, message_opt);
689
690assert.deepEqual = function deepEqual(actual, expected, message) {
691 if (!_deepEqual(actual, expected, false)) {
692 fail(actual, expected, message, 'deepEqual', assert.deepEqual);
693 }
694};
695
696assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
697 if (!_deepEqual(actual, expected, true)) {
698 fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
699 }
700};
701
702function _deepEqual(actual, expected, strict, memos) {
703 // 7.1. All identical values are equivalent, as determined by ===.
704 if (actual === expected) {
705 return true;
706 } else if (isBuffer(actual) && isBuffer(expected)) {
707 return compare(actual, expected) === 0;
708
709 // 7.2. If the expected value is a Date object, the actual value is
710 // equivalent if it is also a Date object that refers to the same time.
711 } else if (util.isDate(actual) && util.isDate(expected)) {
712 return actual.getTime() === expected.getTime();
713
714 // 7.3 If the expected value is a RegExp object, the actual value is
715 // equivalent if it is also a RegExp object with the same source and
716 // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
717 } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
718 return actual.source === expected.source &&
719 actual.global === expected.global &&
720 actual.multiline === expected.multiline &&
721 actual.lastIndex === expected.lastIndex &&
722 actual.ignoreCase === expected.ignoreCase;
723
724 // 7.4. Other pairs that do not both pass typeof value == 'object',
725 // equivalence is determined by ==.
726 } else if ((actual === null || typeof actual !== 'object') &&
727 (expected === null || typeof expected !== 'object')) {
728 return strict ? actual === expected : actual == expected;
729
730 // If both values are instances of typed arrays, wrap their underlying
731 // ArrayBuffers in a Buffer each to increase performance
732 // This optimization requires the arrays to have the same type as checked by
733 // Object.prototype.toString (aka pToString). Never perform binary
734 // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
735 // bit patterns are not identical.
736 } else if (isView(actual) && isView(expected) &&
737 pToString(actual) === pToString(expected) &&
738 !(actual instanceof Float32Array ||
739 actual instanceof Float64Array)) {
740 return compare(new Uint8Array(actual.buffer),
741 new Uint8Array(expected.buffer)) === 0;
742
743 // 7.5 For all other Object pairs, including Array objects, equivalence is
744 // determined by having the same number of owned properties (as verified
745 // with Object.prototype.hasOwnProperty.call), the same set of keys
746 // (although not necessarily the same order), equivalent values for every
747 // corresponding key, and an identical 'prototype' property. Note: this
748 // accounts for both named and indexed properties on Arrays.
749 } else if (isBuffer(actual) !== isBuffer(expected)) {
750 return false;
751 } else {
752 memos = memos || {actual: [], expected: []};
753
754 var actualIndex = memos.actual.indexOf(actual);
755 if (actualIndex !== -1) {
756 if (actualIndex === memos.expected.indexOf(expected)) {
757 return true;
758 }
759 }
760
761 memos.actual.push(actual);
762 memos.expected.push(expected);
763
764 return objEquiv(actual, expected, strict, memos);
765 }
766}
767
768function isArguments(object) {
769 return Object.prototype.toString.call(object) == '[object Arguments]';
770}
771
772function objEquiv(a, b, strict, actualVisitedObjects) {
773 if (a === null || a === undefined || b === null || b === undefined)
774 return false;
775 // if one is a primitive, the other must be same
776 if (util.isPrimitive(a) || util.isPrimitive(b))
777 return a === b;
778 if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
779 return false;
780 var aIsArgs = isArguments(a);
781 var bIsArgs = isArguments(b);
782 if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
783 return false;
784 if (aIsArgs) {
785 a = pSlice.call(a);
786 b = pSlice.call(b);
787 return _deepEqual(a, b, strict);
788 }
789 var ka = objectKeys(a);
790 var kb = objectKeys(b);
791 var key, i;
792 // having the same number of owned properties (keys incorporates
793 // hasOwnProperty)
794 if (ka.length !== kb.length)
795 return false;
796 //the same set of keys (although not necessarily the same order),
797 ka.sort();
798 kb.sort();
799 //~~~cheap key test
800 for (i = ka.length - 1; i >= 0; i--) {
801 if (ka[i] !== kb[i])
802 return false;
803 }
804 //equivalent values for every corresponding key, and
805 //~~~possibly expensive deep test
806 for (i = ka.length - 1; i >= 0; i--) {
807 key = ka[i];
808 if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
809 return false;
810 }
811 return true;
812}
813
814// 8. The non-equivalence assertion tests for any deep inequality.
815// assert.notDeepEqual(actual, expected, message_opt);
816
817assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
818 if (_deepEqual(actual, expected, false)) {
819 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
820 }
821};
822
823assert.notDeepStrictEqual = notDeepStrictEqual;
824function notDeepStrictEqual(actual, expected, message) {
825 if (_deepEqual(actual, expected, true)) {
826 fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
827 }
828}
829
830
831// 9. The strict equality assertion tests strict equality, as determined by ===.
832// assert.strictEqual(actual, expected, message_opt);
833
834assert.strictEqual = function strictEqual(actual, expected, message) {
835 if (actual !== expected) {
836 fail(actual, expected, message, '===', assert.strictEqual);
837 }
838};
839
840// 10. The strict non-equality assertion tests for strict inequality, as
841// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
842
843assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
844 if (actual === expected) {
845 fail(actual, expected, message, '!==', assert.notStrictEqual);
846 }
847};
848
849function expectedException(actual, expected) {
850 if (!actual || !expected) {
851 return false;
852 }
853
854 if (Object.prototype.toString.call(expected) == '[object RegExp]') {
855 return expected.test(actual);
856 }
857
858 try {
859 if (actual instanceof expected) {
860 return true;
861 }
862 } catch (e) {
863 // Ignore. The instanceof check doesn't work for arrow functions.
864 }
865
866 if (Error.isPrototypeOf(expected)) {
867 return false;
868 }
869
870 return expected.call({}, actual) === true;
871}
872
873function _tryBlock(block) {
874 var error;
875 try {
876 block();
877 } catch (e) {
878 error = e;
879 }
880 return error;
881}
882
883function _throws(shouldThrow, block, expected, message) {
884 var actual;
885
886 if (typeof block !== 'function') {
887 throw new TypeError('"block" argument must be a function');
888 }
889
890 if (typeof expected === 'string') {
891 message = expected;
892 expected = null;
893 }
894
895 actual = _tryBlock(block);
896
897 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
898 (message ? ' ' + message : '.');
899
900 if (shouldThrow && !actual) {
901 fail(actual, expected, 'Missing expected exception' + message);
902 }
903
904 var userProvidedMessage = typeof message === 'string';
905 var isUnwantedException = !shouldThrow && util.isError(actual);
906 var isUnexpectedException = !shouldThrow && actual && !expected;
907
908 if ((isUnwantedException &&
909 userProvidedMessage &&
910 expectedException(actual, expected)) ||
911 isUnexpectedException) {
912 fail(actual, expected, 'Got unwanted exception' + message);
913 }
914
915 if ((shouldThrow && actual && expected &&
916 !expectedException(actual, expected)) || (!shouldThrow && actual)) {
917 throw actual;
918 }
919}
920
921// 11. Expected to throw an error:
922// assert.throws(block, Error_opt, message_opt);
923
924assert.throws = function(block, /*optional*/error, /*optional*/message) {
925 _throws(true, block, error, message);
926};
927
928// EXTENSION! This is annoying to write outside this module.
929assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
930 _throws(false, block, error, message);
931};
932
933assert.ifError = function(err) { if (err) throw err; };
934
935// Expose a strict only variant of assert
936function strict(value, message) {
937 if (!value) fail(value, true, message, '==', strict);
938}
939assert.strict = objectAssign(strict, assert, {
940 equal: assert.strictEqual,
941 deepEqual: assert.deepStrictEqual,
942 notEqual: assert.notStrictEqual,
943 notDeepEqual: assert.notDeepStrictEqual
944});
945assert.strict.strict = assert.strict;
946
947var objectKeys = Object.keys || function (obj) {
948 var keys = [];
949 for (var key in obj) {
950 if (hasOwn.call(obj, key)) keys.push(key);
951 }
952 return keys;
953};
954
955}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
956},{"71":71,"9":9}],7:[function(_dereq_,module,exports){
957if (typeof Object.create === 'function') {
958 // implementation from standard node.js 'util' module
959 module.exports = function inherits(ctor, superCtor) {
960 ctor.super_ = superCtor
961 ctor.prototype = Object.create(superCtor.prototype, {
962 constructor: {
963 value: ctor,
964 enumerable: false,
965 writable: true,
966 configurable: true
967 }
968 });
969 };
970} else {
971 // old school shim for old browsers
972 module.exports = function inherits(ctor, superCtor) {
973 ctor.super_ = superCtor
974 var TempCtor = function () {}
975 TempCtor.prototype = superCtor.prototype
976 ctor.prototype = new TempCtor()
977 ctor.prototype.constructor = ctor
978 }
979}
980
981},{}],8:[function(_dereq_,module,exports){
982module.exports = function isBuffer(arg) {
983 return arg && typeof arg === 'object'
984 && typeof arg.copy === 'function'
985 && typeof arg.fill === 'function'
986 && typeof arg.readUInt8 === 'function';
987}
988},{}],9:[function(_dereq_,module,exports){
989(function (process,global){(function (){
990// Copyright Joyent, Inc. and other Node contributors.
991//
992// Permission is hereby granted, free of charge, to any person obtaining a
993// copy of this software and associated documentation files (the
994// "Software"), to deal in the Software without restriction, including
995// without limitation the rights to use, copy, modify, merge, publish,
996// distribute, sublicense, and/or sell copies of the Software, and to permit
997// persons to whom the Software is furnished to do so, subject to the
998// following conditions:
999//
1000// The above copyright notice and this permission notice shall be included
1001// in all copies or substantial portions of the Software.
1002//
1003// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1004// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1005// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
1006// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
1007// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
1008// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
1009// USE OR OTHER DEALINGS IN THE SOFTWARE.
1010
1011var formatRegExp = /%[sdj%]/g;
1012exports.format = function(f) {
1013 if (!isString(f)) {
1014 var objects = [];
1015 for (var i = 0; i < arguments.length; i++) {
1016 objects.push(inspect(arguments[i]));
1017 }
1018 return objects.join(' ');
1019 }
1020
1021 var i = 1;
1022 var args = arguments;
1023 var len = args.length;
1024 var str = String(f).replace(formatRegExp, function(x) {
1025 if (x === '%%') return '%';
1026 if (i >= len) return x;
1027 switch (x) {
1028 case '%s': return String(args[i++]);
1029 case '%d': return Number(args[i++]);
1030 case '%j':
1031 try {
1032 return JSON.stringify(args[i++]);
1033 } catch (_) {
1034 return '[Circular]';
1035 }
1036 default:
1037 return x;
1038 }
1039 });
1040 for (var x = args[i]; i < len; x = args[++i]) {
1041 if (isNull(x) || !isObject(x)) {
1042 str += ' ' + x;
1043 } else {
1044 str += ' ' + inspect(x);
1045 }
1046 }
1047 return str;
1048};
1049
1050
1051// Mark that a method should not be used.
1052// Returns a modified function which warns once by default.
1053// If --no-deprecation is set, then it is a no-op.
1054exports.deprecate = function(fn, msg) {
1055 // Allow for deprecating things in the process of starting up.
1056 if (isUndefined(global.process)) {
1057 return function() {
1058 return exports.deprecate(fn, msg).apply(this, arguments);
1059 };
1060 }
1061
1062 if (process.noDeprecation === true) {
1063 return fn;
1064 }
1065
1066 var warned = false;
1067 function deprecated() {
1068 if (!warned) {
1069 if (process.throwDeprecation) {
1070 throw new Error(msg);
1071 } else if (process.traceDeprecation) {
1072 console.trace(msg);
1073 } else {
1074 console.error(msg);
1075 }
1076 warned = true;
1077 }
1078 return fn.apply(this, arguments);
1079 }
1080
1081 return deprecated;
1082};
1083
1084
1085var debugs = {};
1086var debugEnviron;
1087exports.debuglog = function(set) {
1088 if (isUndefined(debugEnviron))
1089 debugEnviron = process.env.NODE_DEBUG || '';
1090 set = set.toUpperCase();
1091 if (!debugs[set]) {
1092 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
1093 var pid = process.pid;
1094 debugs[set] = function() {
1095 var msg = exports.format.apply(exports, arguments);
1096 console.error('%s %d: %s', set, pid, msg);
1097 };
1098 } else {
1099 debugs[set] = function() {};
1100 }
1101 }
1102 return debugs[set];
1103};
1104
1105
1106/**
1107 * Echos the value of a value. Trys to print the value out
1108 * in the best way possible given the different types.
1109 *
1110 * @param {Object} obj The object to print out.
1111 * @param {Object} opts Optional options object that alters the output.
1112 */
1113/* legacy: obj, showHidden, depth, colors*/
1114function inspect(obj, opts) {
1115 // default options
1116 var ctx = {
1117 seen: [],
1118 stylize: stylizeNoColor
1119 };
1120 // legacy...
1121 if (arguments.length >= 3) ctx.depth = arguments[2];
1122 if (arguments.length >= 4) ctx.colors = arguments[3];
1123 if (isBoolean(opts)) {
1124 // legacy...
1125 ctx.showHidden = opts;
1126 } else if (opts) {
1127 // got an "options" object
1128 exports._extend(ctx, opts);
1129 }
1130 // set default options
1131 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
1132 if (isUndefined(ctx.depth)) ctx.depth = 2;
1133 if (isUndefined(ctx.colors)) ctx.colors = false;
1134 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
1135 if (ctx.colors) ctx.stylize = stylizeWithColor;
1136 return formatValue(ctx, obj, ctx.depth);
1137}
1138exports.inspect = inspect;
1139
1140
1141// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
1142inspect.colors = {
1143 'bold' : [1, 22],
1144 'italic' : [3, 23],
1145 'underline' : [4, 24],
1146 'inverse' : [7, 27],
1147 'white' : [37, 39],
1148 'grey' : [90, 39],
1149 'black' : [30, 39],
1150 'blue' : [34, 39],
1151 'cyan' : [36, 39],
1152 'green' : [32, 39],
1153 'magenta' : [35, 39],
1154 'red' : [31, 39],
1155 'yellow' : [33, 39]
1156};
1157
1158// Don't use 'blue' not visible on cmd.exe
1159inspect.styles = {
1160 'special': 'cyan',
1161 'number': 'yellow',
1162 'boolean': 'yellow',
1163 'undefined': 'grey',
1164 'null': 'bold',
1165 'string': 'green',
1166 'date': 'magenta',
1167 // "name": intentionally not styling
1168 'regexp': 'red'
1169};
1170
1171
1172function stylizeWithColor(str, styleType) {
1173 var style = inspect.styles[styleType];
1174
1175 if (style) {
1176 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
1177 '\u001b[' + inspect.colors[style][1] + 'm';
1178 } else {
1179 return str;
1180 }
1181}
1182
1183
1184function stylizeNoColor(str, styleType) {
1185 return str;
1186}
1187
1188
1189function arrayToHash(array) {
1190 var hash = {};
1191
1192 array.forEach(function(val, idx) {
1193 hash[val] = true;
1194 });
1195
1196 return hash;
1197}
1198
1199
1200function formatValue(ctx, value, recurseTimes) {
1201 // Provide a hook for user-specified inspect functions.
1202 // Check that value is an object with an inspect function on it
1203 if (ctx.customInspect &&
1204 value &&
1205 isFunction(value.inspect) &&
1206 // Filter out the util module, it's inspect function is special
1207 value.inspect !== exports.inspect &&
1208 // Also filter out any prototype objects using the circular check.
1209 !(value.constructor && value.constructor.prototype === value)) {
1210 var ret = value.inspect(recurseTimes, ctx);
1211 if (!isString(ret)) {
1212 ret = formatValue(ctx, ret, recurseTimes);
1213 }
1214 return ret;
1215 }
1216
1217 // Primitive types cannot have properties
1218 var primitive = formatPrimitive(ctx, value);
1219 if (primitive) {
1220 return primitive;
1221 }
1222
1223 // Look up the keys of the object.
1224 var keys = Object.keys(value);
1225 var visibleKeys = arrayToHash(keys);
1226
1227 if (ctx.showHidden) {
1228 keys = Object.getOwnPropertyNames(value);
1229 }
1230
1231 // IE doesn't make error fields non-enumerable
1232 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
1233 if (isError(value)
1234 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
1235 return formatError(value);
1236 }
1237
1238 // Some type of object without properties can be shortcutted.
1239 if (keys.length === 0) {
1240 if (isFunction(value)) {
1241 var name = value.name ? ': ' + value.name : '';
1242 return ctx.stylize('[Function' + name + ']', 'special');
1243 }
1244 if (isRegExp(value)) {
1245 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
1246 }
1247 if (isDate(value)) {
1248 return ctx.stylize(Date.prototype.toString.call(value), 'date');
1249 }
1250 if (isError(value)) {
1251 return formatError(value);
1252 }
1253 }
1254
1255 var base = '', array = false, braces = ['{', '}'];
1256
1257 // Make Array say that they are Array
1258 if (isArray(value)) {
1259 array = true;
1260 braces = ['[', ']'];
1261 }
1262
1263 // Make functions say that they are functions
1264 if (isFunction(value)) {
1265 var n = value.name ? ': ' + value.name : '';
1266 base = ' [Function' + n + ']';
1267 }
1268
1269 // Make RegExps say that they are RegExps
1270 if (isRegExp(value)) {
1271 base = ' ' + RegExp.prototype.toString.call(value);
1272 }
1273
1274 // Make dates with properties first say the date
1275 if (isDate(value)) {
1276 base = ' ' + Date.prototype.toUTCString.call(value);
1277 }
1278
1279 // Make error with message first say the error
1280 if (isError(value)) {
1281 base = ' ' + formatError(value);
1282 }
1283
1284 if (keys.length === 0 && (!array || value.length == 0)) {
1285 return braces[0] + base + braces[1];
1286 }
1287
1288 if (recurseTimes < 0) {
1289 if (isRegExp(value)) {
1290 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
1291 } else {
1292 return ctx.stylize('[Object]', 'special');
1293 }
1294 }
1295
1296 ctx.seen.push(value);
1297
1298 var output;
1299 if (array) {
1300 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
1301 } else {
1302 output = keys.map(function(key) {
1303 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
1304 });
1305 }
1306
1307 ctx.seen.pop();
1308
1309 return reduceToSingleString(output, base, braces);
1310}
1311
1312
1313function formatPrimitive(ctx, value) {
1314 if (isUndefined(value))
1315 return ctx.stylize('undefined', 'undefined');
1316 if (isString(value)) {
1317 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
1318 .replace(/'/g, "\\'")
1319 .replace(/\\"/g, '"') + '\'';
1320 return ctx.stylize(simple, 'string');
1321 }
1322 if (isNumber(value))
1323 return ctx.stylize('' + value, 'number');
1324 if (isBoolean(value))
1325 return ctx.stylize('' + value, 'boolean');
1326 // For some reason typeof null is "object", so special case here.
1327 if (isNull(value))
1328 return ctx.stylize('null', 'null');
1329}
1330
1331
1332function formatError(value) {
1333 return '[' + Error.prototype.toString.call(value) + ']';
1334}
1335
1336
1337function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
1338 var output = [];
1339 for (var i = 0, l = value.length; i < l; ++i) {
1340 if (hasOwnProperty(value, String(i))) {
1341 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
1342 String(i), true));
1343 } else {
1344 output.push('');
1345 }
1346 }
1347 keys.forEach(function(key) {
1348 if (!key.match(/^\d+$/)) {
1349 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
1350 key, true));
1351 }
1352 });
1353 return output;
1354}
1355
1356
1357function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
1358 var name, str, desc;
1359 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
1360 if (desc.get) {
1361 if (desc.set) {
1362 str = ctx.stylize('[Getter/Setter]', 'special');
1363 } else {
1364 str = ctx.stylize('[Getter]', 'special');
1365 }
1366 } else {
1367 if (desc.set) {
1368 str = ctx.stylize('[Setter]', 'special');
1369 }
1370 }
1371 if (!hasOwnProperty(visibleKeys, key)) {
1372 name = '[' + key + ']';
1373 }
1374 if (!str) {
1375 if (ctx.seen.indexOf(desc.value) < 0) {
1376 if (isNull(recurseTimes)) {
1377 str = formatValue(ctx, desc.value, null);
1378 } else {
1379 str = formatValue(ctx, desc.value, recurseTimes - 1);
1380 }
1381 if (str.indexOf('\n') > -1) {
1382 if (array) {
1383 str = str.split('\n').map(function(line) {
1384 return ' ' + line;
1385 }).join('\n').substr(2);
1386 } else {
1387 str = '\n' + str.split('\n').map(function(line) {
1388 return ' ' + line;
1389 }).join('\n');
1390 }
1391 }
1392 } else {
1393 str = ctx.stylize('[Circular]', 'special');
1394 }
1395 }
1396 if (isUndefined(name)) {
1397 if (array && key.match(/^\d+$/)) {
1398 return str;
1399 }
1400 name = JSON.stringify('' + key);
1401 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
1402 name = name.substr(1, name.length - 2);
1403 name = ctx.stylize(name, 'name');
1404 } else {
1405 name = name.replace(/'/g, "\\'")
1406 .replace(/\\"/g, '"')
1407 .replace(/(^"|"$)/g, "'");
1408 name = ctx.stylize(name, 'string');
1409 }
1410 }
1411
1412 return name + ': ' + str;
1413}
1414
1415
1416function reduceToSingleString(output, base, braces) {
1417 var numLinesEst = 0;
1418 var length = output.reduce(function(prev, cur) {
1419 numLinesEst++;
1420 if (cur.indexOf('\n') >= 0) numLinesEst++;
1421 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
1422 }, 0);
1423
1424 if (length > 60) {
1425 return braces[0] +
1426 (base === '' ? '' : base + '\n ') +
1427 ' ' +
1428 output.join(',\n ') +
1429 ' ' +
1430 braces[1];
1431 }
1432
1433 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
1434}
1435
1436
1437// NOTE: These type checking functions intentionally don't use `instanceof`
1438// because it is fragile and can be easily faked with `Object.create()`.
1439function isArray(ar) {
1440 return Array.isArray(ar);
1441}
1442exports.isArray = isArray;
1443
1444function isBoolean(arg) {
1445 return typeof arg === 'boolean';
1446}
1447exports.isBoolean = isBoolean;
1448
1449function isNull(arg) {
1450 return arg === null;
1451}
1452exports.isNull = isNull;
1453
1454function isNullOrUndefined(arg) {
1455 return arg == null;
1456}
1457exports.isNullOrUndefined = isNullOrUndefined;
1458
1459function isNumber(arg) {
1460 return typeof arg === 'number';
1461}
1462exports.isNumber = isNumber;
1463
1464function isString(arg) {
1465 return typeof arg === 'string';
1466}
1467exports.isString = isString;
1468
1469function isSymbol(arg) {
1470 return typeof arg === 'symbol';
1471}
1472exports.isSymbol = isSymbol;
1473
1474function isUndefined(arg) {
1475 return arg === void 0;
1476}
1477exports.isUndefined = isUndefined;
1478
1479function isRegExp(re) {
1480 return isObject(re) && objectToString(re) === '[object RegExp]';
1481}
1482exports.isRegExp = isRegExp;
1483
1484function isObject(arg) {
1485 return typeof arg === 'object' && arg !== null;
1486}
1487exports.isObject = isObject;
1488
1489function isDate(d) {
1490 return isObject(d) && objectToString(d) === '[object Date]';
1491}
1492exports.isDate = isDate;
1493
1494function isError(e) {
1495 return isObject(e) &&
1496 (objectToString(e) === '[object Error]' || e instanceof Error);
1497}
1498exports.isError = isError;
1499
1500function isFunction(arg) {
1501 return typeof arg === 'function';
1502}
1503exports.isFunction = isFunction;
1504
1505function isPrimitive(arg) {
1506 return arg === null ||
1507 typeof arg === 'boolean' ||
1508 typeof arg === 'number' ||
1509 typeof arg === 'string' ||
1510 typeof arg === 'symbol' || // ES6 symbol
1511 typeof arg === 'undefined';
1512}
1513exports.isPrimitive = isPrimitive;
1514
1515exports.isBuffer = _dereq_(8);
1516
1517function objectToString(o) {
1518 return Object.prototype.toString.call(o);
1519}
1520
1521
1522function pad(n) {
1523 return n < 10 ? '0' + n.toString(10) : n.toString(10);
1524}
1525
1526
1527var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
1528 'Oct', 'Nov', 'Dec'];
1529
1530// 26 Feb 16:19:34
1531function timestamp() {
1532 var d = new Date();
1533 var time = [pad(d.getHours()),
1534 pad(d.getMinutes()),
1535 pad(d.getSeconds())].join(':');
1536 return [d.getDate(), months[d.getMonth()], time].join(' ');
1537}
1538
1539
1540// log is just a thin wrapper to console.log that prepends a timestamp
1541exports.log = function() {
1542 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
1543};
1544
1545
1546/**
1547 * Inherit the prototype methods from one constructor into another.
1548 *
1549 * The Function.prototype.inherits from lang.js rewritten as a standalone
1550 * function (not on Function.prototype). NOTE: If this file is to be loaded
1551 * during bootstrapping this function needs to be rewritten using some native
1552 * functions as prototype setup using normal JavaScript does not work as
1553 * expected during bootstrapping (see mirror.js in r114903).
1554 *
1555 * @param {function} ctor Constructor function which needs to inherit the
1556 * prototype.
1557 * @param {function} superCtor Constructor function to inherit prototype from.
1558 */
1559exports.inherits = _dereq_(7);
1560
1561exports._extend = function(origin, add) {
1562 // Don't do anything if add isn't an object
1563 if (!add || !isObject(add)) return origin;
1564
1565 var keys = Object.keys(add);
1566 var i = keys.length;
1567 while (i--) {
1568 origin[keys[i]] = add[keys[i]];
1569 }
1570 return origin;
1571};
1572
1573function hasOwnProperty(obj, prop) {
1574 return Object.prototype.hasOwnProperty.call(obj, prop);
1575}
1576
1577}).call(this)}).call(this,_dereq_(73),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
1578},{"7":7,"73":73,"8":8}],10:[function(_dereq_,module,exports){
1579'use strict'
1580
1581exports.byteLength = byteLength
1582exports.toByteArray = toByteArray
1583exports.fromByteArray = fromByteArray
1584
1585var lookup = []
1586var revLookup = []
1587var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
1588
1589var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
1590for (var i = 0, len = code.length; i < len; ++i) {
1591 lookup[i] = code[i]
1592 revLookup[code.charCodeAt(i)] = i
1593}
1594
1595// Support decoding URL-safe base64 strings, as Node.js does.
1596// See: https://en.wikipedia.org/wiki/Base64#URL_applications
1597revLookup['-'.charCodeAt(0)] = 62
1598revLookup['_'.charCodeAt(0)] = 63
1599
1600function getLens (b64) {
1601 var len = b64.length
1602
1603 if (len % 4 > 0) {
1604 throw new Error('Invalid string. Length must be a multiple of 4')
1605 }
1606
1607 // Trim off extra bytes after placeholder bytes are found
1608 // See: https://github.com/beatgammit/base64-js/issues/42
1609 var validLen = b64.indexOf('=')
1610 if (validLen === -1) validLen = len
1611
1612 var placeHoldersLen = validLen === len
1613 ? 0
1614 : 4 - (validLen % 4)
1615
1616 return [validLen, placeHoldersLen]
1617}
1618
1619// base64 is 4/3 + up to two characters of the original data
1620function byteLength (b64) {
1621 var lens = getLens(b64)
1622 var validLen = lens[0]
1623 var placeHoldersLen = lens[1]
1624 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
1625}
1626
1627function _byteLength (b64, validLen, placeHoldersLen) {
1628 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
1629}
1630
1631function toByteArray (b64) {
1632 var tmp
1633 var lens = getLens(b64)
1634 var validLen = lens[0]
1635 var placeHoldersLen = lens[1]
1636
1637 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
1638
1639 var curByte = 0
1640
1641 // if there are placeholders, only get up to the last complete 4 chars
1642 var len = placeHoldersLen > 0
1643 ? validLen - 4
1644 : validLen
1645
1646 var i
1647 for (i = 0; i < len; i += 4) {
1648 tmp =
1649 (revLookup[b64.charCodeAt(i)] << 18) |
1650 (revLookup[b64.charCodeAt(i + 1)] << 12) |
1651 (revLookup[b64.charCodeAt(i + 2)] << 6) |
1652 revLookup[b64.charCodeAt(i + 3)]
1653 arr[curByte++] = (tmp >> 16) & 0xFF
1654 arr[curByte++] = (tmp >> 8) & 0xFF
1655 arr[curByte++] = tmp & 0xFF
1656 }
1657
1658 if (placeHoldersLen === 2) {
1659 tmp =
1660 (revLookup[b64.charCodeAt(i)] << 2) |
1661 (revLookup[b64.charCodeAt(i + 1)] >> 4)
1662 arr[curByte++] = tmp & 0xFF
1663 }
1664
1665 if (placeHoldersLen === 1) {
1666 tmp =
1667 (revLookup[b64.charCodeAt(i)] << 10) |
1668 (revLookup[b64.charCodeAt(i + 1)] << 4) |
1669 (revLookup[b64.charCodeAt(i + 2)] >> 2)
1670 arr[curByte++] = (tmp >> 8) & 0xFF
1671 arr[curByte++] = tmp & 0xFF
1672 }
1673
1674 return arr
1675}
1676
1677function tripletToBase64 (num) {
1678 return lookup[num >> 18 & 0x3F] +
1679 lookup[num >> 12 & 0x3F] +
1680 lookup[num >> 6 & 0x3F] +
1681 lookup[num & 0x3F]
1682}
1683
1684function encodeChunk (uint8, start, end) {
1685 var tmp
1686 var output = []
1687 for (var i = start; i < end; i += 3) {
1688 tmp =
1689 ((uint8[i] << 16) & 0xFF0000) +
1690 ((uint8[i + 1] << 8) & 0xFF00) +
1691 (uint8[i + 2] & 0xFF)
1692 output.push(tripletToBase64(tmp))
1693 }
1694 return output.join('')
1695}
1696
1697function fromByteArray (uint8) {
1698 var tmp
1699 var len = uint8.length
1700 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
1701 var parts = []
1702 var maxChunkLength = 16383 // must be multiple of 3
1703
1704 // go through the array every three bytes, we'll deal with trailing stuff later
1705 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
1706 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
1707 }
1708
1709 // pad the end with zeros, but make sure to not forget the extra bytes
1710 if (extraBytes === 1) {
1711 tmp = uint8[len - 1]
1712 parts.push(
1713 lookup[tmp >> 2] +
1714 lookup[(tmp << 4) & 0x3F] +
1715 '=='
1716 )
1717 } else if (extraBytes === 2) {
1718 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
1719 parts.push(
1720 lookup[tmp >> 10] +
1721 lookup[(tmp >> 4) & 0x3F] +
1722 lookup[(tmp << 2) & 0x3F] +
1723 '='
1724 )
1725 }
1726
1727 return parts.join('')
1728}
1729
1730},{}],11:[function(_dereq_,module,exports){
1731
1732},{}],12:[function(_dereq_,module,exports){
1733(function (Buffer){(function (){
1734/* eslint-disable node/no-deprecated-api */
1735
1736var toString = Object.prototype.toString
1737
1738var isModern = (
1739 typeof Buffer !== 'undefined' &&
1740 typeof Buffer.alloc === 'function' &&
1741 typeof Buffer.allocUnsafe === 'function' &&
1742 typeof Buffer.from === 'function'
1743)
1744
1745function isArrayBuffer (input) {
1746 return toString.call(input).slice(8, -1) === 'ArrayBuffer'
1747}
1748
1749function fromArrayBuffer (obj, byteOffset, length) {
1750 byteOffset >>>= 0
1751
1752 var maxLength = obj.byteLength - byteOffset
1753
1754 if (maxLength < 0) {
1755 throw new RangeError("'offset' is out of bounds")
1756 }
1757
1758 if (length === undefined) {
1759 length = maxLength
1760 } else {
1761 length >>>= 0
1762
1763 if (length > maxLength) {
1764 throw new RangeError("'length' is out of bounds")
1765 }
1766 }
1767
1768 return isModern
1769 ? Buffer.from(obj.slice(byteOffset, byteOffset + length))
1770 : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
1771}
1772
1773function fromString (string, encoding) {
1774 if (typeof encoding !== 'string' || encoding === '') {
1775 encoding = 'utf8'
1776 }
1777
1778 if (!Buffer.isEncoding(encoding)) {
1779 throw new TypeError('"encoding" must be a valid string encoding')
1780 }
1781
1782 return isModern
1783 ? Buffer.from(string, encoding)
1784 : new Buffer(string, encoding)
1785}
1786
1787function bufferFrom (value, encodingOrOffset, length) {
1788 if (typeof value === 'number') {
1789 throw new TypeError('"value" argument must not be a number')
1790 }
1791
1792 if (isArrayBuffer(value)) {
1793 return fromArrayBuffer(value, encodingOrOffset, length)
1794 }
1795
1796 if (typeof value === 'string') {
1797 return fromString(value, encodingOrOffset)
1798 }
1799
1800 return isModern
1801 ? Buffer.from(value)
1802 : new Buffer(value)
1803}
1804
1805module.exports = bufferFrom
1806
1807}).call(this)}).call(this,_dereq_(13).Buffer)
1808},{"13":13}],13:[function(_dereq_,module,exports){
1809(function (Buffer){(function (){
1810/*!
1811 * The buffer module from node.js, for the browser.
1812 *
1813 * @author Feross Aboukhadijeh <https://feross.org>
1814 * @license MIT
1815 */
1816/* eslint-disable no-proto */
1817
1818'use strict'
1819
1820var base64 = _dereq_(10)
1821var ieee754 = _dereq_(30)
1822var customInspectSymbol =
1823 (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation
1824 ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation
1825 : null
1826
1827exports.Buffer = Buffer
1828exports.SlowBuffer = SlowBuffer
1829exports.INSPECT_MAX_BYTES = 50
1830
1831var K_MAX_LENGTH = 0x7fffffff
1832exports.kMaxLength = K_MAX_LENGTH
1833
1834/**
1835 * If `Buffer.TYPED_ARRAY_SUPPORT`:
1836 * === true Use Uint8Array implementation (fastest)
1837 * === false Print warning and recommend using `buffer` v4.x which has an Object
1838 * implementation (most compatible, even IE6)
1839 *
1840 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
1841 * Opera 11.6+, iOS 4.2+.
1842 *
1843 * We report that the browser does not support typed arrays if the are not subclassable
1844 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
1845 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
1846 * for __proto__ and has a buggy typed array implementation.
1847 */
1848Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
1849
1850if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
1851 typeof console.error === 'function') {
1852 console.error(
1853 'This browser lacks typed array (Uint8Array) support which is required by ' +
1854 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
1855 )
1856}
1857
1858function typedArraySupport () {
1859 // Can typed array instances can be augmented?
1860 try {
1861 var arr = new Uint8Array(1)
1862 var proto = { foo: function () { return 42 } }
1863 Object.setPrototypeOf(proto, Uint8Array.prototype)
1864 Object.setPrototypeOf(arr, proto)
1865 return arr.foo() === 42
1866 } catch (e) {
1867 return false
1868 }
1869}
1870
1871Object.defineProperty(Buffer.prototype, 'parent', {
1872 enumerable: true,
1873 get: function () {
1874 if (!Buffer.isBuffer(this)) return undefined
1875 return this.buffer
1876 }
1877})
1878
1879Object.defineProperty(Buffer.prototype, 'offset', {
1880 enumerable: true,
1881 get: function () {
1882 if (!Buffer.isBuffer(this)) return undefined
1883 return this.byteOffset
1884 }
1885})
1886
1887function createBuffer (length) {
1888 if (length > K_MAX_LENGTH) {
1889 throw new RangeError('The value "' + length + '" is invalid for option "size"')
1890 }
1891 // Return an augmented `Uint8Array` instance
1892 var buf = new Uint8Array(length)
1893 Object.setPrototypeOf(buf, Buffer.prototype)
1894 return buf
1895}
1896
1897/**
1898 * The Buffer constructor returns instances of `Uint8Array` that have their
1899 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
1900 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
1901 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
1902 * returns a single octet.
1903 *
1904 * The `Uint8Array` prototype remains unmodified.
1905 */
1906
1907function Buffer (arg, encodingOrOffset, length) {
1908 // Common case.
1909 if (typeof arg === 'number') {
1910 if (typeof encodingOrOffset === 'string') {
1911 throw new TypeError(
1912 'The "string" argument must be of type string. Received type number'
1913 )
1914 }
1915 return allocUnsafe(arg)
1916 }
1917 return from(arg, encodingOrOffset, length)
1918}
1919
1920Buffer.poolSize = 8192 // not used by this implementation
1921
1922function from (value, encodingOrOffset, length) {
1923 if (typeof value === 'string') {
1924 return fromString(value, encodingOrOffset)
1925 }
1926
1927 if (ArrayBuffer.isView(value)) {
1928 return fromArrayView(value)
1929 }
1930
1931 if (value == null) {
1932 throw new TypeError(
1933 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
1934 'or Array-like Object. Received type ' + (typeof value)
1935 )
1936 }
1937
1938 if (isInstance(value, ArrayBuffer) ||
1939 (value && isInstance(value.buffer, ArrayBuffer))) {
1940 return fromArrayBuffer(value, encodingOrOffset, length)
1941 }
1942
1943 if (typeof SharedArrayBuffer !== 'undefined' &&
1944 (isInstance(value, SharedArrayBuffer) ||
1945 (value && isInstance(value.buffer, SharedArrayBuffer)))) {
1946 return fromArrayBuffer(value, encodingOrOffset, length)
1947 }
1948
1949 if (typeof value === 'number') {
1950 throw new TypeError(
1951 'The "value" argument must not be of type number. Received type number'
1952 )
1953 }
1954
1955 var valueOf = value.valueOf && value.valueOf()
1956 if (valueOf != null && valueOf !== value) {
1957 return Buffer.from(valueOf, encodingOrOffset, length)
1958 }
1959
1960 var b = fromObject(value)
1961 if (b) return b
1962
1963 if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
1964 typeof value[Symbol.toPrimitive] === 'function') {
1965 return Buffer.from(
1966 value[Symbol.toPrimitive]('string'), encodingOrOffset, length
1967 )
1968 }
1969
1970 throw new TypeError(
1971 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
1972 'or Array-like Object. Received type ' + (typeof value)
1973 )
1974}
1975
1976/**
1977 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
1978 * if value is a number.
1979 * Buffer.from(str[, encoding])
1980 * Buffer.from(array)
1981 * Buffer.from(buffer)
1982 * Buffer.from(arrayBuffer[, byteOffset[, length]])
1983 **/
1984Buffer.from = function (value, encodingOrOffset, length) {
1985 return from(value, encodingOrOffset, length)
1986}
1987
1988// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
1989// https://github.com/feross/buffer/pull/148
1990Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)
1991Object.setPrototypeOf(Buffer, Uint8Array)
1992
1993function assertSize (size) {
1994 if (typeof size !== 'number') {
1995 throw new TypeError('"size" argument must be of type number')
1996 } else if (size < 0) {
1997 throw new RangeError('The value "' + size + '" is invalid for option "size"')
1998 }
1999}
2000
2001function alloc (size, fill, encoding) {
2002 assertSize(size)
2003 if (size <= 0) {
2004 return createBuffer(size)
2005 }
2006 if (fill !== undefined) {
2007 // Only pay attention to encoding if it's a string. This
2008 // prevents accidentally sending in a number that would
2009 // be interpreted as a start offset.
2010 return typeof encoding === 'string'
2011 ? createBuffer(size).fill(fill, encoding)
2012 : createBuffer(size).fill(fill)
2013 }
2014 return createBuffer(size)
2015}
2016
2017/**
2018 * Creates a new filled Buffer instance.
2019 * alloc(size[, fill[, encoding]])
2020 **/
2021Buffer.alloc = function (size, fill, encoding) {
2022 return alloc(size, fill, encoding)
2023}
2024
2025function allocUnsafe (size) {
2026 assertSize(size)
2027 return createBuffer(size < 0 ? 0 : checked(size) | 0)
2028}
2029
2030/**
2031 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
2032 * */
2033Buffer.allocUnsafe = function (size) {
2034 return allocUnsafe(size)
2035}
2036/**
2037 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
2038 */
2039Buffer.allocUnsafeSlow = function (size) {
2040 return allocUnsafe(size)
2041}
2042
2043function fromString (string, encoding) {
2044 if (typeof encoding !== 'string' || encoding === '') {
2045 encoding = 'utf8'
2046 }
2047
2048 if (!Buffer.isEncoding(encoding)) {
2049 throw new TypeError('Unknown encoding: ' + encoding)
2050 }
2051
2052 var length = byteLength(string, encoding) | 0
2053 var buf = createBuffer(length)
2054
2055 var actual = buf.write(string, encoding)
2056
2057 if (actual !== length) {
2058 // Writing a hex string, for example, that contains invalid characters will
2059 // cause everything after the first invalid character to be ignored. (e.g.
2060 // 'abxxcd' will be treated as 'ab')
2061 buf = buf.slice(0, actual)
2062 }
2063
2064 return buf
2065}
2066
2067function fromArrayLike (array) {
2068 var length = array.length < 0 ? 0 : checked(array.length) | 0
2069 var buf = createBuffer(length)
2070 for (var i = 0; i < length; i += 1) {
2071 buf[i] = array[i] & 255
2072 }
2073 return buf
2074}
2075
2076function fromArrayView (arrayView) {
2077 if (isInstance(arrayView, Uint8Array)) {
2078 var copy = new Uint8Array(arrayView)
2079 return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)
2080 }
2081 return fromArrayLike(arrayView)
2082}
2083
2084function fromArrayBuffer (array, byteOffset, length) {
2085 if (byteOffset < 0 || array.byteLength < byteOffset) {
2086 throw new RangeError('"offset" is outside of buffer bounds')
2087 }
2088
2089 if (array.byteLength < byteOffset + (length || 0)) {
2090 throw new RangeError('"length" is outside of buffer bounds')
2091 }
2092
2093 var buf
2094 if (byteOffset === undefined && length === undefined) {
2095 buf = new Uint8Array(array)
2096 } else if (length === undefined) {
2097 buf = new Uint8Array(array, byteOffset)
2098 } else {
2099 buf = new Uint8Array(array, byteOffset, length)
2100 }
2101
2102 // Return an augmented `Uint8Array` instance
2103 Object.setPrototypeOf(buf, Buffer.prototype)
2104
2105 return buf
2106}
2107
2108function fromObject (obj) {
2109 if (Buffer.isBuffer(obj)) {
2110 var len = checked(obj.length) | 0
2111 var buf = createBuffer(len)
2112
2113 if (buf.length === 0) {
2114 return buf
2115 }
2116
2117 obj.copy(buf, 0, 0, len)
2118 return buf
2119 }
2120
2121 if (obj.length !== undefined) {
2122 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
2123 return createBuffer(0)
2124 }
2125 return fromArrayLike(obj)
2126 }
2127
2128 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
2129 return fromArrayLike(obj.data)
2130 }
2131}
2132
2133function checked (length) {
2134 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
2135 // length is NaN (which is otherwise coerced to zero.)
2136 if (length >= K_MAX_LENGTH) {
2137 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
2138 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
2139 }
2140 return length | 0
2141}
2142
2143function SlowBuffer (length) {
2144 if (+length != length) { // eslint-disable-line eqeqeq
2145 length = 0
2146 }
2147 return Buffer.alloc(+length)
2148}
2149
2150Buffer.isBuffer = function isBuffer (b) {
2151 return b != null && b._isBuffer === true &&
2152 b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
2153}
2154
2155Buffer.compare = function compare (a, b) {
2156 if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
2157 if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
2158 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
2159 throw new TypeError(
2160 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
2161 )
2162 }
2163
2164 if (a === b) return 0
2165
2166 var x = a.length
2167 var y = b.length
2168
2169 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
2170 if (a[i] !== b[i]) {
2171 x = a[i]
2172 y = b[i]
2173 break
2174 }
2175 }
2176
2177 if (x < y) return -1
2178 if (y < x) return 1
2179 return 0
2180}
2181
2182Buffer.isEncoding = function isEncoding (encoding) {
2183 switch (String(encoding).toLowerCase()) {
2184 case 'hex':
2185 case 'utf8':
2186 case 'utf-8':
2187 case 'ascii':
2188 case 'latin1':
2189 case 'binary':
2190 case 'base64':
2191 case 'ucs2':
2192 case 'ucs-2':
2193 case 'utf16le':
2194 case 'utf-16le':
2195 return true
2196 default:
2197 return false
2198 }
2199}
2200
2201Buffer.concat = function concat (list, length) {
2202 if (!Array.isArray(list)) {
2203 throw new TypeError('"list" argument must be an Array of Buffers')
2204 }
2205
2206 if (list.length === 0) {
2207 return Buffer.alloc(0)
2208 }
2209
2210 var i
2211 if (length === undefined) {
2212 length = 0
2213 for (i = 0; i < list.length; ++i) {
2214 length += list[i].length
2215 }
2216 }
2217
2218 var buffer = Buffer.allocUnsafe(length)
2219 var pos = 0
2220 for (i = 0; i < list.length; ++i) {
2221 var buf = list[i]
2222 if (isInstance(buf, Uint8Array)) {
2223 if (pos + buf.length > buffer.length) {
2224 Buffer.from(buf).copy(buffer, pos)
2225 } else {
2226 Uint8Array.prototype.set.call(
2227 buffer,
2228 buf,
2229 pos
2230 )
2231 }
2232 } else if (!Buffer.isBuffer(buf)) {
2233 throw new TypeError('"list" argument must be an Array of Buffers')
2234 } else {
2235 buf.copy(buffer, pos)
2236 }
2237 pos += buf.length
2238 }
2239 return buffer
2240}
2241
2242function byteLength (string, encoding) {
2243 if (Buffer.isBuffer(string)) {
2244 return string.length
2245 }
2246 if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
2247 return string.byteLength
2248 }
2249 if (typeof string !== 'string') {
2250 throw new TypeError(
2251 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
2252 'Received type ' + typeof string
2253 )
2254 }
2255
2256 var len = string.length
2257 var mustMatch = (arguments.length > 2 && arguments[2] === true)
2258 if (!mustMatch && len === 0) return 0
2259
2260 // Use a for loop to avoid recursion
2261 var loweredCase = false
2262 for (;;) {
2263 switch (encoding) {
2264 case 'ascii':
2265 case 'latin1':
2266 case 'binary':
2267 return len
2268 case 'utf8':
2269 case 'utf-8':
2270 return utf8ToBytes(string).length
2271 case 'ucs2':
2272 case 'ucs-2':
2273 case 'utf16le':
2274 case 'utf-16le':
2275 return len * 2
2276 case 'hex':
2277 return len >>> 1
2278 case 'base64':
2279 return base64ToBytes(string).length
2280 default:
2281 if (loweredCase) {
2282 return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
2283 }
2284 encoding = ('' + encoding).toLowerCase()
2285 loweredCase = true
2286 }
2287 }
2288}
2289Buffer.byteLength = byteLength
2290
2291function slowToString (encoding, start, end) {
2292 var loweredCase = false
2293
2294 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
2295 // property of a typed array.
2296
2297 // This behaves neither like String nor Uint8Array in that we set start/end
2298 // to their upper/lower bounds if the value passed is out of range.
2299 // undefined is handled specially as per ECMA-262 6th Edition,
2300 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
2301 if (start === undefined || start < 0) {
2302 start = 0
2303 }
2304 // Return early if start > this.length. Done here to prevent potential uint32
2305 // coercion fail below.
2306 if (start > this.length) {
2307 return ''
2308 }
2309
2310 if (end === undefined || end > this.length) {
2311 end = this.length
2312 }
2313
2314 if (end <= 0) {
2315 return ''
2316 }
2317
2318 // Force coercion to uint32. This will also coerce falsey/NaN values to 0.
2319 end >>>= 0
2320 start >>>= 0
2321
2322 if (end <= start) {
2323 return ''
2324 }
2325
2326 if (!encoding) encoding = 'utf8'
2327
2328 while (true) {
2329 switch (encoding) {
2330 case 'hex':
2331 return hexSlice(this, start, end)
2332
2333 case 'utf8':
2334 case 'utf-8':
2335 return utf8Slice(this, start, end)
2336
2337 case 'ascii':
2338 return asciiSlice(this, start, end)
2339
2340 case 'latin1':
2341 case 'binary':
2342 return latin1Slice(this, start, end)
2343
2344 case 'base64':
2345 return base64Slice(this, start, end)
2346
2347 case 'ucs2':
2348 case 'ucs-2':
2349 case 'utf16le':
2350 case 'utf-16le':
2351 return utf16leSlice(this, start, end)
2352
2353 default:
2354 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
2355 encoding = (encoding + '').toLowerCase()
2356 loweredCase = true
2357 }
2358 }
2359}
2360
2361// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
2362// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
2363// reliably in a browserify context because there could be multiple different
2364// copies of the 'buffer' package in use. This method works even for Buffer
2365// instances that were created from another copy of the `buffer` package.
2366// See: https://github.com/feross/buffer/issues/154
2367Buffer.prototype._isBuffer = true
2368
2369function swap (b, n, m) {
2370 var i = b[n]
2371 b[n] = b[m]
2372 b[m] = i
2373}
2374
2375Buffer.prototype.swap16 = function swap16 () {
2376 var len = this.length
2377 if (len % 2 !== 0) {
2378 throw new RangeError('Buffer size must be a multiple of 16-bits')
2379 }
2380 for (var i = 0; i < len; i += 2) {
2381 swap(this, i, i + 1)
2382 }
2383 return this
2384}
2385
2386Buffer.prototype.swap32 = function swap32 () {
2387 var len = this.length
2388 if (len % 4 !== 0) {
2389 throw new RangeError('Buffer size must be a multiple of 32-bits')
2390 }
2391 for (var i = 0; i < len; i += 4) {
2392 swap(this, i, i + 3)
2393 swap(this, i + 1, i + 2)
2394 }
2395 return this
2396}
2397
2398Buffer.prototype.swap64 = function swap64 () {
2399 var len = this.length
2400 if (len % 8 !== 0) {
2401 throw new RangeError('Buffer size must be a multiple of 64-bits')
2402 }
2403 for (var i = 0; i < len; i += 8) {
2404 swap(this, i, i + 7)
2405 swap(this, i + 1, i + 6)
2406 swap(this, i + 2, i + 5)
2407 swap(this, i + 3, i + 4)
2408 }
2409 return this
2410}
2411
2412Buffer.prototype.toString = function toString () {
2413 var length = this.length
2414 if (length === 0) return ''
2415 if (arguments.length === 0) return utf8Slice(this, 0, length)
2416 return slowToString.apply(this, arguments)
2417}
2418
2419Buffer.prototype.toLocaleString = Buffer.prototype.toString
2420
2421Buffer.prototype.equals = function equals (b) {
2422 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
2423 if (this === b) return true
2424 return Buffer.compare(this, b) === 0
2425}
2426
2427Buffer.prototype.inspect = function inspect () {
2428 var str = ''
2429 var max = exports.INSPECT_MAX_BYTES
2430 str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
2431 if (this.length > max) str += ' ... '
2432 return '<Buffer ' + str + '>'
2433}
2434if (customInspectSymbol) {
2435 Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect
2436}
2437
2438Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
2439 if (isInstance(target, Uint8Array)) {
2440 target = Buffer.from(target, target.offset, target.byteLength)
2441 }
2442 if (!Buffer.isBuffer(target)) {
2443 throw new TypeError(
2444 'The "target" argument must be one of type Buffer or Uint8Array. ' +
2445 'Received type ' + (typeof target)
2446 )
2447 }
2448
2449 if (start === undefined) {
2450 start = 0
2451 }
2452 if (end === undefined) {
2453 end = target ? target.length : 0
2454 }
2455 if (thisStart === undefined) {
2456 thisStart = 0
2457 }
2458 if (thisEnd === undefined) {
2459 thisEnd = this.length
2460 }
2461
2462 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
2463 throw new RangeError('out of range index')
2464 }
2465
2466 if (thisStart >= thisEnd && start >= end) {
2467 return 0
2468 }
2469 if (thisStart >= thisEnd) {
2470 return -1
2471 }
2472 if (start >= end) {
2473 return 1
2474 }
2475
2476 start >>>= 0
2477 end >>>= 0
2478 thisStart >>>= 0
2479 thisEnd >>>= 0
2480
2481 if (this === target) return 0
2482
2483 var x = thisEnd - thisStart
2484 var y = end - start
2485 var len = Math.min(x, y)
2486
2487 var thisCopy = this.slice(thisStart, thisEnd)
2488 var targetCopy = target.slice(start, end)
2489
2490 for (var i = 0; i < len; ++i) {
2491 if (thisCopy[i] !== targetCopy[i]) {
2492 x = thisCopy[i]
2493 y = targetCopy[i]
2494 break
2495 }
2496 }
2497
2498 if (x < y) return -1
2499 if (y < x) return 1
2500 return 0
2501}
2502
2503// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
2504// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
2505//
2506// Arguments:
2507// - buffer - a Buffer to search
2508// - val - a string, Buffer, or number
2509// - byteOffset - an index into `buffer`; will be clamped to an int32
2510// - encoding - an optional encoding, relevant is val is a string
2511// - dir - true for indexOf, false for lastIndexOf
2512function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
2513 // Empty buffer means no match
2514 if (buffer.length === 0) return -1
2515
2516 // Normalize byteOffset
2517 if (typeof byteOffset === 'string') {
2518 encoding = byteOffset
2519 byteOffset = 0
2520 } else if (byteOffset > 0x7fffffff) {
2521 byteOffset = 0x7fffffff
2522 } else if (byteOffset < -0x80000000) {
2523 byteOffset = -0x80000000
2524 }
2525 byteOffset = +byteOffset // Coerce to Number.
2526 if (numberIsNaN(byteOffset)) {
2527 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
2528 byteOffset = dir ? 0 : (buffer.length - 1)
2529 }
2530
2531 // Normalize byteOffset: negative offsets start from the end of the buffer
2532 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
2533 if (byteOffset >= buffer.length) {
2534 if (dir) return -1
2535 else byteOffset = buffer.length - 1
2536 } else if (byteOffset < 0) {
2537 if (dir) byteOffset = 0
2538 else return -1
2539 }
2540
2541 // Normalize val
2542 if (typeof val === 'string') {
2543 val = Buffer.from(val, encoding)
2544 }
2545
2546 // Finally, search either indexOf (if dir is true) or lastIndexOf
2547 if (Buffer.isBuffer(val)) {
2548 // Special case: looking for empty string/buffer always fails
2549 if (val.length === 0) {
2550 return -1
2551 }
2552 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
2553 } else if (typeof val === 'number') {
2554 val = val & 0xFF // Search for a byte value [0-255]
2555 if (typeof Uint8Array.prototype.indexOf === 'function') {
2556 if (dir) {
2557 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
2558 } else {
2559 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
2560 }
2561 }
2562 return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
2563 }
2564
2565 throw new TypeError('val must be string, number or Buffer')
2566}
2567
2568function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
2569 var indexSize = 1
2570 var arrLength = arr.length
2571 var valLength = val.length
2572
2573 if (encoding !== undefined) {
2574 encoding = String(encoding).toLowerCase()
2575 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
2576 encoding === 'utf16le' || encoding === 'utf-16le') {
2577 if (arr.length < 2 || val.length < 2) {
2578 return -1
2579 }
2580 indexSize = 2
2581 arrLength /= 2
2582 valLength /= 2
2583 byteOffset /= 2
2584 }
2585 }
2586
2587 function read (buf, i) {
2588 if (indexSize === 1) {
2589 return buf[i]
2590 } else {
2591 return buf.readUInt16BE(i * indexSize)
2592 }
2593 }
2594
2595 var i
2596 if (dir) {
2597 var foundIndex = -1
2598 for (i = byteOffset; i < arrLength; i++) {
2599 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
2600 if (foundIndex === -1) foundIndex = i
2601 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
2602 } else {
2603 if (foundIndex !== -1) i -= i - foundIndex
2604 foundIndex = -1
2605 }
2606 }
2607 } else {
2608 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
2609 for (i = byteOffset; i >= 0; i--) {
2610 var found = true
2611 for (var j = 0; j < valLength; j++) {
2612 if (read(arr, i + j) !== read(val, j)) {
2613 found = false
2614 break
2615 }
2616 }
2617 if (found) return i
2618 }
2619 }
2620
2621 return -1
2622}
2623
2624Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
2625 return this.indexOf(val, byteOffset, encoding) !== -1
2626}
2627
2628Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
2629 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
2630}
2631
2632Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
2633 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
2634}
2635
2636function hexWrite (buf, string, offset, length) {
2637 offset = Number(offset) || 0
2638 var remaining = buf.length - offset
2639 if (!length) {
2640 length = remaining
2641 } else {
2642 length = Number(length)
2643 if (length > remaining) {
2644 length = remaining
2645 }
2646 }
2647
2648 var strLen = string.length
2649
2650 if (length > strLen / 2) {
2651 length = strLen / 2
2652 }
2653 for (var i = 0; i < length; ++i) {
2654 var parsed = parseInt(string.substr(i * 2, 2), 16)
2655 if (numberIsNaN(parsed)) return i
2656 buf[offset + i] = parsed
2657 }
2658 return i
2659}
2660
2661function utf8Write (buf, string, offset, length) {
2662 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
2663}
2664
2665function asciiWrite (buf, string, offset, length) {
2666 return blitBuffer(asciiToBytes(string), buf, offset, length)
2667}
2668
2669function base64Write (buf, string, offset, length) {
2670 return blitBuffer(base64ToBytes(string), buf, offset, length)
2671}
2672
2673function ucs2Write (buf, string, offset, length) {
2674 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
2675}
2676
2677Buffer.prototype.write = function write (string, offset, length, encoding) {
2678 // Buffer#write(string)
2679 if (offset === undefined) {
2680 encoding = 'utf8'
2681 length = this.length
2682 offset = 0
2683 // Buffer#write(string, encoding)
2684 } else if (length === undefined && typeof offset === 'string') {
2685 encoding = offset
2686 length = this.length
2687 offset = 0
2688 // Buffer#write(string, offset[, length][, encoding])
2689 } else if (isFinite(offset)) {
2690 offset = offset >>> 0
2691 if (isFinite(length)) {
2692 length = length >>> 0
2693 if (encoding === undefined) encoding = 'utf8'
2694 } else {
2695 encoding = length
2696 length = undefined
2697 }
2698 } else {
2699 throw new Error(
2700 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
2701 )
2702 }
2703
2704 var remaining = this.length - offset
2705 if (length === undefined || length > remaining) length = remaining
2706
2707 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
2708 throw new RangeError('Attempt to write outside buffer bounds')
2709 }
2710
2711 if (!encoding) encoding = 'utf8'
2712
2713 var loweredCase = false
2714 for (;;) {
2715 switch (encoding) {
2716 case 'hex':
2717 return hexWrite(this, string, offset, length)
2718
2719 case 'utf8':
2720 case 'utf-8':
2721 return utf8Write(this, string, offset, length)
2722
2723 case 'ascii':
2724 case 'latin1':
2725 case 'binary':
2726 return asciiWrite(this, string, offset, length)
2727
2728 case 'base64':
2729 // Warning: maxLength not taken into account in base64Write
2730 return base64Write(this, string, offset, length)
2731
2732 case 'ucs2':
2733 case 'ucs-2':
2734 case 'utf16le':
2735 case 'utf-16le':
2736 return ucs2Write(this, string, offset, length)
2737
2738 default:
2739 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
2740 encoding = ('' + encoding).toLowerCase()
2741 loweredCase = true
2742 }
2743 }
2744}
2745
2746Buffer.prototype.toJSON = function toJSON () {
2747 return {
2748 type: 'Buffer',
2749 data: Array.prototype.slice.call(this._arr || this, 0)
2750 }
2751}
2752
2753function base64Slice (buf, start, end) {
2754 if (start === 0 && end === buf.length) {
2755 return base64.fromByteArray(buf)
2756 } else {
2757 return base64.fromByteArray(buf.slice(start, end))
2758 }
2759}
2760
2761function utf8Slice (buf, start, end) {
2762 end = Math.min(buf.length, end)
2763 var res = []
2764
2765 var i = start
2766 while (i < end) {
2767 var firstByte = buf[i]
2768 var codePoint = null
2769 var bytesPerSequence = (firstByte > 0xEF)
2770 ? 4
2771 : (firstByte > 0xDF)
2772 ? 3
2773 : (firstByte > 0xBF)
2774 ? 2
2775 : 1
2776
2777 if (i + bytesPerSequence <= end) {
2778 var secondByte, thirdByte, fourthByte, tempCodePoint
2779
2780 switch (bytesPerSequence) {
2781 case 1:
2782 if (firstByte < 0x80) {
2783 codePoint = firstByte
2784 }
2785 break
2786 case 2:
2787 secondByte = buf[i + 1]
2788 if ((secondByte & 0xC0) === 0x80) {
2789 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
2790 if (tempCodePoint > 0x7F) {
2791 codePoint = tempCodePoint
2792 }
2793 }
2794 break
2795 case 3:
2796 secondByte = buf[i + 1]
2797 thirdByte = buf[i + 2]
2798 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
2799 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
2800 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
2801 codePoint = tempCodePoint
2802 }
2803 }
2804 break
2805 case 4:
2806 secondByte = buf[i + 1]
2807 thirdByte = buf[i + 2]
2808 fourthByte = buf[i + 3]
2809 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
2810 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
2811 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
2812 codePoint = tempCodePoint
2813 }
2814 }
2815 }
2816 }
2817
2818 if (codePoint === null) {
2819 // we did not generate a valid codePoint so insert a
2820 // replacement char (U+FFFD) and advance only 1 byte
2821 codePoint = 0xFFFD
2822 bytesPerSequence = 1
2823 } else if (codePoint > 0xFFFF) {
2824 // encode to utf16 (surrogate pair dance)
2825 codePoint -= 0x10000
2826 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
2827 codePoint = 0xDC00 | codePoint & 0x3FF
2828 }
2829
2830 res.push(codePoint)
2831 i += bytesPerSequence
2832 }
2833
2834 return decodeCodePointsArray(res)
2835}
2836
2837// Based on http://stackoverflow.com/a/22747272/680742, the browser with
2838// the lowest limit is Chrome, with 0x10000 args.
2839// We go 1 magnitude less, for safety
2840var MAX_ARGUMENTS_LENGTH = 0x1000
2841
2842function decodeCodePointsArray (codePoints) {
2843 var len = codePoints.length
2844 if (len <= MAX_ARGUMENTS_LENGTH) {
2845 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
2846 }
2847
2848 // Decode in chunks to avoid "call stack size exceeded".
2849 var res = ''
2850 var i = 0
2851 while (i < len) {
2852 res += String.fromCharCode.apply(
2853 String,
2854 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
2855 )
2856 }
2857 return res
2858}
2859
2860function asciiSlice (buf, start, end) {
2861 var ret = ''
2862 end = Math.min(buf.length, end)
2863
2864 for (var i = start; i < end; ++i) {
2865 ret += String.fromCharCode(buf[i] & 0x7F)
2866 }
2867 return ret
2868}
2869
2870function latin1Slice (buf, start, end) {
2871 var ret = ''
2872 end = Math.min(buf.length, end)
2873
2874 for (var i = start; i < end; ++i) {
2875 ret += String.fromCharCode(buf[i])
2876 }
2877 return ret
2878}
2879
2880function hexSlice (buf, start, end) {
2881 var len = buf.length
2882
2883 if (!start || start < 0) start = 0
2884 if (!end || end < 0 || end > len) end = len
2885
2886 var out = ''
2887 for (var i = start; i < end; ++i) {
2888 out += hexSliceLookupTable[buf[i]]
2889 }
2890 return out
2891}
2892
2893function utf16leSlice (buf, start, end) {
2894 var bytes = buf.slice(start, end)
2895 var res = ''
2896 // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)
2897 for (var i = 0; i < bytes.length - 1; i += 2) {
2898 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
2899 }
2900 return res
2901}
2902
2903Buffer.prototype.slice = function slice (start, end) {
2904 var len = this.length
2905 start = ~~start
2906 end = end === undefined ? len : ~~end
2907
2908 if (start < 0) {
2909 start += len
2910 if (start < 0) start = 0
2911 } else if (start > len) {
2912 start = len
2913 }
2914
2915 if (end < 0) {
2916 end += len
2917 if (end < 0) end = 0
2918 } else if (end > len) {
2919 end = len
2920 }
2921
2922 if (end < start) end = start
2923
2924 var newBuf = this.subarray(start, end)
2925 // Return an augmented `Uint8Array` instance
2926 Object.setPrototypeOf(newBuf, Buffer.prototype)
2927
2928 return newBuf
2929}
2930
2931/*
2932 * Need to make sure that buffer isn't trying to write out of bounds.
2933 */
2934function checkOffset (offset, ext, length) {
2935 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
2936 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
2937}
2938
2939Buffer.prototype.readUintLE =
2940Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
2941 offset = offset >>> 0
2942 byteLength = byteLength >>> 0
2943 if (!noAssert) checkOffset(offset, byteLength, this.length)
2944
2945 var val = this[offset]
2946 var mul = 1
2947 var i = 0
2948 while (++i < byteLength && (mul *= 0x100)) {
2949 val += this[offset + i] * mul
2950 }
2951
2952 return val
2953}
2954
2955Buffer.prototype.readUintBE =
2956Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
2957 offset = offset >>> 0
2958 byteLength = byteLength >>> 0
2959 if (!noAssert) {
2960 checkOffset(offset, byteLength, this.length)
2961 }
2962
2963 var val = this[offset + --byteLength]
2964 var mul = 1
2965 while (byteLength > 0 && (mul *= 0x100)) {
2966 val += this[offset + --byteLength] * mul
2967 }
2968
2969 return val
2970}
2971
2972Buffer.prototype.readUint8 =
2973Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
2974 offset = offset >>> 0
2975 if (!noAssert) checkOffset(offset, 1, this.length)
2976 return this[offset]
2977}
2978
2979Buffer.prototype.readUint16LE =
2980Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
2981 offset = offset >>> 0
2982 if (!noAssert) checkOffset(offset, 2, this.length)
2983 return this[offset] | (this[offset + 1] << 8)
2984}
2985
2986Buffer.prototype.readUint16BE =
2987Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
2988 offset = offset >>> 0
2989 if (!noAssert) checkOffset(offset, 2, this.length)
2990 return (this[offset] << 8) | this[offset + 1]
2991}
2992
2993Buffer.prototype.readUint32LE =
2994Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
2995 offset = offset >>> 0
2996 if (!noAssert) checkOffset(offset, 4, this.length)
2997
2998 return ((this[offset]) |
2999 (this[offset + 1] << 8) |
3000 (this[offset + 2] << 16)) +
3001 (this[offset + 3] * 0x1000000)
3002}
3003
3004Buffer.prototype.readUint32BE =
3005Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
3006 offset = offset >>> 0
3007 if (!noAssert) checkOffset(offset, 4, this.length)
3008
3009 return (this[offset] * 0x1000000) +
3010 ((this[offset + 1] << 16) |
3011 (this[offset + 2] << 8) |
3012 this[offset + 3])
3013}
3014
3015Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
3016 offset = offset >>> 0
3017 byteLength = byteLength >>> 0
3018 if (!noAssert) checkOffset(offset, byteLength, this.length)
3019
3020 var val = this[offset]
3021 var mul = 1
3022 var i = 0
3023 while (++i < byteLength && (mul *= 0x100)) {
3024 val += this[offset + i] * mul
3025 }
3026 mul *= 0x80
3027
3028 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
3029
3030 return val
3031}
3032
3033Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
3034 offset = offset >>> 0
3035 byteLength = byteLength >>> 0
3036 if (!noAssert) checkOffset(offset, byteLength, this.length)
3037
3038 var i = byteLength
3039 var mul = 1
3040 var val = this[offset + --i]
3041 while (i > 0 && (mul *= 0x100)) {
3042 val += this[offset + --i] * mul
3043 }
3044 mul *= 0x80
3045
3046 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
3047
3048 return val
3049}
3050
3051Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
3052 offset = offset >>> 0
3053 if (!noAssert) checkOffset(offset, 1, this.length)
3054 if (!(this[offset] & 0x80)) return (this[offset])
3055 return ((0xff - this[offset] + 1) * -1)
3056}
3057
3058Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
3059 offset = offset >>> 0
3060 if (!noAssert) checkOffset(offset, 2, this.length)
3061 var val = this[offset] | (this[offset + 1] << 8)
3062 return (val & 0x8000) ? val | 0xFFFF0000 : val
3063}
3064
3065Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
3066 offset = offset >>> 0
3067 if (!noAssert) checkOffset(offset, 2, this.length)
3068 var val = this[offset + 1] | (this[offset] << 8)
3069 return (val & 0x8000) ? val | 0xFFFF0000 : val
3070}
3071
3072Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
3073 offset = offset >>> 0
3074 if (!noAssert) checkOffset(offset, 4, this.length)
3075
3076 return (this[offset]) |
3077 (this[offset + 1] << 8) |
3078 (this[offset + 2] << 16) |
3079 (this[offset + 3] << 24)
3080}
3081
3082Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
3083 offset = offset >>> 0
3084 if (!noAssert) checkOffset(offset, 4, this.length)
3085
3086 return (this[offset] << 24) |
3087 (this[offset + 1] << 16) |
3088 (this[offset + 2] << 8) |
3089 (this[offset + 3])
3090}
3091
3092Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
3093 offset = offset >>> 0
3094 if (!noAssert) checkOffset(offset, 4, this.length)
3095 return ieee754.read(this, offset, true, 23, 4)
3096}
3097
3098Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
3099 offset = offset >>> 0
3100 if (!noAssert) checkOffset(offset, 4, this.length)
3101 return ieee754.read(this, offset, false, 23, 4)
3102}
3103
3104Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
3105 offset = offset >>> 0
3106 if (!noAssert) checkOffset(offset, 8, this.length)
3107 return ieee754.read(this, offset, true, 52, 8)
3108}
3109
3110Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
3111 offset = offset >>> 0
3112 if (!noAssert) checkOffset(offset, 8, this.length)
3113 return ieee754.read(this, offset, false, 52, 8)
3114}
3115
3116function checkInt (buf, value, offset, ext, max, min) {
3117 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
3118 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
3119 if (offset + ext > buf.length) throw new RangeError('Index out of range')
3120}
3121
3122Buffer.prototype.writeUintLE =
3123Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
3124 value = +value
3125 offset = offset >>> 0
3126 byteLength = byteLength >>> 0
3127 if (!noAssert) {
3128 var maxBytes = Math.pow(2, 8 * byteLength) - 1
3129 checkInt(this, value, offset, byteLength, maxBytes, 0)
3130 }
3131
3132 var mul = 1
3133 var i = 0
3134 this[offset] = value & 0xFF
3135 while (++i < byteLength && (mul *= 0x100)) {
3136 this[offset + i] = (value / mul) & 0xFF
3137 }
3138
3139 return offset + byteLength
3140}
3141
3142Buffer.prototype.writeUintBE =
3143Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
3144 value = +value
3145 offset = offset >>> 0
3146 byteLength = byteLength >>> 0
3147 if (!noAssert) {
3148 var maxBytes = Math.pow(2, 8 * byteLength) - 1
3149 checkInt(this, value, offset, byteLength, maxBytes, 0)
3150 }
3151
3152 var i = byteLength - 1
3153 var mul = 1
3154 this[offset + i] = value & 0xFF
3155 while (--i >= 0 && (mul *= 0x100)) {
3156 this[offset + i] = (value / mul) & 0xFF
3157 }
3158
3159 return offset + byteLength
3160}
3161
3162Buffer.prototype.writeUint8 =
3163Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
3164 value = +value
3165 offset = offset >>> 0
3166 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
3167 this[offset] = (value & 0xff)
3168 return offset + 1
3169}
3170
3171Buffer.prototype.writeUint16LE =
3172Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
3173 value = +value
3174 offset = offset >>> 0
3175 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
3176 this[offset] = (value & 0xff)
3177 this[offset + 1] = (value >>> 8)
3178 return offset + 2
3179}
3180
3181Buffer.prototype.writeUint16BE =
3182Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
3183 value = +value
3184 offset = offset >>> 0
3185 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
3186 this[offset] = (value >>> 8)
3187 this[offset + 1] = (value & 0xff)
3188 return offset + 2
3189}
3190
3191Buffer.prototype.writeUint32LE =
3192Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
3193 value = +value
3194 offset = offset >>> 0
3195 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
3196 this[offset + 3] = (value >>> 24)
3197 this[offset + 2] = (value >>> 16)
3198 this[offset + 1] = (value >>> 8)
3199 this[offset] = (value & 0xff)
3200 return offset + 4
3201}
3202
3203Buffer.prototype.writeUint32BE =
3204Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
3205 value = +value
3206 offset = offset >>> 0
3207 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
3208 this[offset] = (value >>> 24)
3209 this[offset + 1] = (value >>> 16)
3210 this[offset + 2] = (value >>> 8)
3211 this[offset + 3] = (value & 0xff)
3212 return offset + 4
3213}
3214
3215Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
3216 value = +value
3217 offset = offset >>> 0
3218 if (!noAssert) {
3219 var limit = Math.pow(2, (8 * byteLength) - 1)
3220
3221 checkInt(this, value, offset, byteLength, limit - 1, -limit)
3222 }
3223
3224 var i = 0
3225 var mul = 1
3226 var sub = 0
3227 this[offset] = value & 0xFF
3228 while (++i < byteLength && (mul *= 0x100)) {
3229 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
3230 sub = 1
3231 }
3232 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
3233 }
3234
3235 return offset + byteLength
3236}
3237
3238Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
3239 value = +value
3240 offset = offset >>> 0
3241 if (!noAssert) {
3242 var limit = Math.pow(2, (8 * byteLength) - 1)
3243
3244 checkInt(this, value, offset, byteLength, limit - 1, -limit)
3245 }
3246
3247 var i = byteLength - 1
3248 var mul = 1
3249 var sub = 0
3250 this[offset + i] = value & 0xFF
3251 while (--i >= 0 && (mul *= 0x100)) {
3252 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
3253 sub = 1
3254 }
3255 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
3256 }
3257
3258 return offset + byteLength
3259}
3260
3261Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
3262 value = +value
3263 offset = offset >>> 0
3264 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
3265 if (value < 0) value = 0xff + value + 1
3266 this[offset] = (value & 0xff)
3267 return offset + 1
3268}
3269
3270Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
3271 value = +value
3272 offset = offset >>> 0
3273 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
3274 this[offset] = (value & 0xff)
3275 this[offset + 1] = (value >>> 8)
3276 return offset + 2
3277}
3278
3279Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
3280 value = +value
3281 offset = offset >>> 0
3282 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
3283 this[offset] = (value >>> 8)
3284 this[offset + 1] = (value & 0xff)
3285 return offset + 2
3286}
3287
3288Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
3289 value = +value
3290 offset = offset >>> 0
3291 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
3292 this[offset] = (value & 0xff)
3293 this[offset + 1] = (value >>> 8)
3294 this[offset + 2] = (value >>> 16)
3295 this[offset + 3] = (value >>> 24)
3296 return offset + 4
3297}
3298
3299Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
3300 value = +value
3301 offset = offset >>> 0
3302 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
3303 if (value < 0) value = 0xffffffff + value + 1
3304 this[offset] = (value >>> 24)
3305 this[offset + 1] = (value >>> 16)
3306 this[offset + 2] = (value >>> 8)
3307 this[offset + 3] = (value & 0xff)
3308 return offset + 4
3309}
3310
3311function checkIEEE754 (buf, value, offset, ext, max, min) {
3312 if (offset + ext > buf.length) throw new RangeError('Index out of range')
3313 if (offset < 0) throw new RangeError('Index out of range')
3314}
3315
3316function writeFloat (buf, value, offset, littleEndian, noAssert) {
3317 value = +value
3318 offset = offset >>> 0
3319 if (!noAssert) {
3320 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
3321 }
3322 ieee754.write(buf, value, offset, littleEndian, 23, 4)
3323 return offset + 4
3324}
3325
3326Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
3327 return writeFloat(this, value, offset, true, noAssert)
3328}
3329
3330Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
3331 return writeFloat(this, value, offset, false, noAssert)
3332}
3333
3334function writeDouble (buf, value, offset, littleEndian, noAssert) {
3335 value = +value
3336 offset = offset >>> 0
3337 if (!noAssert) {
3338 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
3339 }
3340 ieee754.write(buf, value, offset, littleEndian, 52, 8)
3341 return offset + 8
3342}
3343
3344Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
3345 return writeDouble(this, value, offset, true, noAssert)
3346}
3347
3348Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
3349 return writeDouble(this, value, offset, false, noAssert)
3350}
3351
3352// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
3353Buffer.prototype.copy = function copy (target, targetStart, start, end) {
3354 if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
3355 if (!start) start = 0
3356 if (!end && end !== 0) end = this.length
3357 if (targetStart >= target.length) targetStart = target.length
3358 if (!targetStart) targetStart = 0
3359 if (end > 0 && end < start) end = start
3360
3361 // Copy 0 bytes; we're done
3362 if (end === start) return 0
3363 if (target.length === 0 || this.length === 0) return 0
3364
3365 // Fatal error conditions
3366 if (targetStart < 0) {
3367 throw new RangeError('targetStart out of bounds')
3368 }
3369 if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
3370 if (end < 0) throw new RangeError('sourceEnd out of bounds')
3371
3372 // Are we oob?
3373 if (end > this.length) end = this.length
3374 if (target.length - targetStart < end - start) {
3375 end = target.length - targetStart + start
3376 }
3377
3378 var len = end - start
3379
3380 if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
3381 // Use built-in when available, missing from IE11
3382 this.copyWithin(targetStart, start, end)
3383 } else {
3384 Uint8Array.prototype.set.call(
3385 target,
3386 this.subarray(start, end),
3387 targetStart
3388 )
3389 }
3390
3391 return len
3392}
3393
3394// Usage:
3395// buffer.fill(number[, offset[, end]])
3396// buffer.fill(buffer[, offset[, end]])
3397// buffer.fill(string[, offset[, end]][, encoding])
3398Buffer.prototype.fill = function fill (val, start, end, encoding) {
3399 // Handle string cases:
3400 if (typeof val === 'string') {
3401 if (typeof start === 'string') {
3402 encoding = start
3403 start = 0
3404 end = this.length
3405 } else if (typeof end === 'string') {
3406 encoding = end
3407 end = this.length
3408 }
3409 if (encoding !== undefined && typeof encoding !== 'string') {
3410 throw new TypeError('encoding must be a string')
3411 }
3412 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
3413 throw new TypeError('Unknown encoding: ' + encoding)
3414 }
3415 if (val.length === 1) {
3416 var code = val.charCodeAt(0)
3417 if ((encoding === 'utf8' && code < 128) ||
3418 encoding === 'latin1') {
3419 // Fast path: If `val` fits into a single byte, use that numeric value.
3420 val = code
3421 }
3422 }
3423 } else if (typeof val === 'number') {
3424 val = val & 255
3425 } else if (typeof val === 'boolean') {
3426 val = Number(val)
3427 }
3428
3429 // Invalid ranges are not set to a default, so can range check early.
3430 if (start < 0 || this.length < start || this.length < end) {
3431 throw new RangeError('Out of range index')
3432 }
3433
3434 if (end <= start) {
3435 return this
3436 }
3437
3438 start = start >>> 0
3439 end = end === undefined ? this.length : end >>> 0
3440
3441 if (!val) val = 0
3442
3443 var i
3444 if (typeof val === 'number') {
3445 for (i = start; i < end; ++i) {
3446 this[i] = val
3447 }
3448 } else {
3449 var bytes = Buffer.isBuffer(val)
3450 ? val
3451 : Buffer.from(val, encoding)
3452 var len = bytes.length
3453 if (len === 0) {
3454 throw new TypeError('The value "' + val +
3455 '" is invalid for argument "value"')
3456 }
3457 for (i = 0; i < end - start; ++i) {
3458 this[i + start] = bytes[i % len]
3459 }
3460 }
3461
3462 return this
3463}
3464
3465// HELPER FUNCTIONS
3466// ================
3467
3468var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
3469
3470function base64clean (str) {
3471 // Node takes equal signs as end of the Base64 encoding
3472 str = str.split('=')[0]
3473 // Node strips out invalid characters like \n and \t from the string, base64-js does not
3474 str = str.trim().replace(INVALID_BASE64_RE, '')
3475 // Node converts strings with length < 2 to ''
3476 if (str.length < 2) return ''
3477 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
3478 while (str.length % 4 !== 0) {
3479 str = str + '='
3480 }
3481 return str
3482}
3483
3484function utf8ToBytes (string, units) {
3485 units = units || Infinity
3486 var codePoint
3487 var length = string.length
3488 var leadSurrogate = null
3489 var bytes = []
3490
3491 for (var i = 0; i < length; ++i) {
3492 codePoint = string.charCodeAt(i)
3493
3494 // is surrogate component
3495 if (codePoint > 0xD7FF && codePoint < 0xE000) {
3496 // last char was a lead
3497 if (!leadSurrogate) {
3498 // no lead yet
3499 if (codePoint > 0xDBFF) {
3500 // unexpected trail
3501 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3502 continue
3503 } else if (i + 1 === length) {
3504 // unpaired lead
3505 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3506 continue
3507 }
3508
3509 // valid lead
3510 leadSurrogate = codePoint
3511
3512 continue
3513 }
3514
3515 // 2 leads in a row
3516 if (codePoint < 0xDC00) {
3517 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3518 leadSurrogate = codePoint
3519 continue
3520 }
3521
3522 // valid surrogate pair
3523 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
3524 } else if (leadSurrogate) {
3525 // valid bmp char, but last char was a lead
3526 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3527 }
3528
3529 leadSurrogate = null
3530
3531 // encode utf8
3532 if (codePoint < 0x80) {
3533 if ((units -= 1) < 0) break
3534 bytes.push(codePoint)
3535 } else if (codePoint < 0x800) {
3536 if ((units -= 2) < 0) break
3537 bytes.push(
3538 codePoint >> 0x6 | 0xC0,
3539 codePoint & 0x3F | 0x80
3540 )
3541 } else if (codePoint < 0x10000) {
3542 if ((units -= 3) < 0) break
3543 bytes.push(
3544 codePoint >> 0xC | 0xE0,
3545 codePoint >> 0x6 & 0x3F | 0x80,
3546 codePoint & 0x3F | 0x80
3547 )
3548 } else if (codePoint < 0x110000) {
3549 if ((units -= 4) < 0) break
3550 bytes.push(
3551 codePoint >> 0x12 | 0xF0,
3552 codePoint >> 0xC & 0x3F | 0x80,
3553 codePoint >> 0x6 & 0x3F | 0x80,
3554 codePoint & 0x3F | 0x80
3555 )
3556 } else {
3557 throw new Error('Invalid code point')
3558 }
3559 }
3560
3561 return bytes
3562}
3563
3564function asciiToBytes (str) {
3565 var byteArray = []
3566 for (var i = 0; i < str.length; ++i) {
3567 // Node's code seems to be doing this and not & 0x7F..
3568 byteArray.push(str.charCodeAt(i) & 0xFF)
3569 }
3570 return byteArray
3571}
3572
3573function utf16leToBytes (str, units) {
3574 var c, hi, lo
3575 var byteArray = []
3576 for (var i = 0; i < str.length; ++i) {
3577 if ((units -= 2) < 0) break
3578
3579 c = str.charCodeAt(i)
3580 hi = c >> 8
3581 lo = c % 256
3582 byteArray.push(lo)
3583 byteArray.push(hi)
3584 }
3585
3586 return byteArray
3587}
3588
3589function base64ToBytes (str) {
3590 return base64.toByteArray(base64clean(str))
3591}
3592
3593function blitBuffer (src, dst, offset, length) {
3594 for (var i = 0; i < length; ++i) {
3595 if ((i + offset >= dst.length) || (i >= src.length)) break
3596 dst[i + offset] = src[i]
3597 }
3598 return i
3599}
3600
3601// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
3602// the `instanceof` check but they should be treated as of that type.
3603// See: https://github.com/feross/buffer/issues/166
3604function isInstance (obj, type) {
3605 return obj instanceof type ||
3606 (obj != null && obj.constructor != null && obj.constructor.name != null &&
3607 obj.constructor.name === type.name)
3608}
3609function numberIsNaN (obj) {
3610 // For IE11 support
3611 return obj !== obj // eslint-disable-line no-self-compare
3612}
3613
3614// Create lookup table for `toString('hex')`
3615// See: https://github.com/feross/buffer/issues/219
3616var hexSliceLookupTable = (function () {
3617 var alphabet = '0123456789abcdef'
3618 var table = new Array(256)
3619 for (var i = 0; i < 16; ++i) {
3620 var i16 = i * 16
3621 for (var j = 0; j < 16; ++j) {
3622 table[i16 + j] = alphabet[i] + alphabet[j]
3623 }
3624 }
3625 return table
3626})()
3627
3628}).call(this)}).call(this,_dereq_(13).Buffer)
3629},{"10":10,"13":13,"30":30}],14:[function(_dereq_,module,exports){
3630// Copyright Joyent, Inc. and other Node contributors.
3631//
3632// Permission is hereby granted, free of charge, to any person obtaining a
3633// copy of this software and associated documentation files (the
3634// "Software"), to deal in the Software without restriction, including
3635// without limitation the rights to use, copy, modify, merge, publish,
3636// distribute, sublicense, and/or sell copies of the Software, and to permit
3637// persons to whom the Software is furnished to do so, subject to the
3638// following conditions:
3639//
3640// The above copyright notice and this permission notice shall be included
3641// in all copies or substantial portions of the Software.
3642//
3643// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3644// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3645// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3646// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3647// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3648// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3649// USE OR OTHER DEALINGS IN THE SOFTWARE.
3650
3651// NOTE: These type checking functions intentionally don't use `instanceof`
3652// because it is fragile and can be easily faked with `Object.create()`.
3653
3654function isArray(arg) {
3655 if (Array.isArray) {
3656 return Array.isArray(arg);
3657 }
3658 return objectToString(arg) === '[object Array]';
3659}
3660exports.isArray = isArray;
3661
3662function isBoolean(arg) {
3663 return typeof arg === 'boolean';
3664}
3665exports.isBoolean = isBoolean;
3666
3667function isNull(arg) {
3668 return arg === null;
3669}
3670exports.isNull = isNull;
3671
3672function isNullOrUndefined(arg) {
3673 return arg == null;
3674}
3675exports.isNullOrUndefined = isNullOrUndefined;
3676
3677function isNumber(arg) {
3678 return typeof arg === 'number';
3679}
3680exports.isNumber = isNumber;
3681
3682function isString(arg) {
3683 return typeof arg === 'string';
3684}
3685exports.isString = isString;
3686
3687function isSymbol(arg) {
3688 return typeof arg === 'symbol';
3689}
3690exports.isSymbol = isSymbol;
3691
3692function isUndefined(arg) {
3693 return arg === void 0;
3694}
3695exports.isUndefined = isUndefined;
3696
3697function isRegExp(re) {
3698 return objectToString(re) === '[object RegExp]';
3699}
3700exports.isRegExp = isRegExp;
3701
3702function isObject(arg) {
3703 return typeof arg === 'object' && arg !== null;
3704}
3705exports.isObject = isObject;
3706
3707function isDate(d) {
3708 return objectToString(d) === '[object Date]';
3709}
3710exports.isDate = isDate;
3711
3712function isError(e) {
3713 return (objectToString(e) === '[object Error]' || e instanceof Error);
3714}
3715exports.isError = isError;
3716
3717function isFunction(arg) {
3718 return typeof arg === 'function';
3719}
3720exports.isFunction = isFunction;
3721
3722function isPrimitive(arg) {
3723 return arg === null ||
3724 typeof arg === 'boolean' ||
3725 typeof arg === 'number' ||
3726 typeof arg === 'string' ||
3727 typeof arg === 'symbol' || // ES6 symbol
3728 typeof arg === 'undefined';
3729}
3730exports.isPrimitive = isPrimitive;
3731
3732exports.isBuffer = _dereq_(13).Buffer.isBuffer;
3733
3734function objectToString(o) {
3735 return Object.prototype.toString.call(o);
3736}
3737
3738},{"13":13}],15:[function(_dereq_,module,exports){
3739var Buffer = _dereq_(13).Buffer
3740
3741var CHARS = '.PYFGCRLAOEUIDHTNSQJKXBMWVZ_pyfgcrlaoeuidhtnsqjkxbmwvz1234567890'
3742 .split('').sort().join('')
3743
3744module.exports = function (chars, exports) {
3745 chars = chars || CHARS
3746 exports = exports || {}
3747 if(chars.length !== 64) throw new Error('a base 64 encoding requires 64 chars')
3748
3749 var codeToIndex = new Buffer(128)
3750 codeToIndex.fill()
3751
3752 for(var i = 0; i < 64; i++) {
3753 var code = chars.charCodeAt(i)
3754 codeToIndex[code] = i
3755 }
3756
3757 exports.encode = function (data) {
3758 var s = '', l = data.length, hang = 0
3759 for(var i = 0; i < l; i++) {
3760 var v = data[i]
3761
3762 switch (i % 3) {
3763 case 0:
3764 s += chars[v >> 2]
3765 hang = (v & 3) << 4
3766 break;
3767 case 1:
3768 s += chars[hang | v >> 4]
3769 hang = (v & 0xf) << 2
3770 break;
3771 case 2:
3772 s += chars[hang | v >> 6]
3773 s += chars[v & 0x3f]
3774 hang = 0
3775 break;
3776 }
3777
3778 }
3779 if(l%3) s += chars[hang]
3780 return s
3781 }
3782 exports.decode = function (str) {
3783 var l = str.length, j = 0
3784 var b = new Buffer(~~((l/4)*3)), hang = 0
3785
3786 for(var i = 0; i < l; i++) {
3787 var v = codeToIndex[str.charCodeAt(i)]
3788
3789 switch (i % 4) {
3790 case 0:
3791 hang = v << 2;
3792 break;
3793 case 1:
3794 b[j++] = hang | v >> 4
3795 hang = (v << 4) & 0xff
3796 break;
3797 case 2:
3798 b[j++] = hang | v >> 2
3799 hang = (v << 6) & 0xff
3800 break;
3801 case 3:
3802 b[j++] = hang | v
3803 break;
3804 }
3805
3806 }
3807 return b
3808 }
3809 return exports
3810}
3811
3812module.exports(CHARS, module.exports)
3813
3814
3815},{"13":13}],16:[function(_dereq_,module,exports){
3816var AbstractIterator = _dereq_(21).AbstractIterator
3817var inherits = _dereq_(37)
3818
3819function DeferredIterator (db, options) {
3820 AbstractIterator.call(this, db)
3821
3822 this._options = options
3823 this._iterator = null
3824 this._operations = []
3825}
3826
3827inherits(DeferredIterator, AbstractIterator)
3828
3829DeferredIterator.prototype.setDb = function (db) {
3830 var it = this._iterator = db.iterator(this._options)
3831 this._operations.forEach(function (op) {
3832 it[op.method].apply(it, op.args)
3833 })
3834}
3835
3836DeferredIterator.prototype._operation = function (method, args) {
3837 if (this._iterator) return this._iterator[method].apply(this._iterator, args)
3838 this._operations.push({ method: method, args: args })
3839}
3840
3841'next end'.split(' ').forEach(function (m) {
3842 DeferredIterator.prototype['_' + m] = function () {
3843 this._operation(m, arguments)
3844 }
3845})
3846
3847// Must defer seek() rather than _seek() because it requires db._serializeKey to be available
3848DeferredIterator.prototype.seek = function () {
3849 this._operation('seek', arguments)
3850}
3851
3852module.exports = DeferredIterator
3853
3854},{"21":21,"37":37}],17:[function(_dereq_,module,exports){
3855var AbstractLevelDOWN = _dereq_(21).AbstractLevelDOWN
3856var inherits = _dereq_(37)
3857var DeferredIterator = _dereq_(16)
3858var deferrables = 'put get del batch clear'.split(' ')
3859var optionalDeferrables = 'approximateSize compactRange'.split(' ')
3860
3861function DeferredLevelDOWN (db) {
3862 AbstractLevelDOWN.call(this, db.supports || {})
3863
3864 // TODO (future major): remove this fallback; db must have manifest that
3865 // declares approximateSize and compactRange in additionalMethods.
3866 optionalDeferrables.forEach(function (m) {
3867 if (typeof db[m] === 'function' && !this.supports.additionalMethods[m]) {
3868 this.supports.additionalMethods[m] = true
3869 }
3870 }, this)
3871
3872 this._db = db
3873 this._operations = []
3874 closed(this)
3875}
3876
3877inherits(DeferredLevelDOWN, AbstractLevelDOWN)
3878
3879DeferredLevelDOWN.prototype.type = 'deferred-leveldown'
3880
3881DeferredLevelDOWN.prototype._open = function (options, callback) {
3882 var self = this
3883
3884 this._db.open(options, function (err) {
3885 if (err) return callback(err)
3886
3887 self._operations.forEach(function (op) {
3888 if (op.iterator) {
3889 op.iterator.setDb(self._db)
3890 } else {
3891 self._db[op.method].apply(self._db, op.args)
3892 }
3893 })
3894 self._operations = []
3895
3896 open(self)
3897 callback()
3898 })
3899}
3900
3901DeferredLevelDOWN.prototype._close = function (callback) {
3902 var self = this
3903
3904 this._db.close(function (err) {
3905 if (err) return callback(err)
3906 closed(self)
3907 callback()
3908 })
3909}
3910
3911function open (self) {
3912 deferrables.concat('iterator').forEach(function (m) {
3913 self['_' + m] = function () {
3914 return this._db[m].apply(this._db, arguments)
3915 }
3916 })
3917 Object.keys(self.supports.additionalMethods).forEach(function (m) {
3918 self[m] = function () {
3919 return this._db[m].apply(this._db, arguments)
3920 }
3921 })
3922}
3923
3924function closed (self) {
3925 deferrables.forEach(function (m) {
3926 self['_' + m] = function () {
3927 this._operations.push({ method: m, args: arguments })
3928 }
3929 })
3930 Object.keys(self.supports.additionalMethods).forEach(function (m) {
3931 self[m] = function () {
3932 this._operations.push({ method: m, args: arguments })
3933 }
3934 })
3935 self._iterator = function (options) {
3936 var it = new DeferredIterator(self, options)
3937 this._operations.push({ iterator: it })
3938 return it
3939 }
3940}
3941
3942DeferredLevelDOWN.prototype._serializeKey = function (key) {
3943 return key
3944}
3945
3946DeferredLevelDOWN.prototype._serializeValue = function (value) {
3947 return value
3948}
3949
3950module.exports = DeferredLevelDOWN
3951module.exports.DeferredIterator = DeferredIterator
3952
3953},{"16":16,"21":21,"37":37}],18:[function(_dereq_,module,exports){
3954var nextTick = _dereq_(22)
3955
3956function AbstractChainedBatch (db) {
3957 if (typeof db !== 'object' || db === null) {
3958 throw new TypeError('First argument must be an abstract-leveldown compliant store')
3959 }
3960
3961 this.db = db
3962 this._operations = []
3963 this._written = false
3964}
3965
3966AbstractChainedBatch.prototype._checkWritten = function () {
3967 if (this._written) {
3968 throw new Error('write() already called on this batch')
3969 }
3970}
3971
3972AbstractChainedBatch.prototype.put = function (key, value) {
3973 this._checkWritten()
3974
3975 var err = this.db._checkKey(key) || this.db._checkValue(value)
3976 if (err) throw err
3977
3978 key = this.db._serializeKey(key)
3979 value = this.db._serializeValue(value)
3980
3981 this._put(key, value)
3982
3983 return this
3984}
3985
3986AbstractChainedBatch.prototype._put = function (key, value) {
3987 this._operations.push({ type: 'put', key: key, value: value })
3988}
3989
3990AbstractChainedBatch.prototype.del = function (key) {
3991 this._checkWritten()
3992
3993 var err = this.db._checkKey(key)
3994 if (err) throw err
3995
3996 key = this.db._serializeKey(key)
3997 this._del(key)
3998
3999 return this
4000}
4001
4002AbstractChainedBatch.prototype._del = function (key) {
4003 this._operations.push({ type: 'del', key: key })
4004}
4005
4006AbstractChainedBatch.prototype.clear = function () {
4007 this._checkWritten()
4008 this._clear()
4009
4010 return this
4011}
4012
4013AbstractChainedBatch.prototype._clear = function () {
4014 this._operations = []
4015}
4016
4017AbstractChainedBatch.prototype.write = function (options, callback) {
4018 this._checkWritten()
4019
4020 if (typeof options === 'function') { callback = options }
4021 if (typeof callback !== 'function') {
4022 throw new Error('write() requires a callback argument')
4023 }
4024 if (typeof options !== 'object' || options === null) {
4025 options = {}
4026 }
4027
4028 this._written = true
4029 this._write(options, callback)
4030}
4031
4032AbstractChainedBatch.prototype._write = function (options, callback) {
4033 this.db._batch(this._operations, options, callback)
4034}
4035
4036// Expose browser-compatible nextTick for dependents
4037AbstractChainedBatch.prototype._nextTick = nextTick
4038
4039module.exports = AbstractChainedBatch
4040
4041},{"22":22}],19:[function(_dereq_,module,exports){
4042var nextTick = _dereq_(22)
4043
4044function AbstractIterator (db) {
4045 if (typeof db !== 'object' || db === null) {
4046 throw new TypeError('First argument must be an abstract-leveldown compliant store')
4047 }
4048
4049 this.db = db
4050 this._ended = false
4051 this._nexting = false
4052}
4053
4054AbstractIterator.prototype.next = function (callback) {
4055 var self = this
4056
4057 if (typeof callback !== 'function') {
4058 throw new Error('next() requires a callback argument')
4059 }
4060
4061 if (self._ended) {
4062 nextTick(callback, new Error('cannot call next() after end()'))
4063 return self
4064 }
4065
4066 if (self._nexting) {
4067 nextTick(callback, new Error('cannot call next() before previous next() has completed'))
4068 return self
4069 }
4070
4071 self._nexting = true
4072 self._next(function () {
4073 self._nexting = false
4074 callback.apply(null, arguments)
4075 })
4076
4077 return self
4078}
4079
4080AbstractIterator.prototype._next = function (callback) {
4081 nextTick(callback)
4082}
4083
4084AbstractIterator.prototype.seek = function (target) {
4085 if (this._ended) {
4086 throw new Error('cannot call seek() after end()')
4087 }
4088 if (this._nexting) {
4089 throw new Error('cannot call seek() before next() has completed')
4090 }
4091
4092 target = this.db._serializeKey(target)
4093 this._seek(target)
4094}
4095
4096AbstractIterator.prototype._seek = function (target) {}
4097
4098AbstractIterator.prototype.end = function (callback) {
4099 if (typeof callback !== 'function') {
4100 throw new Error('end() requires a callback argument')
4101 }
4102
4103 if (this._ended) {
4104 return nextTick(callback, new Error('end() already called on iterator'))
4105 }
4106
4107 this._ended = true
4108 this._end(callback)
4109}
4110
4111AbstractIterator.prototype._end = function (callback) {
4112 nextTick(callback)
4113}
4114
4115// Expose browser-compatible nextTick for dependents
4116AbstractIterator.prototype._nextTick = nextTick
4117
4118module.exports = AbstractIterator
4119
4120},{"22":22}],20:[function(_dereq_,module,exports){
4121var xtend = _dereq_(141)
4122var supports = _dereq_(58)
4123var Buffer = _dereq_(13).Buffer
4124var AbstractIterator = _dereq_(19)
4125var AbstractChainedBatch = _dereq_(18)
4126var nextTick = _dereq_(22)
4127var hasOwnProperty = Object.prototype.hasOwnProperty
4128var rangeOptions = 'start end gt gte lt lte'.split(' ')
4129
4130function AbstractLevelDOWN (manifest) {
4131 this.status = 'new'
4132
4133 // TODO (next major): make this mandatory
4134 this.supports = supports(manifest, {
4135 status: true
4136 })
4137}
4138
4139AbstractLevelDOWN.prototype.open = function (options, callback) {
4140 var self = this
4141 var oldStatus = this.status
4142
4143 if (typeof options === 'function') callback = options
4144
4145 if (typeof callback !== 'function') {
4146 throw new Error('open() requires a callback argument')
4147 }
4148
4149 if (typeof options !== 'object' || options === null) options = {}
4150
4151 options.createIfMissing = options.createIfMissing !== false
4152 options.errorIfExists = !!options.errorIfExists
4153
4154 this.status = 'opening'
4155 this._open(options, function (err) {
4156 if (err) {
4157 self.status = oldStatus
4158 return callback(err)
4159 }
4160 self.status = 'open'
4161 callback()
4162 })
4163}
4164
4165AbstractLevelDOWN.prototype._open = function (options, callback) {
4166 nextTick(callback)
4167}
4168
4169AbstractLevelDOWN.prototype.close = function (callback) {
4170 var self = this
4171 var oldStatus = this.status
4172
4173 if (typeof callback !== 'function') {
4174 throw new Error('close() requires a callback argument')
4175 }
4176
4177 this.status = 'closing'
4178 this._close(function (err) {
4179 if (err) {
4180 self.status = oldStatus
4181 return callback(err)
4182 }
4183 self.status = 'closed'
4184 callback()
4185 })
4186}
4187
4188AbstractLevelDOWN.prototype._close = function (callback) {
4189 nextTick(callback)
4190}
4191
4192AbstractLevelDOWN.prototype.get = function (key, options, callback) {
4193 if (typeof options === 'function') callback = options
4194
4195 if (typeof callback !== 'function') {
4196 throw new Error('get() requires a callback argument')
4197 }
4198
4199 var err = this._checkKey(key)
4200 if (err) return nextTick(callback, err)
4201
4202 key = this._serializeKey(key)
4203
4204 if (typeof options !== 'object' || options === null) options = {}
4205
4206 options.asBuffer = options.asBuffer !== false
4207
4208 this._get(key, options, callback)
4209}
4210
4211AbstractLevelDOWN.prototype._get = function (key, options, callback) {
4212 nextTick(function () { callback(new Error('NotFound')) })
4213}
4214
4215AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
4216 if (typeof options === 'function') callback = options
4217
4218 if (typeof callback !== 'function') {
4219 throw new Error('put() requires a callback argument')
4220 }
4221
4222 var err = this._checkKey(key) || this._checkValue(value)
4223 if (err) return nextTick(callback, err)
4224
4225 key = this._serializeKey(key)
4226 value = this._serializeValue(value)
4227
4228 if (typeof options !== 'object' || options === null) options = {}
4229
4230 this._put(key, value, options, callback)
4231}
4232
4233AbstractLevelDOWN.prototype._put = function (key, value, options, callback) {
4234 nextTick(callback)
4235}
4236
4237AbstractLevelDOWN.prototype.del = function (key, options, callback) {
4238 if (typeof options === 'function') callback = options
4239
4240 if (typeof callback !== 'function') {
4241 throw new Error('del() requires a callback argument')
4242 }
4243
4244 var err = this._checkKey(key)
4245 if (err) return nextTick(callback, err)
4246
4247 key = this._serializeKey(key)
4248
4249 if (typeof options !== 'object' || options === null) options = {}
4250
4251 this._del(key, options, callback)
4252}
4253
4254AbstractLevelDOWN.prototype._del = function (key, options, callback) {
4255 nextTick(callback)
4256}
4257
4258AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
4259 if (!arguments.length) return this._chainedBatch()
4260
4261 if (typeof options === 'function') callback = options
4262
4263 if (typeof array === 'function') callback = array
4264
4265 if (typeof callback !== 'function') {
4266 throw new Error('batch(array) requires a callback argument')
4267 }
4268
4269 if (!Array.isArray(array)) {
4270 return nextTick(callback, new Error('batch(array) requires an array argument'))
4271 }
4272
4273 if (array.length === 0) {
4274 return nextTick(callback)
4275 }
4276
4277 if (typeof options !== 'object' || options === null) options = {}
4278
4279 var serialized = new Array(array.length)
4280
4281 for (var i = 0; i < array.length; i++) {
4282 if (typeof array[i] !== 'object' || array[i] === null) {
4283 return nextTick(callback, new Error('batch(array) element must be an object and not `null`'))
4284 }
4285
4286 var e = xtend(array[i])
4287
4288 if (e.type !== 'put' && e.type !== 'del') {
4289 return nextTick(callback, new Error("`type` must be 'put' or 'del'"))
4290 }
4291
4292 var err = this._checkKey(e.key)
4293 if (err) return nextTick(callback, err)
4294
4295 e.key = this._serializeKey(e.key)
4296
4297 if (e.type === 'put') {
4298 var valueErr = this._checkValue(e.value)
4299 if (valueErr) return nextTick(callback, valueErr)
4300
4301 e.value = this._serializeValue(e.value)
4302 }
4303
4304 serialized[i] = e
4305 }
4306
4307 this._batch(serialized, options, callback)
4308}
4309
4310AbstractLevelDOWN.prototype._batch = function (array, options, callback) {
4311 nextTick(callback)
4312}
4313
4314AbstractLevelDOWN.prototype.clear = function (options, callback) {
4315 if (typeof options === 'function') {
4316 callback = options
4317 } else if (typeof callback !== 'function') {
4318 throw new Error('clear() requires a callback argument')
4319 }
4320
4321 options = cleanRangeOptions(this, options)
4322 options.reverse = !!options.reverse
4323 options.limit = 'limit' in options ? options.limit : -1
4324
4325 this._clear(options, callback)
4326}
4327
4328AbstractLevelDOWN.prototype._clear = function (options, callback) {
4329 // Avoid setupIteratorOptions, would serialize range options a second time.
4330 options.keys = true
4331 options.values = false
4332 options.keyAsBuffer = true
4333 options.valueAsBuffer = true
4334
4335 var iterator = this._iterator(options)
4336 var emptyOptions = {}
4337 var self = this
4338
4339 var next = function (err) {
4340 if (err) {
4341 return iterator.end(function () {
4342 callback(err)
4343 })
4344 }
4345
4346 iterator.next(function (err, key) {
4347 if (err) return next(err)
4348 if (key === undefined) return iterator.end(callback)
4349
4350 // This could be optimized by using a batch, but the default _clear
4351 // is not meant to be fast. Implementations have more room to optimize
4352 // if they override _clear. Note: using _del bypasses key serialization.
4353 self._del(key, emptyOptions, next)
4354 })
4355 }
4356
4357 next()
4358}
4359
4360AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
4361 options = cleanRangeOptions(this, options)
4362
4363 options.reverse = !!options.reverse
4364 options.keys = options.keys !== false
4365 options.values = options.values !== false
4366 options.limit = 'limit' in options ? options.limit : -1
4367 options.keyAsBuffer = options.keyAsBuffer !== false
4368 options.valueAsBuffer = options.valueAsBuffer !== false
4369
4370 return options
4371}
4372
4373function cleanRangeOptions (db, options) {
4374 var result = {}
4375
4376 for (var k in options) {
4377 if (!hasOwnProperty.call(options, k)) continue
4378
4379 var opt = options[k]
4380
4381 if (isRangeOption(k)) {
4382 // Note that we don't reject nullish and empty options here. While
4383 // those types are invalid as keys, they are valid as range options.
4384 opt = db._serializeKey(opt)
4385 }
4386
4387 result[k] = opt
4388 }
4389
4390 return result
4391}
4392
4393function isRangeOption (k) {
4394 return rangeOptions.indexOf(k) !== -1
4395}
4396
4397AbstractLevelDOWN.prototype.iterator = function (options) {
4398 if (typeof options !== 'object' || options === null) options = {}
4399 options = this._setupIteratorOptions(options)
4400 return this._iterator(options)
4401}
4402
4403AbstractLevelDOWN.prototype._iterator = function (options) {
4404 return new AbstractIterator(this)
4405}
4406
4407AbstractLevelDOWN.prototype._chainedBatch = function () {
4408 return new AbstractChainedBatch(this)
4409}
4410
4411AbstractLevelDOWN.prototype._serializeKey = function (key) {
4412 return key
4413}
4414
4415AbstractLevelDOWN.prototype._serializeValue = function (value) {
4416 return value
4417}
4418
4419AbstractLevelDOWN.prototype._checkKey = function (key) {
4420 if (key === null || key === undefined) {
4421 return new Error('key cannot be `null` or `undefined`')
4422 } else if (Buffer.isBuffer(key) && key.length === 0) {
4423 return new Error('key cannot be an empty Buffer')
4424 } else if (key === '') {
4425 return new Error('key cannot be an empty String')
4426 } else if (Array.isArray(key) && key.length === 0) {
4427 return new Error('key cannot be an empty Array')
4428 }
4429}
4430
4431AbstractLevelDOWN.prototype._checkValue = function (value) {
4432 if (value === null || value === undefined) {
4433 return new Error('value cannot be `null` or `undefined`')
4434 }
4435}
4436
4437// Expose browser-compatible nextTick for dependents
4438AbstractLevelDOWN.prototype._nextTick = nextTick
4439
4440module.exports = AbstractLevelDOWN
4441
4442},{"13":13,"141":141,"18":18,"19":19,"22":22,"58":58}],21:[function(_dereq_,module,exports){
4443exports.AbstractLevelDOWN = _dereq_(20)
4444exports.AbstractIterator = _dereq_(19)
4445exports.AbstractChainedBatch = _dereq_(18)
4446
4447},{"18":18,"19":19,"20":20}],22:[function(_dereq_,module,exports){
4448module.exports = _dereq_(31)
4449
4450},{"31":31}],23:[function(_dereq_,module,exports){
4451/**
4452 * Copyright (c) 2013 Petka Antonov
4453 *
4454 * Permission is hereby granted, free of charge, to any person obtaining a copy
4455 * of this software and associated documentation files (the "Software"), to deal
4456 * in the Software without restriction, including without limitation the rights
4457 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
4458 * copies of the Software, and to permit persons to whom the Software is
4459 * furnished to do so, subject to the following conditions:</p>
4460 *
4461 * The above copyright notice and this permission notice shall be included in
4462 * all copies or substantial portions of the Software.
4463 *
4464 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
4465 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
4466 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
4467 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
4468 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
4469 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
4470 * THE SOFTWARE.
4471 */
4472"use strict";
4473function Deque(capacity) {
4474 this._capacity = getCapacity(capacity);
4475 this._length = 0;
4476 this._front = 0;
4477 if (isArray(capacity)) {
4478 var len = capacity.length;
4479 for (var i = 0; i < len; ++i) {
4480 this[i] = capacity[i];
4481 }
4482 this._length = len;
4483 }
4484}
4485
4486Deque.prototype.toArray = function Deque$toArray() {
4487 var len = this._length;
4488 var ret = new Array(len);
4489 var front = this._front;
4490 var capacity = this._capacity;
4491 for (var j = 0; j < len; ++j) {
4492 ret[j] = this[(front + j) & (capacity - 1)];
4493 }
4494 return ret;
4495};
4496
4497Deque.prototype.push = function Deque$push(item) {
4498 var argsLength = arguments.length;
4499 var length = this._length;
4500 if (argsLength > 1) {
4501 var capacity = this._capacity;
4502 if (length + argsLength > capacity) {
4503 for (var i = 0; i < argsLength; ++i) {
4504 this._checkCapacity(length + 1);
4505 var j = (this._front + length) & (this._capacity - 1);
4506 this[j] = arguments[i];
4507 length++;
4508 this._length = length;
4509 }
4510 return length;
4511 }
4512 else {
4513 var j = this._front;
4514 for (var i = 0; i < argsLength; ++i) {
4515 this[(j + length) & (capacity - 1)] = arguments[i];
4516 j++;
4517 }
4518 this._length = length + argsLength;
4519 return length + argsLength;
4520 }
4521
4522 }
4523
4524 if (argsLength === 0) return length;
4525
4526 this._checkCapacity(length + 1);
4527 var i = (this._front + length) & (this._capacity - 1);
4528 this[i] = item;
4529 this._length = length + 1;
4530 return length + 1;
4531};
4532
4533Deque.prototype.pop = function Deque$pop() {
4534 var length = this._length;
4535 if (length === 0) {
4536 return void 0;
4537 }
4538 var i = (this._front + length - 1) & (this._capacity - 1);
4539 var ret = this[i];
4540 this[i] = void 0;
4541 this._length = length - 1;
4542 return ret;
4543};
4544
4545Deque.prototype.shift = function Deque$shift() {
4546 var length = this._length;
4547 if (length === 0) {
4548 return void 0;
4549 }
4550 var front = this._front;
4551 var ret = this[front];
4552 this[front] = void 0;
4553 this._front = (front + 1) & (this._capacity - 1);
4554 this._length = length - 1;
4555 return ret;
4556};
4557
4558Deque.prototype.unshift = function Deque$unshift(item) {
4559 var length = this._length;
4560 var argsLength = arguments.length;
4561
4562
4563 if (argsLength > 1) {
4564 var capacity = this._capacity;
4565 if (length + argsLength > capacity) {
4566 for (var i = argsLength - 1; i >= 0; i--) {
4567 this._checkCapacity(length + 1);
4568 var capacity = this._capacity;
4569 var j = (((( this._front - 1 ) &
4570 ( capacity - 1) ) ^ capacity ) - capacity );
4571 this[j] = arguments[i];
4572 length++;
4573 this._length = length;
4574 this._front = j;
4575 }
4576 return length;
4577 }
4578 else {
4579 var front = this._front;
4580 for (var i = argsLength - 1; i >= 0; i--) {
4581 var j = (((( front - 1 ) &
4582 ( capacity - 1) ) ^ capacity ) - capacity );
4583 this[j] = arguments[i];
4584 front = j;
4585 }
4586 this._front = front;
4587 this._length = length + argsLength;
4588 return length + argsLength;
4589 }
4590 }
4591
4592 if (argsLength === 0) return length;
4593
4594 this._checkCapacity(length + 1);
4595 var capacity = this._capacity;
4596 var i = (((( this._front - 1 ) &
4597 ( capacity - 1) ) ^ capacity ) - capacity );
4598 this[i] = item;
4599 this._length = length + 1;
4600 this._front = i;
4601 return length + 1;
4602};
4603
4604Deque.prototype.peekBack = function Deque$peekBack() {
4605 var length = this._length;
4606 if (length === 0) {
4607 return void 0;
4608 }
4609 var index = (this._front + length - 1) & (this._capacity - 1);
4610 return this[index];
4611};
4612
4613Deque.prototype.peekFront = function Deque$peekFront() {
4614 if (this._length === 0) {
4615 return void 0;
4616 }
4617 return this[this._front];
4618};
4619
4620Deque.prototype.get = function Deque$get(index) {
4621 var i = index;
4622 if ((i !== (i | 0))) {
4623 return void 0;
4624 }
4625 var len = this._length;
4626 if (i < 0) {
4627 i = i + len;
4628 }
4629 if (i < 0 || i >= len) {
4630 return void 0;
4631 }
4632 return this[(this._front + i) & (this._capacity - 1)];
4633};
4634
4635Deque.prototype.isEmpty = function Deque$isEmpty() {
4636 return this._length === 0;
4637};
4638
4639Deque.prototype.clear = function Deque$clear() {
4640 var len = this._length;
4641 var front = this._front;
4642 var capacity = this._capacity;
4643 for (var j = 0; j < len; ++j) {
4644 this[(front + j) & (capacity - 1)] = void 0;
4645 }
4646 this._length = 0;
4647 this._front = 0;
4648};
4649
4650Deque.prototype.toString = function Deque$toString() {
4651 return this.toArray().toString();
4652};
4653
4654Deque.prototype.valueOf = Deque.prototype.toString;
4655Deque.prototype.removeFront = Deque.prototype.shift;
4656Deque.prototype.removeBack = Deque.prototype.pop;
4657Deque.prototype.insertFront = Deque.prototype.unshift;
4658Deque.prototype.insertBack = Deque.prototype.push;
4659Deque.prototype.enqueue = Deque.prototype.push;
4660Deque.prototype.dequeue = Deque.prototype.shift;
4661Deque.prototype.toJSON = Deque.prototype.toArray;
4662
4663Object.defineProperty(Deque.prototype, "length", {
4664 get: function() {
4665 return this._length;
4666 },
4667 set: function() {
4668 throw new RangeError("");
4669 }
4670});
4671
4672Deque.prototype._checkCapacity = function Deque$_checkCapacity(size) {
4673 if (this._capacity < size) {
4674 this._resizeTo(getCapacity(this._capacity * 1.5 + 16));
4675 }
4676};
4677
4678Deque.prototype._resizeTo = function Deque$_resizeTo(capacity) {
4679 var oldCapacity = this._capacity;
4680 this._capacity = capacity;
4681 var front = this._front;
4682 var length = this._length;
4683 if (front + length > oldCapacity) {
4684 var moveItemsCount = (front + length) & (oldCapacity - 1);
4685 arrayMove(this, 0, this, oldCapacity, moveItemsCount);
4686 }
4687};
4688
4689
4690var isArray = Array.isArray;
4691
4692function arrayMove(src, srcIndex, dst, dstIndex, len) {
4693 for (var j = 0; j < len; ++j) {
4694 dst[j + dstIndex] = src[j + srcIndex];
4695 src[j + srcIndex] = void 0;
4696 }
4697}
4698
4699function pow2AtLeast(n) {
4700 n = n >>> 0;
4701 n = n - 1;
4702 n = n | (n >> 1);
4703 n = n | (n >> 2);
4704 n = n | (n >> 4);
4705 n = n | (n >> 8);
4706 n = n | (n >> 16);
4707 return n + 1;
4708}
4709
4710function getCapacity(capacity) {
4711 if (typeof capacity !== "number") {
4712 if (isArray(capacity)) {
4713 capacity = capacity.length;
4714 }
4715 else {
4716 return 16;
4717 }
4718 }
4719 return pow2AtLeast(
4720 Math.min(
4721 Math.max(16, capacity), 1073741824)
4722 );
4723}
4724
4725module.exports = Deque;
4726
4727},{}],24:[function(_dereq_,module,exports){
4728var prr = _dereq_(74)
4729
4730function init (type, message, cause) {
4731 if (!!message && typeof message != 'string') {
4732 message = message.message || message.name
4733 }
4734 prr(this, {
4735 type : type
4736 , name : type
4737 // can be passed just a 'cause'
4738 , cause : typeof message != 'string' ? message : cause
4739 , message : message
4740 }, 'ewr')
4741}
4742
4743// generic prototype, not intended to be actually used - helpful for `instanceof`
4744function CustomError (message, cause) {
4745 Error.call(this)
4746 if (Error.captureStackTrace)
4747 Error.captureStackTrace(this, this.constructor)
4748 init.call(this, 'CustomError', message, cause)
4749}
4750
4751CustomError.prototype = new Error()
4752
4753function createError (errno, type, proto) {
4754 var err = function (message, cause) {
4755 init.call(this, type, message, cause)
4756 //TODO: the specificity here is stupid, errno should be available everywhere
4757 if (type == 'FilesystemError') {
4758 this.code = this.cause.code
4759 this.path = this.cause.path
4760 this.errno = this.cause.errno
4761 this.message =
4762 (errno.errno[this.cause.errno]
4763 ? errno.errno[this.cause.errno].description
4764 : this.cause.message)
4765 + (this.cause.path ? ' [' + this.cause.path + ']' : '')
4766 }
4767 Error.call(this)
4768 if (Error.captureStackTrace)
4769 Error.captureStackTrace(this, err)
4770 }
4771 err.prototype = !!proto ? new proto() : new CustomError()
4772 return err
4773}
4774
4775module.exports = function (errno) {
4776 var ce = function (type, proto) {
4777 return createError(errno, type, proto)
4778 }
4779 return {
4780 CustomError : CustomError
4781 , FilesystemError : ce('FilesystemError')
4782 , createError : ce
4783 }
4784}
4785
4786},{"74":74}],25:[function(_dereq_,module,exports){
4787var all = module.exports.all = [
4788 {
4789 errno: -2,
4790 code: 'ENOENT',
4791 description: 'no such file or directory'
4792 },
4793 {
4794 errno: -1,
4795 code: 'UNKNOWN',
4796 description: 'unknown error'
4797 },
4798 {
4799 errno: 0,
4800 code: 'OK',
4801 description: 'success'
4802 },
4803 {
4804 errno: 1,
4805 code: 'EOF',
4806 description: 'end of file'
4807 },
4808 {
4809 errno: 2,
4810 code: 'EADDRINFO',
4811 description: 'getaddrinfo error'
4812 },
4813 {
4814 errno: 3,
4815 code: 'EACCES',
4816 description: 'permission denied'
4817 },
4818 {
4819 errno: 4,
4820 code: 'EAGAIN',
4821 description: 'resource temporarily unavailable'
4822 },
4823 {
4824 errno: 5,
4825 code: 'EADDRINUSE',
4826 description: 'address already in use'
4827 },
4828 {
4829 errno: 6,
4830 code: 'EADDRNOTAVAIL',
4831 description: 'address not available'
4832 },
4833 {
4834 errno: 7,
4835 code: 'EAFNOSUPPORT',
4836 description: 'address family not supported'
4837 },
4838 {
4839 errno: 8,
4840 code: 'EALREADY',
4841 description: 'connection already in progress'
4842 },
4843 {
4844 errno: 9,
4845 code: 'EBADF',
4846 description: 'bad file descriptor'
4847 },
4848 {
4849 errno: 10,
4850 code: 'EBUSY',
4851 description: 'resource busy or locked'
4852 },
4853 {
4854 errno: 11,
4855 code: 'ECONNABORTED',
4856 description: 'software caused connection abort'
4857 },
4858 {
4859 errno: 12,
4860 code: 'ECONNREFUSED',
4861 description: 'connection refused'
4862 },
4863 {
4864 errno: 13,
4865 code: 'ECONNRESET',
4866 description: 'connection reset by peer'
4867 },
4868 {
4869 errno: 14,
4870 code: 'EDESTADDRREQ',
4871 description: 'destination address required'
4872 },
4873 {
4874 errno: 15,
4875 code: 'EFAULT',
4876 description: 'bad address in system call argument'
4877 },
4878 {
4879 errno: 16,
4880 code: 'EHOSTUNREACH',
4881 description: 'host is unreachable'
4882 },
4883 {
4884 errno: 17,
4885 code: 'EINTR',
4886 description: 'interrupted system call'
4887 },
4888 {
4889 errno: 18,
4890 code: 'EINVAL',
4891 description: 'invalid argument'
4892 },
4893 {
4894 errno: 19,
4895 code: 'EISCONN',
4896 description: 'socket is already connected'
4897 },
4898 {
4899 errno: 20,
4900 code: 'EMFILE',
4901 description: 'too many open files'
4902 },
4903 {
4904 errno: 21,
4905 code: 'EMSGSIZE',
4906 description: 'message too long'
4907 },
4908 {
4909 errno: 22,
4910 code: 'ENETDOWN',
4911 description: 'network is down'
4912 },
4913 {
4914 errno: 23,
4915 code: 'ENETUNREACH',
4916 description: 'network is unreachable'
4917 },
4918 {
4919 errno: 24,
4920 code: 'ENFILE',
4921 description: 'file table overflow'
4922 },
4923 {
4924 errno: 25,
4925 code: 'ENOBUFS',
4926 description: 'no buffer space available'
4927 },
4928 {
4929 errno: 26,
4930 code: 'ENOMEM',
4931 description: 'not enough memory'
4932 },
4933 {
4934 errno: 27,
4935 code: 'ENOTDIR',
4936 description: 'not a directory'
4937 },
4938 {
4939 errno: 28,
4940 code: 'EISDIR',
4941 description: 'illegal operation on a directory'
4942 },
4943 {
4944 errno: 29,
4945 code: 'ENONET',
4946 description: 'machine is not on the network'
4947 },
4948 {
4949 errno: 31,
4950 code: 'ENOTCONN',
4951 description: 'socket is not connected'
4952 },
4953 {
4954 errno: 32,
4955 code: 'ENOTSOCK',
4956 description: 'socket operation on non-socket'
4957 },
4958 {
4959 errno: 33,
4960 code: 'ENOTSUP',
4961 description: 'operation not supported on socket'
4962 },
4963 {
4964 errno: 34,
4965 code: 'ENOENT',
4966 description: 'no such file or directory'
4967 },
4968 {
4969 errno: 35,
4970 code: 'ENOSYS',
4971 description: 'function not implemented'
4972 },
4973 {
4974 errno: 36,
4975 code: 'EPIPE',
4976 description: 'broken pipe'
4977 },
4978 {
4979 errno: 37,
4980 code: 'EPROTO',
4981 description: 'protocol error'
4982 },
4983 {
4984 errno: 38,
4985 code: 'EPROTONOSUPPORT',
4986 description: 'protocol not supported'
4987 },
4988 {
4989 errno: 39,
4990 code: 'EPROTOTYPE',
4991 description: 'protocol wrong type for socket'
4992 },
4993 {
4994 errno: 40,
4995 code: 'ETIMEDOUT',
4996 description: 'connection timed out'
4997 },
4998 {
4999 errno: 41,
5000 code: 'ECHARSET',
5001 description: 'invalid Unicode character'
5002 },
5003 {
5004 errno: 42,
5005 code: 'EAIFAMNOSUPPORT',
5006 description: 'address family for hostname not supported'
5007 },
5008 {
5009 errno: 44,
5010 code: 'EAISERVICE',
5011 description: 'servname not supported for ai_socktype'
5012 },
5013 {
5014 errno: 45,
5015 code: 'EAISOCKTYPE',
5016 description: 'ai_socktype not supported'
5017 },
5018 {
5019 errno: 46,
5020 code: 'ESHUTDOWN',
5021 description: 'cannot send after transport endpoint shutdown'
5022 },
5023 {
5024 errno: 47,
5025 code: 'EEXIST',
5026 description: 'file already exists'
5027 },
5028 {
5029 errno: 48,
5030 code: 'ESRCH',
5031 description: 'no such process'
5032 },
5033 {
5034 errno: 49,
5035 code: 'ENAMETOOLONG',
5036 description: 'name too long'
5037 },
5038 {
5039 errno: 50,
5040 code: 'EPERM',
5041 description: 'operation not permitted'
5042 },
5043 {
5044 errno: 51,
5045 code: 'ELOOP',
5046 description: 'too many symbolic links encountered'
5047 },
5048 {
5049 errno: 52,
5050 code: 'EXDEV',
5051 description: 'cross-device link not permitted'
5052 },
5053 {
5054 errno: 53,
5055 code: 'ENOTEMPTY',
5056 description: 'directory not empty'
5057 },
5058 {
5059 errno: 54,
5060 code: 'ENOSPC',
5061 description: 'no space left on device'
5062 },
5063 {
5064 errno: 55,
5065 code: 'EIO',
5066 description: 'i/o error'
5067 },
5068 {
5069 errno: 56,
5070 code: 'EROFS',
5071 description: 'read-only file system'
5072 },
5073 {
5074 errno: 57,
5075 code: 'ENODEV',
5076 description: 'no such device'
5077 },
5078 {
5079 errno: 58,
5080 code: 'ESPIPE',
5081 description: 'invalid seek'
5082 },
5083 {
5084 errno: 59,
5085 code: 'ECANCELED',
5086 description: 'operation canceled'
5087 }
5088]
5089
5090module.exports.errno = {}
5091module.exports.code = {}
5092
5093all.forEach(function (error) {
5094 module.exports.errno[error.errno] = error
5095 module.exports.code[error.code] = error
5096})
5097
5098module.exports.custom = _dereq_(24)(module.exports)
5099module.exports.create = module.exports.custom.createError
5100
5101},{"24":24}],26:[function(_dereq_,module,exports){
5102// Copyright Joyent, Inc. and other Node contributors.
5103//
5104// Permission is hereby granted, free of charge, to any person obtaining a
5105// copy of this software and associated documentation files (the
5106// "Software"), to deal in the Software without restriction, including
5107// without limitation the rights to use, copy, modify, merge, publish,
5108// distribute, sublicense, and/or sell copies of the Software, and to permit
5109// persons to whom the Software is furnished to do so, subject to the
5110// following conditions:
5111//
5112// The above copyright notice and this permission notice shall be included
5113// in all copies or substantial portions of the Software.
5114//
5115// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5116// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5117// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5118// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5119// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5120// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5121// USE OR OTHER DEALINGS IN THE SOFTWARE.
5122
5123var objectCreate = Object.create || objectCreatePolyfill
5124var objectKeys = Object.keys || objectKeysPolyfill
5125var bind = Function.prototype.bind || functionBindPolyfill
5126
5127function EventEmitter() {
5128 if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
5129 this._events = objectCreate(null);
5130 this._eventsCount = 0;
5131 }
5132
5133 this._maxListeners = this._maxListeners || undefined;
5134}
5135module.exports = EventEmitter;
5136
5137// Backwards-compat with node 0.10.x
5138EventEmitter.EventEmitter = EventEmitter;
5139
5140EventEmitter.prototype._events = undefined;
5141EventEmitter.prototype._maxListeners = undefined;
5142
5143// By default EventEmitters will print a warning if more than 10 listeners are
5144// added to it. This is a useful default which helps finding memory leaks.
5145var defaultMaxListeners = 10;
5146
5147var hasDefineProperty;
5148try {
5149 var o = {};
5150 if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
5151 hasDefineProperty = o.x === 0;
5152} catch (err) { hasDefineProperty = false }
5153if (hasDefineProperty) {
5154 Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
5155 enumerable: true,
5156 get: function() {
5157 return defaultMaxListeners;
5158 },
5159 set: function(arg) {
5160 // check whether the input is a positive number (whose value is zero or
5161 // greater and not a NaN).
5162 if (typeof arg !== 'number' || arg < 0 || arg !== arg)
5163 throw new TypeError('"defaultMaxListeners" must be a positive number');
5164 defaultMaxListeners = arg;
5165 }
5166 });
5167} else {
5168 EventEmitter.defaultMaxListeners = defaultMaxListeners;
5169}
5170
5171// Obviously not all Emitters should be limited to 10. This function allows
5172// that to be increased. Set to zero for unlimited.
5173EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
5174 if (typeof n !== 'number' || n < 0 || isNaN(n))
5175 throw new TypeError('"n" argument must be a positive number');
5176 this._maxListeners = n;
5177 return this;
5178};
5179
5180function $getMaxListeners(that) {
5181 if (that._maxListeners === undefined)
5182 return EventEmitter.defaultMaxListeners;
5183 return that._maxListeners;
5184}
5185
5186EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
5187 return $getMaxListeners(this);
5188};
5189
5190// These standalone emit* functions are used to optimize calling of event
5191// handlers for fast cases because emit() itself often has a variable number of
5192// arguments and can be deoptimized because of that. These functions always have
5193// the same number of arguments and thus do not get deoptimized, so the code
5194// inside them can execute faster.
5195function emitNone(handler, isFn, self) {
5196 if (isFn)
5197 handler.call(self);
5198 else {
5199 var len = handler.length;
5200 var listeners = arrayClone(handler, len);
5201 for (var i = 0; i < len; ++i)
5202 listeners[i].call(self);
5203 }
5204}
5205function emitOne(handler, isFn, self, arg1) {
5206 if (isFn)
5207 handler.call(self, arg1);
5208 else {
5209 var len = handler.length;
5210 var listeners = arrayClone(handler, len);
5211 for (var i = 0; i < len; ++i)
5212 listeners[i].call(self, arg1);
5213 }
5214}
5215function emitTwo(handler, isFn, self, arg1, arg2) {
5216 if (isFn)
5217 handler.call(self, arg1, arg2);
5218 else {
5219 var len = handler.length;
5220 var listeners = arrayClone(handler, len);
5221 for (var i = 0; i < len; ++i)
5222 listeners[i].call(self, arg1, arg2);
5223 }
5224}
5225function emitThree(handler, isFn, self, arg1, arg2, arg3) {
5226 if (isFn)
5227 handler.call(self, arg1, arg2, arg3);
5228 else {
5229 var len = handler.length;
5230 var listeners = arrayClone(handler, len);
5231 for (var i = 0; i < len; ++i)
5232 listeners[i].call(self, arg1, arg2, arg3);
5233 }
5234}
5235
5236function emitMany(handler, isFn, self, args) {
5237 if (isFn)
5238 handler.apply(self, args);
5239 else {
5240 var len = handler.length;
5241 var listeners = arrayClone(handler, len);
5242 for (var i = 0; i < len; ++i)
5243 listeners[i].apply(self, args);
5244 }
5245}
5246
5247EventEmitter.prototype.emit = function emit(type) {
5248 var er, handler, len, args, i, events;
5249 var doError = (type === 'error');
5250
5251 events = this._events;
5252 if (events)
5253 doError = (doError && events.error == null);
5254 else if (!doError)
5255 return false;
5256
5257 // If there is no 'error' event listener then throw.
5258 if (doError) {
5259 if (arguments.length > 1)
5260 er = arguments[1];
5261 if (er instanceof Error) {
5262 throw er; // Unhandled 'error' event
5263 } else {
5264 // At least give some kind of context to the user
5265 var err = new Error('Unhandled "error" event. (' + er + ')');
5266 err.context = er;
5267 throw err;
5268 }
5269 return false;
5270 }
5271
5272 handler = events[type];
5273
5274 if (!handler)
5275 return false;
5276
5277 var isFn = typeof handler === 'function';
5278 len = arguments.length;
5279 switch (len) {
5280 // fast cases
5281 case 1:
5282 emitNone(handler, isFn, this);
5283 break;
5284 case 2:
5285 emitOne(handler, isFn, this, arguments[1]);
5286 break;
5287 case 3:
5288 emitTwo(handler, isFn, this, arguments[1], arguments[2]);
5289 break;
5290 case 4:
5291 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
5292 break;
5293 // slower
5294 default:
5295 args = new Array(len - 1);
5296 for (i = 1; i < len; i++)
5297 args[i - 1] = arguments[i];
5298 emitMany(handler, isFn, this, args);
5299 }
5300
5301 return true;
5302};
5303
5304function _addListener(target, type, listener, prepend) {
5305 var m;
5306 var events;
5307 var existing;
5308
5309 if (typeof listener !== 'function')
5310 throw new TypeError('"listener" argument must be a function');
5311
5312 events = target._events;
5313 if (!events) {
5314 events = target._events = objectCreate(null);
5315 target._eventsCount = 0;
5316 } else {
5317 // To avoid recursion in the case that type === "newListener"! Before
5318 // adding it to the listeners, first emit "newListener".
5319 if (events.newListener) {
5320 target.emit('newListener', type,
5321 listener.listener ? listener.listener : listener);
5322
5323 // Re-assign `events` because a newListener handler could have caused the
5324 // this._events to be assigned to a new object
5325 events = target._events;
5326 }
5327 existing = events[type];
5328 }
5329
5330 if (!existing) {
5331 // Optimize the case of one listener. Don't need the extra array object.
5332 existing = events[type] = listener;
5333 ++target._eventsCount;
5334 } else {
5335 if (typeof existing === 'function') {
5336 // Adding the second element, need to change to array.
5337 existing = events[type] =
5338 prepend ? [listener, existing] : [existing, listener];
5339 } else {
5340 // If we've already got an array, just append.
5341 if (prepend) {
5342 existing.unshift(listener);
5343 } else {
5344 existing.push(listener);
5345 }
5346 }
5347
5348 // Check for listener leak
5349 if (!existing.warned) {
5350 m = $getMaxListeners(target);
5351 if (m && m > 0 && existing.length > m) {
5352 existing.warned = true;
5353 var w = new Error('Possible EventEmitter memory leak detected. ' +
5354 existing.length + ' "' + String(type) + '" listeners ' +
5355 'added. Use emitter.setMaxListeners() to ' +
5356 'increase limit.');
5357 w.name = 'MaxListenersExceededWarning';
5358 w.emitter = target;
5359 w.type = type;
5360 w.count = existing.length;
5361 if (typeof console === 'object' && console.warn) {
5362 console.warn('%s: %s', w.name, w.message);
5363 }
5364 }
5365 }
5366 }
5367
5368 return target;
5369}
5370
5371EventEmitter.prototype.addListener = function addListener(type, listener) {
5372 return _addListener(this, type, listener, false);
5373};
5374
5375EventEmitter.prototype.on = EventEmitter.prototype.addListener;
5376
5377EventEmitter.prototype.prependListener =
5378 function prependListener(type, listener) {
5379 return _addListener(this, type, listener, true);
5380 };
5381
5382function onceWrapper() {
5383 if (!this.fired) {
5384 this.target.removeListener(this.type, this.wrapFn);
5385 this.fired = true;
5386 switch (arguments.length) {
5387 case 0:
5388 return this.listener.call(this.target);
5389 case 1:
5390 return this.listener.call(this.target, arguments[0]);
5391 case 2:
5392 return this.listener.call(this.target, arguments[0], arguments[1]);
5393 case 3:
5394 return this.listener.call(this.target, arguments[0], arguments[1],
5395 arguments[2]);
5396 default:
5397 var args = new Array(arguments.length);
5398 for (var i = 0; i < args.length; ++i)
5399 args[i] = arguments[i];
5400 this.listener.apply(this.target, args);
5401 }
5402 }
5403}
5404
5405function _onceWrap(target, type, listener) {
5406 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
5407 var wrapped = bind.call(onceWrapper, state);
5408 wrapped.listener = listener;
5409 state.wrapFn = wrapped;
5410 return wrapped;
5411}
5412
5413EventEmitter.prototype.once = function once(type, listener) {
5414 if (typeof listener !== 'function')
5415 throw new TypeError('"listener" argument must be a function');
5416 this.on(type, _onceWrap(this, type, listener));
5417 return this;
5418};
5419
5420EventEmitter.prototype.prependOnceListener =
5421 function prependOnceListener(type, listener) {
5422 if (typeof listener !== 'function')
5423 throw new TypeError('"listener" argument must be a function');
5424 this.prependListener(type, _onceWrap(this, type, listener));
5425 return this;
5426 };
5427
5428// Emits a 'removeListener' event if and only if the listener was removed.
5429EventEmitter.prototype.removeListener =
5430 function removeListener(type, listener) {
5431 var list, events, position, i, originalListener;
5432
5433 if (typeof listener !== 'function')
5434 throw new TypeError('"listener" argument must be a function');
5435
5436 events = this._events;
5437 if (!events)
5438 return this;
5439
5440 list = events[type];
5441 if (!list)
5442 return this;
5443
5444 if (list === listener || list.listener === listener) {
5445 if (--this._eventsCount === 0)
5446 this._events = objectCreate(null);
5447 else {
5448 delete events[type];
5449 if (events.removeListener)
5450 this.emit('removeListener', type, list.listener || listener);
5451 }
5452 } else if (typeof list !== 'function') {
5453 position = -1;
5454
5455 for (i = list.length - 1; i >= 0; i--) {
5456 if (list[i] === listener || list[i].listener === listener) {
5457 originalListener = list[i].listener;
5458 position = i;
5459 break;
5460 }
5461 }
5462
5463 if (position < 0)
5464 return this;
5465
5466 if (position === 0)
5467 list.shift();
5468 else
5469 spliceOne(list, position);
5470
5471 if (list.length === 1)
5472 events[type] = list[0];
5473
5474 if (events.removeListener)
5475 this.emit('removeListener', type, originalListener || listener);
5476 }
5477
5478 return this;
5479 };
5480
5481EventEmitter.prototype.removeAllListeners =
5482 function removeAllListeners(type) {
5483 var listeners, events, i;
5484
5485 events = this._events;
5486 if (!events)
5487 return this;
5488
5489 // not listening for removeListener, no need to emit
5490 if (!events.removeListener) {
5491 if (arguments.length === 0) {
5492 this._events = objectCreate(null);
5493 this._eventsCount = 0;
5494 } else if (events[type]) {
5495 if (--this._eventsCount === 0)
5496 this._events = objectCreate(null);
5497 else
5498 delete events[type];
5499 }
5500 return this;
5501 }
5502
5503 // emit removeListener for all listeners on all events
5504 if (arguments.length === 0) {
5505 var keys = objectKeys(events);
5506 var key;
5507 for (i = 0; i < keys.length; ++i) {
5508 key = keys[i];
5509 if (key === 'removeListener') continue;
5510 this.removeAllListeners(key);
5511 }
5512 this.removeAllListeners('removeListener');
5513 this._events = objectCreate(null);
5514 this._eventsCount = 0;
5515 return this;
5516 }
5517
5518 listeners = events[type];
5519
5520 if (typeof listeners === 'function') {
5521 this.removeListener(type, listeners);
5522 } else if (listeners) {
5523 // LIFO order
5524 for (i = listeners.length - 1; i >= 0; i--) {
5525 this.removeListener(type, listeners[i]);
5526 }
5527 }
5528
5529 return this;
5530 };
5531
5532function _listeners(target, type, unwrap) {
5533 var events = target._events;
5534
5535 if (!events)
5536 return [];
5537
5538 var evlistener = events[type];
5539 if (!evlistener)
5540 return [];
5541
5542 if (typeof evlistener === 'function')
5543 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
5544
5545 return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
5546}
5547
5548EventEmitter.prototype.listeners = function listeners(type) {
5549 return _listeners(this, type, true);
5550};
5551
5552EventEmitter.prototype.rawListeners = function rawListeners(type) {
5553 return _listeners(this, type, false);
5554};
5555
5556EventEmitter.listenerCount = function(emitter, type) {
5557 if (typeof emitter.listenerCount === 'function') {
5558 return emitter.listenerCount(type);
5559 } else {
5560 return listenerCount.call(emitter, type);
5561 }
5562};
5563
5564EventEmitter.prototype.listenerCount = listenerCount;
5565function listenerCount(type) {
5566 var events = this._events;
5567
5568 if (events) {
5569 var evlistener = events[type];
5570
5571 if (typeof evlistener === 'function') {
5572 return 1;
5573 } else if (evlistener) {
5574 return evlistener.length;
5575 }
5576 }
5577
5578 return 0;
5579}
5580
5581EventEmitter.prototype.eventNames = function eventNames() {
5582 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
5583};
5584
5585// About 1.5x faster than the two-arg version of Array#splice().
5586function spliceOne(list, index) {
5587 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
5588 list[i] = list[k];
5589 list.pop();
5590}
5591
5592function arrayClone(arr, n) {
5593 var copy = new Array(n);
5594 for (var i = 0; i < n; ++i)
5595 copy[i] = arr[i];
5596 return copy;
5597}
5598
5599function unwrapListeners(arr) {
5600 var ret = new Array(arr.length);
5601 for (var i = 0; i < ret.length; ++i) {
5602 ret[i] = arr[i].listener || arr[i];
5603 }
5604 return ret;
5605}
5606
5607function objectCreatePolyfill(proto) {
5608 var F = function() {};
5609 F.prototype = proto;
5610 return new F;
5611}
5612function objectKeysPolyfill(obj) {
5613 var keys = [];
5614 for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
5615 keys.push(k);
5616 }
5617 return k;
5618}
5619function functionBindPolyfill(context) {
5620 var fn = this;
5621 return function () {
5622 return fn.apply(context, arguments);
5623 };
5624}
5625
5626},{}],27:[function(_dereq_,module,exports){
5627/**
5628 * # hasLocalStorage()
5629 *
5630 * returns `true` or `false` depending on whether localStorage is supported or not.
5631 * Beware that some browsers like Safari do not support localStorage in private mode.
5632 *
5633 * inspired by this cappuccino commit
5634 * https://github.com/cappuccino/cappuccino/commit/063b05d9643c35b303568a28809e4eb3224f71ec
5635 *
5636 * @returns {Boolean}
5637 */
5638function hasLocalStorage() {
5639 try {
5640
5641 // we've to put this in here. I've seen Firefox throwing `Security error: 1000`
5642 // when cookies have been disabled
5643 if (typeof localStorage === 'undefined') {
5644 return false;
5645 }
5646
5647 // Just because localStorage exists does not mean it works. In particular it might be disabled
5648 // as it is when Safari's private browsing mode is active.
5649 localStorage.setItem('Storage-Test', '1');
5650
5651 // that should not happen ...
5652 if (localStorage.getItem('Storage-Test') !== '1') {
5653 return false;
5654 }
5655
5656 // okay, let's clean up if we got here.
5657 localStorage.removeItem('Storage-Test');
5658 } catch (_error) {
5659
5660 // in case of an error, like Safari's Private Mode, return false
5661 return false;
5662 }
5663
5664 // we're good.
5665 return true;
5666}
5667
5668
5669if (typeof exports === 'object') {
5670 module.exports = hasLocalStorage;
5671}
5672
5673},{}],28:[function(_dereq_,module,exports){
5674(function (global){(function (){
5675var exports = module.exports = {};
5676var localStorageMemory = _dereq_(69);
5677exports.hasLocalStorage = _dereq_(27);
5678
5679/**
5680 * returns localStorage-compatible API, either backed by window.localStorage
5681 * or memory if it's not available or not persistent.
5682 *
5683 * It also adds an object API (`.getObject(key)`,
5684 * `.setObject(key, properties)`) and a `isPresistent` property
5685 *
5686 * @returns {Object}
5687 */
5688exports.create = function () {
5689 var api;
5690
5691 if (!exports.hasLocalStorage()) {
5692 api = localStorageMemory;
5693 api.isPersistent = false;
5694 } else {
5695 api = global.localStorage;
5696 api = {
5697 get length() { return global.localStorage.length; },
5698 getItem: global.localStorage.getItem.bind(global.localStorage),
5699 setItem: global.localStorage.setItem.bind(global.localStorage),
5700 removeItem: global.localStorage.removeItem.bind(global.localStorage),
5701 key: global.localStorage.key.bind(global.localStorage),
5702 clear: global.localStorage.clear.bind(global.localStorage),
5703 };
5704
5705 api.isPersistent = true;
5706 }
5707
5708 api.getObject = exports.getObject.bind(null, api);
5709 api.setObject = exports.setObject.bind(null, api);
5710
5711 return api;
5712};
5713
5714/**
5715 * sets key to passed Object.
5716 *
5717 * @returns undefined
5718 */
5719exports.setObject = function (store, key, object) {
5720 if (typeof object !== 'object') {
5721 return store.setItem(key, object);
5722 }
5723
5724 return store.setItem(key, JSON.stringify(object));
5725};
5726
5727/**
5728 * returns Object for key, or null
5729 *
5730 * @returns {Object|null}
5731 */
5732exports.getObject = function (store, key) {
5733 var item = store.getItem(key);
5734
5735 if (!item) {
5736 return null;
5737 }
5738
5739 try {
5740 return JSON.parse(item);
5741 } catch (e) {
5742 return item;
5743 }
5744};
5745
5746}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5747},{"27":27,"69":69}],29:[function(_dereq_,module,exports){
5748var api = _dereq_(28);
5749module.exports = api.create();
5750
5751},{"28":28}],30:[function(_dereq_,module,exports){
5752/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
5753exports.read = function (buffer, offset, isLE, mLen, nBytes) {
5754 var e, m
5755 var eLen = (nBytes * 8) - mLen - 1
5756 var eMax = (1 << eLen) - 1
5757 var eBias = eMax >> 1
5758 var nBits = -7
5759 var i = isLE ? (nBytes - 1) : 0
5760 var d = isLE ? -1 : 1
5761 var s = buffer[offset + i]
5762
5763 i += d
5764
5765 e = s & ((1 << (-nBits)) - 1)
5766 s >>= (-nBits)
5767 nBits += eLen
5768 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
5769
5770 m = e & ((1 << (-nBits)) - 1)
5771 e >>= (-nBits)
5772 nBits += mLen
5773 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
5774
5775 if (e === 0) {
5776 e = 1 - eBias
5777 } else if (e === eMax) {
5778 return m ? NaN : ((s ? -1 : 1) * Infinity)
5779 } else {
5780 m = m + Math.pow(2, mLen)
5781 e = e - eBias
5782 }
5783 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
5784}
5785
5786exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
5787 var e, m, c
5788 var eLen = (nBytes * 8) - mLen - 1
5789 var eMax = (1 << eLen) - 1
5790 var eBias = eMax >> 1
5791 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
5792 var i = isLE ? 0 : (nBytes - 1)
5793 var d = isLE ? 1 : -1
5794 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
5795
5796 value = Math.abs(value)
5797
5798 if (isNaN(value) || value === Infinity) {
5799 m = isNaN(value) ? 1 : 0
5800 e = eMax
5801 } else {
5802 e = Math.floor(Math.log(value) / Math.LN2)
5803 if (value * (c = Math.pow(2, -e)) < 1) {
5804 e--
5805 c *= 2
5806 }
5807 if (e + eBias >= 1) {
5808 value += rt / c
5809 } else {
5810 value += rt * Math.pow(2, 1 - eBias)
5811 }
5812 if (value * c >= 2) {
5813 e++
5814 c /= 2
5815 }
5816
5817 if (e + eBias >= eMax) {
5818 m = 0
5819 e = eMax
5820 } else if (e + eBias >= 1) {
5821 m = ((value * c) - 1) * Math.pow(2, mLen)
5822 e = e + eBias
5823 } else {
5824 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
5825 e = 0
5826 }
5827 }
5828
5829 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
5830
5831 e = (e << mLen) | m
5832 eLen += mLen
5833 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
5834
5835 buffer[offset + i - d] |= s * 128
5836}
5837
5838},{}],31:[function(_dereq_,module,exports){
5839'use strict';
5840var types = [
5841 _dereq_(11),
5842 _dereq_(34),
5843 _dereq_(33),
5844 _dereq_(32),
5845 _dereq_(35),
5846 _dereq_(36)
5847];
5848var draining;
5849var currentQueue;
5850var queueIndex = -1;
5851var queue = [];
5852var scheduled = false;
5853function cleanUpNextTick() {
5854 if (!draining || !currentQueue) {
5855 return;
5856 }
5857 draining = false;
5858 if (currentQueue.length) {
5859 queue = currentQueue.concat(queue);
5860 } else {
5861 queueIndex = -1;
5862 }
5863 if (queue.length) {
5864 nextTick();
5865 }
5866}
5867
5868//named nextTick for less confusing stack traces
5869function nextTick() {
5870 if (draining) {
5871 return;
5872 }
5873 scheduled = false;
5874 draining = true;
5875 var len = queue.length;
5876 var timeout = setTimeout(cleanUpNextTick);
5877 while (len) {
5878 currentQueue = queue;
5879 queue = [];
5880 while (currentQueue && ++queueIndex < len) {
5881 currentQueue[queueIndex].run();
5882 }
5883 queueIndex = -1;
5884 len = queue.length;
5885 }
5886 currentQueue = null;
5887 queueIndex = -1;
5888 draining = false;
5889 clearTimeout(timeout);
5890}
5891var scheduleDrain;
5892var i = -1;
5893var len = types.length;
5894while (++i < len) {
5895 if (types[i] && types[i].test && types[i].test()) {
5896 scheduleDrain = types[i].install(nextTick);
5897 break;
5898 }
5899}
5900// v8 likes predictible objects
5901function Item(fun, array) {
5902 this.fun = fun;
5903 this.array = array;
5904}
5905Item.prototype.run = function () {
5906 var fun = this.fun;
5907 var array = this.array;
5908 switch (array.length) {
5909 case 0:
5910 return fun();
5911 case 1:
5912 return fun(array[0]);
5913 case 2:
5914 return fun(array[0], array[1]);
5915 case 3:
5916 return fun(array[0], array[1], array[2]);
5917 default:
5918 return fun.apply(null, array);
5919 }
5920
5921};
5922module.exports = immediate;
5923function immediate(task) {
5924 var args = new Array(arguments.length - 1);
5925 if (arguments.length > 1) {
5926 for (var i = 1; i < arguments.length; i++) {
5927 args[i - 1] = arguments[i];
5928 }
5929 }
5930 queue.push(new Item(task, args));
5931 if (!scheduled && !draining) {
5932 scheduled = true;
5933 scheduleDrain();
5934 }
5935}
5936
5937},{"11":11,"32":32,"33":33,"34":34,"35":35,"36":36}],32:[function(_dereq_,module,exports){
5938(function (global){(function (){
5939'use strict';
5940
5941exports.test = function () {
5942 if (global.setImmediate) {
5943 // we can only get here in IE10
5944 // which doesn't handel postMessage well
5945 return false;
5946 }
5947 return typeof global.MessageChannel !== 'undefined';
5948};
5949
5950exports.install = function (func) {
5951 var channel = new global.MessageChannel();
5952 channel.port1.onmessage = func;
5953 return function () {
5954 channel.port2.postMessage(0);
5955 };
5956};
5957}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5958},{}],33:[function(_dereq_,module,exports){
5959(function (global){(function (){
5960'use strict';
5961//based off rsvp https://github.com/tildeio/rsvp.js
5962//license https://github.com/tildeio/rsvp.js/blob/master/LICENSE
5963//https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/asap.js
5964
5965var Mutation = global.MutationObserver || global.WebKitMutationObserver;
5966
5967exports.test = function () {
5968 return Mutation;
5969};
5970
5971exports.install = function (handle) {
5972 var called = 0;
5973 var observer = new Mutation(handle);
5974 var element = global.document.createTextNode('');
5975 observer.observe(element, {
5976 characterData: true
5977 });
5978 return function () {
5979 element.data = (called = ++called % 2);
5980 };
5981};
5982}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5983},{}],34:[function(_dereq_,module,exports){
5984(function (global){(function (){
5985'use strict';
5986exports.test = function () {
5987 return typeof global.queueMicrotask === 'function';
5988};
5989
5990exports.install = function (func) {
5991 return function () {
5992 global.queueMicrotask(func);
5993 };
5994};
5995
5996}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5997},{}],35:[function(_dereq_,module,exports){
5998(function (global){(function (){
5999'use strict';
6000
6001exports.test = function () {
6002 return 'document' in global && 'onreadystatechange' in global.document.createElement('script');
6003};
6004
6005exports.install = function (handle) {
6006 return function () {
6007
6008 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
6009 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
6010 var scriptEl = global.document.createElement('script');
6011 scriptEl.onreadystatechange = function () {
6012 handle();
6013
6014 scriptEl.onreadystatechange = null;
6015 scriptEl.parentNode.removeChild(scriptEl);
6016 scriptEl = null;
6017 };
6018 global.document.documentElement.appendChild(scriptEl);
6019
6020 return handle;
6021 };
6022};
6023}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
6024},{}],36:[function(_dereq_,module,exports){
6025'use strict';
6026exports.test = function () {
6027 return true;
6028};
6029
6030exports.install = function (t) {
6031 return function () {
6032 setTimeout(t, 0);
6033 };
6034};
6035},{}],37:[function(_dereq_,module,exports){
6036if (typeof Object.create === 'function') {
6037 // implementation from standard node.js 'util' module
6038 module.exports = function inherits(ctor, superCtor) {
6039 if (superCtor) {
6040 ctor.super_ = superCtor
6041 ctor.prototype = Object.create(superCtor.prototype, {
6042 constructor: {
6043 value: ctor,
6044 enumerable: false,
6045 writable: true,
6046 configurable: true
6047 }
6048 })
6049 }
6050 };
6051} else {
6052 // old school shim for old browsers
6053 module.exports = function inherits(ctor, superCtor) {
6054 if (superCtor) {
6055 ctor.super_ = superCtor
6056 var TempCtor = function () {}
6057 TempCtor.prototype = superCtor.prototype
6058 ctor.prototype = new TempCtor()
6059 ctor.prototype.constructor = ctor
6060 }
6061 }
6062}
6063
6064},{}],38:[function(_dereq_,module,exports){
6065/*!
6066 * Determine if an object is a Buffer
6067 *
6068 * @author Feross Aboukhadijeh <https://feross.org>
6069 * @license MIT
6070 */
6071
6072// The _isBuffer check is for Safari 5-7 support, because it's missing
6073// Object.prototype.constructor. Remove this eventually
6074module.exports = function (obj) {
6075 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
6076}
6077
6078function isBuffer (obj) {
6079 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
6080}
6081
6082// For Node v0.10 support. Remove this eventually.
6083function isSlowBuffer (obj) {
6084 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
6085}
6086
6087},{}],39:[function(_dereq_,module,exports){
6088var encodings = _dereq_(40)
6089
6090module.exports = Codec
6091
6092function Codec (opts) {
6093 if (!(this instanceof Codec)) {
6094 return new Codec(opts)
6095 }
6096 this.opts = opts || {}
6097 this.encodings = encodings
6098}
6099
6100Codec.prototype._encoding = function (encoding) {
6101 if (typeof encoding === 'string') encoding = encodings[encoding]
6102 if (!encoding) encoding = encodings.id
6103 return encoding
6104}
6105
6106Codec.prototype._keyEncoding = function (opts, batchOpts) {
6107 return this._encoding((batchOpts && batchOpts.keyEncoding) ||
6108 (opts && opts.keyEncoding) ||
6109 this.opts.keyEncoding)
6110}
6111
6112Codec.prototype._valueEncoding = function (opts, batchOpts) {
6113 return this._encoding((batchOpts && (batchOpts.valueEncoding || batchOpts.encoding)) ||
6114 (opts && (opts.valueEncoding || opts.encoding)) ||
6115 (this.opts.valueEncoding || this.opts.encoding))
6116}
6117
6118Codec.prototype.encodeKey = function (key, opts, batchOpts) {
6119 return this._keyEncoding(opts, batchOpts).encode(key)
6120}
6121
6122Codec.prototype.encodeValue = function (value, opts, batchOpts) {
6123 return this._valueEncoding(opts, batchOpts).encode(value)
6124}
6125
6126Codec.prototype.decodeKey = function (key, opts) {
6127 return this._keyEncoding(opts).decode(key)
6128}
6129
6130Codec.prototype.decodeValue = function (value, opts) {
6131 return this._valueEncoding(opts).decode(value)
6132}
6133
6134Codec.prototype.encodeBatch = function (ops, opts) {
6135 var self = this
6136
6137 return ops.map(function (_op) {
6138 var op = {
6139 type: _op.type,
6140 key: self.encodeKey(_op.key, opts, _op)
6141 }
6142 if (self.keyAsBuffer(opts, _op)) op.keyEncoding = 'binary'
6143 if (_op.prefix) op.prefix = _op.prefix
6144 if ('value' in _op) {
6145 op.value = self.encodeValue(_op.value, opts, _op)
6146 if (self.valueAsBuffer(opts, _op)) op.valueEncoding = 'binary'
6147 }
6148 return op
6149 })
6150}
6151
6152var ltgtKeys = ['lt', 'gt', 'lte', 'gte', 'start', 'end']
6153
6154Codec.prototype.encodeLtgt = function (ltgt) {
6155 var self = this
6156 var ret = {}
6157 Object.keys(ltgt).forEach(function (key) {
6158 ret[key] = ltgtKeys.indexOf(key) > -1
6159 ? self.encodeKey(ltgt[key], ltgt)
6160 : ltgt[key]
6161 })
6162 return ret
6163}
6164
6165Codec.prototype.createStreamDecoder = function (opts) {
6166 var self = this
6167
6168 if (opts.keys && opts.values) {
6169 return function (key, value) {
6170 return {
6171 key: self.decodeKey(key, opts),
6172 value: self.decodeValue(value, opts)
6173 }
6174 }
6175 } else if (opts.keys) {
6176 return function (key) {
6177 return self.decodeKey(key, opts)
6178 }
6179 } else if (opts.values) {
6180 return function (_, value) {
6181 return self.decodeValue(value, opts)
6182 }
6183 } else {
6184 return function () {}
6185 }
6186}
6187
6188Codec.prototype.keyAsBuffer = function (opts) {
6189 return this._keyEncoding(opts).buffer
6190}
6191
6192Codec.prototype.valueAsBuffer = function (opts) {
6193 return this._valueEncoding(opts).buffer
6194}
6195
6196},{"40":40}],40:[function(_dereq_,module,exports){
6197var Buffer = _dereq_(13).Buffer
6198
6199exports.utf8 = exports['utf-8'] = {
6200 encode: function (data) {
6201 return isBinary(data) ? data : String(data)
6202 },
6203 decode: identity,
6204 buffer: false,
6205 type: 'utf8'
6206}
6207
6208exports.json = {
6209 encode: JSON.stringify,
6210 decode: JSON.parse,
6211 buffer: false,
6212 type: 'json'
6213}
6214
6215exports.binary = {
6216 encode: function (data) {
6217 return isBinary(data) ? data : Buffer.from(data)
6218 },
6219 decode: identity,
6220 buffer: true,
6221 type: 'binary'
6222}
6223
6224exports.none = {
6225 encode: identity,
6226 decode: identity,
6227 buffer: false,
6228 type: 'id'
6229}
6230
6231exports.id = exports.none
6232
6233var bufferEncodings = [
6234 'hex',
6235 'ascii',
6236 'base64',
6237 'ucs2',
6238 'ucs-2',
6239 'utf16le',
6240 'utf-16le'
6241]
6242
6243bufferEncodings.forEach(function (type) {
6244 exports[type] = {
6245 encode: function (data) {
6246 return isBinary(data) ? data : Buffer.from(data, type)
6247 },
6248 decode: function (buffer) {
6249 return buffer.toString(type)
6250 },
6251 buffer: true,
6252 type: type
6253 }
6254})
6255
6256function identity (value) {
6257 return value
6258}
6259
6260function isBinary (data) {
6261 return data === undefined || data === null || Buffer.isBuffer(data)
6262}
6263
6264},{"13":13}],41:[function(_dereq_,module,exports){
6265var createError = _dereq_(25).create
6266var LevelUPError = createError('LevelUPError')
6267var NotFoundError = createError('NotFoundError', LevelUPError)
6268
6269NotFoundError.prototype.notFound = true
6270NotFoundError.prototype.status = 404
6271
6272module.exports = {
6273 LevelUPError: LevelUPError,
6274 InitializationError: createError('InitializationError', LevelUPError),
6275 OpenError: createError('OpenError', LevelUPError),
6276 ReadError: createError('ReadError', LevelUPError),
6277 WriteError: createError('WriteError', LevelUPError),
6278 NotFoundError: NotFoundError,
6279 EncodingError: createError('EncodingError', LevelUPError)
6280}
6281
6282},{"25":25}],42:[function(_dereq_,module,exports){
6283var inherits = _dereq_(37)
6284var Readable = _dereq_(57).Readable
6285var extend = _dereq_(141)
6286
6287module.exports = ReadStream
6288inherits(ReadStream, Readable)
6289
6290function ReadStream (iterator, options) {
6291 if (!(this instanceof ReadStream)) return new ReadStream(iterator, options)
6292 options = options || {}
6293 Readable.call(this, extend(options, {
6294 objectMode: true
6295 }))
6296 this._iterator = iterator
6297 this._options = options
6298 this.on('end', this.destroy.bind(this, null, null))
6299}
6300
6301ReadStream.prototype._read = function () {
6302 var self = this
6303 var options = this._options
6304 if (this.destroyed) return
6305
6306 this._iterator.next(function (err, key, value) {
6307 if (self.destroyed) return
6308 if (err) return self.destroy(err)
6309
6310 if (key === undefined && value === undefined) {
6311 self.push(null)
6312 } else if (options.keys !== false && options.values === false) {
6313 self.push(key)
6314 } else if (options.keys === false && options.values !== false) {
6315 self.push(value)
6316 } else {
6317 self.push({ key: key, value: value })
6318 }
6319 })
6320}
6321
6322ReadStream.prototype._destroy = function (err, callback) {
6323 this._iterator.end(function (err2) {
6324 callback(err || err2)
6325 })
6326}
6327
6328},{"141":141,"37":37,"57":57}],43:[function(_dereq_,module,exports){
6329'use strict';
6330
6331function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
6332
6333var codes = {};
6334
6335function createErrorType(code, message, Base) {
6336 if (!Base) {
6337 Base = Error;
6338 }
6339
6340 function getMessage(arg1, arg2, arg3) {
6341 if (typeof message === 'string') {
6342 return message;
6343 } else {
6344 return message(arg1, arg2, arg3);
6345 }
6346 }
6347
6348 var NodeError =
6349 /*#__PURE__*/
6350 function (_Base) {
6351 _inheritsLoose(NodeError, _Base);
6352
6353 function NodeError(arg1, arg2, arg3) {
6354 return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
6355 }
6356
6357 return NodeError;
6358 }(Base);
6359
6360 NodeError.prototype.name = Base.name;
6361 NodeError.prototype.code = code;
6362 codes[code] = NodeError;
6363} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
6364
6365
6366function oneOf(expected, thing) {
6367 if (Array.isArray(expected)) {
6368 var len = expected.length;
6369 expected = expected.map(function (i) {
6370 return String(i);
6371 });
6372
6373 if (len > 2) {
6374 return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
6375 } else if (len === 2) {
6376 return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
6377 } else {
6378 return "of ".concat(thing, " ").concat(expected[0]);
6379 }
6380 } else {
6381 return "of ".concat(thing, " ").concat(String(expected));
6382 }
6383} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
6384
6385
6386function startsWith(str, search, pos) {
6387 return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
6388} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
6389
6390
6391function endsWith(str, search, this_len) {
6392 if (this_len === undefined || this_len > str.length) {
6393 this_len = str.length;
6394 }
6395
6396 return str.substring(this_len - search.length, this_len) === search;
6397} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
6398
6399
6400function includes(str, search, start) {
6401 if (typeof start !== 'number') {
6402 start = 0;
6403 }
6404
6405 if (start + search.length > str.length) {
6406 return false;
6407 } else {
6408 return str.indexOf(search, start) !== -1;
6409 }
6410}
6411
6412createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
6413 return 'The value "' + value + '" is invalid for option "' + name + '"';
6414}, TypeError);
6415createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
6416 // determiner: 'must be' or 'must not be'
6417 var determiner;
6418
6419 if (typeof expected === 'string' && startsWith(expected, 'not ')) {
6420 determiner = 'must not be';
6421 expected = expected.replace(/^not /, '');
6422 } else {
6423 determiner = 'must be';
6424 }
6425
6426 var msg;
6427
6428 if (endsWith(name, ' argument')) {
6429 // For cases like 'first argument'
6430 msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
6431 } else {
6432 var type = includes(name, '.') ? 'property' : 'argument';
6433 msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
6434 }
6435
6436 msg += ". Received type ".concat(typeof actual);
6437 return msg;
6438}, TypeError);
6439createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
6440createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
6441 return 'The ' + name + ' method is not implemented';
6442});
6443createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
6444createErrorType('ERR_STREAM_DESTROYED', function (name) {
6445 return 'Cannot call ' + name + ' after a stream was destroyed';
6446});
6447createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
6448createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
6449createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
6450createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
6451createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
6452 return 'Unknown encoding: ' + arg;
6453}, TypeError);
6454createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
6455module.exports.codes = codes;
6456
6457},{}],44:[function(_dereq_,module,exports){
6458(function (process){(function (){
6459// Copyright Joyent, Inc. and other Node contributors.
6460//
6461// Permission is hereby granted, free of charge, to any person obtaining a
6462// copy of this software and associated documentation files (the
6463// "Software"), to deal in the Software without restriction, including
6464// without limitation the rights to use, copy, modify, merge, publish,
6465// distribute, sublicense, and/or sell copies of the Software, and to permit
6466// persons to whom the Software is furnished to do so, subject to the
6467// following conditions:
6468//
6469// The above copyright notice and this permission notice shall be included
6470// in all copies or substantial portions of the Software.
6471//
6472// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6473// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6474// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6475// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6476// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6477// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6478// USE OR OTHER DEALINGS IN THE SOFTWARE.
6479// a duplex stream is just a stream that is both readable and writable.
6480// Since JS doesn't have multiple prototypal inheritance, this class
6481// prototypally inherits from Readable, and then parasitically from
6482// Writable.
6483'use strict';
6484/*<replacement>*/
6485
6486var objectKeys = Object.keys || function (obj) {
6487 var keys = [];
6488
6489 for (var key in obj) {
6490 keys.push(key);
6491 }
6492
6493 return keys;
6494};
6495/*</replacement>*/
6496
6497
6498module.exports = Duplex;
6499
6500var Readable = _dereq_(46);
6501
6502var Writable = _dereq_(48);
6503
6504_dereq_(37)(Duplex, Readable);
6505
6506{
6507 // Allow the keys array to be GC'ed.
6508 var keys = objectKeys(Writable.prototype);
6509
6510 for (var v = 0; v < keys.length; v++) {
6511 var method = keys[v];
6512 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
6513 }
6514}
6515
6516function Duplex(options) {
6517 if (!(this instanceof Duplex)) return new Duplex(options);
6518 Readable.call(this, options);
6519 Writable.call(this, options);
6520 this.allowHalfOpen = true;
6521
6522 if (options) {
6523 if (options.readable === false) this.readable = false;
6524 if (options.writable === false) this.writable = false;
6525
6526 if (options.allowHalfOpen === false) {
6527 this.allowHalfOpen = false;
6528 this.once('end', onend);
6529 }
6530 }
6531}
6532
6533Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
6534 // making it explicit this property is not enumerable
6535 // because otherwise some prototype manipulation in
6536 // userland will fail
6537 enumerable: false,
6538 get: function get() {
6539 return this._writableState.highWaterMark;
6540 }
6541});
6542Object.defineProperty(Duplex.prototype, 'writableBuffer', {
6543 // making it explicit this property is not enumerable
6544 // because otherwise some prototype manipulation in
6545 // userland will fail
6546 enumerable: false,
6547 get: function get() {
6548 return this._writableState && this._writableState.getBuffer();
6549 }
6550});
6551Object.defineProperty(Duplex.prototype, 'writableLength', {
6552 // making it explicit this property is not enumerable
6553 // because otherwise some prototype manipulation in
6554 // userland will fail
6555 enumerable: false,
6556 get: function get() {
6557 return this._writableState.length;
6558 }
6559}); // the no-half-open enforcer
6560
6561function onend() {
6562 // If the writable side ended, then we're ok.
6563 if (this._writableState.ended) return; // no more data can be written.
6564 // But allow more writes to happen in this tick.
6565
6566 process.nextTick(onEndNT, this);
6567}
6568
6569function onEndNT(self) {
6570 self.end();
6571}
6572
6573Object.defineProperty(Duplex.prototype, 'destroyed', {
6574 // making it explicit this property is not enumerable
6575 // because otherwise some prototype manipulation in
6576 // userland will fail
6577 enumerable: false,
6578 get: function get() {
6579 if (this._readableState === undefined || this._writableState === undefined) {
6580 return false;
6581 }
6582
6583 return this._readableState.destroyed && this._writableState.destroyed;
6584 },
6585 set: function set(value) {
6586 // we ignore the value if the stream
6587 // has not been initialized yet
6588 if (this._readableState === undefined || this._writableState === undefined) {
6589 return;
6590 } // backward compatibility, the user is explicitly
6591 // managing destroyed
6592
6593
6594 this._readableState.destroyed = value;
6595 this._writableState.destroyed = value;
6596 }
6597});
6598}).call(this)}).call(this,_dereq_(73))
6599},{"37":37,"46":46,"48":48,"73":73}],45:[function(_dereq_,module,exports){
6600// Copyright Joyent, Inc. and other Node contributors.
6601//
6602// Permission is hereby granted, free of charge, to any person obtaining a
6603// copy of this software and associated documentation files (the
6604// "Software"), to deal in the Software without restriction, including
6605// without limitation the rights to use, copy, modify, merge, publish,
6606// distribute, sublicense, and/or sell copies of the Software, and to permit
6607// persons to whom the Software is furnished to do so, subject to the
6608// following conditions:
6609//
6610// The above copyright notice and this permission notice shall be included
6611// in all copies or substantial portions of the Software.
6612//
6613// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6614// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6615// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6616// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6617// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6618// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6619// USE OR OTHER DEALINGS IN THE SOFTWARE.
6620// a passthrough stream.
6621// basically just the most minimal sort of Transform stream.
6622// Every written chunk gets output as-is.
6623'use strict';
6624
6625module.exports = PassThrough;
6626
6627var Transform = _dereq_(47);
6628
6629_dereq_(37)(PassThrough, Transform);
6630
6631function PassThrough(options) {
6632 if (!(this instanceof PassThrough)) return new PassThrough(options);
6633 Transform.call(this, options);
6634}
6635
6636PassThrough.prototype._transform = function (chunk, encoding, cb) {
6637 cb(null, chunk);
6638};
6639},{"37":37,"47":47}],46:[function(_dereq_,module,exports){
6640(function (process,global){(function (){
6641// Copyright Joyent, Inc. and other Node contributors.
6642//
6643// Permission is hereby granted, free of charge, to any person obtaining a
6644// copy of this software and associated documentation files (the
6645// "Software"), to deal in the Software without restriction, including
6646// without limitation the rights to use, copy, modify, merge, publish,
6647// distribute, sublicense, and/or sell copies of the Software, and to permit
6648// persons to whom the Software is furnished to do so, subject to the
6649// following conditions:
6650//
6651// The above copyright notice and this permission notice shall be included
6652// in all copies or substantial portions of the Software.
6653//
6654// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6655// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6656// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6657// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6658// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6659// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6660// USE OR OTHER DEALINGS IN THE SOFTWARE.
6661'use strict';
6662
6663module.exports = Readable;
6664/*<replacement>*/
6665
6666var Duplex;
6667/*</replacement>*/
6668
6669Readable.ReadableState = ReadableState;
6670/*<replacement>*/
6671
6672var EE = _dereq_(26).EventEmitter;
6673
6674var EElistenerCount = function EElistenerCount(emitter, type) {
6675 return emitter.listeners(type).length;
6676};
6677/*</replacement>*/
6678
6679/*<replacement>*/
6680
6681
6682var Stream = _dereq_(56);
6683/*</replacement>*/
6684
6685
6686var Buffer = _dereq_(13).Buffer;
6687
6688var OurUint8Array = global.Uint8Array || function () {};
6689
6690function _uint8ArrayToBuffer(chunk) {
6691 return Buffer.from(chunk);
6692}
6693
6694function _isUint8Array(obj) {
6695 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
6696}
6697/*<replacement>*/
6698
6699
6700var debugUtil = _dereq_(11);
6701
6702var debug;
6703
6704if (debugUtil && debugUtil.debuglog) {
6705 debug = debugUtil.debuglog('stream');
6706} else {
6707 debug = function debug() {};
6708}
6709/*</replacement>*/
6710
6711
6712var BufferList = _dereq_(50);
6713
6714var destroyImpl = _dereq_(51);
6715
6716var _require = _dereq_(55),
6717 getHighWaterMark = _require.getHighWaterMark;
6718
6719var _require$codes = _dereq_(43).codes,
6720 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
6721 ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
6722 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
6723 ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.
6724
6725
6726var StringDecoder;
6727var createReadableStreamAsyncIterator;
6728var from;
6729
6730_dereq_(37)(Readable, Stream);
6731
6732var errorOrDestroy = destroyImpl.errorOrDestroy;
6733var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
6734
6735function prependListener(emitter, event, fn) {
6736 // Sadly this is not cacheable as some libraries bundle their own
6737 // event emitter implementation with them.
6738 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
6739 // userland ones. NEVER DO THIS. This is here only because this code needs
6740 // to continue to work with older versions of Node.js that do not include
6741 // the prependListener() method. The goal is to eventually remove this hack.
6742
6743 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]];
6744}
6745
6746function ReadableState(options, stream, isDuplex) {
6747 Duplex = Duplex || _dereq_(44);
6748 options = options || {}; // Duplex streams are both readable and writable, but share
6749 // the same options object.
6750 // However, some cases require setting options to different
6751 // values for the readable and the writable sides of the duplex stream.
6752 // These options can be provided separately as readableXXX and writableXXX.
6753
6754 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to
6755 // make all the buffer merging and length checks go away
6756
6757 this.objectMode = !!options.objectMode;
6758 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
6759 // Note: 0 is a valid value, means "don't call _read preemptively ever"
6760
6761 this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the
6762 // linked list can remove elements from the beginning faster than
6763 // array.shift()
6764
6765 this.buffer = new BufferList();
6766 this.length = 0;
6767 this.pipes = null;
6768 this.pipesCount = 0;
6769 this.flowing = null;
6770 this.ended = false;
6771 this.endEmitted = false;
6772 this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted
6773 // immediately, or on a later tick. We set this to true at first, because
6774 // any actions that shouldn't happen until "later" should generally also
6775 // not happen before the first read call.
6776
6777 this.sync = true; // whenever we return null, then we set a flag to say
6778 // that we're awaiting a 'readable' event emission.
6779
6780 this.needReadable = false;
6781 this.emittedReadable = false;
6782 this.readableListening = false;
6783 this.resumeScheduled = false;
6784 this.paused = true; // Should close be emitted on destroy. Defaults to true.
6785
6786 this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')
6787
6788 this.autoDestroy = !!options.autoDestroy; // has it been destroyed
6789
6790 this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string
6791 // encoding is 'binary' so we have to make this configurable.
6792 // Everything else in the universe uses 'utf8', though.
6793
6794 this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s
6795
6796 this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled
6797
6798 this.readingMore = false;
6799 this.decoder = null;
6800 this.encoding = null;
6801
6802 if (options.encoding) {
6803 if (!StringDecoder) StringDecoder = _dereq_(102).StringDecoder;
6804 this.decoder = new StringDecoder(options.encoding);
6805 this.encoding = options.encoding;
6806 }
6807}
6808
6809function Readable(options) {
6810 Duplex = Duplex || _dereq_(44);
6811 if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside
6812 // the ReadableState constructor, at least with V8 6.5
6813
6814 var isDuplex = this instanceof Duplex;
6815 this._readableState = new ReadableState(options, this, isDuplex); // legacy
6816
6817 this.readable = true;
6818
6819 if (options) {
6820 if (typeof options.read === 'function') this._read = options.read;
6821 if (typeof options.destroy === 'function') this._destroy = options.destroy;
6822 }
6823
6824 Stream.call(this);
6825}
6826
6827Object.defineProperty(Readable.prototype, 'destroyed', {
6828 // making it explicit this property is not enumerable
6829 // because otherwise some prototype manipulation in
6830 // userland will fail
6831 enumerable: false,
6832 get: function get() {
6833 if (this._readableState === undefined) {
6834 return false;
6835 }
6836
6837 return this._readableState.destroyed;
6838 },
6839 set: function set(value) {
6840 // we ignore the value if the stream
6841 // has not been initialized yet
6842 if (!this._readableState) {
6843 return;
6844 } // backward compatibility, the user is explicitly
6845 // managing destroyed
6846
6847
6848 this._readableState.destroyed = value;
6849 }
6850});
6851Readable.prototype.destroy = destroyImpl.destroy;
6852Readable.prototype._undestroy = destroyImpl.undestroy;
6853
6854Readable.prototype._destroy = function (err, cb) {
6855 cb(err);
6856}; // Manually shove something into the read() buffer.
6857// This returns true if the highWaterMark has not been hit yet,
6858// similar to how Writable.write() returns true if you should
6859// write() some more.
6860
6861
6862Readable.prototype.push = function (chunk, encoding) {
6863 var state = this._readableState;
6864 var skipChunkCheck;
6865
6866 if (!state.objectMode) {
6867 if (typeof chunk === 'string') {
6868 encoding = encoding || state.defaultEncoding;
6869
6870 if (encoding !== state.encoding) {
6871 chunk = Buffer.from(chunk, encoding);
6872 encoding = '';
6873 }
6874
6875 skipChunkCheck = true;
6876 }
6877 } else {
6878 skipChunkCheck = true;
6879 }
6880
6881 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
6882}; // Unshift should *always* be something directly out of read()
6883
6884
6885Readable.prototype.unshift = function (chunk) {
6886 return readableAddChunk(this, chunk, null, true, false);
6887};
6888
6889function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
6890 debug('readableAddChunk', chunk);
6891 var state = stream._readableState;
6892
6893 if (chunk === null) {
6894 state.reading = false;
6895 onEofChunk(stream, state);
6896 } else {
6897 var er;
6898 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
6899
6900 if (er) {
6901 errorOrDestroy(stream, er);
6902 } else if (state.objectMode || chunk && chunk.length > 0) {
6903 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
6904 chunk = _uint8ArrayToBuffer(chunk);
6905 }
6906
6907 if (addToFront) {
6908 if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
6909 } else if (state.ended) {
6910 errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
6911 } else if (state.destroyed) {
6912 return false;
6913 } else {
6914 state.reading = false;
6915
6916 if (state.decoder && !encoding) {
6917 chunk = state.decoder.write(chunk);
6918 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
6919 } else {
6920 addChunk(stream, state, chunk, false);
6921 }
6922 }
6923 } else if (!addToFront) {
6924 state.reading = false;
6925 maybeReadMore(stream, state);
6926 }
6927 } // We can push more data if we are below the highWaterMark.
6928 // Also, if we have no data yet, we can stand some more bytes.
6929 // This is to work around cases where hwm=0, such as the repl.
6930
6931
6932 return !state.ended && (state.length < state.highWaterMark || state.length === 0);
6933}
6934
6935function addChunk(stream, state, chunk, addToFront) {
6936 if (state.flowing && state.length === 0 && !state.sync) {
6937 state.awaitDrain = 0;
6938 stream.emit('data', chunk);
6939 } else {
6940 // update the buffer info.
6941 state.length += state.objectMode ? 1 : chunk.length;
6942 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
6943 if (state.needReadable) emitReadable(stream);
6944 }
6945
6946 maybeReadMore(stream, state);
6947}
6948
6949function chunkInvalid(state, chunk) {
6950 var er;
6951
6952 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
6953 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
6954 }
6955
6956 return er;
6957}
6958
6959Readable.prototype.isPaused = function () {
6960 return this._readableState.flowing === false;
6961}; // backwards compatibility.
6962
6963
6964Readable.prototype.setEncoding = function (enc) {
6965 if (!StringDecoder) StringDecoder = _dereq_(102).StringDecoder;
6966 var decoder = new StringDecoder(enc);
6967 this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8
6968
6969 this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:
6970
6971 var p = this._readableState.buffer.head;
6972 var content = '';
6973
6974 while (p !== null) {
6975 content += decoder.write(p.data);
6976 p = p.next;
6977 }
6978
6979 this._readableState.buffer.clear();
6980
6981 if (content !== '') this._readableState.buffer.push(content);
6982 this._readableState.length = content.length;
6983 return this;
6984}; // Don't raise the hwm > 1GB
6985
6986
6987var MAX_HWM = 0x40000000;
6988
6989function computeNewHighWaterMark(n) {
6990 if (n >= MAX_HWM) {
6991 // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
6992 n = MAX_HWM;
6993 } else {
6994 // Get the next highest power of 2 to prevent increasing hwm excessively in
6995 // tiny amounts
6996 n--;
6997 n |= n >>> 1;
6998 n |= n >>> 2;
6999 n |= n >>> 4;
7000 n |= n >>> 8;
7001 n |= n >>> 16;
7002 n++;
7003 }
7004
7005 return n;
7006} // This function is designed to be inlinable, so please take care when making
7007// changes to the function body.
7008
7009
7010function howMuchToRead(n, state) {
7011 if (n <= 0 || state.length === 0 && state.ended) return 0;
7012 if (state.objectMode) return 1;
7013
7014 if (n !== n) {
7015 // Only flow one buffer at a time
7016 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
7017 } // If we're asking for more than the current hwm, then raise the hwm.
7018
7019
7020 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
7021 if (n <= state.length) return n; // Don't have enough
7022
7023 if (!state.ended) {
7024 state.needReadable = true;
7025 return 0;
7026 }
7027
7028 return state.length;
7029} // you can override either this method, or the async _read(n) below.
7030
7031
7032Readable.prototype.read = function (n) {
7033 debug('read', n);
7034 n = parseInt(n, 10);
7035 var state = this._readableState;
7036 var nOrig = n;
7037 if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we
7038 // already have a bunch of data in the buffer, then just trigger
7039 // the 'readable' event and move on.
7040
7041 if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
7042 debug('read: emitReadable', state.length, state.ended);
7043 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
7044 return null;
7045 }
7046
7047 n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.
7048
7049 if (n === 0 && state.ended) {
7050 if (state.length === 0) endReadable(this);
7051 return null;
7052 } // All the actual chunk generation logic needs to be
7053 // *below* the call to _read. The reason is that in certain
7054 // synthetic stream cases, such as passthrough streams, _read
7055 // may be a completely synchronous operation which may change
7056 // the state of the read buffer, providing enough data when
7057 // before there was *not* enough.
7058 //
7059 // So, the steps are:
7060 // 1. Figure out what the state of things will be after we do
7061 // a read from the buffer.
7062 //
7063 // 2. If that resulting state will trigger a _read, then call _read.
7064 // Note that this may be asynchronous, or synchronous. Yes, it is
7065 // deeply ugly to write APIs this way, but that still doesn't mean
7066 // that the Readable class should behave improperly, as streams are
7067 // designed to be sync/async agnostic.
7068 // Take note if the _read call is sync or async (ie, if the read call
7069 // has returned yet), so that we know whether or not it's safe to emit
7070 // 'readable' etc.
7071 //
7072 // 3. Actually pull the requested chunks out of the buffer and return.
7073 // if we need a readable event, then we need to do some reading.
7074
7075
7076 var doRead = state.needReadable;
7077 debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some
7078
7079 if (state.length === 0 || state.length - n < state.highWaterMark) {
7080 doRead = true;
7081 debug('length less than watermark', doRead);
7082 } // however, if we've ended, then there's no point, and if we're already
7083 // reading, then it's unnecessary.
7084
7085
7086 if (state.ended || state.reading) {
7087 doRead = false;
7088 debug('reading or ended', doRead);
7089 } else if (doRead) {
7090 debug('do read');
7091 state.reading = true;
7092 state.sync = true; // if the length is currently zero, then we *need* a readable event.
7093
7094 if (state.length === 0) state.needReadable = true; // call internal read method
7095
7096 this._read(state.highWaterMark);
7097
7098 state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
7099 // and we need to re-evaluate how much data we can return to the user.
7100
7101 if (!state.reading) n = howMuchToRead(nOrig, state);
7102 }
7103
7104 var ret;
7105 if (n > 0) ret = fromList(n, state);else ret = null;
7106
7107 if (ret === null) {
7108 state.needReadable = state.length <= state.highWaterMark;
7109 n = 0;
7110 } else {
7111 state.length -= n;
7112 state.awaitDrain = 0;
7113 }
7114
7115 if (state.length === 0) {
7116 // If we have nothing in the buffer, then we want to know
7117 // as soon as we *do* get something into the buffer.
7118 if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
7119
7120 if (nOrig !== n && state.ended) endReadable(this);
7121 }
7122
7123 if (ret !== null) this.emit('data', ret);
7124 return ret;
7125};
7126
7127function onEofChunk(stream, state) {
7128 debug('onEofChunk');
7129 if (state.ended) return;
7130
7131 if (state.decoder) {
7132 var chunk = state.decoder.end();
7133
7134 if (chunk && chunk.length) {
7135 state.buffer.push(chunk);
7136 state.length += state.objectMode ? 1 : chunk.length;
7137 }
7138 }
7139
7140 state.ended = true;
7141
7142 if (state.sync) {
7143 // if we are sync, wait until next tick to emit the data.
7144 // Otherwise we risk emitting data in the flow()
7145 // the readable code triggers during a read() call
7146 emitReadable(stream);
7147 } else {
7148 // emit 'readable' now to make sure it gets picked up.
7149 state.needReadable = false;
7150
7151 if (!state.emittedReadable) {
7152 state.emittedReadable = true;
7153 emitReadable_(stream);
7154 }
7155 }
7156} // Don't emit readable right away in sync mode, because this can trigger
7157// another read() call => stack overflow. This way, it might trigger
7158// a nextTick recursion warning, but that's not so bad.
7159
7160
7161function emitReadable(stream) {
7162 var state = stream._readableState;
7163 debug('emitReadable', state.needReadable, state.emittedReadable);
7164 state.needReadable = false;
7165
7166 if (!state.emittedReadable) {
7167 debug('emitReadable', state.flowing);
7168 state.emittedReadable = true;
7169 process.nextTick(emitReadable_, stream);
7170 }
7171}
7172
7173function emitReadable_(stream) {
7174 var state = stream._readableState;
7175 debug('emitReadable_', state.destroyed, state.length, state.ended);
7176
7177 if (!state.destroyed && (state.length || state.ended)) {
7178 stream.emit('readable');
7179 state.emittedReadable = false;
7180 } // The stream needs another readable event if
7181 // 1. It is not flowing, as the flow mechanism will take
7182 // care of it.
7183 // 2. It is not ended.
7184 // 3. It is below the highWaterMark, so we can schedule
7185 // another readable later.
7186
7187
7188 state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
7189 flow(stream);
7190} // at this point, the user has presumably seen the 'readable' event,
7191// and called read() to consume some data. that may have triggered
7192// in turn another _read(n) call, in which case reading = true if
7193// it's in progress.
7194// However, if we're not ended, or reading, and the length < hwm,
7195// then go ahead and try to read some more preemptively.
7196
7197
7198function maybeReadMore(stream, state) {
7199 if (!state.readingMore) {
7200 state.readingMore = true;
7201 process.nextTick(maybeReadMore_, stream, state);
7202 }
7203}
7204
7205function maybeReadMore_(stream, state) {
7206 // Attempt to read more data if we should.
7207 //
7208 // The conditions for reading more data are (one of):
7209 // - Not enough data buffered (state.length < state.highWaterMark). The loop
7210 // is responsible for filling the buffer with enough data if such data
7211 // is available. If highWaterMark is 0 and we are not in the flowing mode
7212 // we should _not_ attempt to buffer any extra data. We'll get more data
7213 // when the stream consumer calls read() instead.
7214 // - No data in the buffer, and the stream is in flowing mode. In this mode
7215 // the loop below is responsible for ensuring read() is called. Failing to
7216 // call read here would abort the flow and there's no other mechanism for
7217 // continuing the flow if the stream consumer has just subscribed to the
7218 // 'data' event.
7219 //
7220 // In addition to the above conditions to keep reading data, the following
7221 // conditions prevent the data from being read:
7222 // - The stream has ended (state.ended).
7223 // - There is already a pending 'read' operation (state.reading). This is a
7224 // case where the the stream has called the implementation defined _read()
7225 // method, but they are processing the call asynchronously and have _not_
7226 // called push() with new data. In this case we skip performing more
7227 // read()s. The execution ends in this method again after the _read() ends
7228 // up calling push() with more data.
7229 while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
7230 var len = state.length;
7231 debug('maybeReadMore read 0');
7232 stream.read(0);
7233 if (len === state.length) // didn't get any data, stop spinning.
7234 break;
7235 }
7236
7237 state.readingMore = false;
7238} // abstract method. to be overridden in specific implementation classes.
7239// call cb(er, data) where data is <= n in length.
7240// for virtual (non-string, non-buffer) streams, "length" is somewhat
7241// arbitrary, and perhaps not very meaningful.
7242
7243
7244Readable.prototype._read = function (n) {
7245 errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
7246};
7247
7248Readable.prototype.pipe = function (dest, pipeOpts) {
7249 var src = this;
7250 var state = this._readableState;
7251
7252 switch (state.pipesCount) {
7253 case 0:
7254 state.pipes = dest;
7255 break;
7256
7257 case 1:
7258 state.pipes = [state.pipes, dest];
7259 break;
7260
7261 default:
7262 state.pipes.push(dest);
7263 break;
7264 }
7265
7266 state.pipesCount += 1;
7267 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
7268 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
7269 var endFn = doEnd ? onend : unpipe;
7270 if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
7271 dest.on('unpipe', onunpipe);
7272
7273 function onunpipe(readable, unpipeInfo) {
7274 debug('onunpipe');
7275
7276 if (readable === src) {
7277 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
7278 unpipeInfo.hasUnpiped = true;
7279 cleanup();
7280 }
7281 }
7282 }
7283
7284 function onend() {
7285 debug('onend');
7286 dest.end();
7287 } // when the dest drains, it reduces the awaitDrain counter
7288 // on the source. This would be more elegant with a .once()
7289 // handler in flow(), but adding and removing repeatedly is
7290 // too slow.
7291
7292
7293 var ondrain = pipeOnDrain(src);
7294 dest.on('drain', ondrain);
7295 var cleanedUp = false;
7296
7297 function cleanup() {
7298 debug('cleanup'); // cleanup event handlers once the pipe is broken
7299
7300 dest.removeListener('close', onclose);
7301 dest.removeListener('finish', onfinish);
7302 dest.removeListener('drain', ondrain);
7303 dest.removeListener('error', onerror);
7304 dest.removeListener('unpipe', onunpipe);
7305 src.removeListener('end', onend);
7306 src.removeListener('end', unpipe);
7307 src.removeListener('data', ondata);
7308 cleanedUp = true; // if the reader is waiting for a drain event from this
7309 // specific writer, then it would cause it to never start
7310 // flowing again.
7311 // So, if this is awaiting a drain, then we just call it now.
7312 // If we don't know, then assume that we are waiting for one.
7313
7314 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
7315 }
7316
7317 src.on('data', ondata);
7318
7319 function ondata(chunk) {
7320 debug('ondata');
7321 var ret = dest.write(chunk);
7322 debug('dest.write', ret);
7323
7324 if (ret === false) {
7325 // If the user unpiped during `dest.write()`, it is possible
7326 // to get stuck in a permanently paused state if that write
7327 // also returned false.
7328 // => Check whether `dest` is still a piping destination.
7329 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
7330 debug('false write response, pause', state.awaitDrain);
7331 state.awaitDrain++;
7332 }
7333
7334 src.pause();
7335 }
7336 } // if the dest has an error, then stop piping into it.
7337 // however, don't suppress the throwing behavior for this.
7338
7339
7340 function onerror(er) {
7341 debug('onerror', er);
7342 unpipe();
7343 dest.removeListener('error', onerror);
7344 if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
7345 } // Make sure our error handler is attached before userland ones.
7346
7347
7348 prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
7349
7350 function onclose() {
7351 dest.removeListener('finish', onfinish);
7352 unpipe();
7353 }
7354
7355 dest.once('close', onclose);
7356
7357 function onfinish() {
7358 debug('onfinish');
7359 dest.removeListener('close', onclose);
7360 unpipe();
7361 }
7362
7363 dest.once('finish', onfinish);
7364
7365 function unpipe() {
7366 debug('unpipe');
7367 src.unpipe(dest);
7368 } // tell the dest that it's being piped to
7369
7370
7371 dest.emit('pipe', src); // start the flow if it hasn't been started already.
7372
7373 if (!state.flowing) {
7374 debug('pipe resume');
7375 src.resume();
7376 }
7377
7378 return dest;
7379};
7380
7381function pipeOnDrain(src) {
7382 return function pipeOnDrainFunctionResult() {
7383 var state = src._readableState;
7384 debug('pipeOnDrain', state.awaitDrain);
7385 if (state.awaitDrain) state.awaitDrain--;
7386
7387 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
7388 state.flowing = true;
7389 flow(src);
7390 }
7391 };
7392}
7393
7394Readable.prototype.unpipe = function (dest) {
7395 var state = this._readableState;
7396 var unpipeInfo = {
7397 hasUnpiped: false
7398 }; // if we're not piping anywhere, then do nothing.
7399
7400 if (state.pipesCount === 0) return this; // just one destination. most common case.
7401
7402 if (state.pipesCount === 1) {
7403 // passed in one, but it's not the right one.
7404 if (dest && dest !== state.pipes) return this;
7405 if (!dest) dest = state.pipes; // got a match.
7406
7407 state.pipes = null;
7408 state.pipesCount = 0;
7409 state.flowing = false;
7410 if (dest) dest.emit('unpipe', this, unpipeInfo);
7411 return this;
7412 } // slow case. multiple pipe destinations.
7413
7414
7415 if (!dest) {
7416 // remove all.
7417 var dests = state.pipes;
7418 var len = state.pipesCount;
7419 state.pipes = null;
7420 state.pipesCount = 0;
7421 state.flowing = false;
7422
7423 for (var i = 0; i < len; i++) {
7424 dests[i].emit('unpipe', this, {
7425 hasUnpiped: false
7426 });
7427 }
7428
7429 return this;
7430 } // try to find the right one.
7431
7432
7433 var index = indexOf(state.pipes, dest);
7434 if (index === -1) return this;
7435 state.pipes.splice(index, 1);
7436 state.pipesCount -= 1;
7437 if (state.pipesCount === 1) state.pipes = state.pipes[0];
7438 dest.emit('unpipe', this, unpipeInfo);
7439 return this;
7440}; // set up data events if they are asked for
7441// Ensure readable listeners eventually get something
7442
7443
7444Readable.prototype.on = function (ev, fn) {
7445 var res = Stream.prototype.on.call(this, ev, fn);
7446 var state = this._readableState;
7447
7448 if (ev === 'data') {
7449 // update readableListening so that resume() may be a no-op
7450 // a few lines down. This is needed to support once('readable').
7451 state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused
7452
7453 if (state.flowing !== false) this.resume();
7454 } else if (ev === 'readable') {
7455 if (!state.endEmitted && !state.readableListening) {
7456 state.readableListening = state.needReadable = true;
7457 state.flowing = false;
7458 state.emittedReadable = false;
7459 debug('on readable', state.length, state.reading);
7460
7461 if (state.length) {
7462 emitReadable(this);
7463 } else if (!state.reading) {
7464 process.nextTick(nReadingNextTick, this);
7465 }
7466 }
7467 }
7468
7469 return res;
7470};
7471
7472Readable.prototype.addListener = Readable.prototype.on;
7473
7474Readable.prototype.removeListener = function (ev, fn) {
7475 var res = Stream.prototype.removeListener.call(this, ev, fn);
7476
7477 if (ev === 'readable') {
7478 // We need to check if there is someone still listening to
7479 // readable and reset the state. However this needs to happen
7480 // after readable has been emitted but before I/O (nextTick) to
7481 // support once('readable', fn) cycles. This means that calling
7482 // resume within the same tick will have no
7483 // effect.
7484 process.nextTick(updateReadableListening, this);
7485 }
7486
7487 return res;
7488};
7489
7490Readable.prototype.removeAllListeners = function (ev) {
7491 var res = Stream.prototype.removeAllListeners.apply(this, arguments);
7492
7493 if (ev === 'readable' || ev === undefined) {
7494 // We need to check if there is someone still listening to
7495 // readable and reset the state. However this needs to happen
7496 // after readable has been emitted but before I/O (nextTick) to
7497 // support once('readable', fn) cycles. This means that calling
7498 // resume within the same tick will have no
7499 // effect.
7500 process.nextTick(updateReadableListening, this);
7501 }
7502
7503 return res;
7504};
7505
7506function updateReadableListening(self) {
7507 var state = self._readableState;
7508 state.readableListening = self.listenerCount('readable') > 0;
7509
7510 if (state.resumeScheduled && !state.paused) {
7511 // flowing needs to be set to true now, otherwise
7512 // the upcoming resume will not flow.
7513 state.flowing = true; // crude way to check if we should resume
7514 } else if (self.listenerCount('data') > 0) {
7515 self.resume();
7516 }
7517}
7518
7519function nReadingNextTick(self) {
7520 debug('readable nexttick read 0');
7521 self.read(0);
7522} // pause() and resume() are remnants of the legacy readable stream API
7523// If the user uses them, then switch into old mode.
7524
7525
7526Readable.prototype.resume = function () {
7527 var state = this._readableState;
7528
7529 if (!state.flowing) {
7530 debug('resume'); // we flow only if there is no one listening
7531 // for readable, but we still have to call
7532 // resume()
7533
7534 state.flowing = !state.readableListening;
7535 resume(this, state);
7536 }
7537
7538 state.paused = false;
7539 return this;
7540};
7541
7542function resume(stream, state) {
7543 if (!state.resumeScheduled) {
7544 state.resumeScheduled = true;
7545 process.nextTick(resume_, stream, state);
7546 }
7547}
7548
7549function resume_(stream, state) {
7550 debug('resume', state.reading);
7551
7552 if (!state.reading) {
7553 stream.read(0);
7554 }
7555
7556 state.resumeScheduled = false;
7557 stream.emit('resume');
7558 flow(stream);
7559 if (state.flowing && !state.reading) stream.read(0);
7560}
7561
7562Readable.prototype.pause = function () {
7563 debug('call pause flowing=%j', this._readableState.flowing);
7564
7565 if (this._readableState.flowing !== false) {
7566 debug('pause');
7567 this._readableState.flowing = false;
7568 this.emit('pause');
7569 }
7570
7571 this._readableState.paused = true;
7572 return this;
7573};
7574
7575function flow(stream) {
7576 var state = stream._readableState;
7577 debug('flow', state.flowing);
7578
7579 while (state.flowing && stream.read() !== null) {
7580 ;
7581 }
7582} // wrap an old-style stream as the async data source.
7583// This is *not* part of the readable stream interface.
7584// It is an ugly unfortunate mess of history.
7585
7586
7587Readable.prototype.wrap = function (stream) {
7588 var _this = this;
7589
7590 var state = this._readableState;
7591 var paused = false;
7592 stream.on('end', function () {
7593 debug('wrapped end');
7594
7595 if (state.decoder && !state.ended) {
7596 var chunk = state.decoder.end();
7597 if (chunk && chunk.length) _this.push(chunk);
7598 }
7599
7600 _this.push(null);
7601 });
7602 stream.on('data', function (chunk) {
7603 debug('wrapped data');
7604 if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
7605
7606 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
7607
7608 var ret = _this.push(chunk);
7609
7610 if (!ret) {
7611 paused = true;
7612 stream.pause();
7613 }
7614 }); // proxy all the other methods.
7615 // important when wrapping filters and duplexes.
7616
7617 for (var i in stream) {
7618 if (this[i] === undefined && typeof stream[i] === 'function') {
7619 this[i] = function methodWrap(method) {
7620 return function methodWrapReturnFunction() {
7621 return stream[method].apply(stream, arguments);
7622 };
7623 }(i);
7624 }
7625 } // proxy certain important events.
7626
7627
7628 for (var n = 0; n < kProxyEvents.length; n++) {
7629 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
7630 } // when we try to consume some more bytes, simply unpause the
7631 // underlying stream.
7632
7633
7634 this._read = function (n) {
7635 debug('wrapped _read', n);
7636
7637 if (paused) {
7638 paused = false;
7639 stream.resume();
7640 }
7641 };
7642
7643 return this;
7644};
7645
7646if (typeof Symbol === 'function') {
7647 Readable.prototype[Symbol.asyncIterator] = function () {
7648 if (createReadableStreamAsyncIterator === undefined) {
7649 createReadableStreamAsyncIterator = _dereq_(49);
7650 }
7651
7652 return createReadableStreamAsyncIterator(this);
7653 };
7654}
7655
7656Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
7657 // making it explicit this property is not enumerable
7658 // because otherwise some prototype manipulation in
7659 // userland will fail
7660 enumerable: false,
7661 get: function get() {
7662 return this._readableState.highWaterMark;
7663 }
7664});
7665Object.defineProperty(Readable.prototype, 'readableBuffer', {
7666 // making it explicit this property is not enumerable
7667 // because otherwise some prototype manipulation in
7668 // userland will fail
7669 enumerable: false,
7670 get: function get() {
7671 return this._readableState && this._readableState.buffer;
7672 }
7673});
7674Object.defineProperty(Readable.prototype, 'readableFlowing', {
7675 // making it explicit this property is not enumerable
7676 // because otherwise some prototype manipulation in
7677 // userland will fail
7678 enumerable: false,
7679 get: function get() {
7680 return this._readableState.flowing;
7681 },
7682 set: function set(state) {
7683 if (this._readableState) {
7684 this._readableState.flowing = state;
7685 }
7686 }
7687}); // exposed for testing purposes only.
7688
7689Readable._fromList = fromList;
7690Object.defineProperty(Readable.prototype, 'readableLength', {
7691 // making it explicit this property is not enumerable
7692 // because otherwise some prototype manipulation in
7693 // userland will fail
7694 enumerable: false,
7695 get: function get() {
7696 return this._readableState.length;
7697 }
7698}); // Pluck off n bytes from an array of buffers.
7699// Length is the combined lengths of all the buffers in the list.
7700// This function is designed to be inlinable, so please take care when making
7701// changes to the function body.
7702
7703function fromList(n, state) {
7704 // nothing buffered
7705 if (state.length === 0) return null;
7706 var ret;
7707 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
7708 // read it all, truncate the list
7709 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
7710 state.buffer.clear();
7711 } else {
7712 // read part of list
7713 ret = state.buffer.consume(n, state.decoder);
7714 }
7715 return ret;
7716}
7717
7718function endReadable(stream) {
7719 var state = stream._readableState;
7720 debug('endReadable', state.endEmitted);
7721
7722 if (!state.endEmitted) {
7723 state.ended = true;
7724 process.nextTick(endReadableNT, state, stream);
7725 }
7726}
7727
7728function endReadableNT(state, stream) {
7729 debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.
7730
7731 if (!state.endEmitted && state.length === 0) {
7732 state.endEmitted = true;
7733 stream.readable = false;
7734 stream.emit('end');
7735
7736 if (state.autoDestroy) {
7737 // In case of duplex streams we need a way to detect
7738 // if the writable side is ready for autoDestroy as well
7739 var wState = stream._writableState;
7740
7741 if (!wState || wState.autoDestroy && wState.finished) {
7742 stream.destroy();
7743 }
7744 }
7745 }
7746}
7747
7748if (typeof Symbol === 'function') {
7749 Readable.from = function (iterable, opts) {
7750 if (from === undefined) {
7751 from = _dereq_(53);
7752 }
7753
7754 return from(Readable, iterable, opts);
7755 };
7756}
7757
7758function indexOf(xs, x) {
7759 for (var i = 0, l = xs.length; i < l; i++) {
7760 if (xs[i] === x) return i;
7761 }
7762
7763 return -1;
7764}
7765}).call(this)}).call(this,_dereq_(73),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
7766},{"102":102,"11":11,"13":13,"26":26,"37":37,"43":43,"44":44,"49":49,"50":50,"51":51,"53":53,"55":55,"56":56,"73":73}],47:[function(_dereq_,module,exports){
7767// Copyright Joyent, Inc. and other Node contributors.
7768//
7769// Permission is hereby granted, free of charge, to any person obtaining a
7770// copy of this software and associated documentation files (the
7771// "Software"), to deal in the Software without restriction, including
7772// without limitation the rights to use, copy, modify, merge, publish,
7773// distribute, sublicense, and/or sell copies of the Software, and to permit
7774// persons to whom the Software is furnished to do so, subject to the
7775// following conditions:
7776//
7777// The above copyright notice and this permission notice shall be included
7778// in all copies or substantial portions of the Software.
7779//
7780// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7781// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7782// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7783// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7784// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7785// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7786// USE OR OTHER DEALINGS IN THE SOFTWARE.
7787// a transform stream is a readable/writable stream where you do
7788// something with the data. Sometimes it's called a "filter",
7789// but that's not a great name for it, since that implies a thing where
7790// some bits pass through, and others are simply ignored. (That would
7791// be a valid example of a transform, of course.)
7792//
7793// While the output is causally related to the input, it's not a
7794// necessarily symmetric or synchronous transformation. For example,
7795// a zlib stream might take multiple plain-text writes(), and then
7796// emit a single compressed chunk some time in the future.
7797//
7798// Here's how this works:
7799//
7800// The Transform stream has all the aspects of the readable and writable
7801// stream classes. When you write(chunk), that calls _write(chunk,cb)
7802// internally, and returns false if there's a lot of pending writes
7803// buffered up. When you call read(), that calls _read(n) until
7804// there's enough pending readable data buffered up.
7805//
7806// In a transform stream, the written data is placed in a buffer. When
7807// _read(n) is called, it transforms the queued up data, calling the
7808// buffered _write cb's as it consumes chunks. If consuming a single
7809// written chunk would result in multiple output chunks, then the first
7810// outputted bit calls the readcb, and subsequent chunks just go into
7811// the read buffer, and will cause it to emit 'readable' if necessary.
7812//
7813// This way, back-pressure is actually determined by the reading side,
7814// since _read has to be called to start processing a new chunk. However,
7815// a pathological inflate type of transform can cause excessive buffering
7816// here. For example, imagine a stream where every byte of input is
7817// interpreted as an integer from 0-255, and then results in that many
7818// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
7819// 1kb of data being output. In this case, you could write a very small
7820// amount of input, and end up with a very large amount of output. In
7821// such a pathological inflating mechanism, there'd be no way to tell
7822// the system to stop doing the transform. A single 4MB write could
7823// cause the system to run out of memory.
7824//
7825// However, even in such a pathological case, only a single written chunk
7826// would be consumed, and then the rest would wait (un-transformed) until
7827// the results of the previous transformed chunk were consumed.
7828'use strict';
7829
7830module.exports = Transform;
7831
7832var _require$codes = _dereq_(43).codes,
7833 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
7834 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
7835 ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
7836 ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
7837
7838var Duplex = _dereq_(44);
7839
7840_dereq_(37)(Transform, Duplex);
7841
7842function afterTransform(er, data) {
7843 var ts = this._transformState;
7844 ts.transforming = false;
7845 var cb = ts.writecb;
7846
7847 if (cb === null) {
7848 return this.emit('error', new ERR_MULTIPLE_CALLBACK());
7849 }
7850
7851 ts.writechunk = null;
7852 ts.writecb = null;
7853 if (data != null) // single equals check for both `null` and `undefined`
7854 this.push(data);
7855 cb(er);
7856 var rs = this._readableState;
7857 rs.reading = false;
7858
7859 if (rs.needReadable || rs.length < rs.highWaterMark) {
7860 this._read(rs.highWaterMark);
7861 }
7862}
7863
7864function Transform(options) {
7865 if (!(this instanceof Transform)) return new Transform(options);
7866 Duplex.call(this, options);
7867 this._transformState = {
7868 afterTransform: afterTransform.bind(this),
7869 needTransform: false,
7870 transforming: false,
7871 writecb: null,
7872 writechunk: null,
7873 writeencoding: null
7874 }; // start out asking for a readable event once data is transformed.
7875
7876 this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
7877 // that Readable wants before the first _read call, so unset the
7878 // sync guard flag.
7879
7880 this._readableState.sync = false;
7881
7882 if (options) {
7883 if (typeof options.transform === 'function') this._transform = options.transform;
7884 if (typeof options.flush === 'function') this._flush = options.flush;
7885 } // When the writable side finishes, then flush out anything remaining.
7886
7887
7888 this.on('prefinish', prefinish);
7889}
7890
7891function prefinish() {
7892 var _this = this;
7893
7894 if (typeof this._flush === 'function' && !this._readableState.destroyed) {
7895 this._flush(function (er, data) {
7896 done(_this, er, data);
7897 });
7898 } else {
7899 done(this, null, null);
7900 }
7901}
7902
7903Transform.prototype.push = function (chunk, encoding) {
7904 this._transformState.needTransform = false;
7905 return Duplex.prototype.push.call(this, chunk, encoding);
7906}; // This is the part where you do stuff!
7907// override this function in implementation classes.
7908// 'chunk' is an input chunk.
7909//
7910// Call `push(newChunk)` to pass along transformed output
7911// to the readable side. You may call 'push' zero or more times.
7912//
7913// Call `cb(err)` when you are done with this chunk. If you pass
7914// an error, then that'll put the hurt on the whole operation. If you
7915// never call cb(), then you'll never get another chunk.
7916
7917
7918Transform.prototype._transform = function (chunk, encoding, cb) {
7919 cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
7920};
7921
7922Transform.prototype._write = function (chunk, encoding, cb) {
7923 var ts = this._transformState;
7924 ts.writecb = cb;
7925 ts.writechunk = chunk;
7926 ts.writeencoding = encoding;
7927
7928 if (!ts.transforming) {
7929 var rs = this._readableState;
7930 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
7931 }
7932}; // Doesn't matter what the args are here.
7933// _transform does all the work.
7934// That we got here means that the readable side wants more data.
7935
7936
7937Transform.prototype._read = function (n) {
7938 var ts = this._transformState;
7939
7940 if (ts.writechunk !== null && !ts.transforming) {
7941 ts.transforming = true;
7942
7943 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
7944 } else {
7945 // mark that we need a transform, so that any data that comes in
7946 // will get processed, now that we've asked for it.
7947 ts.needTransform = true;
7948 }
7949};
7950
7951Transform.prototype._destroy = function (err, cb) {
7952 Duplex.prototype._destroy.call(this, err, function (err2) {
7953 cb(err2);
7954 });
7955};
7956
7957function done(stream, er, data) {
7958 if (er) return stream.emit('error', er);
7959 if (data != null) // single equals check for both `null` and `undefined`
7960 stream.push(data); // TODO(BridgeAR): Write a test for these two error cases
7961 // if there's nothing in the write buffer, then that means
7962 // that nothing more will ever be provided
7963
7964 if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
7965 if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
7966 return stream.push(null);
7967}
7968},{"37":37,"43":43,"44":44}],48:[function(_dereq_,module,exports){
7969(function (process,global){(function (){
7970// Copyright Joyent, Inc. and other Node contributors.
7971//
7972// Permission is hereby granted, free of charge, to any person obtaining a
7973// copy of this software and associated documentation files (the
7974// "Software"), to deal in the Software without restriction, including
7975// without limitation the rights to use, copy, modify, merge, publish,
7976// distribute, sublicense, and/or sell copies of the Software, and to permit
7977// persons to whom the Software is furnished to do so, subject to the
7978// following conditions:
7979//
7980// The above copyright notice and this permission notice shall be included
7981// in all copies or substantial portions of the Software.
7982//
7983// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7984// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7985// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7986// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7987// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7988// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7989// USE OR OTHER DEALINGS IN THE SOFTWARE.
7990// A bit simpler than readable streams.
7991// Implement an async ._write(chunk, encoding, cb), and it'll handle all
7992// the drain event emission and buffering.
7993'use strict';
7994
7995module.exports = Writable;
7996/* <replacement> */
7997
7998function WriteReq(chunk, encoding, cb) {
7999 this.chunk = chunk;
8000 this.encoding = encoding;
8001 this.callback = cb;
8002 this.next = null;
8003} // It seems a linked list but it is not
8004// there will be only 2 of these for each stream
8005
8006
8007function CorkedRequest(state) {
8008 var _this = this;
8009
8010 this.next = null;
8011 this.entry = null;
8012
8013 this.finish = function () {
8014 onCorkedFinish(_this, state);
8015 };
8016}
8017/* </replacement> */
8018
8019/*<replacement>*/
8020
8021
8022var Duplex;
8023/*</replacement>*/
8024
8025Writable.WritableState = WritableState;
8026/*<replacement>*/
8027
8028var internalUtil = {
8029 deprecate: _dereq_(121)
8030};
8031/*</replacement>*/
8032
8033/*<replacement>*/
8034
8035var Stream = _dereq_(56);
8036/*</replacement>*/
8037
8038
8039var Buffer = _dereq_(13).Buffer;
8040
8041var OurUint8Array = global.Uint8Array || function () {};
8042
8043function _uint8ArrayToBuffer(chunk) {
8044 return Buffer.from(chunk);
8045}
8046
8047function _isUint8Array(obj) {
8048 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
8049}
8050
8051var destroyImpl = _dereq_(51);
8052
8053var _require = _dereq_(55),
8054 getHighWaterMark = _require.getHighWaterMark;
8055
8056var _require$codes = _dereq_(43).codes,
8057 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
8058 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
8059 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
8060 ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
8061 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
8062 ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
8063 ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
8064 ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
8065
8066var errorOrDestroy = destroyImpl.errorOrDestroy;
8067
8068_dereq_(37)(Writable, Stream);
8069
8070function nop() {}
8071
8072function WritableState(options, stream, isDuplex) {
8073 Duplex = Duplex || _dereq_(44);
8074 options = options || {}; // Duplex streams are both readable and writable, but share
8075 // the same options object.
8076 // However, some cases require setting options to different
8077 // values for the readable and the writable sides of the duplex stream,
8078 // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
8079
8080 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream
8081 // contains buffers or objects.
8082
8083 this.objectMode = !!options.objectMode;
8084 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
8085 // Note: 0 is a valid value, means that we always return false if
8086 // the entire buffer is not flushed immediately on write()
8087
8088 this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called
8089
8090 this.finalCalled = false; // drain event flag.
8091
8092 this.needDrain = false; // at the start of calling end()
8093
8094 this.ending = false; // when end() has been called, and returned
8095
8096 this.ended = false; // when 'finish' is emitted
8097
8098 this.finished = false; // has it been destroyed
8099
8100 this.destroyed = false; // should we decode strings into buffers before passing to _write?
8101 // this is here so that some node-core streams can optimize string
8102 // handling at a lower level.
8103
8104 var noDecode = options.decodeStrings === false;
8105 this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string
8106 // encoding is 'binary' so we have to make this configurable.
8107 // Everything else in the universe uses 'utf8', though.
8108
8109 this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement
8110 // of how much we're waiting to get pushed to some underlying
8111 // socket or file.
8112
8113 this.length = 0; // a flag to see when we're in the middle of a write.
8114
8115 this.writing = false; // when true all writes will be buffered until .uncork() call
8116
8117 this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,
8118 // or on a later tick. We set this to true at first, because any
8119 // actions that shouldn't happen until "later" should generally also
8120 // not happen before the first write call.
8121
8122 this.sync = true; // a flag to know if we're processing previously buffered items, which
8123 // may call the _write() callback in the same tick, so that we don't
8124 // end up in an overlapped onwrite situation.
8125
8126 this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)
8127
8128 this.onwrite = function (er) {
8129 onwrite(stream, er);
8130 }; // the callback that the user supplies to write(chunk,encoding,cb)
8131
8132
8133 this.writecb = null; // the amount that is being written when _write is called.
8134
8135 this.writelen = 0;
8136 this.bufferedRequest = null;
8137 this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
8138 // this must be 0 before 'finish' can be emitted
8139
8140 this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
8141 // This is relevant for synchronous Transform streams
8142
8143 this.prefinished = false; // True if the error was already emitted and should not be thrown again
8144
8145 this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.
8146
8147 this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')
8148
8149 this.autoDestroy = !!options.autoDestroy; // count buffered requests
8150
8151 this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always
8152 // one allocated and free to use, and we maintain at most two
8153
8154 this.corkedRequestsFree = new CorkedRequest(this);
8155}
8156
8157WritableState.prototype.getBuffer = function getBuffer() {
8158 var current = this.bufferedRequest;
8159 var out = [];
8160
8161 while (current) {
8162 out.push(current);
8163 current = current.next;
8164 }
8165
8166 return out;
8167};
8168
8169(function () {
8170 try {
8171 Object.defineProperty(WritableState.prototype, 'buffer', {
8172 get: internalUtil.deprecate(function writableStateBufferGetter() {
8173 return this.getBuffer();
8174 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
8175 });
8176 } catch (_) {}
8177})(); // Test _writableState for inheritance to account for Duplex streams,
8178// whose prototype chain only points to Readable.
8179
8180
8181var realHasInstance;
8182
8183if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
8184 realHasInstance = Function.prototype[Symbol.hasInstance];
8185 Object.defineProperty(Writable, Symbol.hasInstance, {
8186 value: function value(object) {
8187 if (realHasInstance.call(this, object)) return true;
8188 if (this !== Writable) return false;
8189 return object && object._writableState instanceof WritableState;
8190 }
8191 });
8192} else {
8193 realHasInstance = function realHasInstance(object) {
8194 return object instanceof this;
8195 };
8196}
8197
8198function Writable(options) {
8199 Duplex = Duplex || _dereq_(44); // Writable ctor is applied to Duplexes, too.
8200 // `realHasInstance` is necessary because using plain `instanceof`
8201 // would return false, as no `_writableState` property is attached.
8202 // Trying to use the custom `instanceof` for Writable here will also break the
8203 // Node.js LazyTransform implementation, which has a non-trivial getter for
8204 // `_writableState` that would lead to infinite recursion.
8205 // Checking for a Stream.Duplex instance is faster here instead of inside
8206 // the WritableState constructor, at least with V8 6.5
8207
8208 var isDuplex = this instanceof Duplex;
8209 if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
8210 this._writableState = new WritableState(options, this, isDuplex); // legacy.
8211
8212 this.writable = true;
8213
8214 if (options) {
8215 if (typeof options.write === 'function') this._write = options.write;
8216 if (typeof options.writev === 'function') this._writev = options.writev;
8217 if (typeof options.destroy === 'function') this._destroy = options.destroy;
8218 if (typeof options.final === 'function') this._final = options.final;
8219 }
8220
8221 Stream.call(this);
8222} // Otherwise people can pipe Writable streams, which is just wrong.
8223
8224
8225Writable.prototype.pipe = function () {
8226 errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
8227};
8228
8229function writeAfterEnd(stream, cb) {
8230 var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
8231
8232 errorOrDestroy(stream, er);
8233 process.nextTick(cb, er);
8234} // Checks that a user-supplied chunk is valid, especially for the particular
8235// mode the stream is in. Currently this means that `null` is never accepted
8236// and undefined/non-string values are only allowed in object mode.
8237
8238
8239function validChunk(stream, state, chunk, cb) {
8240 var er;
8241
8242 if (chunk === null) {
8243 er = new ERR_STREAM_NULL_VALUES();
8244 } else if (typeof chunk !== 'string' && !state.objectMode) {
8245 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
8246 }
8247
8248 if (er) {
8249 errorOrDestroy(stream, er);
8250 process.nextTick(cb, er);
8251 return false;
8252 }
8253
8254 return true;
8255}
8256
8257Writable.prototype.write = function (chunk, encoding, cb) {
8258 var state = this._writableState;
8259 var ret = false;
8260
8261 var isBuf = !state.objectMode && _isUint8Array(chunk);
8262
8263 if (isBuf && !Buffer.isBuffer(chunk)) {
8264 chunk = _uint8ArrayToBuffer(chunk);
8265 }
8266
8267 if (typeof encoding === 'function') {
8268 cb = encoding;
8269 encoding = null;
8270 }
8271
8272 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
8273 if (typeof cb !== 'function') cb = nop;
8274 if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
8275 state.pendingcb++;
8276 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
8277 }
8278 return ret;
8279};
8280
8281Writable.prototype.cork = function () {
8282 this._writableState.corked++;
8283};
8284
8285Writable.prototype.uncork = function () {
8286 var state = this._writableState;
8287
8288 if (state.corked) {
8289 state.corked--;
8290 if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
8291 }
8292};
8293
8294Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
8295 // node::ParseEncoding() requires lower case.
8296 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
8297 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);
8298 this._writableState.defaultEncoding = encoding;
8299 return this;
8300};
8301
8302Object.defineProperty(Writable.prototype, 'writableBuffer', {
8303 // making it explicit this property is not enumerable
8304 // because otherwise some prototype manipulation in
8305 // userland will fail
8306 enumerable: false,
8307 get: function get() {
8308 return this._writableState && this._writableState.getBuffer();
8309 }
8310});
8311
8312function decodeChunk(state, chunk, encoding) {
8313 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
8314 chunk = Buffer.from(chunk, encoding);
8315 }
8316
8317 return chunk;
8318}
8319
8320Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
8321 // making it explicit this property is not enumerable
8322 // because otherwise some prototype manipulation in
8323 // userland will fail
8324 enumerable: false,
8325 get: function get() {
8326 return this._writableState.highWaterMark;
8327 }
8328}); // if we're already writing something, then just put this
8329// in the queue, and wait our turn. Otherwise, call _write
8330// If we return false, then we need a drain event, so set that flag.
8331
8332function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
8333 if (!isBuf) {
8334 var newChunk = decodeChunk(state, chunk, encoding);
8335
8336 if (chunk !== newChunk) {
8337 isBuf = true;
8338 encoding = 'buffer';
8339 chunk = newChunk;
8340 }
8341 }
8342
8343 var len = state.objectMode ? 1 : chunk.length;
8344 state.length += len;
8345 var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
8346
8347 if (!ret) state.needDrain = true;
8348
8349 if (state.writing || state.corked) {
8350 var last = state.lastBufferedRequest;
8351 state.lastBufferedRequest = {
8352 chunk: chunk,
8353 encoding: encoding,
8354 isBuf: isBuf,
8355 callback: cb,
8356 next: null
8357 };
8358
8359 if (last) {
8360 last.next = state.lastBufferedRequest;
8361 } else {
8362 state.bufferedRequest = state.lastBufferedRequest;
8363 }
8364
8365 state.bufferedRequestCount += 1;
8366 } else {
8367 doWrite(stream, state, false, len, chunk, encoding, cb);
8368 }
8369
8370 return ret;
8371}
8372
8373function doWrite(stream, state, writev, len, chunk, encoding, cb) {
8374 state.writelen = len;
8375 state.writecb = cb;
8376 state.writing = true;
8377 state.sync = true;
8378 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);
8379 state.sync = false;
8380}
8381
8382function onwriteError(stream, state, sync, er, cb) {
8383 --state.pendingcb;
8384
8385 if (sync) {
8386 // defer the callback if we are being called synchronously
8387 // to avoid piling up things on the stack
8388 process.nextTick(cb, er); // this can emit finish, and it will always happen
8389 // after error
8390
8391 process.nextTick(finishMaybe, stream, state);
8392 stream._writableState.errorEmitted = true;
8393 errorOrDestroy(stream, er);
8394 } else {
8395 // the caller expect this to happen before if
8396 // it is async
8397 cb(er);
8398 stream._writableState.errorEmitted = true;
8399 errorOrDestroy(stream, er); // this can emit finish, but finish must
8400 // always follow error
8401
8402 finishMaybe(stream, state);
8403 }
8404}
8405
8406function onwriteStateUpdate(state) {
8407 state.writing = false;
8408 state.writecb = null;
8409 state.length -= state.writelen;
8410 state.writelen = 0;
8411}
8412
8413function onwrite(stream, er) {
8414 var state = stream._writableState;
8415 var sync = state.sync;
8416 var cb = state.writecb;
8417 if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
8418 onwriteStateUpdate(state);
8419 if (er) onwriteError(stream, state, sync, er, cb);else {
8420 // Check if we're actually ready to finish, but don't emit yet
8421 var finished = needFinish(state) || stream.destroyed;
8422
8423 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
8424 clearBuffer(stream, state);
8425 }
8426
8427 if (sync) {
8428 process.nextTick(afterWrite, stream, state, finished, cb);
8429 } else {
8430 afterWrite(stream, state, finished, cb);
8431 }
8432 }
8433}
8434
8435function afterWrite(stream, state, finished, cb) {
8436 if (!finished) onwriteDrain(stream, state);
8437 state.pendingcb--;
8438 cb();
8439 finishMaybe(stream, state);
8440} // Must force callback to be called on nextTick, so that we don't
8441// emit 'drain' before the write() consumer gets the 'false' return
8442// value, and has a chance to attach a 'drain' listener.
8443
8444
8445function onwriteDrain(stream, state) {
8446 if (state.length === 0 && state.needDrain) {
8447 state.needDrain = false;
8448 stream.emit('drain');
8449 }
8450} // if there's something in the buffer waiting, then process it
8451
8452
8453function clearBuffer(stream, state) {
8454 state.bufferProcessing = true;
8455 var entry = state.bufferedRequest;
8456
8457 if (stream._writev && entry && entry.next) {
8458 // Fast case, write everything using _writev()
8459 var l = state.bufferedRequestCount;
8460 var buffer = new Array(l);
8461 var holder = state.corkedRequestsFree;
8462 holder.entry = entry;
8463 var count = 0;
8464 var allBuffers = true;
8465
8466 while (entry) {
8467 buffer[count] = entry;
8468 if (!entry.isBuf) allBuffers = false;
8469 entry = entry.next;
8470 count += 1;
8471 }
8472
8473 buffer.allBuffers = allBuffers;
8474 doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
8475 // as the hot path ends with doWrite
8476
8477 state.pendingcb++;
8478 state.lastBufferedRequest = null;
8479
8480 if (holder.next) {
8481 state.corkedRequestsFree = holder.next;
8482 holder.next = null;
8483 } else {
8484 state.corkedRequestsFree = new CorkedRequest(state);
8485 }
8486
8487 state.bufferedRequestCount = 0;
8488 } else {
8489 // Slow case, write chunks one-by-one
8490 while (entry) {
8491 var chunk = entry.chunk;
8492 var encoding = entry.encoding;
8493 var cb = entry.callback;
8494 var len = state.objectMode ? 1 : chunk.length;
8495 doWrite(stream, state, false, len, chunk, encoding, cb);
8496 entry = entry.next;
8497 state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then
8498 // it means that we need to wait until it does.
8499 // also, that means that the chunk and cb are currently
8500 // being processed, so move the buffer counter past them.
8501
8502 if (state.writing) {
8503 break;
8504 }
8505 }
8506
8507 if (entry === null) state.lastBufferedRequest = null;
8508 }
8509
8510 state.bufferedRequest = entry;
8511 state.bufferProcessing = false;
8512}
8513
8514Writable.prototype._write = function (chunk, encoding, cb) {
8515 cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
8516};
8517
8518Writable.prototype._writev = null;
8519
8520Writable.prototype.end = function (chunk, encoding, cb) {
8521 var state = this._writableState;
8522
8523 if (typeof chunk === 'function') {
8524 cb = chunk;
8525 chunk = null;
8526 encoding = null;
8527 } else if (typeof encoding === 'function') {
8528 cb = encoding;
8529 encoding = null;
8530 }
8531
8532 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks
8533
8534 if (state.corked) {
8535 state.corked = 1;
8536 this.uncork();
8537 } // ignore unnecessary end() calls.
8538
8539
8540 if (!state.ending) endWritable(this, state, cb);
8541 return this;
8542};
8543
8544Object.defineProperty(Writable.prototype, 'writableLength', {
8545 // making it explicit this property is not enumerable
8546 // because otherwise some prototype manipulation in
8547 // userland will fail
8548 enumerable: false,
8549 get: function get() {
8550 return this._writableState.length;
8551 }
8552});
8553
8554function needFinish(state) {
8555 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
8556}
8557
8558function callFinal(stream, state) {
8559 stream._final(function (err) {
8560 state.pendingcb--;
8561
8562 if (err) {
8563 errorOrDestroy(stream, err);
8564 }
8565
8566 state.prefinished = true;
8567 stream.emit('prefinish');
8568 finishMaybe(stream, state);
8569 });
8570}
8571
8572function prefinish(stream, state) {
8573 if (!state.prefinished && !state.finalCalled) {
8574 if (typeof stream._final === 'function' && !state.destroyed) {
8575 state.pendingcb++;
8576 state.finalCalled = true;
8577 process.nextTick(callFinal, stream, state);
8578 } else {
8579 state.prefinished = true;
8580 stream.emit('prefinish');
8581 }
8582 }
8583}
8584
8585function finishMaybe(stream, state) {
8586 var need = needFinish(state);
8587
8588 if (need) {
8589 prefinish(stream, state);
8590
8591 if (state.pendingcb === 0) {
8592 state.finished = true;
8593 stream.emit('finish');
8594
8595 if (state.autoDestroy) {
8596 // In case of duplex streams we need a way to detect
8597 // if the readable side is ready for autoDestroy as well
8598 var rState = stream._readableState;
8599
8600 if (!rState || rState.autoDestroy && rState.endEmitted) {
8601 stream.destroy();
8602 }
8603 }
8604 }
8605 }
8606
8607 return need;
8608}
8609
8610function endWritable(stream, state, cb) {
8611 state.ending = true;
8612 finishMaybe(stream, state);
8613
8614 if (cb) {
8615 if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
8616 }
8617
8618 state.ended = true;
8619 stream.writable = false;
8620}
8621
8622function onCorkedFinish(corkReq, state, err) {
8623 var entry = corkReq.entry;
8624 corkReq.entry = null;
8625
8626 while (entry) {
8627 var cb = entry.callback;
8628 state.pendingcb--;
8629 cb(err);
8630 entry = entry.next;
8631 } // reuse the free corkReq.
8632
8633
8634 state.corkedRequestsFree.next = corkReq;
8635}
8636
8637Object.defineProperty(Writable.prototype, 'destroyed', {
8638 // making it explicit this property is not enumerable
8639 // because otherwise some prototype manipulation in
8640 // userland will fail
8641 enumerable: false,
8642 get: function get() {
8643 if (this._writableState === undefined) {
8644 return false;
8645 }
8646
8647 return this._writableState.destroyed;
8648 },
8649 set: function set(value) {
8650 // we ignore the value if the stream
8651 // has not been initialized yet
8652 if (!this._writableState) {
8653 return;
8654 } // backward compatibility, the user is explicitly
8655 // managing destroyed
8656
8657
8658 this._writableState.destroyed = value;
8659 }
8660});
8661Writable.prototype.destroy = destroyImpl.destroy;
8662Writable.prototype._undestroy = destroyImpl.undestroy;
8663
8664Writable.prototype._destroy = function (err, cb) {
8665 cb(err);
8666};
8667}).call(this)}).call(this,_dereq_(73),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
8668},{"121":121,"13":13,"37":37,"43":43,"44":44,"51":51,"55":55,"56":56,"73":73}],49:[function(_dereq_,module,exports){
8669(function (process){(function (){
8670'use strict';
8671
8672var _Object$setPrototypeO;
8673
8674function _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; }
8675
8676var finished = _dereq_(52);
8677
8678var kLastResolve = Symbol('lastResolve');
8679var kLastReject = Symbol('lastReject');
8680var kError = Symbol('error');
8681var kEnded = Symbol('ended');
8682var kLastPromise = Symbol('lastPromise');
8683var kHandlePromise = Symbol('handlePromise');
8684var kStream = Symbol('stream');
8685
8686function createIterResult(value, done) {
8687 return {
8688 value: value,
8689 done: done
8690 };
8691}
8692
8693function readAndResolve(iter) {
8694 var resolve = iter[kLastResolve];
8695
8696 if (resolve !== null) {
8697 var data = iter[kStream].read(); // we defer if data is null
8698 // we can be expecting either 'end' or
8699 // 'error'
8700
8701 if (data !== null) {
8702 iter[kLastPromise] = null;
8703 iter[kLastResolve] = null;
8704 iter[kLastReject] = null;
8705 resolve(createIterResult(data, false));
8706 }
8707 }
8708}
8709
8710function onReadable(iter) {
8711 // we wait for the next tick, because it might
8712 // emit an error with process.nextTick
8713 process.nextTick(readAndResolve, iter);
8714}
8715
8716function wrapForNext(lastPromise, iter) {
8717 return function (resolve, reject) {
8718 lastPromise.then(function () {
8719 if (iter[kEnded]) {
8720 resolve(createIterResult(undefined, true));
8721 return;
8722 }
8723
8724 iter[kHandlePromise](resolve, reject);
8725 }, reject);
8726 };
8727}
8728
8729var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
8730var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
8731 get stream() {
8732 return this[kStream];
8733 },
8734
8735 next: function next() {
8736 var _this = this;
8737
8738 // if we have detected an error in the meanwhile
8739 // reject straight away
8740 var error = this[kError];
8741
8742 if (error !== null) {
8743 return Promise.reject(error);
8744 }
8745
8746 if (this[kEnded]) {
8747 return Promise.resolve(createIterResult(undefined, true));
8748 }
8749
8750 if (this[kStream].destroyed) {
8751 // We need to defer via nextTick because if .destroy(err) is
8752 // called, the error will be emitted via nextTick, and
8753 // we cannot guarantee that there is no error lingering around
8754 // waiting to be emitted.
8755 return new Promise(function (resolve, reject) {
8756 process.nextTick(function () {
8757 if (_this[kError]) {
8758 reject(_this[kError]);
8759 } else {
8760 resolve(createIterResult(undefined, true));
8761 }
8762 });
8763 });
8764 } // if we have multiple next() calls
8765 // we will wait for the previous Promise to finish
8766 // this logic is optimized to support for await loops,
8767 // where next() is only called once at a time
8768
8769
8770 var lastPromise = this[kLastPromise];
8771 var promise;
8772
8773 if (lastPromise) {
8774 promise = new Promise(wrapForNext(lastPromise, this));
8775 } else {
8776 // fast path needed to support multiple this.push()
8777 // without triggering the next() queue
8778 var data = this[kStream].read();
8779
8780 if (data !== null) {
8781 return Promise.resolve(createIterResult(data, false));
8782 }
8783
8784 promise = new Promise(this[kHandlePromise]);
8785 }
8786
8787 this[kLastPromise] = promise;
8788 return promise;
8789 }
8790}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
8791 return this;
8792}), _defineProperty(_Object$setPrototypeO, "return", function _return() {
8793 var _this2 = this;
8794
8795 // destroy(err, cb) is a private API
8796 // we can guarantee we have that here, because we control the
8797 // Readable class this is attached to
8798 return new Promise(function (resolve, reject) {
8799 _this2[kStream].destroy(null, function (err) {
8800 if (err) {
8801 reject(err);
8802 return;
8803 }
8804
8805 resolve(createIterResult(undefined, true));
8806 });
8807 });
8808}), _Object$setPrototypeO), AsyncIteratorPrototype);
8809
8810var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
8811 var _Object$create;
8812
8813 var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
8814 value: stream,
8815 writable: true
8816 }), _defineProperty(_Object$create, kLastResolve, {
8817 value: null,
8818 writable: true
8819 }), _defineProperty(_Object$create, kLastReject, {
8820 value: null,
8821 writable: true
8822 }), _defineProperty(_Object$create, kError, {
8823 value: null,
8824 writable: true
8825 }), _defineProperty(_Object$create, kEnded, {
8826 value: stream._readableState.endEmitted,
8827 writable: true
8828 }), _defineProperty(_Object$create, kHandlePromise, {
8829 value: function value(resolve, reject) {
8830 var data = iterator[kStream].read();
8831
8832 if (data) {
8833 iterator[kLastPromise] = null;
8834 iterator[kLastResolve] = null;
8835 iterator[kLastReject] = null;
8836 resolve(createIterResult(data, false));
8837 } else {
8838 iterator[kLastResolve] = resolve;
8839 iterator[kLastReject] = reject;
8840 }
8841 },
8842 writable: true
8843 }), _Object$create));
8844 iterator[kLastPromise] = null;
8845 finished(stream, function (err) {
8846 if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
8847 var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise
8848 // returned by next() and store the error
8849
8850 if (reject !== null) {
8851 iterator[kLastPromise] = null;
8852 iterator[kLastResolve] = null;
8853 iterator[kLastReject] = null;
8854 reject(err);
8855 }
8856
8857 iterator[kError] = err;
8858 return;
8859 }
8860
8861 var resolve = iterator[kLastResolve];
8862
8863 if (resolve !== null) {
8864 iterator[kLastPromise] = null;
8865 iterator[kLastResolve] = null;
8866 iterator[kLastReject] = null;
8867 resolve(createIterResult(undefined, true));
8868 }
8869
8870 iterator[kEnded] = true;
8871 });
8872 stream.on('readable', onReadable.bind(null, iterator));
8873 return iterator;
8874};
8875
8876module.exports = createReadableStreamAsyncIterator;
8877}).call(this)}).call(this,_dereq_(73))
8878},{"52":52,"73":73}],50:[function(_dereq_,module,exports){
8879'use strict';
8880
8881function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
8882
8883function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
8884
8885function _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; }
8886
8887function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
8888
8889function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
8890
8891function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
8892
8893var _require = _dereq_(13),
8894 Buffer = _require.Buffer;
8895
8896var _require2 = _dereq_(11),
8897 inspect = _require2.inspect;
8898
8899var custom = inspect && inspect.custom || 'inspect';
8900
8901function copyBuffer(src, target, offset) {
8902 Buffer.prototype.copy.call(src, target, offset);
8903}
8904
8905module.exports =
8906/*#__PURE__*/
8907function () {
8908 function BufferList() {
8909 _classCallCheck(this, BufferList);
8910
8911 this.head = null;
8912 this.tail = null;
8913 this.length = 0;
8914 }
8915
8916 _createClass(BufferList, [{
8917 key: "push",
8918 value: function push(v) {
8919 var entry = {
8920 data: v,
8921 next: null
8922 };
8923 if (this.length > 0) this.tail.next = entry;else this.head = entry;
8924 this.tail = entry;
8925 ++this.length;
8926 }
8927 }, {
8928 key: "unshift",
8929 value: function unshift(v) {
8930 var entry = {
8931 data: v,
8932 next: this.head
8933 };
8934 if (this.length === 0) this.tail = entry;
8935 this.head = entry;
8936 ++this.length;
8937 }
8938 }, {
8939 key: "shift",
8940 value: function shift() {
8941 if (this.length === 0) return;
8942 var ret = this.head.data;
8943 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
8944 --this.length;
8945 return ret;
8946 }
8947 }, {
8948 key: "clear",
8949 value: function clear() {
8950 this.head = this.tail = null;
8951 this.length = 0;
8952 }
8953 }, {
8954 key: "join",
8955 value: function join(s) {
8956 if (this.length === 0) return '';
8957 var p = this.head;
8958 var ret = '' + p.data;
8959
8960 while (p = p.next) {
8961 ret += s + p.data;
8962 }
8963
8964 return ret;
8965 }
8966 }, {
8967 key: "concat",
8968 value: function concat(n) {
8969 if (this.length === 0) return Buffer.alloc(0);
8970 var ret = Buffer.allocUnsafe(n >>> 0);
8971 var p = this.head;
8972 var i = 0;
8973
8974 while (p) {
8975 copyBuffer(p.data, ret, i);
8976 i += p.data.length;
8977 p = p.next;
8978 }
8979
8980 return ret;
8981 } // Consumes a specified amount of bytes or characters from the buffered data.
8982
8983 }, {
8984 key: "consume",
8985 value: function consume(n, hasStrings) {
8986 var ret;
8987
8988 if (n < this.head.data.length) {
8989 // `slice` is the same for buffers and strings.
8990 ret = this.head.data.slice(0, n);
8991 this.head.data = this.head.data.slice(n);
8992 } else if (n === this.head.data.length) {
8993 // First chunk is a perfect match.
8994 ret = this.shift();
8995 } else {
8996 // Result spans more than one buffer.
8997 ret = hasStrings ? this._getString(n) : this._getBuffer(n);
8998 }
8999
9000 return ret;
9001 }
9002 }, {
9003 key: "first",
9004 value: function first() {
9005 return this.head.data;
9006 } // Consumes a specified amount of characters from the buffered data.
9007
9008 }, {
9009 key: "_getString",
9010 value: function _getString(n) {
9011 var p = this.head;
9012 var c = 1;
9013 var ret = p.data;
9014 n -= ret.length;
9015
9016 while (p = p.next) {
9017 var str = p.data;
9018 var nb = n > str.length ? str.length : n;
9019 if (nb === str.length) ret += str;else ret += str.slice(0, n);
9020 n -= nb;
9021
9022 if (n === 0) {
9023 if (nb === str.length) {
9024 ++c;
9025 if (p.next) this.head = p.next;else this.head = this.tail = null;
9026 } else {
9027 this.head = p;
9028 p.data = str.slice(nb);
9029 }
9030
9031 break;
9032 }
9033
9034 ++c;
9035 }
9036
9037 this.length -= c;
9038 return ret;
9039 } // Consumes a specified amount of bytes from the buffered data.
9040
9041 }, {
9042 key: "_getBuffer",
9043 value: function _getBuffer(n) {
9044 var ret = Buffer.allocUnsafe(n);
9045 var p = this.head;
9046 var c = 1;
9047 p.data.copy(ret);
9048 n -= p.data.length;
9049
9050 while (p = p.next) {
9051 var buf = p.data;
9052 var nb = n > buf.length ? buf.length : n;
9053 buf.copy(ret, ret.length - n, 0, nb);
9054 n -= nb;
9055
9056 if (n === 0) {
9057 if (nb === buf.length) {
9058 ++c;
9059 if (p.next) this.head = p.next;else this.head = this.tail = null;
9060 } else {
9061 this.head = p;
9062 p.data = buf.slice(nb);
9063 }
9064
9065 break;
9066 }
9067
9068 ++c;
9069 }
9070
9071 this.length -= c;
9072 return ret;
9073 } // Make sure the linked list only shows the minimal necessary information.
9074
9075 }, {
9076 key: custom,
9077 value: function value(_, options) {
9078 return inspect(this, _objectSpread({}, options, {
9079 // Only inspect one level.
9080 depth: 0,
9081 // It should not recurse.
9082 customInspect: false
9083 }));
9084 }
9085 }]);
9086
9087 return BufferList;
9088}();
9089},{"11":11,"13":13}],51:[function(_dereq_,module,exports){
9090(function (process){(function (){
9091'use strict'; // undocumented cb() API, needed for core, not for public API
9092
9093function destroy(err, cb) {
9094 var _this = this;
9095
9096 var readableDestroyed = this._readableState && this._readableState.destroyed;
9097 var writableDestroyed = this._writableState && this._writableState.destroyed;
9098
9099 if (readableDestroyed || writableDestroyed) {
9100 if (cb) {
9101 cb(err);
9102 } else if (err) {
9103 if (!this._writableState) {
9104 process.nextTick(emitErrorNT, this, err);
9105 } else if (!this._writableState.errorEmitted) {
9106 this._writableState.errorEmitted = true;
9107 process.nextTick(emitErrorNT, this, err);
9108 }
9109 }
9110
9111 return this;
9112 } // we set destroyed to true before firing error callbacks in order
9113 // to make it re-entrance safe in case destroy() is called within callbacks
9114
9115
9116 if (this._readableState) {
9117 this._readableState.destroyed = true;
9118 } // if this is a duplex stream mark the writable part as destroyed as well
9119
9120
9121 if (this._writableState) {
9122 this._writableState.destroyed = true;
9123 }
9124
9125 this._destroy(err || null, function (err) {
9126 if (!cb && err) {
9127 if (!_this._writableState) {
9128 process.nextTick(emitErrorAndCloseNT, _this, err);
9129 } else if (!_this._writableState.errorEmitted) {
9130 _this._writableState.errorEmitted = true;
9131 process.nextTick(emitErrorAndCloseNT, _this, err);
9132 } else {
9133 process.nextTick(emitCloseNT, _this);
9134 }
9135 } else if (cb) {
9136 process.nextTick(emitCloseNT, _this);
9137 cb(err);
9138 } else {
9139 process.nextTick(emitCloseNT, _this);
9140 }
9141 });
9142
9143 return this;
9144}
9145
9146function emitErrorAndCloseNT(self, err) {
9147 emitErrorNT(self, err);
9148 emitCloseNT(self);
9149}
9150
9151function emitCloseNT(self) {
9152 if (self._writableState && !self._writableState.emitClose) return;
9153 if (self._readableState && !self._readableState.emitClose) return;
9154 self.emit('close');
9155}
9156
9157function undestroy() {
9158 if (this._readableState) {
9159 this._readableState.destroyed = false;
9160 this._readableState.reading = false;
9161 this._readableState.ended = false;
9162 this._readableState.endEmitted = false;
9163 }
9164
9165 if (this._writableState) {
9166 this._writableState.destroyed = false;
9167 this._writableState.ended = false;
9168 this._writableState.ending = false;
9169 this._writableState.finalCalled = false;
9170 this._writableState.prefinished = false;
9171 this._writableState.finished = false;
9172 this._writableState.errorEmitted = false;
9173 }
9174}
9175
9176function emitErrorNT(self, err) {
9177 self.emit('error', err);
9178}
9179
9180function errorOrDestroy(stream, err) {
9181 // We have tests that rely on errors being emitted
9182 // in the same tick, so changing this is semver major.
9183 // For now when you opt-in to autoDestroy we allow
9184 // the error to be emitted nextTick. In a future
9185 // semver major update we should change the default to this.
9186 var rState = stream._readableState;
9187 var wState = stream._writableState;
9188 if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
9189}
9190
9191module.exports = {
9192 destroy: destroy,
9193 undestroy: undestroy,
9194 errorOrDestroy: errorOrDestroy
9195};
9196}).call(this)}).call(this,_dereq_(73))
9197},{"73":73}],52:[function(_dereq_,module,exports){
9198// Ported from https://github.com/mafintosh/end-of-stream with
9199// permission from the author, Mathias Buus (@mafintosh).
9200'use strict';
9201
9202var ERR_STREAM_PREMATURE_CLOSE = _dereq_(43).codes.ERR_STREAM_PREMATURE_CLOSE;
9203
9204function once(callback) {
9205 var called = false;
9206 return function () {
9207 if (called) return;
9208 called = true;
9209
9210 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
9211 args[_key] = arguments[_key];
9212 }
9213
9214 callback.apply(this, args);
9215 };
9216}
9217
9218function noop() {}
9219
9220function isRequest(stream) {
9221 return stream.setHeader && typeof stream.abort === 'function';
9222}
9223
9224function eos(stream, opts, callback) {
9225 if (typeof opts === 'function') return eos(stream, null, opts);
9226 if (!opts) opts = {};
9227 callback = once(callback || noop);
9228 var readable = opts.readable || opts.readable !== false && stream.readable;
9229 var writable = opts.writable || opts.writable !== false && stream.writable;
9230
9231 var onlegacyfinish = function onlegacyfinish() {
9232 if (!stream.writable) onfinish();
9233 };
9234
9235 var writableEnded = stream._writableState && stream._writableState.finished;
9236
9237 var onfinish = function onfinish() {
9238 writable = false;
9239 writableEnded = true;
9240 if (!readable) callback.call(stream);
9241 };
9242
9243 var readableEnded = stream._readableState && stream._readableState.endEmitted;
9244
9245 var onend = function onend() {
9246 readable = false;
9247 readableEnded = true;
9248 if (!writable) callback.call(stream);
9249 };
9250
9251 var onerror = function onerror(err) {
9252 callback.call(stream, err);
9253 };
9254
9255 var onclose = function onclose() {
9256 var err;
9257
9258 if (readable && !readableEnded) {
9259 if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
9260 return callback.call(stream, err);
9261 }
9262
9263 if (writable && !writableEnded) {
9264 if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
9265 return callback.call(stream, err);
9266 }
9267 };
9268
9269 var onrequest = function onrequest() {
9270 stream.req.on('finish', onfinish);
9271 };
9272
9273 if (isRequest(stream)) {
9274 stream.on('complete', onfinish);
9275 stream.on('abort', onclose);
9276 if (stream.req) onrequest();else stream.on('request', onrequest);
9277 } else if (writable && !stream._writableState) {
9278 // legacy streams
9279 stream.on('end', onlegacyfinish);
9280 stream.on('close', onlegacyfinish);
9281 }
9282
9283 stream.on('end', onend);
9284 stream.on('finish', onfinish);
9285 if (opts.error !== false) stream.on('error', onerror);
9286 stream.on('close', onclose);
9287 return function () {
9288 stream.removeListener('complete', onfinish);
9289 stream.removeListener('abort', onclose);
9290 stream.removeListener('request', onrequest);
9291 if (stream.req) stream.req.removeListener('finish', onfinish);
9292 stream.removeListener('end', onlegacyfinish);
9293 stream.removeListener('close', onlegacyfinish);
9294 stream.removeListener('finish', onfinish);
9295 stream.removeListener('end', onend);
9296 stream.removeListener('error', onerror);
9297 stream.removeListener('close', onclose);
9298 };
9299}
9300
9301module.exports = eos;
9302},{"43":43}],53:[function(_dereq_,module,exports){
9303module.exports = function () {
9304 throw new Error('Readable.from is not available in the browser')
9305};
9306
9307},{}],54:[function(_dereq_,module,exports){
9308// Ported from https://github.com/mafintosh/pump with
9309// permission from the author, Mathias Buus (@mafintosh).
9310'use strict';
9311
9312var eos;
9313
9314function once(callback) {
9315 var called = false;
9316 return function () {
9317 if (called) return;
9318 called = true;
9319 callback.apply(void 0, arguments);
9320 };
9321}
9322
9323var _require$codes = _dereq_(43).codes,
9324 ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
9325 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
9326
9327function noop(err) {
9328 // Rethrow the error if it exists to avoid swallowing it
9329 if (err) throw err;
9330}
9331
9332function isRequest(stream) {
9333 return stream.setHeader && typeof stream.abort === 'function';
9334}
9335
9336function destroyer(stream, reading, writing, callback) {
9337 callback = once(callback);
9338 var closed = false;
9339 stream.on('close', function () {
9340 closed = true;
9341 });
9342 if (eos === undefined) eos = _dereq_(52);
9343 eos(stream, {
9344 readable: reading,
9345 writable: writing
9346 }, function (err) {
9347 if (err) return callback(err);
9348 closed = true;
9349 callback();
9350 });
9351 var destroyed = false;
9352 return function (err) {
9353 if (closed) return;
9354 if (destroyed) return;
9355 destroyed = true; // request.destroy just do .end - .abort is what we want
9356
9357 if (isRequest(stream)) return stream.abort();
9358 if (typeof stream.destroy === 'function') return stream.destroy();
9359 callback(err || new ERR_STREAM_DESTROYED('pipe'));
9360 };
9361}
9362
9363function call(fn) {
9364 fn();
9365}
9366
9367function pipe(from, to) {
9368 return from.pipe(to);
9369}
9370
9371function popCallback(streams) {
9372 if (!streams.length) return noop;
9373 if (typeof streams[streams.length - 1] !== 'function') return noop;
9374 return streams.pop();
9375}
9376
9377function pipeline() {
9378 for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
9379 streams[_key] = arguments[_key];
9380 }
9381
9382 var callback = popCallback(streams);
9383 if (Array.isArray(streams[0])) streams = streams[0];
9384
9385 if (streams.length < 2) {
9386 throw new ERR_MISSING_ARGS('streams');
9387 }
9388
9389 var error;
9390 var destroys = streams.map(function (stream, i) {
9391 var reading = i < streams.length - 1;
9392 var writing = i > 0;
9393 return destroyer(stream, reading, writing, function (err) {
9394 if (!error) error = err;
9395 if (err) destroys.forEach(call);
9396 if (reading) return;
9397 destroys.forEach(call);
9398 callback(error);
9399 });
9400 });
9401 return streams.reduce(pipe);
9402}
9403
9404module.exports = pipeline;
9405},{"43":43,"52":52}],55:[function(_dereq_,module,exports){
9406'use strict';
9407
9408var ERR_INVALID_OPT_VALUE = _dereq_(43).codes.ERR_INVALID_OPT_VALUE;
9409
9410function highWaterMarkFrom(options, isDuplex, duplexKey) {
9411 return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
9412}
9413
9414function getHighWaterMark(state, options, duplexKey, isDuplex) {
9415 var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
9416
9417 if (hwm != null) {
9418 if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
9419 var name = isDuplex ? duplexKey : 'highWaterMark';
9420 throw new ERR_INVALID_OPT_VALUE(name, hwm);
9421 }
9422
9423 return Math.floor(hwm);
9424 } // Default value
9425
9426
9427 return state.objectMode ? 16 : 16 * 1024;
9428}
9429
9430module.exports = {
9431 getHighWaterMark: getHighWaterMark
9432};
9433},{"43":43}],56:[function(_dereq_,module,exports){
9434module.exports = _dereq_(26).EventEmitter;
9435
9436},{"26":26}],57:[function(_dereq_,module,exports){
9437exports = module.exports = _dereq_(46);
9438exports.Stream = exports;
9439exports.Readable = exports;
9440exports.Writable = _dereq_(48);
9441exports.Duplex = _dereq_(44);
9442exports.Transform = _dereq_(47);
9443exports.PassThrough = _dereq_(45);
9444exports.finished = _dereq_(52);
9445exports.pipeline = _dereq_(54);
9446
9447},{"44":44,"45":45,"46":46,"47":47,"48":48,"52":52,"54":54}],58:[function(_dereq_,module,exports){
9448'use strict'
9449
9450// For (old) browser support
9451var xtend = _dereq_(141)
9452var assign = _dereq_(142)
9453
9454module.exports = function supports () {
9455 var manifest = xtend.apply(null, arguments)
9456
9457 return assign(manifest, {
9458 // Features of abstract-leveldown
9459 bufferKeys: manifest.bufferKeys || false,
9460 snapshots: manifest.snapshots || false,
9461 permanence: manifest.permanence || false,
9462 seek: manifest.seek || false,
9463 clear: manifest.clear || false,
9464
9465 // Features of abstract-leveldown that levelup doesn't have
9466 status: manifest.status || false,
9467
9468 // Features of disk-based implementations
9469 createIfMissing: manifest.createIfMissing || false,
9470 errorIfExists: manifest.errorIfExists || false,
9471
9472 // Features of level(up) that abstract-leveldown doesn't have yet
9473 deferredOpen: manifest.deferredOpen || false,
9474 openCallback: manifest.openCallback || false,
9475 promises: manifest.promises || false,
9476 streams: manifest.streams || false,
9477 encodings: manifest.encodings || false,
9478
9479 // Methods that are not part of abstract-leveldown or levelup
9480 additionalMethods: xtend(manifest.additionalMethods)
9481 })
9482}
9483
9484},{"141":141,"142":142}],59:[function(_dereq_,module,exports){
9485var WriteError = _dereq_(41).WriteError
9486var promisify = _dereq_(62)
9487var getCallback = _dereq_(60).getCallback
9488var getOptions = _dereq_(60).getOptions
9489
9490function Batch (levelup) {
9491 // TODO (next major): remove this._levelup alias
9492 this.db = this._levelup = levelup
9493 this.batch = levelup.db.batch()
9494 this.ops = []
9495 this.length = 0
9496}
9497
9498Batch.prototype.put = function (key, value) {
9499 try {
9500 this.batch.put(key, value)
9501 } catch (e) {
9502 throw new WriteError(e)
9503 }
9504
9505 this.ops.push({ type: 'put', key: key, value: value })
9506 this.length++
9507
9508 return this
9509}
9510
9511Batch.prototype.del = function (key) {
9512 try {
9513 this.batch.del(key)
9514 } catch (err) {
9515 throw new WriteError(err)
9516 }
9517
9518 this.ops.push({ type: 'del', key: key })
9519 this.length++
9520
9521 return this
9522}
9523
9524Batch.prototype.clear = function () {
9525 try {
9526 this.batch.clear()
9527 } catch (err) {
9528 throw new WriteError(err)
9529 }
9530
9531 this.ops = []
9532 this.length = 0
9533
9534 return this
9535}
9536
9537Batch.prototype.write = function (options, callback) {
9538 var levelup = this._levelup
9539 var ops = this.ops
9540 var promise
9541
9542 callback = getCallback(options, callback)
9543
9544 if (!callback) {
9545 callback = promisify()
9546 promise = callback.promise
9547 }
9548
9549 options = getOptions(options)
9550
9551 try {
9552 this.batch.write(options, function (err) {
9553 if (err) { return callback(new WriteError(err)) }
9554 levelup.emit('batch', ops)
9555 callback()
9556 })
9557 } catch (err) {
9558 throw new WriteError(err)
9559 }
9560
9561 return promise
9562}
9563
9564module.exports = Batch
9565
9566},{"41":41,"60":60,"62":62}],60:[function(_dereq_,module,exports){
9567exports.getCallback = function (options, callback) {
9568 return typeof options === 'function' ? options : callback
9569}
9570
9571exports.getOptions = function (options) {
9572 return typeof options === 'object' && options !== null ? options : {}
9573}
9574
9575},{}],61:[function(_dereq_,module,exports){
9576(function (process){(function (){
9577var EventEmitter = _dereq_(26).EventEmitter
9578var inherits = _dereq_(124).inherits
9579var extend = _dereq_(141)
9580var DeferredLevelDOWN = _dereq_(17)
9581var IteratorStream = _dereq_(42)
9582var Batch = _dereq_(59)
9583var errors = _dereq_(41)
9584var supports = _dereq_(58)
9585var assert = _dereq_(6)
9586var promisify = _dereq_(62)
9587var getCallback = _dereq_(60).getCallback
9588var getOptions = _dereq_(60).getOptions
9589
9590var WriteError = errors.WriteError
9591var ReadError = errors.ReadError
9592var NotFoundError = errors.NotFoundError
9593var OpenError = errors.OpenError
9594var InitializationError = errors.InitializationError
9595
9596// Possible AbstractLevelDOWN#status values:
9597// - 'new' - newly created, not opened or closed
9598// - 'opening' - waiting for the database to be opened, post open()
9599// - 'open' - successfully opened the database, available for use
9600// - 'closing' - waiting for the database to be closed, post close()
9601// - 'closed' - database has been successfully closed, should not be
9602// used except for another open() operation
9603
9604function LevelUP (db, options, callback) {
9605 if (!(this instanceof LevelUP)) {
9606 return new LevelUP(db, options, callback)
9607 }
9608
9609 var error
9610 var self = this
9611
9612 EventEmitter.call(this)
9613 this.setMaxListeners(Infinity)
9614
9615 if (typeof options === 'function') {
9616 callback = options
9617 options = {}
9618 }
9619
9620 options = options || {}
9621
9622 if (!db || typeof db !== 'object') {
9623 error = new InitializationError('First argument must be an abstract-leveldown compliant store')
9624 if (typeof callback === 'function') {
9625 return process.nextTick(callback, error)
9626 }
9627 throw error
9628 }
9629
9630 assert.strictEqual(typeof db.status, 'string', '.status required, old abstract-leveldown')
9631
9632 this.options = getOptions(options)
9633 this._db = db
9634 this.db = new DeferredLevelDOWN(db)
9635 this.open(callback || function (err) {
9636 if (err) self.emit('error', err)
9637 })
9638
9639 // Create manifest based on deferred-leveldown's
9640 this.supports = supports(this.db.supports, {
9641 status: false,
9642 deferredOpen: true,
9643 openCallback: true,
9644 promises: true,
9645 streams: true
9646 })
9647
9648 // Experimental: enrich levelup interface
9649 Object.keys(this.supports.additionalMethods).forEach(function (method) {
9650 if (this[method] != null) return
9651
9652 // Don't do this.db[method].bind() because this.db is dynamic.
9653 this[method] = function () {
9654 return this.db[method].apply(this.db, arguments)
9655 }
9656 }, this)
9657}
9658
9659LevelUP.prototype.emit = EventEmitter.prototype.emit
9660LevelUP.prototype.once = EventEmitter.prototype.once
9661inherits(LevelUP, EventEmitter)
9662
9663LevelUP.prototype.open = function (opts, callback) {
9664 var self = this
9665 var promise
9666
9667 if (typeof opts === 'function') {
9668 callback = opts
9669 opts = null
9670 }
9671
9672 if (!callback) {
9673 callback = promisify()
9674 promise = callback.promise
9675 }
9676
9677 if (!opts) {
9678 opts = this.options
9679 }
9680
9681 if (this.isOpen()) {
9682 process.nextTick(callback, null, self)
9683 return promise
9684 }
9685
9686 if (this._isOpening()) {
9687 this.once('open', function () { callback(null, self) })
9688 return promise
9689 }
9690
9691 this.emit('opening')
9692
9693 this.db.open(opts, function (err) {
9694 if (err) {
9695 return callback(new OpenError(err))
9696 }
9697 self.db = self._db
9698 callback(null, self)
9699 self.emit('open')
9700 self.emit('ready')
9701 })
9702
9703 return promise
9704}
9705
9706LevelUP.prototype.close = function (callback) {
9707 var self = this
9708 var promise
9709
9710 if (!callback) {
9711 callback = promisify()
9712 promise = callback.promise
9713 }
9714
9715 if (this.isOpen()) {
9716 this.db.close(function () {
9717 self.emit('closed')
9718 callback.apply(null, arguments)
9719 })
9720 this.emit('closing')
9721 this.db = new DeferredLevelDOWN(this._db)
9722 } else if (this.isClosed()) {
9723 process.nextTick(callback)
9724 } else if (this.db.status === 'closing') {
9725 this.once('closed', callback)
9726 } else if (this._isOpening()) {
9727 this.once('open', function () {
9728 self.close(callback)
9729 })
9730 }
9731
9732 return promise
9733}
9734
9735LevelUP.prototype.isOpen = function () {
9736 return this.db.status === 'open'
9737}
9738
9739LevelUP.prototype._isOpening = function () {
9740 return this.db.status === 'opening'
9741}
9742
9743LevelUP.prototype.isClosed = function () {
9744 return (/^clos|new/).test(this.db.status)
9745}
9746
9747LevelUP.prototype.get = function (key, options, callback) {
9748 var promise
9749
9750 callback = getCallback(options, callback)
9751
9752 if (!callback) {
9753 callback = promisify()
9754 promise = callback.promise
9755 }
9756
9757 if (maybeError(this, callback)) { return promise }
9758
9759 options = getOptions(options)
9760
9761 this.db.get(key, options, function (err, value) {
9762 if (err) {
9763 if ((/notfound/i).test(err) || err.notFound) {
9764 err = new NotFoundError('Key not found in database [' + key + ']', err)
9765 } else {
9766 err = new ReadError(err)
9767 }
9768 return callback(err)
9769 }
9770 callback(null, value)
9771 })
9772
9773 return promise
9774}
9775
9776LevelUP.prototype.put = function (key, value, options, callback) {
9777 var self = this
9778 var promise
9779
9780 callback = getCallback(options, callback)
9781
9782 if (!callback) {
9783 callback = promisify()
9784 promise = callback.promise
9785 }
9786
9787 if (maybeError(this, callback)) { return promise }
9788
9789 options = getOptions(options)
9790
9791 this.db.put(key, value, options, function (err) {
9792 if (err) {
9793 return callback(new WriteError(err))
9794 }
9795 self.emit('put', key, value)
9796 callback()
9797 })
9798
9799 return promise
9800}
9801
9802LevelUP.prototype.del = function (key, options, callback) {
9803 var self = this
9804 var promise
9805
9806 callback = getCallback(options, callback)
9807
9808 if (!callback) {
9809 callback = promisify()
9810 promise = callback.promise
9811 }
9812
9813 if (maybeError(this, callback)) { return promise }
9814
9815 options = getOptions(options)
9816
9817 this.db.del(key, options, function (err) {
9818 if (err) {
9819 return callback(new WriteError(err))
9820 }
9821 self.emit('del', key)
9822 callback()
9823 })
9824
9825 return promise
9826}
9827
9828LevelUP.prototype.batch = function (arr, options, callback) {
9829 if (!arguments.length) {
9830 return new Batch(this)
9831 }
9832
9833 var self = this
9834 var promise
9835
9836 if (typeof arr === 'function') callback = arr
9837 else callback = getCallback(options, callback)
9838
9839 if (!callback) {
9840 callback = promisify()
9841 promise = callback.promise
9842 }
9843
9844 if (maybeError(this, callback)) { return promise }
9845
9846 options = getOptions(options)
9847
9848 this.db.batch(arr, options, function (err) {
9849 if (err) {
9850 return callback(new WriteError(err))
9851 }
9852 self.emit('batch', arr)
9853 callback()
9854 })
9855
9856 return promise
9857}
9858
9859LevelUP.prototype.iterator = function (options) {
9860 return this.db.iterator(options)
9861}
9862
9863LevelUP.prototype.clear = function (options, callback) {
9864 var self = this
9865 var promise
9866
9867 callback = getCallback(options, callback)
9868 options = getOptions(options)
9869
9870 if (!callback) {
9871 callback = promisify()
9872 promise = callback.promise
9873 }
9874
9875 if (maybeError(this, callback)) {
9876 return promise
9877 }
9878
9879 this.db.clear(options, function (err) {
9880 if (err) {
9881 return callback(new WriteError(err))
9882 }
9883 self.emit('clear', options)
9884 callback()
9885 })
9886
9887 return promise
9888}
9889
9890LevelUP.prototype.readStream =
9891LevelUP.prototype.createReadStream = function (options) {
9892 options = extend({ keys: true, values: true }, options)
9893 if (typeof options.limit !== 'number') { options.limit = -1 }
9894 return new IteratorStream(this.db.iterator(options), options)
9895}
9896
9897LevelUP.prototype.keyStream =
9898LevelUP.prototype.createKeyStream = function (options) {
9899 return this.createReadStream(extend(options, { keys: true, values: false }))
9900}
9901
9902LevelUP.prototype.valueStream =
9903LevelUP.prototype.createValueStream = function (options) {
9904 return this.createReadStream(extend(options, { keys: false, values: true }))
9905}
9906
9907LevelUP.prototype.toString = function () {
9908 return 'LevelUP'
9909}
9910
9911LevelUP.prototype.type = 'levelup'
9912
9913function maybeError (db, callback) {
9914 if (!db._isOpening() && !db.isOpen()) {
9915 process.nextTick(callback, new ReadError('Database is not open'))
9916 return true
9917 }
9918}
9919
9920LevelUP.errors = errors
9921module.exports = LevelUP.default = LevelUP
9922
9923}).call(this)}).call(this,_dereq_(73))
9924},{"124":124,"141":141,"17":17,"26":26,"41":41,"42":42,"58":58,"59":59,"6":6,"60":60,"62":62,"73":73}],62:[function(_dereq_,module,exports){
9925function promisify () {
9926 var callback
9927 var promise = new Promise(function (resolve, reject) {
9928 callback = function callback (err, value) {
9929 if (err) reject(err)
9930 else resolve(value)
9931 }
9932 })
9933 callback.promise = promise
9934 return callback
9935}
9936
9937module.exports = promisify
9938
9939},{}],63:[function(_dereq_,module,exports){
9940(function (Buffer,process,global){(function (){
9941'use strict';
9942
9943var inherits = _dereq_(37);
9944var bufferFrom = _dereq_(68);
9945var AbstractLevelDOWN = _dereq_(3).AbstractLevelDOWN;
9946var AbstractIterator = _dereq_(3).AbstractIterator;
9947
9948var LocalStorage = _dereq_(65).LocalStorage;
9949var LocalStorageCore = _dereq_(64);
9950var utils = _dereq_(67);
9951
9952// see http://stackoverflow.com/a/15349865/680742
9953var nextTick = global.setImmediate || process.nextTick;
9954
9955function LDIterator(db, options) {
9956
9957 AbstractIterator.call(this, db);
9958
9959 this._reverse = !!options.reverse;
9960 this._endkey = options.end;
9961 this._startkey = options.start;
9962 this._gt = options.gt;
9963 this._gte = options.gte;
9964 this._lt = options.lt;
9965 this._lte = options.lte;
9966 this._exclusiveStart = options.exclusiveStart;
9967 this._keysOnly = options.values === false;
9968 this._limit = options.limit;
9969 this._count = 0;
9970
9971 this.onInitCompleteListeners = [];
9972}
9973
9974inherits(LDIterator, AbstractIterator);
9975
9976LDIterator.prototype._init = function (callback) {
9977 nextTick(function () {
9978 callback();
9979 });
9980};
9981
9982LDIterator.prototype._next = function (callback) {
9983 var self = this;
9984
9985 function onInitComplete() {
9986 if (self._pos === self._keys.length || self._pos < 0) { // done reading
9987 return callback();
9988 }
9989
9990 var key = self._keys[self._pos];
9991
9992 if (!!self._endkey && (self._reverse ? key < self._endkey : key > self._endkey)) {
9993 return callback();
9994 }
9995
9996 if (!!self._limit && self._limit > 0 && self._count++ >= self._limit) {
9997 return callback();
9998 }
9999
10000 if ((self._lt && key >= self._lt) ||
10001 (self._lte && key > self._lte) ||
10002 (self._gt && key <= self._gt) ||
10003 (self._gte && key < self._gte)) {
10004 return callback();
10005 }
10006
10007 self._pos += self._reverse ? -1 : 1;
10008 if (self._keysOnly) {
10009 return callback(null, key);
10010 }
10011
10012 self.db.container.getItem(key, function (err, value) {
10013 if (err) {
10014 if (err.message === 'NotFound') {
10015 return nextTick(function () {
10016 self._next(callback);
10017 });
10018 }
10019 return callback(err);
10020 }
10021 callback(null, key, value);
10022 });
10023 }
10024 if (!self.initStarted) {
10025 process.nextTick(function () {
10026 self.initStarted = true;
10027 self._init(function (err) {
10028 if (err) {
10029 return callback(err);
10030 }
10031 self.db.container.keys(function (err, keys) {
10032 if (err) {
10033 return callback(err);
10034 }
10035 self._keys = keys;
10036 if (self._startkey) {
10037 var index = utils.sortedIndexOf(self._keys, self._startkey);
10038 var startkey = (index >= self._keys.length || index < 0) ?
10039 undefined : self._keys[index];
10040 self._pos = index;
10041 if (self._reverse) {
10042 if (self._exclusiveStart || startkey !== self._startkey) {
10043 self._pos--;
10044 }
10045 } else if (self._exclusiveStart && startkey === self._startkey) {
10046 self._pos++;
10047 }
10048 } else {
10049 self._pos = self._reverse ? self._keys.length - 1 : 0;
10050 }
10051 onInitComplete();
10052
10053 self.initCompleted = true;
10054 var i = -1;
10055 while (++i < self.onInitCompleteListeners.length) {
10056 nextTick(self.onInitCompleteListeners[i]);
10057 }
10058 });
10059 });
10060 });
10061 } else if (!self.initCompleted) {
10062 self.onInitCompleteListeners.push(onInitComplete);
10063 } else {
10064 process.nextTick(onInitComplete);
10065 }
10066};
10067
10068function LD(location) {
10069 if (!(this instanceof LD)) {
10070 return new LD(location);
10071 }
10072 AbstractLevelDOWN.call(this, location);
10073 this.container = new LocalStorage(location);
10074}
10075
10076inherits(LD, AbstractLevelDOWN);
10077
10078LD.prototype._open = function (options, callback) {
10079 this.container.init(callback);
10080};
10081
10082LD.prototype._put = function (key, value, options, callback) {
10083
10084 var err = checkKeyValue(key, 'key');
10085
10086 if (err) {
10087 return nextTick(function () {
10088 callback(err);
10089 });
10090 }
10091
10092 err = checkKeyValue(value, 'value');
10093
10094 if (err) {
10095 return nextTick(function () {
10096 callback(err);
10097 });
10098 }
10099
10100 if (typeof value === 'object' && !Buffer.isBuffer(value) && value.buffer === undefined) {
10101 var obj = {};
10102 obj.storetype = "json";
10103 obj.data = value;
10104 value = JSON.stringify(obj);
10105 }
10106
10107 this.container.setItem(key, value, callback);
10108};
10109
10110LD.prototype._get = function (key, options, callback) {
10111
10112 var err = checkKeyValue(key, 'key');
10113
10114 if (err) {
10115 return nextTick(function () {
10116 callback(err);
10117 });
10118 }
10119
10120 if (!Buffer.isBuffer(key)) {
10121 key = String(key);
10122 }
10123 this.container.getItem(key, function (err, value) {
10124
10125 if (err) {
10126 return callback(err);
10127 }
10128
10129 if (options.asBuffer !== false && !Buffer.isBuffer(value)) {
10130 value = bufferFrom(value);
10131 }
10132
10133
10134 if (options.asBuffer === false) {
10135 if (value.indexOf("{\"storetype\":\"json\",\"data\"") > -1) {
10136 var res = JSON.parse(value);
10137 value = res.data;
10138 }
10139 }
10140 callback(null, value);
10141 });
10142};
10143
10144LD.prototype._del = function (key, options, callback) {
10145
10146 var err = checkKeyValue(key, 'key');
10147
10148 if (err) {
10149 return nextTick(function () {
10150 callback(err);
10151 });
10152 }
10153 if (!Buffer.isBuffer(key)) {
10154 key = String(key);
10155 }
10156
10157 this.container.removeItem(key, callback);
10158};
10159
10160LD.prototype._batch = function (array, options, callback) {
10161 var self = this;
10162 nextTick(function () {
10163 var err;
10164 var key;
10165 var value;
10166
10167 var numDone = 0;
10168 var overallErr;
10169 function checkDone() {
10170 if (++numDone === array.length) {
10171 callback(overallErr);
10172 }
10173 }
10174
10175 if (Array.isArray(array) && array.length) {
10176 for (var i = 0; i < array.length; i++) {
10177 var task = array[i];
10178 if (task) {
10179 key = Buffer.isBuffer(task.key) ? task.key : String(task.key);
10180 err = checkKeyValue(key, 'key');
10181 if (err) {
10182 overallErr = err;
10183 checkDone();
10184 } else if (task.type === 'del') {
10185 self._del(task.key, options, checkDone);
10186 } else if (task.type === 'put') {
10187 value = Buffer.isBuffer(task.value) ? task.value : String(task.value);
10188 err = checkKeyValue(value, 'value');
10189 if (err) {
10190 overallErr = err;
10191 checkDone();
10192 } else {
10193 self._put(key, value, options, checkDone);
10194 }
10195 }
10196 } else {
10197 checkDone();
10198 }
10199 }
10200 } else {
10201 callback();
10202 }
10203 });
10204};
10205
10206LD.prototype._iterator = function (options) {
10207 return new LDIterator(this, options);
10208};
10209
10210LD.destroy = function (name, callback) {
10211 LocalStorageCore.destroy(name, callback);
10212};
10213
10214function checkKeyValue(obj, type) {
10215 if (obj === null || obj === undefined) {
10216 return new Error(type + ' cannot be `null` or `undefined`');
10217 }
10218 if (obj === null || obj === undefined) {
10219 return new Error(type + ' cannot be `null` or `undefined`');
10220 }
10221
10222 if (type === 'key') {
10223
10224 if (obj instanceof Boolean) {
10225 return new Error(type + ' cannot be `null` or `undefined`');
10226 }
10227 if (obj === '') {
10228 return new Error(type + ' cannot be empty');
10229 }
10230 }
10231 if (obj.toString().indexOf("[object ArrayBuffer]") === 0) {
10232 if (obj.byteLength === 0 || obj.byteLength === undefined) {
10233 return new Error(type + ' cannot be an empty Buffer');
10234 }
10235 }
10236
10237 if (Buffer.isBuffer(obj)) {
10238 if (obj.length === 0) {
10239 return new Error(type + ' cannot be an empty Buffer');
10240 }
10241 } else if (String(obj) === '') {
10242 return new Error(type + ' cannot be an empty String');
10243 }
10244}
10245
10246module.exports = LD;
10247
10248}).call(this)}).call(this,{"isBuffer":_dereq_(38)},_dereq_(73),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10249},{"3":3,"37":37,"38":38,"64":64,"65":65,"67":67,"68":68,"73":73}],64:[function(_dereq_,module,exports){
10250(function (process,global){(function (){
10251'use strict';
10252
10253//
10254// Class that should contain everything necessary to interact
10255// with localStorage as a generic key-value store.
10256// The idea is that authors who want to create an AbstractKeyValueDOWN
10257// module (e.g. on lawnchair, S3, whatever) will only have to
10258// reimplement this file.
10259//
10260
10261// see http://stackoverflow.com/a/15349865/680742
10262var nextTick = global.setImmediate || process.nextTick;
10263
10264// We use humble-localstorage as a wrapper for localStorage because
10265// it falls back to an in-memory implementation in environments without
10266// localStorage, like Node or Safari private browsing.
10267var storage = _dereq_(29);
10268
10269function callbackify(callback, fun) {
10270 var val;
10271 var err;
10272 try {
10273 val = fun();
10274 } catch (e) {
10275 err = e;
10276 }
10277 nextTick(function () {
10278 callback(err, val);
10279 });
10280}
10281
10282function createPrefix(dbname) {
10283 return dbname.replace(/!/g, '!!') + '!'; // escape bangs in dbname;
10284}
10285
10286function LocalStorageCore(dbname) {
10287 this._prefix = createPrefix(dbname);
10288}
10289
10290LocalStorageCore.prototype.getKeys = function (callback) {
10291 var self = this;
10292 callbackify(callback, function () {
10293 var keys = [];
10294 var prefixLen = self._prefix.length;
10295 var i = -1;
10296 var len = storage.length;
10297 while (++i < len) {
10298 var fullKey = storage.key(i);
10299 if (fullKey.substring(0, prefixLen) === self._prefix) {
10300 keys.push(fullKey.substring(prefixLen));
10301 }
10302 }
10303 keys.sort();
10304 return keys;
10305 });
10306};
10307
10308LocalStorageCore.prototype.put = function (key, value, callback) {
10309 var self = this;
10310 callbackify(callback, function () {
10311 storage.setItem(self._prefix + key, value);
10312 });
10313};
10314
10315LocalStorageCore.prototype.get = function (key, callback) {
10316 var self = this;
10317 callbackify(callback, function () {
10318 return storage.getItem(self._prefix + key);
10319 });
10320};
10321
10322LocalStorageCore.prototype.remove = function (key, callback) {
10323 var self = this;
10324 callbackify(callback, function () {
10325 storage.removeItem(self._prefix + key);
10326 });
10327};
10328
10329LocalStorageCore.destroy = function (dbname, callback) {
10330 var prefix = createPrefix(dbname);
10331 callbackify(callback, function () {
10332 var keysToDelete = [];
10333 var i = -1;
10334 var len = storage.length;
10335 while (++i < len) {
10336 var key = storage.key(i);
10337 if (key.substring(0, prefix.length) === prefix) {
10338 keysToDelete.push(key);
10339 }
10340 }
10341 keysToDelete.forEach(function (key) {
10342 storage.removeItem(key);
10343 });
10344 });
10345};
10346
10347module.exports = LocalStorageCore;
10348}).call(this)}).call(this,_dereq_(73),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10349},{"29":29,"73":73}],65:[function(_dereq_,module,exports){
10350(function (Buffer){(function (){
10351'use strict';
10352
10353// ArrayBuffer/Uint8Array are old formats that date back to before we
10354// had a proper browserified buffer type. they may be removed later
10355var arrayBuffPrefix = 'ArrayBuffer:';
10356var arrayBuffRegex = new RegExp('^' + arrayBuffPrefix);
10357var uintPrefix = 'Uint8Array:';
10358var uintRegex = new RegExp('^' + uintPrefix);
10359
10360// this is the new encoding format used going forward
10361var bufferPrefix = 'Buff:';
10362var bufferRegex = new RegExp('^' + bufferPrefix);
10363
10364var utils = _dereq_(67);
10365var LocalStorageCore = _dereq_(64);
10366var TaskQueue = _dereq_(66);
10367var d64 = _dereq_(15);
10368
10369function LocalStorage(dbname) {
10370 this._store = new LocalStorageCore(dbname);
10371 this._queue = new TaskQueue();
10372}
10373
10374LocalStorage.prototype.sequentialize = function (callback, fun) {
10375 this._queue.add(fun, callback);
10376};
10377
10378LocalStorage.prototype.init = function (callback) {
10379 var self = this;
10380 self.sequentialize(callback, function (callback) {
10381 self._store.getKeys(function (err, keys) {
10382 if (err) {
10383 return callback(err);
10384 }
10385 self._keys = keys;
10386 return callback();
10387 });
10388 });
10389};
10390
10391LocalStorage.prototype.keys = function (callback) {
10392 var self = this;
10393 self.sequentialize(callback, function (callback) {
10394 self._store.getKeys(function (err, keys) {
10395 callback(null, keys.slice());
10396 });
10397 });
10398};
10399
10400//setItem: Saves and item at the key provided.
10401LocalStorage.prototype.setItem = function (key, value, callback) {
10402 var self = this;
10403 self.sequentialize(callback, function (callback) {
10404 if (Buffer.isBuffer(value)) {
10405 value = bufferPrefix + d64.encode(value);
10406 }
10407
10408 var idx = utils.sortedIndexOf(self._keys, key);
10409 if (self._keys[idx] !== key) {
10410 self._keys.splice(idx, 0, key);
10411 }
10412 self._store.put(key, value, callback);
10413 });
10414};
10415
10416//getItem: Returns the item identified by it's key.
10417LocalStorage.prototype.getItem = function (key, callback) {
10418 var self = this;
10419 self.sequentialize(callback, function (callback) {
10420 self._store.get(key, function (err, retval) {
10421 if (err) {
10422 return callback(err);
10423 }
10424 if (typeof retval === 'undefined' || retval === null) {
10425 // 'NotFound' error, consistent with LevelDOWN API
10426 return callback(new Error('NotFound'));
10427 }
10428 if (typeof retval !== 'undefined') {
10429 if (bufferRegex.test(retval)) {
10430 retval = d64.decode(retval.substring(bufferPrefix.length));
10431 } else if (arrayBuffRegex.test(retval)) {
10432 // this type is kept for backwards
10433 // compatibility with older databases, but may be removed
10434 // after a major version bump
10435 retval = retval.substring(arrayBuffPrefix.length);
10436 retval = new ArrayBuffer(atob(retval).split('').map(function (c) {
10437 return c.charCodeAt(0);
10438 }));
10439 } else if (uintRegex.test(retval)) {
10440 // ditto
10441 retval = retval.substring(uintPrefix.length);
10442 retval = new Uint8Array(atob(retval).split('').map(function (c) {
10443 return c.charCodeAt(0);
10444 }));
10445 }
10446 }
10447 callback(null, retval);
10448 });
10449 });
10450};
10451
10452//removeItem: Removes the item identified by it's key.
10453LocalStorage.prototype.removeItem = function (key, callback) {
10454 var self = this;
10455 self.sequentialize(callback, function (callback) {
10456 var idx = utils.sortedIndexOf(self._keys, key);
10457 if (self._keys[idx] === key) {
10458 self._keys.splice(idx, 1);
10459 self._store.remove(key, function (err) {
10460 if (err) {
10461 return callback(err);
10462 }
10463 callback();
10464 });
10465 } else {
10466 callback();
10467 }
10468 });
10469};
10470
10471LocalStorage.prototype.length = function (callback) {
10472 var self = this;
10473 self.sequentialize(callback, function (callback) {
10474 callback(null, self._keys.length);
10475 });
10476};
10477
10478exports.LocalStorage = LocalStorage;
10479
10480}).call(this)}).call(this,{"isBuffer":_dereq_(38)})
10481},{"15":15,"38":38,"64":64,"66":66,"67":67}],66:[function(_dereq_,module,exports){
10482(function (process,global){(function (){
10483'use strict';
10484
10485var argsarray = _dereq_(5);
10486var Queue = _dereq_(120);
10487
10488// see http://stackoverflow.com/a/15349865/680742
10489var nextTick = global.setImmediate || process.nextTick;
10490
10491function TaskQueue() {
10492 this.queue = new Queue();
10493 this.running = false;
10494}
10495
10496TaskQueue.prototype.add = function (fun, callback) {
10497 this.queue.push({fun: fun, callback: callback});
10498 this.processNext();
10499};
10500
10501TaskQueue.prototype.processNext = function () {
10502 var self = this;
10503 if (self.running || !self.queue.length) {
10504 return;
10505 }
10506 self.running = true;
10507
10508 var task = self.queue.shift();
10509 nextTick(function () {
10510 task.fun(argsarray(function (args) {
10511 task.callback.apply(null, args);
10512 self.running = false;
10513 self.processNext();
10514 }));
10515 });
10516};
10517
10518module.exports = TaskQueue;
10519
10520}).call(this)}).call(this,_dereq_(73),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10521},{"120":120,"5":5,"73":73}],67:[function(_dereq_,module,exports){
10522'use strict';
10523// taken from rvagg/memdown commit 2078b40
10524exports.sortedIndexOf = function(arr, item) {
10525 var low = 0;
10526 var high = arr.length;
10527 var mid;
10528 while (low < high) {
10529 mid = (low + high) >>> 1;
10530 if (arr[mid] < item) {
10531 low = mid + 1;
10532 } else {
10533 high = mid;
10534 }
10535 }
10536 return low;
10537};
10538
10539},{}],68:[function(_dereq_,module,exports){
10540(function (Buffer){(function (){
10541var toString = Object.prototype.toString
10542
10543var isModern = (
10544 typeof Buffer.alloc === 'function' &&
10545 typeof Buffer.allocUnsafe === 'function' &&
10546 typeof Buffer.from === 'function'
10547)
10548
10549function isArrayBuffer (input) {
10550 return toString.call(input).slice(8, -1) === 'ArrayBuffer'
10551}
10552
10553function fromArrayBuffer (obj, byteOffset, length) {
10554 byteOffset >>>= 0
10555
10556 var maxLength = obj.byteLength - byteOffset
10557
10558 if (maxLength < 0) {
10559 throw new RangeError("'offset' is out of bounds")
10560 }
10561
10562 if (length === undefined) {
10563 length = maxLength
10564 } else {
10565 length >>>= 0
10566
10567 if (length > maxLength) {
10568 throw new RangeError("'length' is out of bounds")
10569 }
10570 }
10571
10572 return isModern
10573 ? Buffer.from(obj.slice(byteOffset, byteOffset + length))
10574 : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
10575}
10576
10577function fromString (string, encoding) {
10578 if (typeof encoding !== 'string' || encoding === '') {
10579 encoding = 'utf8'
10580 }
10581
10582 if (!Buffer.isEncoding(encoding)) {
10583 throw new TypeError('"encoding" must be a valid string encoding')
10584 }
10585
10586 return isModern
10587 ? Buffer.from(string, encoding)
10588 : new Buffer(string, encoding)
10589}
10590
10591function bufferFrom (value, encodingOrOffset, length) {
10592 if (typeof value === 'number') {
10593 throw new TypeError('"value" argument must not be a number')
10594 }
10595
10596 if (isArrayBuffer(value)) {
10597 return fromArrayBuffer(value, encodingOrOffset, length)
10598 }
10599
10600 if (typeof value === 'string') {
10601 return fromString(value, encodingOrOffset)
10602 }
10603
10604 return isModern
10605 ? Buffer.from(value)
10606 : new Buffer(value)
10607}
10608
10609module.exports = bufferFrom
10610
10611}).call(this)}).call(this,_dereq_(13).Buffer)
10612},{"13":13}],69:[function(_dereq_,module,exports){
10613(function (root) {
10614 var localStorageMemory = {}
10615 var cache = {}
10616
10617 /**
10618 * number of stored items.
10619 */
10620 localStorageMemory.length = 0
10621
10622 /**
10623 * returns item for passed key, or null
10624 *
10625 * @para {String} key
10626 * name of item to be returned
10627 * @returns {String|null}
10628 */
10629 localStorageMemory.getItem = function (key) {
10630 if (key in cache) {
10631 return cache[key]
10632 }
10633
10634 return null
10635 }
10636
10637 /**
10638 * sets item for key to passed value, as String
10639 *
10640 * @para {String} key
10641 * name of item to be set
10642 * @para {String} value
10643 * value, will always be turned into a String
10644 * @returns {undefined}
10645 */
10646 localStorageMemory.setItem = function (key, value) {
10647 if (typeof value === 'undefined') {
10648 localStorageMemory.removeItem(key)
10649 } else {
10650 if (!(cache.hasOwnProperty(key))) {
10651 localStorageMemory.length++
10652 }
10653
10654 cache[key] = '' + value
10655 }
10656 }
10657
10658 /**
10659 * removes item for passed key
10660 *
10661 * @para {String} key
10662 * name of item to be removed
10663 * @returns {undefined}
10664 */
10665 localStorageMemory.removeItem = function (key) {
10666 if (cache.hasOwnProperty(key)) {
10667 delete cache[key]
10668 localStorageMemory.length--
10669 }
10670 }
10671
10672 /**
10673 * returns name of key at passed index
10674 *
10675 * @para {Number} index
10676 * Position for key to be returned (starts at 0)
10677 * @returns {String|null}
10678 */
10679 localStorageMemory.key = function (index) {
10680 return Object.keys(cache)[index] || null
10681 }
10682
10683 /**
10684 * removes all stored items and sets length to 0
10685 *
10686 * @returns {undefined}
10687 */
10688 localStorageMemory.clear = function () {
10689 cache = {}
10690 localStorageMemory.length = 0
10691 }
10692
10693 if (typeof exports === 'object') {
10694 module.exports = localStorageMemory
10695 } else {
10696 root.localStorageMemory = localStorageMemory
10697 }
10698})(this)
10699
10700},{}],70:[function(_dereq_,module,exports){
10701(function (Buffer){(function (){
10702
10703exports.compare = function (a, b) {
10704
10705 if(Buffer.isBuffer(a)) {
10706 var l = Math.min(a.length, b.length)
10707 for(var i = 0; i < l; i++) {
10708 var cmp = a[i] - b[i]
10709 if(cmp) return cmp
10710 }
10711 return a.length - b.length
10712 }
10713
10714 return a < b ? -1 : a > b ? 1 : 0
10715}
10716
10717// to be compatible with the current abstract-leveldown tests
10718// nullish or empty strings.
10719// I could use !!val but I want to permit numbers and booleans,
10720// if possible.
10721
10722function isDef (val) {
10723 return val !== undefined && val !== ''
10724}
10725
10726function has (range, name) {
10727 return Object.hasOwnProperty.call(range, name)
10728}
10729
10730function hasKey(range, name) {
10731 return Object.hasOwnProperty.call(range, name) && name
10732}
10733
10734var lowerBoundKey = exports.lowerBoundKey = function (range) {
10735 return (
10736 hasKey(range, 'gt')
10737 || hasKey(range, 'gte')
10738 || hasKey(range, 'min')
10739 || (range.reverse ? hasKey(range, 'end') : hasKey(range, 'start'))
10740 || undefined
10741 )
10742}
10743
10744var lowerBound = exports.lowerBound = function (range, def) {
10745 var k = lowerBoundKey(range)
10746 return k ? range[k] : def
10747}
10748
10749var lowerBoundInclusive = exports.lowerBoundInclusive = function (range) {
10750 return has(range, 'gt') ? false : true
10751}
10752
10753var upperBoundInclusive = exports.upperBoundInclusive =
10754 function (range) {
10755 return (has(range, 'lt') /*&& !range.maxEx*/) ? false : true
10756 }
10757
10758var lowerBoundExclusive = exports.lowerBoundExclusive =
10759 function (range) {
10760 return !lowerBoundInclusive(range)
10761 }
10762
10763var upperBoundExclusive = exports.upperBoundExclusive =
10764 function (range) {
10765 return !upperBoundInclusive(range)
10766 }
10767
10768var upperBoundKey = exports.upperBoundKey = function (range) {
10769 return (
10770 hasKey(range, 'lt')
10771 || hasKey(range, 'lte')
10772 || hasKey(range, 'max')
10773 || (range.reverse ? hasKey(range, 'start') : hasKey(range, 'end'))
10774 || undefined
10775 )
10776}
10777
10778var upperBound = exports.upperBound = function (range, def) {
10779 var k = upperBoundKey(range)
10780 return k ? range[k] : def
10781}
10782
10783exports.start = function (range, def) {
10784 return range.reverse ? upperBound(range, def) : lowerBound(range, def)
10785}
10786exports.end = function (range, def) {
10787 return range.reverse ? lowerBound(range, def) : upperBound(range, def)
10788}
10789exports.startInclusive = function (range) {
10790 return (
10791 range.reverse
10792 ? upperBoundInclusive(range)
10793 : lowerBoundInclusive(range)
10794 )
10795}
10796exports.endInclusive = function (range) {
10797 return (
10798 range.reverse
10799 ? lowerBoundInclusive(range)
10800 : upperBoundInclusive(range)
10801 )
10802}
10803
10804function id (e) { return e }
10805
10806exports.toLtgt = function (range, _range, map, lower, upper) {
10807 _range = _range || {}
10808 map = map || id
10809 var defaults = arguments.length > 3
10810 var lb = exports.lowerBoundKey(range)
10811 var ub = exports.upperBoundKey(range)
10812 if(lb) {
10813 if(lb === 'gt') _range.gt = map(range.gt, false)
10814 else _range.gte = map(range[lb], false)
10815 }
10816 else if(defaults)
10817 _range.gte = map(lower, false)
10818
10819 if(ub) {
10820 if(ub === 'lt') _range.lt = map(range.lt, true)
10821 else _range.lte = map(range[ub], true)
10822 }
10823 else if(defaults)
10824 _range.lte = map(upper, true)
10825
10826 if(range.reverse != null)
10827 _range.reverse = !!range.reverse
10828
10829 //if range was used mutably
10830 //(in level-sublevel it's part of an options object
10831 //that has more properties on it.)
10832 if(has(_range, 'max')) delete _range.max
10833 if(has(_range, 'min')) delete _range.min
10834 if(has(_range, 'start')) delete _range.start
10835 if(has(_range, 'end')) delete _range.end
10836
10837 return _range
10838}
10839
10840exports.contains = function (range, key, compare) {
10841 compare = compare || exports.compare
10842
10843 var lb = lowerBound(range)
10844 if(isDef(lb)) {
10845 var cmp = compare(key, lb)
10846 if(cmp < 0 || (cmp === 0 && lowerBoundExclusive(range)))
10847 return false
10848 }
10849
10850 var ub = upperBound(range)
10851 if(isDef(ub)) {
10852 var cmp = compare(key, ub)
10853 if(cmp > 0 || (cmp === 0) && upperBoundExclusive(range))
10854 return false
10855 }
10856
10857 return true
10858}
10859
10860exports.filter = function (range, compare) {
10861 return function (key) {
10862 return exports.contains(range, key, compare)
10863 }
10864}
10865
10866
10867
10868}).call(this)}).call(this,{"isBuffer":_dereq_(38)})
10869},{"38":38}],71:[function(_dereq_,module,exports){
10870/*
10871object-assign
10872(c) Sindre Sorhus
10873@license MIT
10874*/
10875
10876'use strict';
10877/* eslint-disable no-unused-vars */
10878var getOwnPropertySymbols = Object.getOwnPropertySymbols;
10879var hasOwnProperty = Object.prototype.hasOwnProperty;
10880var propIsEnumerable = Object.prototype.propertyIsEnumerable;
10881
10882function toObject(val) {
10883 if (val === null || val === undefined) {
10884 throw new TypeError('Object.assign cannot be called with null or undefined');
10885 }
10886
10887 return Object(val);
10888}
10889
10890function shouldUseNative() {
10891 try {
10892 if (!Object.assign) {
10893 return false;
10894 }
10895
10896 // Detect buggy property enumeration order in older V8 versions.
10897
10898 // https://bugs.chromium.org/p/v8/issues/detail?id=4118
10899 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
10900 test1[5] = 'de';
10901 if (Object.getOwnPropertyNames(test1)[0] === '5') {
10902 return false;
10903 }
10904
10905 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
10906 var test2 = {};
10907 for (var i = 0; i < 10; i++) {
10908 test2['_' + String.fromCharCode(i)] = i;
10909 }
10910 var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
10911 return test2[n];
10912 });
10913 if (order2.join('') !== '0123456789') {
10914 return false;
10915 }
10916
10917 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
10918 var test3 = {};
10919 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
10920 test3[letter] = letter;
10921 });
10922 if (Object.keys(Object.assign({}, test3)).join('') !==
10923 'abcdefghijklmnopqrst') {
10924 return false;
10925 }
10926
10927 return true;
10928 } catch (err) {
10929 // We don't expect any of the above to throw, but better to be safe.
10930 return false;
10931 }
10932}
10933
10934module.exports = shouldUseNative() ? Object.assign : function (target, source) {
10935 var from;
10936 var to = toObject(target);
10937 var symbols;
10938
10939 for (var s = 1; s < arguments.length; s++) {
10940 from = Object(arguments[s]);
10941
10942 for (var key in from) {
10943 if (hasOwnProperty.call(from, key)) {
10944 to[key] = from[key];
10945 }
10946 }
10947
10948 if (getOwnPropertySymbols) {
10949 symbols = getOwnPropertySymbols(from);
10950 for (var i = 0; i < symbols.length; i++) {
10951 if (propIsEnumerable.call(from, symbols[i])) {
10952 to[symbols[i]] = from[symbols[i]];
10953 }
10954 }
10955 }
10956 }
10957
10958 return to;
10959};
10960
10961},{}],72:[function(_dereq_,module,exports){
10962(function (process){(function (){
10963'use strict';
10964
10965if (typeof process === 'undefined' ||
10966 !process.version ||
10967 process.version.indexOf('v0.') === 0 ||
10968 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
10969 module.exports = { nextTick: nextTick };
10970} else {
10971 module.exports = process
10972}
10973
10974function nextTick(fn, arg1, arg2, arg3) {
10975 if (typeof fn !== 'function') {
10976 throw new TypeError('"callback" argument must be a function');
10977 }
10978 var len = arguments.length;
10979 var args, i;
10980 switch (len) {
10981 case 0:
10982 case 1:
10983 return process.nextTick(fn);
10984 case 2:
10985 return process.nextTick(function afterTickOne() {
10986 fn.call(null, arg1);
10987 });
10988 case 3:
10989 return process.nextTick(function afterTickTwo() {
10990 fn.call(null, arg1, arg2);
10991 });
10992 case 4:
10993 return process.nextTick(function afterTickThree() {
10994 fn.call(null, arg1, arg2, arg3);
10995 });
10996 default:
10997 args = new Array(len - 1);
10998 i = 0;
10999 while (i < args.length) {
11000 args[i++] = arguments[i];
11001 }
11002 return process.nextTick(function afterTick() {
11003 fn.apply(null, args);
11004 });
11005 }
11006}
11007
11008
11009}).call(this)}).call(this,_dereq_(73))
11010},{"73":73}],73:[function(_dereq_,module,exports){
11011// shim for using process in browser
11012var process = module.exports = {};
11013
11014// cached from whatever global is present so that test runners that stub it
11015// don't break things. But we need to wrap it in a try catch in case it is
11016// wrapped in strict mode code which doesn't define any globals. It's inside a
11017// function because try/catches deoptimize in certain engines.
11018
11019var cachedSetTimeout;
11020var cachedClearTimeout;
11021
11022function defaultSetTimout() {
11023 throw new Error('setTimeout has not been defined');
11024}
11025function defaultClearTimeout () {
11026 throw new Error('clearTimeout has not been defined');
11027}
11028(function () {
11029 try {
11030 if (typeof setTimeout === 'function') {
11031 cachedSetTimeout = setTimeout;
11032 } else {
11033 cachedSetTimeout = defaultSetTimout;
11034 }
11035 } catch (e) {
11036 cachedSetTimeout = defaultSetTimout;
11037 }
11038 try {
11039 if (typeof clearTimeout === 'function') {
11040 cachedClearTimeout = clearTimeout;
11041 } else {
11042 cachedClearTimeout = defaultClearTimeout;
11043 }
11044 } catch (e) {
11045 cachedClearTimeout = defaultClearTimeout;
11046 }
11047} ())
11048function runTimeout(fun) {
11049 if (cachedSetTimeout === setTimeout) {
11050 //normal enviroments in sane situations
11051 return setTimeout(fun, 0);
11052 }
11053 // if setTimeout wasn't available but was latter defined
11054 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
11055 cachedSetTimeout = setTimeout;
11056 return setTimeout(fun, 0);
11057 }
11058 try {
11059 // when when somebody has screwed with setTimeout but no I.E. maddness
11060 return cachedSetTimeout(fun, 0);
11061 } catch(e){
11062 try {
11063 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
11064 return cachedSetTimeout.call(null, fun, 0);
11065 } catch(e){
11066 // 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
11067 return cachedSetTimeout.call(this, fun, 0);
11068 }
11069 }
11070
11071
11072}
11073function runClearTimeout(marker) {
11074 if (cachedClearTimeout === clearTimeout) {
11075 //normal enviroments in sane situations
11076 return clearTimeout(marker);
11077 }
11078 // if clearTimeout wasn't available but was latter defined
11079 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
11080 cachedClearTimeout = clearTimeout;
11081 return clearTimeout(marker);
11082 }
11083 try {
11084 // when when somebody has screwed with setTimeout but no I.E. maddness
11085 return cachedClearTimeout(marker);
11086 } catch (e){
11087 try {
11088 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
11089 return cachedClearTimeout.call(null, marker);
11090 } catch (e){
11091 // 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.
11092 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
11093 return cachedClearTimeout.call(this, marker);
11094 }
11095 }
11096
11097
11098
11099}
11100var queue = [];
11101var draining = false;
11102var currentQueue;
11103var queueIndex = -1;
11104
11105function cleanUpNextTick() {
11106 if (!draining || !currentQueue) {
11107 return;
11108 }
11109 draining = false;
11110 if (currentQueue.length) {
11111 queue = currentQueue.concat(queue);
11112 } else {
11113 queueIndex = -1;
11114 }
11115 if (queue.length) {
11116 drainQueue();
11117 }
11118}
11119
11120function drainQueue() {
11121 if (draining) {
11122 return;
11123 }
11124 var timeout = runTimeout(cleanUpNextTick);
11125 draining = true;
11126
11127 var len = queue.length;
11128 while(len) {
11129 currentQueue = queue;
11130 queue = [];
11131 while (++queueIndex < len) {
11132 if (currentQueue) {
11133 currentQueue[queueIndex].run();
11134 }
11135 }
11136 queueIndex = -1;
11137 len = queue.length;
11138 }
11139 currentQueue = null;
11140 draining = false;
11141 runClearTimeout(timeout);
11142}
11143
11144process.nextTick = function (fun) {
11145 var args = new Array(arguments.length - 1);
11146 if (arguments.length > 1) {
11147 for (var i = 1; i < arguments.length; i++) {
11148 args[i - 1] = arguments[i];
11149 }
11150 }
11151 queue.push(new Item(fun, args));
11152 if (queue.length === 1 && !draining) {
11153 runTimeout(drainQueue);
11154 }
11155};
11156
11157// v8 likes predictible objects
11158function Item(fun, array) {
11159 this.fun = fun;
11160 this.array = array;
11161}
11162Item.prototype.run = function () {
11163 this.fun.apply(null, this.array);
11164};
11165process.title = 'browser';
11166process.browser = true;
11167process.env = {};
11168process.argv = [];
11169process.version = ''; // empty string to avoid regexp issues
11170process.versions = {};
11171
11172function noop() {}
11173
11174process.on = noop;
11175process.addListener = noop;
11176process.once = noop;
11177process.off = noop;
11178process.removeListener = noop;
11179process.removeAllListeners = noop;
11180process.emit = noop;
11181process.prependListener = noop;
11182process.prependOnceListener = noop;
11183
11184process.listeners = function (name) { return [] }
11185
11186process.binding = function (name) {
11187 throw new Error('process.binding is not supported');
11188};
11189
11190process.cwd = function () { return '/' };
11191process.chdir = function (dir) {
11192 throw new Error('process.chdir is not supported');
11193};
11194process.umask = function() { return 0; };
11195
11196},{}],74:[function(_dereq_,module,exports){
11197/*!
11198 * prr
11199 * (c) 2013 Rod Vagg <rod@vagg.org>
11200 * https://github.com/rvagg/prr
11201 * License: MIT
11202 */
11203
11204(function (name, context, definition) {
11205 if (typeof module != 'undefined' && module.exports)
11206 module.exports = definition()
11207 else
11208 context[name] = definition()
11209})('prr', this, function() {
11210
11211 var setProperty = typeof Object.defineProperty == 'function'
11212 ? function (obj, key, options) {
11213 Object.defineProperty(obj, key, options)
11214 return obj
11215 }
11216 : function (obj, key, options) { // < es5
11217 obj[key] = options.value
11218 return obj
11219 }
11220
11221 , makeOptions = function (value, options) {
11222 var oo = typeof options == 'object'
11223 , os = !oo && typeof options == 'string'
11224 , op = function (p) {
11225 return oo
11226 ? !!options[p]
11227 : os
11228 ? options.indexOf(p[0]) > -1
11229 : false
11230 }
11231
11232 return {
11233 enumerable : op('enumerable')
11234 , configurable : op('configurable')
11235 , writable : op('writable')
11236 , value : value
11237 }
11238 }
11239
11240 , prr = function (obj, key, value, options) {
11241 var k
11242
11243 options = makeOptions(value, options)
11244
11245 if (typeof key == 'object') {
11246 for (k in key) {
11247 if (Object.hasOwnProperty.call(key, k)) {
11248 options.value = key[k]
11249 setProperty(obj, k, options)
11250 }
11251 }
11252 return obj
11253 }
11254
11255 return setProperty(obj, key, options)
11256 }
11257
11258 return prr
11259})
11260},{}],75:[function(_dereq_,module,exports){
11261(function (process){(function (){
11262// Copyright Joyent, Inc. and other Node contributors.
11263//
11264// Permission is hereby granted, free of charge, to any person obtaining a
11265// copy of this software and associated documentation files (the
11266// "Software"), to deal in the Software without restriction, including
11267// without limitation the rights to use, copy, modify, merge, publish,
11268// distribute, sublicense, and/or sell copies of the Software, and to permit
11269// persons to whom the Software is furnished to do so, subject to the
11270// following conditions:
11271//
11272// The above copyright notice and this permission notice shall be included
11273// in all copies or substantial portions of the Software.
11274//
11275// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11276// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11277// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11278// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11279// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11280// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11281// USE OR OTHER DEALINGS IN THE SOFTWARE.
11282
11283// a duplex stream is just a stream that is both readable and writable.
11284// Since JS doesn't have multiple prototypal inheritance, this class
11285// prototypally inherits from Readable, and then parasitically from
11286// Writable.
11287
11288module.exports = Duplex;
11289
11290/*<replacement>*/
11291var objectKeys = Object.keys || function (obj) {
11292 var keys = [];
11293 for (var key in obj) keys.push(key);
11294 return keys;
11295}
11296/*</replacement>*/
11297
11298
11299/*<replacement>*/
11300var util = _dereq_(14);
11301util.inherits = _dereq_(37);
11302/*</replacement>*/
11303
11304var Readable = _dereq_(77);
11305var Writable = _dereq_(79);
11306
11307util.inherits(Duplex, Readable);
11308
11309forEach(objectKeys(Writable.prototype), function(method) {
11310 if (!Duplex.prototype[method])
11311 Duplex.prototype[method] = Writable.prototype[method];
11312});
11313
11314function Duplex(options) {
11315 if (!(this instanceof Duplex))
11316 return new Duplex(options);
11317
11318 Readable.call(this, options);
11319 Writable.call(this, options);
11320
11321 if (options && options.readable === false)
11322 this.readable = false;
11323
11324 if (options && options.writable === false)
11325 this.writable = false;
11326
11327 this.allowHalfOpen = true;
11328 if (options && options.allowHalfOpen === false)
11329 this.allowHalfOpen = false;
11330
11331 this.once('end', onend);
11332}
11333
11334// the no-half-open enforcer
11335function onend() {
11336 // if we allow half-open state, or if the writable side ended,
11337 // then we're ok.
11338 if (this.allowHalfOpen || this._writableState.ended)
11339 return;
11340
11341 // no more data can be written.
11342 // But allow more writes to happen in this tick.
11343 process.nextTick(this.end.bind(this));
11344}
11345
11346function forEach (xs, f) {
11347 for (var i = 0, l = xs.length; i < l; i++) {
11348 f(xs[i], i);
11349 }
11350}
11351
11352}).call(this)}).call(this,_dereq_(73))
11353},{"14":14,"37":37,"73":73,"77":77,"79":79}],76:[function(_dereq_,module,exports){
11354// Copyright Joyent, Inc. and other Node contributors.
11355//
11356// Permission is hereby granted, free of charge, to any person obtaining a
11357// copy of this software and associated documentation files (the
11358// "Software"), to deal in the Software without restriction, including
11359// without limitation the rights to use, copy, modify, merge, publish,
11360// distribute, sublicense, and/or sell copies of the Software, and to permit
11361// persons to whom the Software is furnished to do so, subject to the
11362// following conditions:
11363//
11364// The above copyright notice and this permission notice shall be included
11365// in all copies or substantial portions of the Software.
11366//
11367// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11368// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11369// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11370// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11371// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11372// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11373// USE OR OTHER DEALINGS IN THE SOFTWARE.
11374
11375// a passthrough stream.
11376// basically just the most minimal sort of Transform stream.
11377// Every written chunk gets output as-is.
11378
11379module.exports = PassThrough;
11380
11381var Transform = _dereq_(78);
11382
11383/*<replacement>*/
11384var util = _dereq_(14);
11385util.inherits = _dereq_(37);
11386/*</replacement>*/
11387
11388util.inherits(PassThrough, Transform);
11389
11390function PassThrough(options) {
11391 if (!(this instanceof PassThrough))
11392 return new PassThrough(options);
11393
11394 Transform.call(this, options);
11395}
11396
11397PassThrough.prototype._transform = function(chunk, encoding, cb) {
11398 cb(null, chunk);
11399};
11400
11401},{"14":14,"37":37,"78":78}],77:[function(_dereq_,module,exports){
11402(function (process){(function (){
11403// Copyright Joyent, Inc. and other Node contributors.
11404//
11405// Permission is hereby granted, free of charge, to any person obtaining a
11406// copy of this software and associated documentation files (the
11407// "Software"), to deal in the Software without restriction, including
11408// without limitation the rights to use, copy, modify, merge, publish,
11409// distribute, sublicense, and/or sell copies of the Software, and to permit
11410// persons to whom the Software is furnished to do so, subject to the
11411// following conditions:
11412//
11413// The above copyright notice and this permission notice shall be included
11414// in all copies or substantial portions of the Software.
11415//
11416// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11417// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11418// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11419// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11420// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11421// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11422// USE OR OTHER DEALINGS IN THE SOFTWARE.
11423
11424module.exports = Readable;
11425
11426/*<replacement>*/
11427var isArray = _dereq_(80);
11428/*</replacement>*/
11429
11430
11431/*<replacement>*/
11432var Buffer = _dereq_(13).Buffer;
11433/*</replacement>*/
11434
11435Readable.ReadableState = ReadableState;
11436
11437var EE = _dereq_(26).EventEmitter;
11438
11439/*<replacement>*/
11440if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
11441 return emitter.listeners(type).length;
11442};
11443/*</replacement>*/
11444
11445var Stream = _dereq_(85);
11446
11447/*<replacement>*/
11448var util = _dereq_(14);
11449util.inherits = _dereq_(37);
11450/*</replacement>*/
11451
11452var StringDecoder;
11453
11454
11455/*<replacement>*/
11456var debug = _dereq_(11);
11457if (debug && debug.debuglog) {
11458 debug = debug.debuglog('stream');
11459} else {
11460 debug = function () {};
11461}
11462/*</replacement>*/
11463
11464
11465util.inherits(Readable, Stream);
11466
11467function ReadableState(options, stream) {
11468 var Duplex = _dereq_(75);
11469
11470 options = options || {};
11471
11472 // the point at which it stops calling _read() to fill the buffer
11473 // Note: 0 is a valid value, means "don't call _read preemptively ever"
11474 var hwm = options.highWaterMark;
11475 var defaultHwm = options.objectMode ? 16 : 16 * 1024;
11476 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
11477
11478 // cast to ints.
11479 this.highWaterMark = ~~this.highWaterMark;
11480
11481 this.buffer = [];
11482 this.length = 0;
11483 this.pipes = null;
11484 this.pipesCount = 0;
11485 this.flowing = null;
11486 this.ended = false;
11487 this.endEmitted = false;
11488 this.reading = false;
11489
11490 // a flag to be able to tell if the onwrite cb is called immediately,
11491 // or on a later tick. We set this to true at first, because any
11492 // actions that shouldn't happen until "later" should generally also
11493 // not happen before the first write call.
11494 this.sync = true;
11495
11496 // whenever we return null, then we set a flag to say
11497 // that we're awaiting a 'readable' event emission.
11498 this.needReadable = false;
11499 this.emittedReadable = false;
11500 this.readableListening = false;
11501
11502
11503 // object stream flag. Used to make read(n) ignore n and to
11504 // make all the buffer merging and length checks go away
11505 this.objectMode = !!options.objectMode;
11506
11507 if (stream instanceof Duplex)
11508 this.objectMode = this.objectMode || !!options.readableObjectMode;
11509
11510 // Crypto is kind of old and crusty. Historically, its default string
11511 // encoding is 'binary' so we have to make this configurable.
11512 // Everything else in the universe uses 'utf8', though.
11513 this.defaultEncoding = options.defaultEncoding || 'utf8';
11514
11515 // when piping, we only care about 'readable' events that happen
11516 // after read()ing all the bytes and not getting any pushback.
11517 this.ranOut = false;
11518
11519 // the number of writers that are awaiting a drain event in .pipe()s
11520 this.awaitDrain = 0;
11521
11522 // if true, a maybeReadMore has been scheduled
11523 this.readingMore = false;
11524
11525 this.decoder = null;
11526 this.encoding = null;
11527 if (options.encoding) {
11528 if (!StringDecoder)
11529 StringDecoder = _dereq_(81).StringDecoder;
11530 this.decoder = new StringDecoder(options.encoding);
11531 this.encoding = options.encoding;
11532 }
11533}
11534
11535function Readable(options) {
11536 var Duplex = _dereq_(75);
11537
11538 if (!(this instanceof Readable))
11539 return new Readable(options);
11540
11541 this._readableState = new ReadableState(options, this);
11542
11543 // legacy
11544 this.readable = true;
11545
11546 Stream.call(this);
11547}
11548
11549// Manually shove something into the read() buffer.
11550// This returns true if the highWaterMark has not been hit yet,
11551// similar to how Writable.write() returns true if you should
11552// write() some more.
11553Readable.prototype.push = function(chunk, encoding) {
11554 var state = this._readableState;
11555
11556 if (util.isString(chunk) && !state.objectMode) {
11557 encoding = encoding || state.defaultEncoding;
11558 if (encoding !== state.encoding) {
11559 chunk = new Buffer(chunk, encoding);
11560 encoding = '';
11561 }
11562 }
11563
11564 return readableAddChunk(this, state, chunk, encoding, false);
11565};
11566
11567// Unshift should *always* be something directly out of read()
11568Readable.prototype.unshift = function(chunk) {
11569 var state = this._readableState;
11570 return readableAddChunk(this, state, chunk, '', true);
11571};
11572
11573function readableAddChunk(stream, state, chunk, encoding, addToFront) {
11574 var er = chunkInvalid(state, chunk);
11575 if (er) {
11576 stream.emit('error', er);
11577 } else if (util.isNullOrUndefined(chunk)) {
11578 state.reading = false;
11579 if (!state.ended)
11580 onEofChunk(stream, state);
11581 } else if (state.objectMode || chunk && chunk.length > 0) {
11582 if (state.ended && !addToFront) {
11583 var e = new Error('stream.push() after EOF');
11584 stream.emit('error', e);
11585 } else if (state.endEmitted && addToFront) {
11586 var e = new Error('stream.unshift() after end event');
11587 stream.emit('error', e);
11588 } else {
11589 if (state.decoder && !addToFront && !encoding)
11590 chunk = state.decoder.write(chunk);
11591
11592 if (!addToFront)
11593 state.reading = false;
11594
11595 // if we want the data now, just emit it.
11596 if (state.flowing && state.length === 0 && !state.sync) {
11597 stream.emit('data', chunk);
11598 stream.read(0);
11599 } else {
11600 // update the buffer info.
11601 state.length += state.objectMode ? 1 : chunk.length;
11602 if (addToFront)
11603 state.buffer.unshift(chunk);
11604 else
11605 state.buffer.push(chunk);
11606
11607 if (state.needReadable)
11608 emitReadable(stream);
11609 }
11610
11611 maybeReadMore(stream, state);
11612 }
11613 } else if (!addToFront) {
11614 state.reading = false;
11615 }
11616
11617 return needMoreData(state);
11618}
11619
11620
11621
11622// if it's past the high water mark, we can push in some more.
11623// Also, if we have no data yet, we can stand some
11624// more bytes. This is to work around cases where hwm=0,
11625// such as the repl. Also, if the push() triggered a
11626// readable event, and the user called read(largeNumber) such that
11627// needReadable was set, then we ought to push more, so that another
11628// 'readable' event will be triggered.
11629function needMoreData(state) {
11630 return !state.ended &&
11631 (state.needReadable ||
11632 state.length < state.highWaterMark ||
11633 state.length === 0);
11634}
11635
11636// backwards compatibility.
11637Readable.prototype.setEncoding = function(enc) {
11638 if (!StringDecoder)
11639 StringDecoder = _dereq_(81).StringDecoder;
11640 this._readableState.decoder = new StringDecoder(enc);
11641 this._readableState.encoding = enc;
11642 return this;
11643};
11644
11645// Don't raise the hwm > 128MB
11646var MAX_HWM = 0x800000;
11647function roundUpToNextPowerOf2(n) {
11648 if (n >= MAX_HWM) {
11649 n = MAX_HWM;
11650 } else {
11651 // Get the next highest power of 2
11652 n--;
11653 for (var p = 1; p < 32; p <<= 1) n |= n >> p;
11654 n++;
11655 }
11656 return n;
11657}
11658
11659function howMuchToRead(n, state) {
11660 if (state.length === 0 && state.ended)
11661 return 0;
11662
11663 if (state.objectMode)
11664 return n === 0 ? 0 : 1;
11665
11666 if (isNaN(n) || util.isNull(n)) {
11667 // only flow one buffer at a time
11668 if (state.flowing && state.buffer.length)
11669 return state.buffer[0].length;
11670 else
11671 return state.length;
11672 }
11673
11674 if (n <= 0)
11675 return 0;
11676
11677 // If we're asking for more than the target buffer level,
11678 // then raise the water mark. Bump up to the next highest
11679 // power of 2, to prevent increasing it excessively in tiny
11680 // amounts.
11681 if (n > state.highWaterMark)
11682 state.highWaterMark = roundUpToNextPowerOf2(n);
11683
11684 // don't have that much. return null, unless we've ended.
11685 if (n > state.length) {
11686 if (!state.ended) {
11687 state.needReadable = true;
11688 return 0;
11689 } else
11690 return state.length;
11691 }
11692
11693 return n;
11694}
11695
11696// you can override either this method, or the async _read(n) below.
11697Readable.prototype.read = function(n) {
11698 debug('read', n);
11699 var state = this._readableState;
11700 var nOrig = n;
11701
11702 if (!util.isNumber(n) || n > 0)
11703 state.emittedReadable = false;
11704
11705 // if we're doing read(0) to trigger a readable event, but we
11706 // already have a bunch of data in the buffer, then just trigger
11707 // the 'readable' event and move on.
11708 if (n === 0 &&
11709 state.needReadable &&
11710 (state.length >= state.highWaterMark || state.ended)) {
11711 debug('read: emitReadable', state.length, state.ended);
11712 if (state.length === 0 && state.ended)
11713 endReadable(this);
11714 else
11715 emitReadable(this);
11716 return null;
11717 }
11718
11719 n = howMuchToRead(n, state);
11720
11721 // if we've ended, and we're now clear, then finish it up.
11722 if (n === 0 && state.ended) {
11723 if (state.length === 0)
11724 endReadable(this);
11725 return null;
11726 }
11727
11728 // All the actual chunk generation logic needs to be
11729 // *below* the call to _read. The reason is that in certain
11730 // synthetic stream cases, such as passthrough streams, _read
11731 // may be a completely synchronous operation which may change
11732 // the state of the read buffer, providing enough data when
11733 // before there was *not* enough.
11734 //
11735 // So, the steps are:
11736 // 1. Figure out what the state of things will be after we do
11737 // a read from the buffer.
11738 //
11739 // 2. If that resulting state will trigger a _read, then call _read.
11740 // Note that this may be asynchronous, or synchronous. Yes, it is
11741 // deeply ugly to write APIs this way, but that still doesn't mean
11742 // that the Readable class should behave improperly, as streams are
11743 // designed to be sync/async agnostic.
11744 // Take note if the _read call is sync or async (ie, if the read call
11745 // has returned yet), so that we know whether or not it's safe to emit
11746 // 'readable' etc.
11747 //
11748 // 3. Actually pull the requested chunks out of the buffer and return.
11749
11750 // if we need a readable event, then we need to do some reading.
11751 var doRead = state.needReadable;
11752 debug('need readable', doRead);
11753
11754 // if we currently have less than the highWaterMark, then also read some
11755 if (state.length === 0 || state.length - n < state.highWaterMark) {
11756 doRead = true;
11757 debug('length less than watermark', doRead);
11758 }
11759
11760 // however, if we've ended, then there's no point, and if we're already
11761 // reading, then it's unnecessary.
11762 if (state.ended || state.reading) {
11763 doRead = false;
11764 debug('reading or ended', doRead);
11765 }
11766
11767 if (doRead) {
11768 debug('do read');
11769 state.reading = true;
11770 state.sync = true;
11771 // if the length is currently zero, then we *need* a readable event.
11772 if (state.length === 0)
11773 state.needReadable = true;
11774 // call internal read method
11775 this._read(state.highWaterMark);
11776 state.sync = false;
11777 }
11778
11779 // If _read pushed data synchronously, then `reading` will be false,
11780 // and we need to re-evaluate how much data we can return to the user.
11781 if (doRead && !state.reading)
11782 n = howMuchToRead(nOrig, state);
11783
11784 var ret;
11785 if (n > 0)
11786 ret = fromList(n, state);
11787 else
11788 ret = null;
11789
11790 if (util.isNull(ret)) {
11791 state.needReadable = true;
11792 n = 0;
11793 }
11794
11795 state.length -= n;
11796
11797 // If we have nothing in the buffer, then we want to know
11798 // as soon as we *do* get something into the buffer.
11799 if (state.length === 0 && !state.ended)
11800 state.needReadable = true;
11801
11802 // If we tried to read() past the EOF, then emit end on the next tick.
11803 if (nOrig !== n && state.ended && state.length === 0)
11804 endReadable(this);
11805
11806 if (!util.isNull(ret))
11807 this.emit('data', ret);
11808
11809 return ret;
11810};
11811
11812function chunkInvalid(state, chunk) {
11813 var er = null;
11814 if (!util.isBuffer(chunk) &&
11815 !util.isString(chunk) &&
11816 !util.isNullOrUndefined(chunk) &&
11817 !state.objectMode) {
11818 er = new TypeError('Invalid non-string/buffer chunk');
11819 }
11820 return er;
11821}
11822
11823
11824function onEofChunk(stream, state) {
11825 if (state.decoder && !state.ended) {
11826 var chunk = state.decoder.end();
11827 if (chunk && chunk.length) {
11828 state.buffer.push(chunk);
11829 state.length += state.objectMode ? 1 : chunk.length;
11830 }
11831 }
11832 state.ended = true;
11833
11834 // emit 'readable' now to make sure it gets picked up.
11835 emitReadable(stream);
11836}
11837
11838// Don't emit readable right away in sync mode, because this can trigger
11839// another read() call => stack overflow. This way, it might trigger
11840// a nextTick recursion warning, but that's not so bad.
11841function emitReadable(stream) {
11842 var state = stream._readableState;
11843 state.needReadable = false;
11844 if (!state.emittedReadable) {
11845 debug('emitReadable', state.flowing);
11846 state.emittedReadable = true;
11847 if (state.sync)
11848 process.nextTick(function() {
11849 emitReadable_(stream);
11850 });
11851 else
11852 emitReadable_(stream);
11853 }
11854}
11855
11856function emitReadable_(stream) {
11857 debug('emit readable');
11858 stream.emit('readable');
11859 flow(stream);
11860}
11861
11862
11863// at this point, the user has presumably seen the 'readable' event,
11864// and called read() to consume some data. that may have triggered
11865// in turn another _read(n) call, in which case reading = true if
11866// it's in progress.
11867// However, if we're not ended, or reading, and the length < hwm,
11868// then go ahead and try to read some more preemptively.
11869function maybeReadMore(stream, state) {
11870 if (!state.readingMore) {
11871 state.readingMore = true;
11872 process.nextTick(function() {
11873 maybeReadMore_(stream, state);
11874 });
11875 }
11876}
11877
11878function maybeReadMore_(stream, state) {
11879 var len = state.length;
11880 while (!state.reading && !state.flowing && !state.ended &&
11881 state.length < state.highWaterMark) {
11882 debug('maybeReadMore read 0');
11883 stream.read(0);
11884 if (len === state.length)
11885 // didn't get any data, stop spinning.
11886 break;
11887 else
11888 len = state.length;
11889 }
11890 state.readingMore = false;
11891}
11892
11893// abstract method. to be overridden in specific implementation classes.
11894// call cb(er, data) where data is <= n in length.
11895// for virtual (non-string, non-buffer) streams, "length" is somewhat
11896// arbitrary, and perhaps not very meaningful.
11897Readable.prototype._read = function(n) {
11898 this.emit('error', new Error('not implemented'));
11899};
11900
11901Readable.prototype.pipe = function(dest, pipeOpts) {
11902 var src = this;
11903 var state = this._readableState;
11904
11905 switch (state.pipesCount) {
11906 case 0:
11907 state.pipes = dest;
11908 break;
11909 case 1:
11910 state.pipes = [state.pipes, dest];
11911 break;
11912 default:
11913 state.pipes.push(dest);
11914 break;
11915 }
11916 state.pipesCount += 1;
11917 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
11918
11919 var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
11920 dest !== process.stdout &&
11921 dest !== process.stderr;
11922
11923 var endFn = doEnd ? onend : cleanup;
11924 if (state.endEmitted)
11925 process.nextTick(endFn);
11926 else
11927 src.once('end', endFn);
11928
11929 dest.on('unpipe', onunpipe);
11930 function onunpipe(readable) {
11931 debug('onunpipe');
11932 if (readable === src) {
11933 cleanup();
11934 }
11935 }
11936
11937 function onend() {
11938 debug('onend');
11939 dest.end();
11940 }
11941
11942 // when the dest drains, it reduces the awaitDrain counter
11943 // on the source. This would be more elegant with a .once()
11944 // handler in flow(), but adding and removing repeatedly is
11945 // too slow.
11946 var ondrain = pipeOnDrain(src);
11947 dest.on('drain', ondrain);
11948
11949 function cleanup() {
11950 debug('cleanup');
11951 // cleanup event handlers once the pipe is broken
11952 dest.removeListener('close', onclose);
11953 dest.removeListener('finish', onfinish);
11954 dest.removeListener('drain', ondrain);
11955 dest.removeListener('error', onerror);
11956 dest.removeListener('unpipe', onunpipe);
11957 src.removeListener('end', onend);
11958 src.removeListener('end', cleanup);
11959 src.removeListener('data', ondata);
11960
11961 // if the reader is waiting for a drain event from this
11962 // specific writer, then it would cause it to never start
11963 // flowing again.
11964 // So, if this is awaiting a drain, then we just call it now.
11965 // If we don't know, then assume that we are waiting for one.
11966 if (state.awaitDrain &&
11967 (!dest._writableState || dest._writableState.needDrain))
11968 ondrain();
11969 }
11970
11971 src.on('data', ondata);
11972 function ondata(chunk) {
11973 debug('ondata');
11974 var ret = dest.write(chunk);
11975 if (false === ret) {
11976 debug('false write response, pause',
11977 src._readableState.awaitDrain);
11978 src._readableState.awaitDrain++;
11979 src.pause();
11980 }
11981 }
11982
11983 // if the dest has an error, then stop piping into it.
11984 // however, don't suppress the throwing behavior for this.
11985 function onerror(er) {
11986 debug('onerror', er);
11987 unpipe();
11988 dest.removeListener('error', onerror);
11989 if (EE.listenerCount(dest, 'error') === 0)
11990 dest.emit('error', er);
11991 }
11992 // This is a brutally ugly hack to make sure that our error handler
11993 // is attached before any userland ones. NEVER DO THIS.
11994 if (!dest._events || !dest._events.error)
11995 dest.on('error', onerror);
11996 else if (isArray(dest._events.error))
11997 dest._events.error.unshift(onerror);
11998 else
11999 dest._events.error = [onerror, dest._events.error];
12000
12001
12002
12003 // Both close and finish should trigger unpipe, but only once.
12004 function onclose() {
12005 dest.removeListener('finish', onfinish);
12006 unpipe();
12007 }
12008 dest.once('close', onclose);
12009 function onfinish() {
12010 debug('onfinish');
12011 dest.removeListener('close', onclose);
12012 unpipe();
12013 }
12014 dest.once('finish', onfinish);
12015
12016 function unpipe() {
12017 debug('unpipe');
12018 src.unpipe(dest);
12019 }
12020
12021 // tell the dest that it's being piped to
12022 dest.emit('pipe', src);
12023
12024 // start the flow if it hasn't been started already.
12025 if (!state.flowing) {
12026 debug('pipe resume');
12027 src.resume();
12028 }
12029
12030 return dest;
12031};
12032
12033function pipeOnDrain(src) {
12034 return function() {
12035 var state = src._readableState;
12036 debug('pipeOnDrain', state.awaitDrain);
12037 if (state.awaitDrain)
12038 state.awaitDrain--;
12039 if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
12040 state.flowing = true;
12041 flow(src);
12042 }
12043 };
12044}
12045
12046
12047Readable.prototype.unpipe = function(dest) {
12048 var state = this._readableState;
12049
12050 // if we're not piping anywhere, then do nothing.
12051 if (state.pipesCount === 0)
12052 return this;
12053
12054 // just one destination. most common case.
12055 if (state.pipesCount === 1) {
12056 // passed in one, but it's not the right one.
12057 if (dest && dest !== state.pipes)
12058 return this;
12059
12060 if (!dest)
12061 dest = state.pipes;
12062
12063 // got a match.
12064 state.pipes = null;
12065 state.pipesCount = 0;
12066 state.flowing = false;
12067 if (dest)
12068 dest.emit('unpipe', this);
12069 return this;
12070 }
12071
12072 // slow case. multiple pipe destinations.
12073
12074 if (!dest) {
12075 // remove all.
12076 var dests = state.pipes;
12077 var len = state.pipesCount;
12078 state.pipes = null;
12079 state.pipesCount = 0;
12080 state.flowing = false;
12081
12082 for (var i = 0; i < len; i++)
12083 dests[i].emit('unpipe', this);
12084 return this;
12085 }
12086
12087 // try to find the right one.
12088 var i = indexOf(state.pipes, dest);
12089 if (i === -1)
12090 return this;
12091
12092 state.pipes.splice(i, 1);
12093 state.pipesCount -= 1;
12094 if (state.pipesCount === 1)
12095 state.pipes = state.pipes[0];
12096
12097 dest.emit('unpipe', this);
12098
12099 return this;
12100};
12101
12102// set up data events if they are asked for
12103// Ensure readable listeners eventually get something
12104Readable.prototype.on = function(ev, fn) {
12105 var res = Stream.prototype.on.call(this, ev, fn);
12106
12107 // If listening to data, and it has not explicitly been paused,
12108 // then call resume to start the flow of data on the next tick.
12109 if (ev === 'data' && false !== this._readableState.flowing) {
12110 this.resume();
12111 }
12112
12113 if (ev === 'readable' && this.readable) {
12114 var state = this._readableState;
12115 if (!state.readableListening) {
12116 state.readableListening = true;
12117 state.emittedReadable = false;
12118 state.needReadable = true;
12119 if (!state.reading) {
12120 var self = this;
12121 process.nextTick(function() {
12122 debug('readable nexttick read 0');
12123 self.read(0);
12124 });
12125 } else if (state.length) {
12126 emitReadable(this, state);
12127 }
12128 }
12129 }
12130
12131 return res;
12132};
12133Readable.prototype.addListener = Readable.prototype.on;
12134
12135// pause() and resume() are remnants of the legacy readable stream API
12136// If the user uses them, then switch into old mode.
12137Readable.prototype.resume = function() {
12138 var state = this._readableState;
12139 if (!state.flowing) {
12140 debug('resume');
12141 state.flowing = true;
12142 if (!state.reading) {
12143 debug('resume read 0');
12144 this.read(0);
12145 }
12146 resume(this, state);
12147 }
12148 return this;
12149};
12150
12151function resume(stream, state) {
12152 if (!state.resumeScheduled) {
12153 state.resumeScheduled = true;
12154 process.nextTick(function() {
12155 resume_(stream, state);
12156 });
12157 }
12158}
12159
12160function resume_(stream, state) {
12161 state.resumeScheduled = false;
12162 stream.emit('resume');
12163 flow(stream);
12164 if (state.flowing && !state.reading)
12165 stream.read(0);
12166}
12167
12168Readable.prototype.pause = function() {
12169 debug('call pause flowing=%j', this._readableState.flowing);
12170 if (false !== this._readableState.flowing) {
12171 debug('pause');
12172 this._readableState.flowing = false;
12173 this.emit('pause');
12174 }
12175 return this;
12176};
12177
12178function flow(stream) {
12179 var state = stream._readableState;
12180 debug('flow', state.flowing);
12181 if (state.flowing) {
12182 do {
12183 var chunk = stream.read();
12184 } while (null !== chunk && state.flowing);
12185 }
12186}
12187
12188// wrap an old-style stream as the async data source.
12189// This is *not* part of the readable stream interface.
12190// It is an ugly unfortunate mess of history.
12191Readable.prototype.wrap = function(stream) {
12192 var state = this._readableState;
12193 var paused = false;
12194
12195 var self = this;
12196 stream.on('end', function() {
12197 debug('wrapped end');
12198 if (state.decoder && !state.ended) {
12199 var chunk = state.decoder.end();
12200 if (chunk && chunk.length)
12201 self.push(chunk);
12202 }
12203
12204 self.push(null);
12205 });
12206
12207 stream.on('data', function(chunk) {
12208 debug('wrapped data');
12209 if (state.decoder)
12210 chunk = state.decoder.write(chunk);
12211 if (!chunk || !state.objectMode && !chunk.length)
12212 return;
12213
12214 var ret = self.push(chunk);
12215 if (!ret) {
12216 paused = true;
12217 stream.pause();
12218 }
12219 });
12220
12221 // proxy all the other methods.
12222 // important when wrapping filters and duplexes.
12223 for (var i in stream) {
12224 if (util.isFunction(stream[i]) && util.isUndefined(this[i])) {
12225 this[i] = function(method) { return function() {
12226 return stream[method].apply(stream, arguments);
12227 }}(i);
12228 }
12229 }
12230
12231 // proxy certain important events.
12232 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
12233 forEach(events, function(ev) {
12234 stream.on(ev, self.emit.bind(self, ev));
12235 });
12236
12237 // when we try to consume some more bytes, simply unpause the
12238 // underlying stream.
12239 self._read = function(n) {
12240 debug('wrapped _read', n);
12241 if (paused) {
12242 paused = false;
12243 stream.resume();
12244 }
12245 };
12246
12247 return self;
12248};
12249
12250
12251
12252// exposed for testing purposes only.
12253Readable._fromList = fromList;
12254
12255// Pluck off n bytes from an array of buffers.
12256// Length is the combined lengths of all the buffers in the list.
12257function fromList(n, state) {
12258 var list = state.buffer;
12259 var length = state.length;
12260 var stringMode = !!state.decoder;
12261 var objectMode = !!state.objectMode;
12262 var ret;
12263
12264 // nothing in the list, definitely empty.
12265 if (list.length === 0)
12266 return null;
12267
12268 if (length === 0)
12269 ret = null;
12270 else if (objectMode)
12271 ret = list.shift();
12272 else if (!n || n >= length) {
12273 // read it all, truncate the array.
12274 if (stringMode)
12275 ret = list.join('');
12276 else
12277 ret = Buffer.concat(list, length);
12278 list.length = 0;
12279 } else {
12280 // read just some of it.
12281 if (n < list[0].length) {
12282 // just take a part of the first list item.
12283 // slice is the same for buffers and strings.
12284 var buf = list[0];
12285 ret = buf.slice(0, n);
12286 list[0] = buf.slice(n);
12287 } else if (n === list[0].length) {
12288 // first list is a perfect match
12289 ret = list.shift();
12290 } else {
12291 // complex case.
12292 // we have enough to cover it, but it spans past the first buffer.
12293 if (stringMode)
12294 ret = '';
12295 else
12296 ret = new Buffer(n);
12297
12298 var c = 0;
12299 for (var i = 0, l = list.length; i < l && c < n; i++) {
12300 var buf = list[0];
12301 var cpy = Math.min(n - c, buf.length);
12302
12303 if (stringMode)
12304 ret += buf.slice(0, cpy);
12305 else
12306 buf.copy(ret, c, 0, cpy);
12307
12308 if (cpy < buf.length)
12309 list[0] = buf.slice(cpy);
12310 else
12311 list.shift();
12312
12313 c += cpy;
12314 }
12315 }
12316 }
12317
12318 return ret;
12319}
12320
12321function endReadable(stream) {
12322 var state = stream._readableState;
12323
12324 // If we get here before consuming all the bytes, then that is a
12325 // bug in node. Should never happen.
12326 if (state.length > 0)
12327 throw new Error('endReadable called on non-empty stream');
12328
12329 if (!state.endEmitted) {
12330 state.ended = true;
12331 process.nextTick(function() {
12332 // Check that we didn't get one last unshift.
12333 if (!state.endEmitted && state.length === 0) {
12334 state.endEmitted = true;
12335 stream.readable = false;
12336 stream.emit('end');
12337 }
12338 });
12339 }
12340}
12341
12342function forEach (xs, f) {
12343 for (var i = 0, l = xs.length; i < l; i++) {
12344 f(xs[i], i);
12345 }
12346}
12347
12348function indexOf (xs, x) {
12349 for (var i = 0, l = xs.length; i < l; i++) {
12350 if (xs[i] === x) return i;
12351 }
12352 return -1;
12353}
12354
12355}).call(this)}).call(this,_dereq_(73))
12356},{"11":11,"13":13,"14":14,"26":26,"37":37,"73":73,"75":75,"80":80,"81":81,"85":85}],78:[function(_dereq_,module,exports){
12357// Copyright Joyent, Inc. and other Node contributors.
12358//
12359// Permission is hereby granted, free of charge, to any person obtaining a
12360// copy of this software and associated documentation files (the
12361// "Software"), to deal in the Software without restriction, including
12362// without limitation the rights to use, copy, modify, merge, publish,
12363// distribute, sublicense, and/or sell copies of the Software, and to permit
12364// persons to whom the Software is furnished to do so, subject to the
12365// following conditions:
12366//
12367// The above copyright notice and this permission notice shall be included
12368// in all copies or substantial portions of the Software.
12369//
12370// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12371// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12372// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12373// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12374// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12375// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12376// USE OR OTHER DEALINGS IN THE SOFTWARE.
12377
12378
12379// a transform stream is a readable/writable stream where you do
12380// something with the data. Sometimes it's called a "filter",
12381// but that's not a great name for it, since that implies a thing where
12382// some bits pass through, and others are simply ignored. (That would
12383// be a valid example of a transform, of course.)
12384//
12385// While the output is causally related to the input, it's not a
12386// necessarily symmetric or synchronous transformation. For example,
12387// a zlib stream might take multiple plain-text writes(), and then
12388// emit a single compressed chunk some time in the future.
12389//
12390// Here's how this works:
12391//
12392// The Transform stream has all the aspects of the readable and writable
12393// stream classes. When you write(chunk), that calls _write(chunk,cb)
12394// internally, and returns false if there's a lot of pending writes
12395// buffered up. When you call read(), that calls _read(n) until
12396// there's enough pending readable data buffered up.
12397//
12398// In a transform stream, the written data is placed in a buffer. When
12399// _read(n) is called, it transforms the queued up data, calling the
12400// buffered _write cb's as it consumes chunks. If consuming a single
12401// written chunk would result in multiple output chunks, then the first
12402// outputted bit calls the readcb, and subsequent chunks just go into
12403// the read buffer, and will cause it to emit 'readable' if necessary.
12404//
12405// This way, back-pressure is actually determined by the reading side,
12406// since _read has to be called to start processing a new chunk. However,
12407// a pathological inflate type of transform can cause excessive buffering
12408// here. For example, imagine a stream where every byte of input is
12409// interpreted as an integer from 0-255, and then results in that many
12410// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
12411// 1kb of data being output. In this case, you could write a very small
12412// amount of input, and end up with a very large amount of output. In
12413// such a pathological inflating mechanism, there'd be no way to tell
12414// the system to stop doing the transform. A single 4MB write could
12415// cause the system to run out of memory.
12416//
12417// However, even in such a pathological case, only a single written chunk
12418// would be consumed, and then the rest would wait (un-transformed) until
12419// the results of the previous transformed chunk were consumed.
12420
12421module.exports = Transform;
12422
12423var Duplex = _dereq_(75);
12424
12425/*<replacement>*/
12426var util = _dereq_(14);
12427util.inherits = _dereq_(37);
12428/*</replacement>*/
12429
12430util.inherits(Transform, Duplex);
12431
12432
12433function TransformState(options, stream) {
12434 this.afterTransform = function(er, data) {
12435 return afterTransform(stream, er, data);
12436 };
12437
12438 this.needTransform = false;
12439 this.transforming = false;
12440 this.writecb = null;
12441 this.writechunk = null;
12442}
12443
12444function afterTransform(stream, er, data) {
12445 var ts = stream._transformState;
12446 ts.transforming = false;
12447
12448 var cb = ts.writecb;
12449
12450 if (!cb)
12451 return stream.emit('error', new Error('no writecb in Transform class'));
12452
12453 ts.writechunk = null;
12454 ts.writecb = null;
12455
12456 if (!util.isNullOrUndefined(data))
12457 stream.push(data);
12458
12459 if (cb)
12460 cb(er);
12461
12462 var rs = stream._readableState;
12463 rs.reading = false;
12464 if (rs.needReadable || rs.length < rs.highWaterMark) {
12465 stream._read(rs.highWaterMark);
12466 }
12467}
12468
12469
12470function Transform(options) {
12471 if (!(this instanceof Transform))
12472 return new Transform(options);
12473
12474 Duplex.call(this, options);
12475
12476 this._transformState = new TransformState(options, this);
12477
12478 // when the writable side finishes, then flush out anything remaining.
12479 var stream = this;
12480
12481 // start out asking for a readable event once data is transformed.
12482 this._readableState.needReadable = true;
12483
12484 // we have implemented the _read method, and done the other things
12485 // that Readable wants before the first _read call, so unset the
12486 // sync guard flag.
12487 this._readableState.sync = false;
12488
12489 this.once('prefinish', function() {
12490 if (util.isFunction(this._flush))
12491 this._flush(function(er) {
12492 done(stream, er);
12493 });
12494 else
12495 done(stream);
12496 });
12497}
12498
12499Transform.prototype.push = function(chunk, encoding) {
12500 this._transformState.needTransform = false;
12501 return Duplex.prototype.push.call(this, chunk, encoding);
12502};
12503
12504// This is the part where you do stuff!
12505// override this function in implementation classes.
12506// 'chunk' is an input chunk.
12507//
12508// Call `push(newChunk)` to pass along transformed output
12509// to the readable side. You may call 'push' zero or more times.
12510//
12511// Call `cb(err)` when you are done with this chunk. If you pass
12512// an error, then that'll put the hurt on the whole operation. If you
12513// never call cb(), then you'll never get another chunk.
12514Transform.prototype._transform = function(chunk, encoding, cb) {
12515 throw new Error('not implemented');
12516};
12517
12518Transform.prototype._write = function(chunk, encoding, cb) {
12519 var ts = this._transformState;
12520 ts.writecb = cb;
12521 ts.writechunk = chunk;
12522 ts.writeencoding = encoding;
12523 if (!ts.transforming) {
12524 var rs = this._readableState;
12525 if (ts.needTransform ||
12526 rs.needReadable ||
12527 rs.length < rs.highWaterMark)
12528 this._read(rs.highWaterMark);
12529 }
12530};
12531
12532// Doesn't matter what the args are here.
12533// _transform does all the work.
12534// That we got here means that the readable side wants more data.
12535Transform.prototype._read = function(n) {
12536 var ts = this._transformState;
12537
12538 if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) {
12539 ts.transforming = true;
12540 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
12541 } else {
12542 // mark that we need a transform, so that any data that comes in
12543 // will get processed, now that we've asked for it.
12544 ts.needTransform = true;
12545 }
12546};
12547
12548
12549function done(stream, er) {
12550 if (er)
12551 return stream.emit('error', er);
12552
12553 // if there's nothing in the write buffer, then that means
12554 // that nothing more will ever be provided
12555 var ws = stream._writableState;
12556 var ts = stream._transformState;
12557
12558 if (ws.length)
12559 throw new Error('calling transform done when ws.length != 0');
12560
12561 if (ts.transforming)
12562 throw new Error('calling transform done when still transforming');
12563
12564 return stream.push(null);
12565}
12566
12567},{"14":14,"37":37,"75":75}],79:[function(_dereq_,module,exports){
12568(function (process){(function (){
12569// Copyright Joyent, Inc. and other Node contributors.
12570//
12571// Permission is hereby granted, free of charge, to any person obtaining a
12572// copy of this software and associated documentation files (the
12573// "Software"), to deal in the Software without restriction, including
12574// without limitation the rights to use, copy, modify, merge, publish,
12575// distribute, sublicense, and/or sell copies of the Software, and to permit
12576// persons to whom the Software is furnished to do so, subject to the
12577// following conditions:
12578//
12579// The above copyright notice and this permission notice shall be included
12580// in all copies or substantial portions of the Software.
12581//
12582// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12583// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12584// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12585// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12586// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12587// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12588// USE OR OTHER DEALINGS IN THE SOFTWARE.
12589
12590// A bit simpler than readable streams.
12591// Implement an async ._write(chunk, cb), and it'll handle all
12592// the drain event emission and buffering.
12593
12594module.exports = Writable;
12595
12596/*<replacement>*/
12597var Buffer = _dereq_(13).Buffer;
12598/*</replacement>*/
12599
12600Writable.WritableState = WritableState;
12601
12602
12603/*<replacement>*/
12604var util = _dereq_(14);
12605util.inherits = _dereq_(37);
12606/*</replacement>*/
12607
12608var Stream = _dereq_(85);
12609
12610util.inherits(Writable, Stream);
12611
12612function WriteReq(chunk, encoding, cb) {
12613 this.chunk = chunk;
12614 this.encoding = encoding;
12615 this.callback = cb;
12616}
12617
12618function WritableState(options, stream) {
12619 var Duplex = _dereq_(75);
12620
12621 options = options || {};
12622
12623 // the point at which write() starts returning false
12624 // Note: 0 is a valid value, means that we always return false if
12625 // the entire buffer is not flushed immediately on write()
12626 var hwm = options.highWaterMark;
12627 var defaultHwm = options.objectMode ? 16 : 16 * 1024;
12628 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
12629
12630 // object stream flag to indicate whether or not this stream
12631 // contains buffers or objects.
12632 this.objectMode = !!options.objectMode;
12633
12634 if (stream instanceof Duplex)
12635 this.objectMode = this.objectMode || !!options.writableObjectMode;
12636
12637 // cast to ints.
12638 this.highWaterMark = ~~this.highWaterMark;
12639
12640 this.needDrain = false;
12641 // at the start of calling end()
12642 this.ending = false;
12643 // when end() has been called, and returned
12644 this.ended = false;
12645 // when 'finish' is emitted
12646 this.finished = false;
12647
12648 // should we decode strings into buffers before passing to _write?
12649 // this is here so that some node-core streams can optimize string
12650 // handling at a lower level.
12651 var noDecode = options.decodeStrings === false;
12652 this.decodeStrings = !noDecode;
12653
12654 // Crypto is kind of old and crusty. Historically, its default string
12655 // encoding is 'binary' so we have to make this configurable.
12656 // Everything else in the universe uses 'utf8', though.
12657 this.defaultEncoding = options.defaultEncoding || 'utf8';
12658
12659 // not an actual buffer we keep track of, but a measurement
12660 // of how much we're waiting to get pushed to some underlying
12661 // socket or file.
12662 this.length = 0;
12663
12664 // a flag to see when we're in the middle of a write.
12665 this.writing = false;
12666
12667 // when true all writes will be buffered until .uncork() call
12668 this.corked = 0;
12669
12670 // a flag to be able to tell if the onwrite cb is called immediately,
12671 // or on a later tick. We set this to true at first, because any
12672 // actions that shouldn't happen until "later" should generally also
12673 // not happen before the first write call.
12674 this.sync = true;
12675
12676 // a flag to know if we're processing previously buffered items, which
12677 // may call the _write() callback in the same tick, so that we don't
12678 // end up in an overlapped onwrite situation.
12679 this.bufferProcessing = false;
12680
12681 // the callback that's passed to _write(chunk,cb)
12682 this.onwrite = function(er) {
12683 onwrite(stream, er);
12684 };
12685
12686 // the callback that the user supplies to write(chunk,encoding,cb)
12687 this.writecb = null;
12688
12689 // the amount that is being written when _write is called.
12690 this.writelen = 0;
12691
12692 this.buffer = [];
12693
12694 // number of pending user-supplied write callbacks
12695 // this must be 0 before 'finish' can be emitted
12696 this.pendingcb = 0;
12697
12698 // emit prefinish if the only thing we're waiting for is _write cbs
12699 // This is relevant for synchronous Transform streams
12700 this.prefinished = false;
12701
12702 // True if the error was already emitted and should not be thrown again
12703 this.errorEmitted = false;
12704}
12705
12706function Writable(options) {
12707 var Duplex = _dereq_(75);
12708
12709 // Writable ctor is applied to Duplexes, though they're not
12710 // instanceof Writable, they're instanceof Readable.
12711 if (!(this instanceof Writable) && !(this instanceof Duplex))
12712 return new Writable(options);
12713
12714 this._writableState = new WritableState(options, this);
12715
12716 // legacy.
12717 this.writable = true;
12718
12719 Stream.call(this);
12720}
12721
12722// Otherwise people can pipe Writable streams, which is just wrong.
12723Writable.prototype.pipe = function() {
12724 this.emit('error', new Error('Cannot pipe. Not readable.'));
12725};
12726
12727
12728function writeAfterEnd(stream, state, cb) {
12729 var er = new Error('write after end');
12730 // TODO: defer error events consistently everywhere, not just the cb
12731 stream.emit('error', er);
12732 process.nextTick(function() {
12733 cb(er);
12734 });
12735}
12736
12737// If we get something that is not a buffer, string, null, or undefined,
12738// and we're not in objectMode, then that's an error.
12739// Otherwise stream chunks are all considered to be of length=1, and the
12740// watermarks determine how many objects to keep in the buffer, rather than
12741// how many bytes or characters.
12742function validChunk(stream, state, chunk, cb) {
12743 var valid = true;
12744 if (!util.isBuffer(chunk) &&
12745 !util.isString(chunk) &&
12746 !util.isNullOrUndefined(chunk) &&
12747 !state.objectMode) {
12748 var er = new TypeError('Invalid non-string/buffer chunk');
12749 stream.emit('error', er);
12750 process.nextTick(function() {
12751 cb(er);
12752 });
12753 valid = false;
12754 }
12755 return valid;
12756}
12757
12758Writable.prototype.write = function(chunk, encoding, cb) {
12759 var state = this._writableState;
12760 var ret = false;
12761
12762 if (util.isFunction(encoding)) {
12763 cb = encoding;
12764 encoding = null;
12765 }
12766
12767 if (util.isBuffer(chunk))
12768 encoding = 'buffer';
12769 else if (!encoding)
12770 encoding = state.defaultEncoding;
12771
12772 if (!util.isFunction(cb))
12773 cb = function() {};
12774
12775 if (state.ended)
12776 writeAfterEnd(this, state, cb);
12777 else if (validChunk(this, state, chunk, cb)) {
12778 state.pendingcb++;
12779 ret = writeOrBuffer(this, state, chunk, encoding, cb);
12780 }
12781
12782 return ret;
12783};
12784
12785Writable.prototype.cork = function() {
12786 var state = this._writableState;
12787
12788 state.corked++;
12789};
12790
12791Writable.prototype.uncork = function() {
12792 var state = this._writableState;
12793
12794 if (state.corked) {
12795 state.corked--;
12796
12797 if (!state.writing &&
12798 !state.corked &&
12799 !state.finished &&
12800 !state.bufferProcessing &&
12801 state.buffer.length)
12802 clearBuffer(this, state);
12803 }
12804};
12805
12806function decodeChunk(state, chunk, encoding) {
12807 if (!state.objectMode &&
12808 state.decodeStrings !== false &&
12809 util.isString(chunk)) {
12810 chunk = new Buffer(chunk, encoding);
12811 }
12812 return chunk;
12813}
12814
12815// if we're already writing something, then just put this
12816// in the queue, and wait our turn. Otherwise, call _write
12817// If we return false, then we need a drain event, so set that flag.
12818function writeOrBuffer(stream, state, chunk, encoding, cb) {
12819 chunk = decodeChunk(state, chunk, encoding);
12820 if (util.isBuffer(chunk))
12821 encoding = 'buffer';
12822 var len = state.objectMode ? 1 : chunk.length;
12823
12824 state.length += len;
12825
12826 var ret = state.length < state.highWaterMark;
12827 // we must ensure that previous needDrain will not be reset to false.
12828 if (!ret)
12829 state.needDrain = true;
12830
12831 if (state.writing || state.corked)
12832 state.buffer.push(new WriteReq(chunk, encoding, cb));
12833 else
12834 doWrite(stream, state, false, len, chunk, encoding, cb);
12835
12836 return ret;
12837}
12838
12839function doWrite(stream, state, writev, len, chunk, encoding, cb) {
12840 state.writelen = len;
12841 state.writecb = cb;
12842 state.writing = true;
12843 state.sync = true;
12844 if (writev)
12845 stream._writev(chunk, state.onwrite);
12846 else
12847 stream._write(chunk, encoding, state.onwrite);
12848 state.sync = false;
12849}
12850
12851function onwriteError(stream, state, sync, er, cb) {
12852 if (sync)
12853 process.nextTick(function() {
12854 state.pendingcb--;
12855 cb(er);
12856 });
12857 else {
12858 state.pendingcb--;
12859 cb(er);
12860 }
12861
12862 stream._writableState.errorEmitted = true;
12863 stream.emit('error', er);
12864}
12865
12866function onwriteStateUpdate(state) {
12867 state.writing = false;
12868 state.writecb = null;
12869 state.length -= state.writelen;
12870 state.writelen = 0;
12871}
12872
12873function onwrite(stream, er) {
12874 var state = stream._writableState;
12875 var sync = state.sync;
12876 var cb = state.writecb;
12877
12878 onwriteStateUpdate(state);
12879
12880 if (er)
12881 onwriteError(stream, state, sync, er, cb);
12882 else {
12883 // Check if we're actually ready to finish, but don't emit yet
12884 var finished = needFinish(stream, state);
12885
12886 if (!finished &&
12887 !state.corked &&
12888 !state.bufferProcessing &&
12889 state.buffer.length) {
12890 clearBuffer(stream, state);
12891 }
12892
12893 if (sync) {
12894 process.nextTick(function() {
12895 afterWrite(stream, state, finished, cb);
12896 });
12897 } else {
12898 afterWrite(stream, state, finished, cb);
12899 }
12900 }
12901}
12902
12903function afterWrite(stream, state, finished, cb) {
12904 if (!finished)
12905 onwriteDrain(stream, state);
12906 state.pendingcb--;
12907 cb();
12908 finishMaybe(stream, state);
12909}
12910
12911// Must force callback to be called on nextTick, so that we don't
12912// emit 'drain' before the write() consumer gets the 'false' return
12913// value, and has a chance to attach a 'drain' listener.
12914function onwriteDrain(stream, state) {
12915 if (state.length === 0 && state.needDrain) {
12916 state.needDrain = false;
12917 stream.emit('drain');
12918 }
12919}
12920
12921
12922// if there's something in the buffer waiting, then process it
12923function clearBuffer(stream, state) {
12924 state.bufferProcessing = true;
12925
12926 if (stream._writev && state.buffer.length > 1) {
12927 // Fast case, write everything using _writev()
12928 var cbs = [];
12929 for (var c = 0; c < state.buffer.length; c++)
12930 cbs.push(state.buffer[c].callback);
12931
12932 // count the one we are adding, as well.
12933 // TODO(isaacs) clean this up
12934 state.pendingcb++;
12935 doWrite(stream, state, true, state.length, state.buffer, '', function(err) {
12936 for (var i = 0; i < cbs.length; i++) {
12937 state.pendingcb--;
12938 cbs[i](err);
12939 }
12940 });
12941
12942 // Clear buffer
12943 state.buffer = [];
12944 } else {
12945 // Slow case, write chunks one-by-one
12946 for (var c = 0; c < state.buffer.length; c++) {
12947 var entry = state.buffer[c];
12948 var chunk = entry.chunk;
12949 var encoding = entry.encoding;
12950 var cb = entry.callback;
12951 var len = state.objectMode ? 1 : chunk.length;
12952
12953 doWrite(stream, state, false, len, chunk, encoding, cb);
12954
12955 // if we didn't call the onwrite immediately, then
12956 // it means that we need to wait until it does.
12957 // also, that means that the chunk and cb are currently
12958 // being processed, so move the buffer counter past them.
12959 if (state.writing) {
12960 c++;
12961 break;
12962 }
12963 }
12964
12965 if (c < state.buffer.length)
12966 state.buffer = state.buffer.slice(c);
12967 else
12968 state.buffer.length = 0;
12969 }
12970
12971 state.bufferProcessing = false;
12972}
12973
12974Writable.prototype._write = function(chunk, encoding, cb) {
12975 cb(new Error('not implemented'));
12976
12977};
12978
12979Writable.prototype._writev = null;
12980
12981Writable.prototype.end = function(chunk, encoding, cb) {
12982 var state = this._writableState;
12983
12984 if (util.isFunction(chunk)) {
12985 cb = chunk;
12986 chunk = null;
12987 encoding = null;
12988 } else if (util.isFunction(encoding)) {
12989 cb = encoding;
12990 encoding = null;
12991 }
12992
12993 if (!util.isNullOrUndefined(chunk))
12994 this.write(chunk, encoding);
12995
12996 // .end() fully uncorks
12997 if (state.corked) {
12998 state.corked = 1;
12999 this.uncork();
13000 }
13001
13002 // ignore unnecessary end() calls.
13003 if (!state.ending && !state.finished)
13004 endWritable(this, state, cb);
13005};
13006
13007
13008function needFinish(stream, state) {
13009 return (state.ending &&
13010 state.length === 0 &&
13011 !state.finished &&
13012 !state.writing);
13013}
13014
13015function prefinish(stream, state) {
13016 if (!state.prefinished) {
13017 state.prefinished = true;
13018 stream.emit('prefinish');
13019 }
13020}
13021
13022function finishMaybe(stream, state) {
13023 var need = needFinish(stream, state);
13024 if (need) {
13025 if (state.pendingcb === 0) {
13026 prefinish(stream, state);
13027 state.finished = true;
13028 stream.emit('finish');
13029 } else
13030 prefinish(stream, state);
13031 }
13032 return need;
13033}
13034
13035function endWritable(stream, state, cb) {
13036 state.ending = true;
13037 finishMaybe(stream, state);
13038 if (cb) {
13039 if (state.finished)
13040 process.nextTick(cb);
13041 else
13042 stream.once('finish', cb);
13043 }
13044 state.ended = true;
13045}
13046
13047}).call(this)}).call(this,_dereq_(73))
13048},{"13":13,"14":14,"37":37,"73":73,"75":75,"85":85}],80:[function(_dereq_,module,exports){
13049module.exports = Array.isArray || function (arr) {
13050 return Object.prototype.toString.call(arr) == '[object Array]';
13051};
13052
13053},{}],81:[function(_dereq_,module,exports){
13054// Copyright Joyent, Inc. and other Node contributors.
13055//
13056// Permission is hereby granted, free of charge, to any person obtaining a
13057// copy of this software and associated documentation files (the
13058// "Software"), to deal in the Software without restriction, including
13059// without limitation the rights to use, copy, modify, merge, publish,
13060// distribute, sublicense, and/or sell copies of the Software, and to permit
13061// persons to whom the Software is furnished to do so, subject to the
13062// following conditions:
13063//
13064// The above copyright notice and this permission notice shall be included
13065// in all copies or substantial portions of the Software.
13066//
13067// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13068// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13069// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13070// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13071// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13072// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13073// USE OR OTHER DEALINGS IN THE SOFTWARE.
13074
13075var Buffer = _dereq_(13).Buffer;
13076
13077var isBufferEncoding = Buffer.isEncoding
13078 || function(encoding) {
13079 switch (encoding && encoding.toLowerCase()) {
13080 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;
13081 default: return false;
13082 }
13083 }
13084
13085
13086function assertEncoding(encoding) {
13087 if (encoding && !isBufferEncoding(encoding)) {
13088 throw new Error('Unknown encoding: ' + encoding);
13089 }
13090}
13091
13092// StringDecoder provides an interface for efficiently splitting a series of
13093// buffers into a series of JS strings without breaking apart multi-byte
13094// characters. CESU-8 is handled as part of the UTF-8 encoding.
13095//
13096// @TODO Handling all encodings inside a single object makes it very difficult
13097// to reason about this code, so it should be split up in the future.
13098// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
13099// points as used by CESU-8.
13100var StringDecoder = exports.StringDecoder = function(encoding) {
13101 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
13102 assertEncoding(encoding);
13103 switch (this.encoding) {
13104 case 'utf8':
13105 // CESU-8 represents each of Surrogate Pair by 3-bytes
13106 this.surrogateSize = 3;
13107 break;
13108 case 'ucs2':
13109 case 'utf16le':
13110 // UTF-16 represents each of Surrogate Pair by 2-bytes
13111 this.surrogateSize = 2;
13112 this.detectIncompleteChar = utf16DetectIncompleteChar;
13113 break;
13114 case 'base64':
13115 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
13116 this.surrogateSize = 3;
13117 this.detectIncompleteChar = base64DetectIncompleteChar;
13118 break;
13119 default:
13120 this.write = passThroughWrite;
13121 return;
13122 }
13123
13124 // Enough space to store all bytes of a single character. UTF-8 needs 4
13125 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
13126 this.charBuffer = new Buffer(6);
13127 // Number of bytes received for the current incomplete multi-byte character.
13128 this.charReceived = 0;
13129 // Number of bytes expected for the current incomplete multi-byte character.
13130 this.charLength = 0;
13131};
13132
13133
13134// write decodes the given buffer and returns it as JS string that is
13135// guaranteed to not contain any partial multi-byte characters. Any partial
13136// character found at the end of the buffer is buffered up, and will be
13137// returned when calling write again with the remaining bytes.
13138//
13139// Note: Converting a Buffer containing an orphan surrogate to a String
13140// currently works, but converting a String to a Buffer (via `new Buffer`, or
13141// Buffer#write) will replace incomplete surrogates with the unicode
13142// replacement character. See https://codereview.chromium.org/121173009/ .
13143StringDecoder.prototype.write = function(buffer) {
13144 var charStr = '';
13145 // if our last write ended with an incomplete multibyte character
13146 while (this.charLength) {
13147 // determine how many remaining bytes this buffer has to offer for this char
13148 var available = (buffer.length >= this.charLength - this.charReceived) ?
13149 this.charLength - this.charReceived :
13150 buffer.length;
13151
13152 // add the new bytes to the char buffer
13153 buffer.copy(this.charBuffer, this.charReceived, 0, available);
13154 this.charReceived += available;
13155
13156 if (this.charReceived < this.charLength) {
13157 // still not enough chars in this buffer? wait for more ...
13158 return '';
13159 }
13160
13161 // remove bytes belonging to the current character from the buffer
13162 buffer = buffer.slice(available, buffer.length);
13163
13164 // get the character that was split
13165 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
13166
13167 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
13168 var charCode = charStr.charCodeAt(charStr.length - 1);
13169 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
13170 this.charLength += this.surrogateSize;
13171 charStr = '';
13172 continue;
13173 }
13174 this.charReceived = this.charLength = 0;
13175
13176 // if there are no more bytes in this buffer, just emit our char
13177 if (buffer.length === 0) {
13178 return charStr;
13179 }
13180 break;
13181 }
13182
13183 // determine and set charLength / charReceived
13184 this.detectIncompleteChar(buffer);
13185
13186 var end = buffer.length;
13187 if (this.charLength) {
13188 // buffer the incomplete character bytes we got
13189 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
13190 end -= this.charReceived;
13191 }
13192
13193 charStr += buffer.toString(this.encoding, 0, end);
13194
13195 var end = charStr.length - 1;
13196 var charCode = charStr.charCodeAt(end);
13197 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
13198 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
13199 var size = this.surrogateSize;
13200 this.charLength += size;
13201 this.charReceived += size;
13202 this.charBuffer.copy(this.charBuffer, size, 0, size);
13203 buffer.copy(this.charBuffer, 0, 0, size);
13204 return charStr.substring(0, end);
13205 }
13206
13207 // or just emit the charStr
13208 return charStr;
13209};
13210
13211// detectIncompleteChar determines if there is an incomplete UTF-8 character at
13212// the end of the given buffer. If so, it sets this.charLength to the byte
13213// length that character, and sets this.charReceived to the number of bytes
13214// that are available for this character.
13215StringDecoder.prototype.detectIncompleteChar = function(buffer) {
13216 // determine how many bytes we have to check at the end of this buffer
13217 var i = (buffer.length >= 3) ? 3 : buffer.length;
13218
13219 // Figure out if one of the last i bytes of our buffer announces an
13220 // incomplete char.
13221 for (; i > 0; i--) {
13222 var c = buffer[buffer.length - i];
13223
13224 // See http://en.wikipedia.org/wiki/UTF-8#Description
13225
13226 // 110XXXXX
13227 if (i == 1 && c >> 5 == 0x06) {
13228 this.charLength = 2;
13229 break;
13230 }
13231
13232 // 1110XXXX
13233 if (i <= 2 && c >> 4 == 0x0E) {
13234 this.charLength = 3;
13235 break;
13236 }
13237
13238 // 11110XXX
13239 if (i <= 3 && c >> 3 == 0x1E) {
13240 this.charLength = 4;
13241 break;
13242 }
13243 }
13244 this.charReceived = i;
13245};
13246
13247StringDecoder.prototype.end = function(buffer) {
13248 var res = '';
13249 if (buffer && buffer.length)
13250 res = this.write(buffer);
13251
13252 if (this.charReceived) {
13253 var cr = this.charReceived;
13254 var buf = this.charBuffer;
13255 var enc = this.encoding;
13256 res += buf.slice(0, cr).toString(enc);
13257 }
13258
13259 return res;
13260};
13261
13262function passThroughWrite(buffer) {
13263 return buffer.toString(this.encoding);
13264}
13265
13266function utf16DetectIncompleteChar(buffer) {
13267 this.charReceived = buffer.length % 2;
13268 this.charLength = this.charReceived ? 2 : 0;
13269}
13270
13271function base64DetectIncompleteChar(buffer) {
13272 this.charReceived = buffer.length % 3;
13273 this.charLength = this.charReceived ? 3 : 0;
13274}
13275
13276},{"13":13}],82:[function(_dereq_,module,exports){
13277(function (process){(function (){
13278exports = module.exports = _dereq_(77);
13279exports.Stream = _dereq_(85);
13280exports.Readable = exports;
13281exports.Writable = _dereq_(79);
13282exports.Duplex = _dereq_(75);
13283exports.Transform = _dereq_(78);
13284exports.PassThrough = _dereq_(76);
13285if (!process.browser && process.env.READABLE_STREAM === 'disable') {
13286 module.exports = _dereq_(85);
13287}
13288
13289}).call(this)}).call(this,_dereq_(73))
13290},{"73":73,"75":75,"76":76,"77":77,"78":78,"79":79,"85":85}],83:[function(_dereq_,module,exports){
13291/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
13292/* eslint-disable node/no-deprecated-api */
13293var buffer = _dereq_(13)
13294var Buffer = buffer.Buffer
13295
13296// alternative to using Object.keys for old browsers
13297function copyProps (src, dst) {
13298 for (var key in src) {
13299 dst[key] = src[key]
13300 }
13301}
13302if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
13303 module.exports = buffer
13304} else {
13305 // Copy properties from require('buffer')
13306 copyProps(buffer, exports)
13307 exports.Buffer = SafeBuffer
13308}
13309
13310function SafeBuffer (arg, encodingOrOffset, length) {
13311 return Buffer(arg, encodingOrOffset, length)
13312}
13313
13314SafeBuffer.prototype = Object.create(Buffer.prototype)
13315
13316// Copy static methods from Buffer
13317copyProps(Buffer, SafeBuffer)
13318
13319SafeBuffer.from = function (arg, encodingOrOffset, length) {
13320 if (typeof arg === 'number') {
13321 throw new TypeError('Argument must not be a number')
13322 }
13323 return Buffer(arg, encodingOrOffset, length)
13324}
13325
13326SafeBuffer.alloc = function (size, fill, encoding) {
13327 if (typeof size !== 'number') {
13328 throw new TypeError('Argument must be a number')
13329 }
13330 var buf = Buffer(size)
13331 if (fill !== undefined) {
13332 if (typeof encoding === 'string') {
13333 buf.fill(fill, encoding)
13334 } else {
13335 buf.fill(fill)
13336 }
13337 } else {
13338 buf.fill(0)
13339 }
13340 return buf
13341}
13342
13343SafeBuffer.allocUnsafe = function (size) {
13344 if (typeof size !== 'number') {
13345 throw new TypeError('Argument must be a number')
13346 }
13347 return Buffer(size)
13348}
13349
13350SafeBuffer.allocUnsafeSlow = function (size) {
13351 if (typeof size !== 'number') {
13352 throw new TypeError('Argument must be a number')
13353 }
13354 return buffer.SlowBuffer(size)
13355}
13356
13357},{"13":13}],84:[function(_dereq_,module,exports){
13358(function (factory) {
13359 if (typeof exports === 'object') {
13360 // Node/CommonJS
13361 module.exports = factory();
13362 } else if (typeof define === 'function' && define.amd) {
13363 // AMD
13364 define(factory);
13365 } else {
13366 // Browser globals (with support for web workers)
13367 var glob;
13368
13369 try {
13370 glob = window;
13371 } catch (e) {
13372 glob = self;
13373 }
13374
13375 glob.SparkMD5 = factory();
13376 }
13377}(function (undefined) {
13378
13379 'use strict';
13380
13381 /*
13382 * Fastest md5 implementation around (JKM md5).
13383 * Credits: Joseph Myers
13384 *
13385 * @see http://www.myersdaily.org/joseph/javascript/md5-text.html
13386 * @see http://jsperf.com/md5-shootout/7
13387 */
13388
13389 /* this function is much faster,
13390 so if possible we use it. Some IEs
13391 are the only ones I know of that
13392 need the idiotic second function,
13393 generated by an if clause. */
13394 var add32 = function (a, b) {
13395 return (a + b) & 0xFFFFFFFF;
13396 },
13397 hex_chr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
13398
13399
13400 function cmn(q, a, b, x, s, t) {
13401 a = add32(add32(a, q), add32(x, t));
13402 return add32((a << s) | (a >>> (32 - s)), b);
13403 }
13404
13405 function md5cycle(x, k) {
13406 var a = x[0],
13407 b = x[1],
13408 c = x[2],
13409 d = x[3];
13410
13411 a += (b & c | ~b & d) + k[0] - 680876936 | 0;
13412 a = (a << 7 | a >>> 25) + b | 0;
13413 d += (a & b | ~a & c) + k[1] - 389564586 | 0;
13414 d = (d << 12 | d >>> 20) + a | 0;
13415 c += (d & a | ~d & b) + k[2] + 606105819 | 0;
13416 c = (c << 17 | c >>> 15) + d | 0;
13417 b += (c & d | ~c & a) + k[3] - 1044525330 | 0;
13418 b = (b << 22 | b >>> 10) + c | 0;
13419 a += (b & c | ~b & d) + k[4] - 176418897 | 0;
13420 a = (a << 7 | a >>> 25) + b | 0;
13421 d += (a & b | ~a & c) + k[5] + 1200080426 | 0;
13422 d = (d << 12 | d >>> 20) + a | 0;
13423 c += (d & a | ~d & b) + k[6] - 1473231341 | 0;
13424 c = (c << 17 | c >>> 15) + d | 0;
13425 b += (c & d | ~c & a) + k[7] - 45705983 | 0;
13426 b = (b << 22 | b >>> 10) + c | 0;
13427 a += (b & c | ~b & d) + k[8] + 1770035416 | 0;
13428 a = (a << 7 | a >>> 25) + b | 0;
13429 d += (a & b | ~a & c) + k[9] - 1958414417 | 0;
13430 d = (d << 12 | d >>> 20) + a | 0;
13431 c += (d & a | ~d & b) + k[10] - 42063 | 0;
13432 c = (c << 17 | c >>> 15) + d | 0;
13433 b += (c & d | ~c & a) + k[11] - 1990404162 | 0;
13434 b = (b << 22 | b >>> 10) + c | 0;
13435 a += (b & c | ~b & d) + k[12] + 1804603682 | 0;
13436 a = (a << 7 | a >>> 25) + b | 0;
13437 d += (a & b | ~a & c) + k[13] - 40341101 | 0;
13438 d = (d << 12 | d >>> 20) + a | 0;
13439 c += (d & a | ~d & b) + k[14] - 1502002290 | 0;
13440 c = (c << 17 | c >>> 15) + d | 0;
13441 b += (c & d | ~c & a) + k[15] + 1236535329 | 0;
13442 b = (b << 22 | b >>> 10) + c | 0;
13443
13444 a += (b & d | c & ~d) + k[1] - 165796510 | 0;
13445 a = (a << 5 | a >>> 27) + b | 0;
13446 d += (a & c | b & ~c) + k[6] - 1069501632 | 0;
13447 d = (d << 9 | d >>> 23) + a | 0;
13448 c += (d & b | a & ~b) + k[11] + 643717713 | 0;
13449 c = (c << 14 | c >>> 18) + d | 0;
13450 b += (c & a | d & ~a) + k[0] - 373897302 | 0;
13451 b = (b << 20 | b >>> 12) + c | 0;
13452 a += (b & d | c & ~d) + k[5] - 701558691 | 0;
13453 a = (a << 5 | a >>> 27) + b | 0;
13454 d += (a & c | b & ~c) + k[10] + 38016083 | 0;
13455 d = (d << 9 | d >>> 23) + a | 0;
13456 c += (d & b | a & ~b) + k[15] - 660478335 | 0;
13457 c = (c << 14 | c >>> 18) + d | 0;
13458 b += (c & a | d & ~a) + k[4] - 405537848 | 0;
13459 b = (b << 20 | b >>> 12) + c | 0;
13460 a += (b & d | c & ~d) + k[9] + 568446438 | 0;
13461 a = (a << 5 | a >>> 27) + b | 0;
13462 d += (a & c | b & ~c) + k[14] - 1019803690 | 0;
13463 d = (d << 9 | d >>> 23) + a | 0;
13464 c += (d & b | a & ~b) + k[3] - 187363961 | 0;
13465 c = (c << 14 | c >>> 18) + d | 0;
13466 b += (c & a | d & ~a) + k[8] + 1163531501 | 0;
13467 b = (b << 20 | b >>> 12) + c | 0;
13468 a += (b & d | c & ~d) + k[13] - 1444681467 | 0;
13469 a = (a << 5 | a >>> 27) + b | 0;
13470 d += (a & c | b & ~c) + k[2] - 51403784 | 0;
13471 d = (d << 9 | d >>> 23) + a | 0;
13472 c += (d & b | a & ~b) + k[7] + 1735328473 | 0;
13473 c = (c << 14 | c >>> 18) + d | 0;
13474 b += (c & a | d & ~a) + k[12] - 1926607734 | 0;
13475 b = (b << 20 | b >>> 12) + c | 0;
13476
13477 a += (b ^ c ^ d) + k[5] - 378558 | 0;
13478 a = (a << 4 | a >>> 28) + b | 0;
13479 d += (a ^ b ^ c) + k[8] - 2022574463 | 0;
13480 d = (d << 11 | d >>> 21) + a | 0;
13481 c += (d ^ a ^ b) + k[11] + 1839030562 | 0;
13482 c = (c << 16 | c >>> 16) + d | 0;
13483 b += (c ^ d ^ a) + k[14] - 35309556 | 0;
13484 b = (b << 23 | b >>> 9) + c | 0;
13485 a += (b ^ c ^ d) + k[1] - 1530992060 | 0;
13486 a = (a << 4 | a >>> 28) + b | 0;
13487 d += (a ^ b ^ c) + k[4] + 1272893353 | 0;
13488 d = (d << 11 | d >>> 21) + a | 0;
13489 c += (d ^ a ^ b) + k[7] - 155497632 | 0;
13490 c = (c << 16 | c >>> 16) + d | 0;
13491 b += (c ^ d ^ a) + k[10] - 1094730640 | 0;
13492 b = (b << 23 | b >>> 9) + c | 0;
13493 a += (b ^ c ^ d) + k[13] + 681279174 | 0;
13494 a = (a << 4 | a >>> 28) + b | 0;
13495 d += (a ^ b ^ c) + k[0] - 358537222 | 0;
13496 d = (d << 11 | d >>> 21) + a | 0;
13497 c += (d ^ a ^ b) + k[3] - 722521979 | 0;
13498 c = (c << 16 | c >>> 16) + d | 0;
13499 b += (c ^ d ^ a) + k[6] + 76029189 | 0;
13500 b = (b << 23 | b >>> 9) + c | 0;
13501 a += (b ^ c ^ d) + k[9] - 640364487 | 0;
13502 a = (a << 4 | a >>> 28) + b | 0;
13503 d += (a ^ b ^ c) + k[12] - 421815835 | 0;
13504 d = (d << 11 | d >>> 21) + a | 0;
13505 c += (d ^ a ^ b) + k[15] + 530742520 | 0;
13506 c = (c << 16 | c >>> 16) + d | 0;
13507 b += (c ^ d ^ a) + k[2] - 995338651 | 0;
13508 b = (b << 23 | b >>> 9) + c | 0;
13509
13510 a += (c ^ (b | ~d)) + k[0] - 198630844 | 0;
13511 a = (a << 6 | a >>> 26) + b | 0;
13512 d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0;
13513 d = (d << 10 | d >>> 22) + a | 0;
13514 c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0;
13515 c = (c << 15 | c >>> 17) + d | 0;
13516 b += (d ^ (c | ~a)) + k[5] - 57434055 | 0;
13517 b = (b << 21 |b >>> 11) + c | 0;
13518 a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0;
13519 a = (a << 6 | a >>> 26) + b | 0;
13520 d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0;
13521 d = (d << 10 | d >>> 22) + a | 0;
13522 c += (a ^ (d | ~b)) + k[10] - 1051523 | 0;
13523 c = (c << 15 | c >>> 17) + d | 0;
13524 b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0;
13525 b = (b << 21 |b >>> 11) + c | 0;
13526 a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0;
13527 a = (a << 6 | a >>> 26) + b | 0;
13528 d += (b ^ (a | ~c)) + k[15] - 30611744 | 0;
13529 d = (d << 10 | d >>> 22) + a | 0;
13530 c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0;
13531 c = (c << 15 | c >>> 17) + d | 0;
13532 b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0;
13533 b = (b << 21 |b >>> 11) + c | 0;
13534 a += (c ^ (b | ~d)) + k[4] - 145523070 | 0;
13535 a = (a << 6 | a >>> 26) + b | 0;
13536 d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0;
13537 d = (d << 10 | d >>> 22) + a | 0;
13538 c += (a ^ (d | ~b)) + k[2] + 718787259 | 0;
13539 c = (c << 15 | c >>> 17) + d | 0;
13540 b += (d ^ (c | ~a)) + k[9] - 343485551 | 0;
13541 b = (b << 21 | b >>> 11) + c | 0;
13542
13543 x[0] = a + x[0] | 0;
13544 x[1] = b + x[1] | 0;
13545 x[2] = c + x[2] | 0;
13546 x[3] = d + x[3] | 0;
13547 }
13548
13549 function md5blk(s) {
13550 var md5blks = [],
13551 i; /* Andy King said do it this way. */
13552
13553 for (i = 0; i < 64; i += 4) {
13554 md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
13555 }
13556 return md5blks;
13557 }
13558
13559 function md5blk_array(a) {
13560 var md5blks = [],
13561 i; /* Andy King said do it this way. */
13562
13563 for (i = 0; i < 64; i += 4) {
13564 md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);
13565 }
13566 return md5blks;
13567 }
13568
13569 function md51(s) {
13570 var n = s.length,
13571 state = [1732584193, -271733879, -1732584194, 271733878],
13572 i,
13573 length,
13574 tail,
13575 tmp,
13576 lo,
13577 hi;
13578
13579 for (i = 64; i <= n; i += 64) {
13580 md5cycle(state, md5blk(s.substring(i - 64, i)));
13581 }
13582 s = s.substring(i - 64);
13583 length = s.length;
13584 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
13585 for (i = 0; i < length; i += 1) {
13586 tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
13587 }
13588 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13589 if (i > 55) {
13590 md5cycle(state, tail);
13591 for (i = 0; i < 16; i += 1) {
13592 tail[i] = 0;
13593 }
13594 }
13595
13596 // Beware that the final length might not fit in 32 bits so we take care of that
13597 tmp = n * 8;
13598 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
13599 lo = parseInt(tmp[2], 16);
13600 hi = parseInt(tmp[1], 16) || 0;
13601
13602 tail[14] = lo;
13603 tail[15] = hi;
13604
13605 md5cycle(state, tail);
13606 return state;
13607 }
13608
13609 function md51_array(a) {
13610 var n = a.length,
13611 state = [1732584193, -271733879, -1732584194, 271733878],
13612 i,
13613 length,
13614 tail,
13615 tmp,
13616 lo,
13617 hi;
13618
13619 for (i = 64; i <= n; i += 64) {
13620 md5cycle(state, md5blk_array(a.subarray(i - 64, i)));
13621 }
13622
13623 // Not sure if it is a bug, however IE10 will always produce a sub array of length 1
13624 // containing the last element of the parent array if the sub array specified starts
13625 // beyond the length of the parent array - weird.
13626 // https://connect.microsoft.com/IE/feedback/details/771452/typed-array-subarray-issue
13627 a = (i - 64) < n ? a.subarray(i - 64) : new Uint8Array(0);
13628
13629 length = a.length;
13630 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
13631 for (i = 0; i < length; i += 1) {
13632 tail[i >> 2] |= a[i] << ((i % 4) << 3);
13633 }
13634
13635 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13636 if (i > 55) {
13637 md5cycle(state, tail);
13638 for (i = 0; i < 16; i += 1) {
13639 tail[i] = 0;
13640 }
13641 }
13642
13643 // Beware that the final length might not fit in 32 bits so we take care of that
13644 tmp = n * 8;
13645 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
13646 lo = parseInt(tmp[2], 16);
13647 hi = parseInt(tmp[1], 16) || 0;
13648
13649 tail[14] = lo;
13650 tail[15] = hi;
13651
13652 md5cycle(state, tail);
13653
13654 return state;
13655 }
13656
13657 function rhex(n) {
13658 var s = '',
13659 j;
13660 for (j = 0; j < 4; j += 1) {
13661 s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
13662 }
13663 return s;
13664 }
13665
13666 function hex(x) {
13667 var i;
13668 for (i = 0; i < x.length; i += 1) {
13669 x[i] = rhex(x[i]);
13670 }
13671 return x.join('');
13672 }
13673
13674 // In some cases the fast add32 function cannot be used..
13675 if (hex(md51('hello')) !== '5d41402abc4b2a76b9719d911017c592') {
13676 add32 = function (x, y) {
13677 var lsw = (x & 0xFFFF) + (y & 0xFFFF),
13678 msw = (x >> 16) + (y >> 16) + (lsw >> 16);
13679 return (msw << 16) | (lsw & 0xFFFF);
13680 };
13681 }
13682
13683 // ---------------------------------------------------
13684
13685 /**
13686 * ArrayBuffer slice polyfill.
13687 *
13688 * @see https://github.com/ttaubert/node-arraybuffer-slice
13689 */
13690
13691 if (typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.prototype.slice) {
13692 (function () {
13693 function clamp(val, length) {
13694 val = (val | 0) || 0;
13695
13696 if (val < 0) {
13697 return Math.max(val + length, 0);
13698 }
13699
13700 return Math.min(val, length);
13701 }
13702
13703 ArrayBuffer.prototype.slice = function (from, to) {
13704 var length = this.byteLength,
13705 begin = clamp(from, length),
13706 end = length,
13707 num,
13708 target,
13709 targetArray,
13710 sourceArray;
13711
13712 if (to !== undefined) {
13713 end = clamp(to, length);
13714 }
13715
13716 if (begin > end) {
13717 return new ArrayBuffer(0);
13718 }
13719
13720 num = end - begin;
13721 target = new ArrayBuffer(num);
13722 targetArray = new Uint8Array(target);
13723
13724 sourceArray = new Uint8Array(this, begin, num);
13725 targetArray.set(sourceArray);
13726
13727 return target;
13728 };
13729 })();
13730 }
13731
13732 // ---------------------------------------------------
13733
13734 /**
13735 * Helpers.
13736 */
13737
13738 function toUtf8(str) {
13739 if (/[\u0080-\uFFFF]/.test(str)) {
13740 str = unescape(encodeURIComponent(str));
13741 }
13742
13743 return str;
13744 }
13745
13746 function utf8Str2ArrayBuffer(str, returnUInt8Array) {
13747 var length = str.length,
13748 buff = new ArrayBuffer(length),
13749 arr = new Uint8Array(buff),
13750 i;
13751
13752 for (i = 0; i < length; i += 1) {
13753 arr[i] = str.charCodeAt(i);
13754 }
13755
13756 return returnUInt8Array ? arr : buff;
13757 }
13758
13759 function arrayBuffer2Utf8Str(buff) {
13760 return String.fromCharCode.apply(null, new Uint8Array(buff));
13761 }
13762
13763 function concatenateArrayBuffers(first, second, returnUInt8Array) {
13764 var result = new Uint8Array(first.byteLength + second.byteLength);
13765
13766 result.set(new Uint8Array(first));
13767 result.set(new Uint8Array(second), first.byteLength);
13768
13769 return returnUInt8Array ? result : result.buffer;
13770 }
13771
13772 function hexToBinaryString(hex) {
13773 var bytes = [],
13774 length = hex.length,
13775 x;
13776
13777 for (x = 0; x < length - 1; x += 2) {
13778 bytes.push(parseInt(hex.substr(x, 2), 16));
13779 }
13780
13781 return String.fromCharCode.apply(String, bytes);
13782 }
13783
13784 // ---------------------------------------------------
13785
13786 /**
13787 * SparkMD5 OOP implementation.
13788 *
13789 * Use this class to perform an incremental md5, otherwise use the
13790 * static methods instead.
13791 */
13792
13793 function SparkMD5() {
13794 // call reset to init the instance
13795 this.reset();
13796 }
13797
13798 /**
13799 * Appends a string.
13800 * A conversion will be applied if an utf8 string is detected.
13801 *
13802 * @param {String} str The string to be appended
13803 *
13804 * @return {SparkMD5} The instance itself
13805 */
13806 SparkMD5.prototype.append = function (str) {
13807 // Converts the string to utf8 bytes if necessary
13808 // Then append as binary
13809 this.appendBinary(toUtf8(str));
13810
13811 return this;
13812 };
13813
13814 /**
13815 * Appends a binary string.
13816 *
13817 * @param {String} contents The binary string to be appended
13818 *
13819 * @return {SparkMD5} The instance itself
13820 */
13821 SparkMD5.prototype.appendBinary = function (contents) {
13822 this._buff += contents;
13823 this._length += contents.length;
13824
13825 var length = this._buff.length,
13826 i;
13827
13828 for (i = 64; i <= length; i += 64) {
13829 md5cycle(this._hash, md5blk(this._buff.substring(i - 64, i)));
13830 }
13831
13832 this._buff = this._buff.substring(i - 64);
13833
13834 return this;
13835 };
13836
13837 /**
13838 * Finishes the incremental computation, reseting the internal state and
13839 * returning the result.
13840 *
13841 * @param {Boolean} raw True to get the raw string, false to get the hex string
13842 *
13843 * @return {String} The result
13844 */
13845 SparkMD5.prototype.end = function (raw) {
13846 var buff = this._buff,
13847 length = buff.length,
13848 i,
13849 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
13850 ret;
13851
13852 for (i = 0; i < length; i += 1) {
13853 tail[i >> 2] |= buff.charCodeAt(i) << ((i % 4) << 3);
13854 }
13855
13856 this._finish(tail, length);
13857 ret = hex(this._hash);
13858
13859 if (raw) {
13860 ret = hexToBinaryString(ret);
13861 }
13862
13863 this.reset();
13864
13865 return ret;
13866 };
13867
13868 /**
13869 * Resets the internal state of the computation.
13870 *
13871 * @return {SparkMD5} The instance itself
13872 */
13873 SparkMD5.prototype.reset = function () {
13874 this._buff = '';
13875 this._length = 0;
13876 this._hash = [1732584193, -271733879, -1732584194, 271733878];
13877
13878 return this;
13879 };
13880
13881 /**
13882 * Gets the internal state of the computation.
13883 *
13884 * @return {Object} The state
13885 */
13886 SparkMD5.prototype.getState = function () {
13887 return {
13888 buff: this._buff,
13889 length: this._length,
13890 hash: this._hash.slice()
13891 };
13892 };
13893
13894 /**
13895 * Gets the internal state of the computation.
13896 *
13897 * @param {Object} state The state
13898 *
13899 * @return {SparkMD5} The instance itself
13900 */
13901 SparkMD5.prototype.setState = function (state) {
13902 this._buff = state.buff;
13903 this._length = state.length;
13904 this._hash = state.hash;
13905
13906 return this;
13907 };
13908
13909 /**
13910 * Releases memory used by the incremental buffer and other additional
13911 * resources. If you plan to use the instance again, use reset instead.
13912 */
13913 SparkMD5.prototype.destroy = function () {
13914 delete this._hash;
13915 delete this._buff;
13916 delete this._length;
13917 };
13918
13919 /**
13920 * Finish the final calculation based on the tail.
13921 *
13922 * @param {Array} tail The tail (will be modified)
13923 * @param {Number} length The length of the remaining buffer
13924 */
13925 SparkMD5.prototype._finish = function (tail, length) {
13926 var i = length,
13927 tmp,
13928 lo,
13929 hi;
13930
13931 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13932 if (i > 55) {
13933 md5cycle(this._hash, tail);
13934 for (i = 0; i < 16; i += 1) {
13935 tail[i] = 0;
13936 }
13937 }
13938
13939 // Do the final computation based on the tail and length
13940 // Beware that the final length may not fit in 32 bits so we take care of that
13941 tmp = this._length * 8;
13942 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
13943 lo = parseInt(tmp[2], 16);
13944 hi = parseInt(tmp[1], 16) || 0;
13945
13946 tail[14] = lo;
13947 tail[15] = hi;
13948 md5cycle(this._hash, tail);
13949 };
13950
13951 /**
13952 * Performs the md5 hash on a string.
13953 * A conversion will be applied if utf8 string is detected.
13954 *
13955 * @param {String} str The string
13956 * @param {Boolean} [raw] True to get the raw string, false to get the hex string
13957 *
13958 * @return {String} The result
13959 */
13960 SparkMD5.hash = function (str, raw) {
13961 // Converts the string to utf8 bytes if necessary
13962 // Then compute it using the binary function
13963 return SparkMD5.hashBinary(toUtf8(str), raw);
13964 };
13965
13966 /**
13967 * Performs the md5 hash on a binary string.
13968 *
13969 * @param {String} content The binary string
13970 * @param {Boolean} [raw] True to get the raw string, false to get the hex string
13971 *
13972 * @return {String} The result
13973 */
13974 SparkMD5.hashBinary = function (content, raw) {
13975 var hash = md51(content),
13976 ret = hex(hash);
13977
13978 return raw ? hexToBinaryString(ret) : ret;
13979 };
13980
13981 // ---------------------------------------------------
13982
13983 /**
13984 * SparkMD5 OOP implementation for array buffers.
13985 *
13986 * Use this class to perform an incremental md5 ONLY for array buffers.
13987 */
13988 SparkMD5.ArrayBuffer = function () {
13989 // call reset to init the instance
13990 this.reset();
13991 };
13992
13993 /**
13994 * Appends an array buffer.
13995 *
13996 * @param {ArrayBuffer} arr The array to be appended
13997 *
13998 * @return {SparkMD5.ArrayBuffer} The instance itself
13999 */
14000 SparkMD5.ArrayBuffer.prototype.append = function (arr) {
14001 var buff = concatenateArrayBuffers(this._buff.buffer, arr, true),
14002 length = buff.length,
14003 i;
14004
14005 this._length += arr.byteLength;
14006
14007 for (i = 64; i <= length; i += 64) {
14008 md5cycle(this._hash, md5blk_array(buff.subarray(i - 64, i)));
14009 }
14010
14011 this._buff = (i - 64) < length ? new Uint8Array(buff.buffer.slice(i - 64)) : new Uint8Array(0);
14012
14013 return this;
14014 };
14015
14016 /**
14017 * Finishes the incremental computation, reseting the internal state and
14018 * returning the result.
14019 *
14020 * @param {Boolean} raw True to get the raw string, false to get the hex string
14021 *
14022 * @return {String} The result
14023 */
14024 SparkMD5.ArrayBuffer.prototype.end = function (raw) {
14025 var buff = this._buff,
14026 length = buff.length,
14027 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
14028 i,
14029 ret;
14030
14031 for (i = 0; i < length; i += 1) {
14032 tail[i >> 2] |= buff[i] << ((i % 4) << 3);
14033 }
14034
14035 this._finish(tail, length);
14036 ret = hex(this._hash);
14037
14038 if (raw) {
14039 ret = hexToBinaryString(ret);
14040 }
14041
14042 this.reset();
14043
14044 return ret;
14045 };
14046
14047 /**
14048 * Resets the internal state of the computation.
14049 *
14050 * @return {SparkMD5.ArrayBuffer} The instance itself
14051 */
14052 SparkMD5.ArrayBuffer.prototype.reset = function () {
14053 this._buff = new Uint8Array(0);
14054 this._length = 0;
14055 this._hash = [1732584193, -271733879, -1732584194, 271733878];
14056
14057 return this;
14058 };
14059
14060 /**
14061 * Gets the internal state of the computation.
14062 *
14063 * @return {Object} The state
14064 */
14065 SparkMD5.ArrayBuffer.prototype.getState = function () {
14066 var state = SparkMD5.prototype.getState.call(this);
14067
14068 // Convert buffer to a string
14069 state.buff = arrayBuffer2Utf8Str(state.buff);
14070
14071 return state;
14072 };
14073
14074 /**
14075 * Gets the internal state of the computation.
14076 *
14077 * @param {Object} state The state
14078 *
14079 * @return {SparkMD5.ArrayBuffer} The instance itself
14080 */
14081 SparkMD5.ArrayBuffer.prototype.setState = function (state) {
14082 // Convert string to buffer
14083 state.buff = utf8Str2ArrayBuffer(state.buff, true);
14084
14085 return SparkMD5.prototype.setState.call(this, state);
14086 };
14087
14088 SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
14089
14090 SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
14091
14092 /**
14093 * Performs the md5 hash on an array buffer.
14094 *
14095 * @param {ArrayBuffer} arr The array buffer
14096 * @param {Boolean} [raw] True to get the raw string, false to get the hex one
14097 *
14098 * @return {String} The result
14099 */
14100 SparkMD5.ArrayBuffer.hash = function (arr, raw) {
14101 var hash = md51_array(new Uint8Array(arr)),
14102 ret = hex(hash);
14103
14104 return raw ? hexToBinaryString(ret) : ret;
14105 };
14106
14107 return SparkMD5;
14108}));
14109
14110},{}],85:[function(_dereq_,module,exports){
14111// Copyright Joyent, Inc. and other Node contributors.
14112//
14113// Permission is hereby granted, free of charge, to any person obtaining a
14114// copy of this software and associated documentation files (the
14115// "Software"), to deal in the Software without restriction, including
14116// without limitation the rights to use, copy, modify, merge, publish,
14117// distribute, sublicense, and/or sell copies of the Software, and to permit
14118// persons to whom the Software is furnished to do so, subject to the
14119// following conditions:
14120//
14121// The above copyright notice and this permission notice shall be included
14122// in all copies or substantial portions of the Software.
14123//
14124// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14125// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14126// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14127// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14128// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14129// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14130// USE OR OTHER DEALINGS IN THE SOFTWARE.
14131
14132module.exports = Stream;
14133
14134var EE = _dereq_(26).EventEmitter;
14135var inherits = _dereq_(37);
14136
14137inherits(Stream, EE);
14138Stream.Readable = _dereq_(97);
14139Stream.Writable = _dereq_(99);
14140Stream.Duplex = _dereq_(87);
14141Stream.Transform = _dereq_(98);
14142Stream.PassThrough = _dereq_(96);
14143
14144// Backwards-compat with node 0.4.x
14145Stream.Stream = Stream;
14146
14147
14148
14149// old-style streams. Note that the pipe method (the only relevant
14150// part of this class) is overridden in the Readable class.
14151
14152function Stream() {
14153 EE.call(this);
14154}
14155
14156Stream.prototype.pipe = function(dest, options) {
14157 var source = this;
14158
14159 function ondata(chunk) {
14160 if (dest.writable) {
14161 if (false === dest.write(chunk) && source.pause) {
14162 source.pause();
14163 }
14164 }
14165 }
14166
14167 source.on('data', ondata);
14168
14169 function ondrain() {
14170 if (source.readable && source.resume) {
14171 source.resume();
14172 }
14173 }
14174
14175 dest.on('drain', ondrain);
14176
14177 // If the 'end' option is not supplied, dest.end() will be called when
14178 // source gets the 'end' or 'close' events. Only dest.end() once.
14179 if (!dest._isStdio && (!options || options.end !== false)) {
14180 source.on('end', onend);
14181 source.on('close', onclose);
14182 }
14183
14184 var didOnEnd = false;
14185 function onend() {
14186 if (didOnEnd) return;
14187 didOnEnd = true;
14188
14189 dest.end();
14190 }
14191
14192
14193 function onclose() {
14194 if (didOnEnd) return;
14195 didOnEnd = true;
14196
14197 if (typeof dest.destroy === 'function') dest.destroy();
14198 }
14199
14200 // don't leave dangling pipes when there are errors.
14201 function onerror(er) {
14202 cleanup();
14203 if (EE.listenerCount(this, 'error') === 0) {
14204 throw er; // Unhandled stream error in pipe.
14205 }
14206 }
14207
14208 source.on('error', onerror);
14209 dest.on('error', onerror);
14210
14211 // remove all the event listeners that were added.
14212 function cleanup() {
14213 source.removeListener('data', ondata);
14214 dest.removeListener('drain', ondrain);
14215
14216 source.removeListener('end', onend);
14217 source.removeListener('close', onclose);
14218
14219 source.removeListener('error', onerror);
14220 dest.removeListener('error', onerror);
14221
14222 source.removeListener('end', cleanup);
14223 source.removeListener('close', cleanup);
14224
14225 dest.removeListener('close', cleanup);
14226 }
14227
14228 source.on('end', cleanup);
14229 source.on('close', cleanup);
14230
14231 dest.on('close', cleanup);
14232
14233 dest.emit('pipe', source);
14234
14235 // Allow for unix-like usage: A.pipe(B).pipe(C)
14236 return dest;
14237};
14238
14239},{"26":26,"37":37,"87":87,"96":96,"97":97,"98":98,"99":99}],86:[function(_dereq_,module,exports){
14240var toString = {}.toString;
14241
14242module.exports = Array.isArray || function (arr) {
14243 return toString.call(arr) == '[object Array]';
14244};
14245
14246},{}],87:[function(_dereq_,module,exports){
14247module.exports = _dereq_(88);
14248
14249},{"88":88}],88:[function(_dereq_,module,exports){
14250// Copyright Joyent, Inc. and other Node contributors.
14251//
14252// Permission is hereby granted, free of charge, to any person obtaining a
14253// copy of this software and associated documentation files (the
14254// "Software"), to deal in the Software without restriction, including
14255// without limitation the rights to use, copy, modify, merge, publish,
14256// distribute, sublicense, and/or sell copies of the Software, and to permit
14257// persons to whom the Software is furnished to do so, subject to the
14258// following conditions:
14259//
14260// The above copyright notice and this permission notice shall be included
14261// in all copies or substantial portions of the Software.
14262//
14263// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14264// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14265// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14266// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14267// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14268// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14269// USE OR OTHER DEALINGS IN THE SOFTWARE.
14270
14271// a duplex stream is just a stream that is both readable and writable.
14272// Since JS doesn't have multiple prototypal inheritance, this class
14273// prototypally inherits from Readable, and then parasitically from
14274// Writable.
14275
14276'use strict';
14277
14278/*<replacement>*/
14279
14280var pna = _dereq_(72);
14281/*</replacement>*/
14282
14283/*<replacement>*/
14284var objectKeys = Object.keys || function (obj) {
14285 var keys = [];
14286 for (var key in obj) {
14287 keys.push(key);
14288 }return keys;
14289};
14290/*</replacement>*/
14291
14292module.exports = Duplex;
14293
14294/*<replacement>*/
14295var util = Object.create(_dereq_(14));
14296util.inherits = _dereq_(37);
14297/*</replacement>*/
14298
14299var Readable = _dereq_(90);
14300var Writable = _dereq_(92);
14301
14302util.inherits(Duplex, Readable);
14303
14304{
14305 // avoid scope creep, the keys array can then be collected
14306 var keys = objectKeys(Writable.prototype);
14307 for (var v = 0; v < keys.length; v++) {
14308 var method = keys[v];
14309 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
14310 }
14311}
14312
14313function Duplex(options) {
14314 if (!(this instanceof Duplex)) return new Duplex(options);
14315
14316 Readable.call(this, options);
14317 Writable.call(this, options);
14318
14319 if (options && options.readable === false) this.readable = false;
14320
14321 if (options && options.writable === false) this.writable = false;
14322
14323 this.allowHalfOpen = true;
14324 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
14325
14326 this.once('end', onend);
14327}
14328
14329Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
14330 // making it explicit this property is not enumerable
14331 // because otherwise some prototype manipulation in
14332 // userland will fail
14333 enumerable: false,
14334 get: function () {
14335 return this._writableState.highWaterMark;
14336 }
14337});
14338
14339// the no-half-open enforcer
14340function onend() {
14341 // if we allow half-open state, or if the writable side ended,
14342 // then we're ok.
14343 if (this.allowHalfOpen || this._writableState.ended) return;
14344
14345 // no more data can be written.
14346 // But allow more writes to happen in this tick.
14347 pna.nextTick(onEndNT, this);
14348}
14349
14350function onEndNT(self) {
14351 self.end();
14352}
14353
14354Object.defineProperty(Duplex.prototype, 'destroyed', {
14355 get: function () {
14356 if (this._readableState === undefined || this._writableState === undefined) {
14357 return false;
14358 }
14359 return this._readableState.destroyed && this._writableState.destroyed;
14360 },
14361 set: function (value) {
14362 // we ignore the value if the stream
14363 // has not been initialized yet
14364 if (this._readableState === undefined || this._writableState === undefined) {
14365 return;
14366 }
14367
14368 // backward compatibility, the user is explicitly
14369 // managing destroyed
14370 this._readableState.destroyed = value;
14371 this._writableState.destroyed = value;
14372 }
14373});
14374
14375Duplex.prototype._destroy = function (err, cb) {
14376 this.push(null);
14377 this.end();
14378
14379 pna.nextTick(cb, err);
14380};
14381},{"14":14,"37":37,"72":72,"90":90,"92":92}],89:[function(_dereq_,module,exports){
14382// Copyright Joyent, Inc. and other Node contributors.
14383//
14384// Permission is hereby granted, free of charge, to any person obtaining a
14385// copy of this software and associated documentation files (the
14386// "Software"), to deal in the Software without restriction, including
14387// without limitation the rights to use, copy, modify, merge, publish,
14388// distribute, sublicense, and/or sell copies of the Software, and to permit
14389// persons to whom the Software is furnished to do so, subject to the
14390// following conditions:
14391//
14392// The above copyright notice and this permission notice shall be included
14393// in all copies or substantial portions of the Software.
14394//
14395// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14396// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14397// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14398// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14399// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14400// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14401// USE OR OTHER DEALINGS IN THE SOFTWARE.
14402
14403// a passthrough stream.
14404// basically just the most minimal sort of Transform stream.
14405// Every written chunk gets output as-is.
14406
14407'use strict';
14408
14409module.exports = PassThrough;
14410
14411var Transform = _dereq_(91);
14412
14413/*<replacement>*/
14414var util = Object.create(_dereq_(14));
14415util.inherits = _dereq_(37);
14416/*</replacement>*/
14417
14418util.inherits(PassThrough, Transform);
14419
14420function PassThrough(options) {
14421 if (!(this instanceof PassThrough)) return new PassThrough(options);
14422
14423 Transform.call(this, options);
14424}
14425
14426PassThrough.prototype._transform = function (chunk, encoding, cb) {
14427 cb(null, chunk);
14428};
14429},{"14":14,"37":37,"91":91}],90:[function(_dereq_,module,exports){
14430(function (process,global){(function (){
14431// Copyright Joyent, Inc. and other Node contributors.
14432//
14433// Permission is hereby granted, free of charge, to any person obtaining a
14434// copy of this software and associated documentation files (the
14435// "Software"), to deal in the Software without restriction, including
14436// without limitation the rights to use, copy, modify, merge, publish,
14437// distribute, sublicense, and/or sell copies of the Software, and to permit
14438// persons to whom the Software is furnished to do so, subject to the
14439// following conditions:
14440//
14441// The above copyright notice and this permission notice shall be included
14442// in all copies or substantial portions of the Software.
14443//
14444// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14445// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14446// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14447// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14448// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14449// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14450// USE OR OTHER DEALINGS IN THE SOFTWARE.
14451
14452'use strict';
14453
14454/*<replacement>*/
14455
14456var pna = _dereq_(72);
14457/*</replacement>*/
14458
14459module.exports = Readable;
14460
14461/*<replacement>*/
14462var isArray = _dereq_(86);
14463/*</replacement>*/
14464
14465/*<replacement>*/
14466var Duplex;
14467/*</replacement>*/
14468
14469Readable.ReadableState = ReadableState;
14470
14471/*<replacement>*/
14472var EE = _dereq_(26).EventEmitter;
14473
14474var EElistenerCount = function (emitter, type) {
14475 return emitter.listeners(type).length;
14476};
14477/*</replacement>*/
14478
14479/*<replacement>*/
14480var Stream = _dereq_(95);
14481/*</replacement>*/
14482
14483/*<replacement>*/
14484
14485var Buffer = _dereq_(100).Buffer;
14486var OurUint8Array = global.Uint8Array || function () {};
14487function _uint8ArrayToBuffer(chunk) {
14488 return Buffer.from(chunk);
14489}
14490function _isUint8Array(obj) {
14491 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
14492}
14493
14494/*</replacement>*/
14495
14496/*<replacement>*/
14497var util = Object.create(_dereq_(14));
14498util.inherits = _dereq_(37);
14499/*</replacement>*/
14500
14501/*<replacement>*/
14502var debugUtil = _dereq_(11);
14503var debug = void 0;
14504if (debugUtil && debugUtil.debuglog) {
14505 debug = debugUtil.debuglog('stream');
14506} else {
14507 debug = function () {};
14508}
14509/*</replacement>*/
14510
14511var BufferList = _dereq_(93);
14512var destroyImpl = _dereq_(94);
14513var StringDecoder;
14514
14515util.inherits(Readable, Stream);
14516
14517var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
14518
14519function prependListener(emitter, event, fn) {
14520 // Sadly this is not cacheable as some libraries bundle their own
14521 // event emitter implementation with them.
14522 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
14523
14524 // This is a hack to make sure that our error handler is attached before any
14525 // userland ones. NEVER DO THIS. This is here only because this code needs
14526 // to continue to work with older versions of Node.js that do not include
14527 // the prependListener() method. The goal is to eventually remove this hack.
14528 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]];
14529}
14530
14531function ReadableState(options, stream) {
14532 Duplex = Duplex || _dereq_(88);
14533
14534 options = options || {};
14535
14536 // Duplex streams are both readable and writable, but share
14537 // the same options object.
14538 // However, some cases require setting options to different
14539 // values for the readable and the writable sides of the duplex stream.
14540 // These options can be provided separately as readableXXX and writableXXX.
14541 var isDuplex = stream instanceof Duplex;
14542
14543 // object stream flag. Used to make read(n) ignore n and to
14544 // make all the buffer merging and length checks go away
14545 this.objectMode = !!options.objectMode;
14546
14547 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
14548
14549 // the point at which it stops calling _read() to fill the buffer
14550 // Note: 0 is a valid value, means "don't call _read preemptively ever"
14551 var hwm = options.highWaterMark;
14552 var readableHwm = options.readableHighWaterMark;
14553 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
14554
14555 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
14556
14557 // cast to ints.
14558 this.highWaterMark = Math.floor(this.highWaterMark);
14559
14560 // A linked list is used to store data chunks instead of an array because the
14561 // linked list can remove elements from the beginning faster than
14562 // array.shift()
14563 this.buffer = new BufferList();
14564 this.length = 0;
14565 this.pipes = null;
14566 this.pipesCount = 0;
14567 this.flowing = null;
14568 this.ended = false;
14569 this.endEmitted = false;
14570 this.reading = false;
14571
14572 // a flag to be able to tell if the event 'readable'/'data' is emitted
14573 // immediately, or on a later tick. We set this to true at first, because
14574 // any actions that shouldn't happen until "later" should generally also
14575 // not happen before the first read call.
14576 this.sync = true;
14577
14578 // whenever we return null, then we set a flag to say
14579 // that we're awaiting a 'readable' event emission.
14580 this.needReadable = false;
14581 this.emittedReadable = false;
14582 this.readableListening = false;
14583 this.resumeScheduled = false;
14584
14585 // has it been destroyed
14586 this.destroyed = false;
14587
14588 // Crypto is kind of old and crusty. Historically, its default string
14589 // encoding is 'binary' so we have to make this configurable.
14590 // Everything else in the universe uses 'utf8', though.
14591 this.defaultEncoding = options.defaultEncoding || 'utf8';
14592
14593 // the number of writers that are awaiting a drain event in .pipe()s
14594 this.awaitDrain = 0;
14595
14596 // if true, a maybeReadMore has been scheduled
14597 this.readingMore = false;
14598
14599 this.decoder = null;
14600 this.encoding = null;
14601 if (options.encoding) {
14602 if (!StringDecoder) StringDecoder = _dereq_(101).StringDecoder;
14603 this.decoder = new StringDecoder(options.encoding);
14604 this.encoding = options.encoding;
14605 }
14606}
14607
14608function Readable(options) {
14609 Duplex = Duplex || _dereq_(88);
14610
14611 if (!(this instanceof Readable)) return new Readable(options);
14612
14613 this._readableState = new ReadableState(options, this);
14614
14615 // legacy
14616 this.readable = true;
14617
14618 if (options) {
14619 if (typeof options.read === 'function') this._read = options.read;
14620
14621 if (typeof options.destroy === 'function') this._destroy = options.destroy;
14622 }
14623
14624 Stream.call(this);
14625}
14626
14627Object.defineProperty(Readable.prototype, 'destroyed', {
14628 get: function () {
14629 if (this._readableState === undefined) {
14630 return false;
14631 }
14632 return this._readableState.destroyed;
14633 },
14634 set: function (value) {
14635 // we ignore the value if the stream
14636 // has not been initialized yet
14637 if (!this._readableState) {
14638 return;
14639 }
14640
14641 // backward compatibility, the user is explicitly
14642 // managing destroyed
14643 this._readableState.destroyed = value;
14644 }
14645});
14646
14647Readable.prototype.destroy = destroyImpl.destroy;
14648Readable.prototype._undestroy = destroyImpl.undestroy;
14649Readable.prototype._destroy = function (err, cb) {
14650 this.push(null);
14651 cb(err);
14652};
14653
14654// Manually shove something into the read() buffer.
14655// This returns true if the highWaterMark has not been hit yet,
14656// similar to how Writable.write() returns true if you should
14657// write() some more.
14658Readable.prototype.push = function (chunk, encoding) {
14659 var state = this._readableState;
14660 var skipChunkCheck;
14661
14662 if (!state.objectMode) {
14663 if (typeof chunk === 'string') {
14664 encoding = encoding || state.defaultEncoding;
14665 if (encoding !== state.encoding) {
14666 chunk = Buffer.from(chunk, encoding);
14667 encoding = '';
14668 }
14669 skipChunkCheck = true;
14670 }
14671 } else {
14672 skipChunkCheck = true;
14673 }
14674
14675 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
14676};
14677
14678// Unshift should *always* be something directly out of read()
14679Readable.prototype.unshift = function (chunk) {
14680 return readableAddChunk(this, chunk, null, true, false);
14681};
14682
14683function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
14684 var state = stream._readableState;
14685 if (chunk === null) {
14686 state.reading = false;
14687 onEofChunk(stream, state);
14688 } else {
14689 var er;
14690 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
14691 if (er) {
14692 stream.emit('error', er);
14693 } else if (state.objectMode || chunk && chunk.length > 0) {
14694 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
14695 chunk = _uint8ArrayToBuffer(chunk);
14696 }
14697
14698 if (addToFront) {
14699 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
14700 } else if (state.ended) {
14701 stream.emit('error', new Error('stream.push() after EOF'));
14702 } else {
14703 state.reading = false;
14704 if (state.decoder && !encoding) {
14705 chunk = state.decoder.write(chunk);
14706 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
14707 } else {
14708 addChunk(stream, state, chunk, false);
14709 }
14710 }
14711 } else if (!addToFront) {
14712 state.reading = false;
14713 }
14714 }
14715
14716 return needMoreData(state);
14717}
14718
14719function addChunk(stream, state, chunk, addToFront) {
14720 if (state.flowing && state.length === 0 && !state.sync) {
14721 stream.emit('data', chunk);
14722 stream.read(0);
14723 } else {
14724 // update the buffer info.
14725 state.length += state.objectMode ? 1 : chunk.length;
14726 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
14727
14728 if (state.needReadable) emitReadable(stream);
14729 }
14730 maybeReadMore(stream, state);
14731}
14732
14733function chunkInvalid(state, chunk) {
14734 var er;
14735 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
14736 er = new TypeError('Invalid non-string/buffer chunk');
14737 }
14738 return er;
14739}
14740
14741// if it's past the high water mark, we can push in some more.
14742// Also, if we have no data yet, we can stand some
14743// more bytes. This is to work around cases where hwm=0,
14744// such as the repl. Also, if the push() triggered a
14745// readable event, and the user called read(largeNumber) such that
14746// needReadable was set, then we ought to push more, so that another
14747// 'readable' event will be triggered.
14748function needMoreData(state) {
14749 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
14750}
14751
14752Readable.prototype.isPaused = function () {
14753 return this._readableState.flowing === false;
14754};
14755
14756// backwards compatibility.
14757Readable.prototype.setEncoding = function (enc) {
14758 if (!StringDecoder) StringDecoder = _dereq_(101).StringDecoder;
14759 this._readableState.decoder = new StringDecoder(enc);
14760 this._readableState.encoding = enc;
14761 return this;
14762};
14763
14764// Don't raise the hwm > 8MB
14765var MAX_HWM = 0x800000;
14766function computeNewHighWaterMark(n) {
14767 if (n >= MAX_HWM) {
14768 n = MAX_HWM;
14769 } else {
14770 // Get the next highest power of 2 to prevent increasing hwm excessively in
14771 // tiny amounts
14772 n--;
14773 n |= n >>> 1;
14774 n |= n >>> 2;
14775 n |= n >>> 4;
14776 n |= n >>> 8;
14777 n |= n >>> 16;
14778 n++;
14779 }
14780 return n;
14781}
14782
14783// This function is designed to be inlinable, so please take care when making
14784// changes to the function body.
14785function howMuchToRead(n, state) {
14786 if (n <= 0 || state.length === 0 && state.ended) return 0;
14787 if (state.objectMode) return 1;
14788 if (n !== n) {
14789 // Only flow one buffer at a time
14790 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
14791 }
14792 // If we're asking for more than the current hwm, then raise the hwm.
14793 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
14794 if (n <= state.length) return n;
14795 // Don't have enough
14796 if (!state.ended) {
14797 state.needReadable = true;
14798 return 0;
14799 }
14800 return state.length;
14801}
14802
14803// you can override either this method, or the async _read(n) below.
14804Readable.prototype.read = function (n) {
14805 debug('read', n);
14806 n = parseInt(n, 10);
14807 var state = this._readableState;
14808 var nOrig = n;
14809
14810 if (n !== 0) state.emittedReadable = false;
14811
14812 // if we're doing read(0) to trigger a readable event, but we
14813 // already have a bunch of data in the buffer, then just trigger
14814 // the 'readable' event and move on.
14815 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
14816 debug('read: emitReadable', state.length, state.ended);
14817 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
14818 return null;
14819 }
14820
14821 n = howMuchToRead(n, state);
14822
14823 // if we've ended, and we're now clear, then finish it up.
14824 if (n === 0 && state.ended) {
14825 if (state.length === 0) endReadable(this);
14826 return null;
14827 }
14828
14829 // All the actual chunk generation logic needs to be
14830 // *below* the call to _read. The reason is that in certain
14831 // synthetic stream cases, such as passthrough streams, _read
14832 // may be a completely synchronous operation which may change
14833 // the state of the read buffer, providing enough data when
14834 // before there was *not* enough.
14835 //
14836 // So, the steps are:
14837 // 1. Figure out what the state of things will be after we do
14838 // a read from the buffer.
14839 //
14840 // 2. If that resulting state will trigger a _read, then call _read.
14841 // Note that this may be asynchronous, or synchronous. Yes, it is
14842 // deeply ugly to write APIs this way, but that still doesn't mean
14843 // that the Readable class should behave improperly, as streams are
14844 // designed to be sync/async agnostic.
14845 // Take note if the _read call is sync or async (ie, if the read call
14846 // has returned yet), so that we know whether or not it's safe to emit
14847 // 'readable' etc.
14848 //
14849 // 3. Actually pull the requested chunks out of the buffer and return.
14850
14851 // if we need a readable event, then we need to do some reading.
14852 var doRead = state.needReadable;
14853 debug('need readable', doRead);
14854
14855 // if we currently have less than the highWaterMark, then also read some
14856 if (state.length === 0 || state.length - n < state.highWaterMark) {
14857 doRead = true;
14858 debug('length less than watermark', doRead);
14859 }
14860
14861 // however, if we've ended, then there's no point, and if we're already
14862 // reading, then it's unnecessary.
14863 if (state.ended || state.reading) {
14864 doRead = false;
14865 debug('reading or ended', doRead);
14866 } else if (doRead) {
14867 debug('do read');
14868 state.reading = true;
14869 state.sync = true;
14870 // if the length is currently zero, then we *need* a readable event.
14871 if (state.length === 0) state.needReadable = true;
14872 // call internal read method
14873 this._read(state.highWaterMark);
14874 state.sync = false;
14875 // If _read pushed data synchronously, then `reading` will be false,
14876 // and we need to re-evaluate how much data we can return to the user.
14877 if (!state.reading) n = howMuchToRead(nOrig, state);
14878 }
14879
14880 var ret;
14881 if (n > 0) ret = fromList(n, state);else ret = null;
14882
14883 if (ret === null) {
14884 state.needReadable = true;
14885 n = 0;
14886 } else {
14887 state.length -= n;
14888 }
14889
14890 if (state.length === 0) {
14891 // If we have nothing in the buffer, then we want to know
14892 // as soon as we *do* get something into the buffer.
14893 if (!state.ended) state.needReadable = true;
14894
14895 // If we tried to read() past the EOF, then emit end on the next tick.
14896 if (nOrig !== n && state.ended) endReadable(this);
14897 }
14898
14899 if (ret !== null) this.emit('data', ret);
14900
14901 return ret;
14902};
14903
14904function onEofChunk(stream, state) {
14905 if (state.ended) return;
14906 if (state.decoder) {
14907 var chunk = state.decoder.end();
14908 if (chunk && chunk.length) {
14909 state.buffer.push(chunk);
14910 state.length += state.objectMode ? 1 : chunk.length;
14911 }
14912 }
14913 state.ended = true;
14914
14915 // emit 'readable' now to make sure it gets picked up.
14916 emitReadable(stream);
14917}
14918
14919// Don't emit readable right away in sync mode, because this can trigger
14920// another read() call => stack overflow. This way, it might trigger
14921// a nextTick recursion warning, but that's not so bad.
14922function emitReadable(stream) {
14923 var state = stream._readableState;
14924 state.needReadable = false;
14925 if (!state.emittedReadable) {
14926 debug('emitReadable', state.flowing);
14927 state.emittedReadable = true;
14928 if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
14929 }
14930}
14931
14932function emitReadable_(stream) {
14933 debug('emit readable');
14934 stream.emit('readable');
14935 flow(stream);
14936}
14937
14938// at this point, the user has presumably seen the 'readable' event,
14939// and called read() to consume some data. that may have triggered
14940// in turn another _read(n) call, in which case reading = true if
14941// it's in progress.
14942// However, if we're not ended, or reading, and the length < hwm,
14943// then go ahead and try to read some more preemptively.
14944function maybeReadMore(stream, state) {
14945 if (!state.readingMore) {
14946 state.readingMore = true;
14947 pna.nextTick(maybeReadMore_, stream, state);
14948 }
14949}
14950
14951function maybeReadMore_(stream, state) {
14952 var len = state.length;
14953 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
14954 debug('maybeReadMore read 0');
14955 stream.read(0);
14956 if (len === state.length)
14957 // didn't get any data, stop spinning.
14958 break;else len = state.length;
14959 }
14960 state.readingMore = false;
14961}
14962
14963// abstract method. to be overridden in specific implementation classes.
14964// call cb(er, data) where data is <= n in length.
14965// for virtual (non-string, non-buffer) streams, "length" is somewhat
14966// arbitrary, and perhaps not very meaningful.
14967Readable.prototype._read = function (n) {
14968 this.emit('error', new Error('_read() is not implemented'));
14969};
14970
14971Readable.prototype.pipe = function (dest, pipeOpts) {
14972 var src = this;
14973 var state = this._readableState;
14974
14975 switch (state.pipesCount) {
14976 case 0:
14977 state.pipes = dest;
14978 break;
14979 case 1:
14980 state.pipes = [state.pipes, dest];
14981 break;
14982 default:
14983 state.pipes.push(dest);
14984 break;
14985 }
14986 state.pipesCount += 1;
14987 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
14988
14989 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
14990
14991 var endFn = doEnd ? onend : unpipe;
14992 if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
14993
14994 dest.on('unpipe', onunpipe);
14995 function onunpipe(readable, unpipeInfo) {
14996 debug('onunpipe');
14997 if (readable === src) {
14998 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
14999 unpipeInfo.hasUnpiped = true;
15000 cleanup();
15001 }
15002 }
15003 }
15004
15005 function onend() {
15006 debug('onend');
15007 dest.end();
15008 }
15009
15010 // when the dest drains, it reduces the awaitDrain counter
15011 // on the source. This would be more elegant with a .once()
15012 // handler in flow(), but adding and removing repeatedly is
15013 // too slow.
15014 var ondrain = pipeOnDrain(src);
15015 dest.on('drain', ondrain);
15016
15017 var cleanedUp = false;
15018 function cleanup() {
15019 debug('cleanup');
15020 // cleanup event handlers once the pipe is broken
15021 dest.removeListener('close', onclose);
15022 dest.removeListener('finish', onfinish);
15023 dest.removeListener('drain', ondrain);
15024 dest.removeListener('error', onerror);
15025 dest.removeListener('unpipe', onunpipe);
15026 src.removeListener('end', onend);
15027 src.removeListener('end', unpipe);
15028 src.removeListener('data', ondata);
15029
15030 cleanedUp = true;
15031
15032 // if the reader is waiting for a drain event from this
15033 // specific writer, then it would cause it to never start
15034 // flowing again.
15035 // So, if this is awaiting a drain, then we just call it now.
15036 // If we don't know, then assume that we are waiting for one.
15037 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
15038 }
15039
15040 // If the user pushes more data while we're writing to dest then we'll end up
15041 // in ondata again. However, we only want to increase awaitDrain once because
15042 // dest will only emit one 'drain' event for the multiple writes.
15043 // => Introduce a guard on increasing awaitDrain.
15044 var increasedAwaitDrain = false;
15045 src.on('data', ondata);
15046 function ondata(chunk) {
15047 debug('ondata');
15048 increasedAwaitDrain = false;
15049 var ret = dest.write(chunk);
15050 if (false === ret && !increasedAwaitDrain) {
15051 // If the user unpiped during `dest.write()`, it is possible
15052 // to get stuck in a permanently paused state if that write
15053 // also returned false.
15054 // => Check whether `dest` is still a piping destination.
15055 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
15056 debug('false write response, pause', src._readableState.awaitDrain);
15057 src._readableState.awaitDrain++;
15058 increasedAwaitDrain = true;
15059 }
15060 src.pause();
15061 }
15062 }
15063
15064 // if the dest has an error, then stop piping into it.
15065 // however, don't suppress the throwing behavior for this.
15066 function onerror(er) {
15067 debug('onerror', er);
15068 unpipe();
15069 dest.removeListener('error', onerror);
15070 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
15071 }
15072
15073 // Make sure our error handler is attached before userland ones.
15074 prependListener(dest, 'error', onerror);
15075
15076 // Both close and finish should trigger unpipe, but only once.
15077 function onclose() {
15078 dest.removeListener('finish', onfinish);
15079 unpipe();
15080 }
15081 dest.once('close', onclose);
15082 function onfinish() {
15083 debug('onfinish');
15084 dest.removeListener('close', onclose);
15085 unpipe();
15086 }
15087 dest.once('finish', onfinish);
15088
15089 function unpipe() {
15090 debug('unpipe');
15091 src.unpipe(dest);
15092 }
15093
15094 // tell the dest that it's being piped to
15095 dest.emit('pipe', src);
15096
15097 // start the flow if it hasn't been started already.
15098 if (!state.flowing) {
15099 debug('pipe resume');
15100 src.resume();
15101 }
15102
15103 return dest;
15104};
15105
15106function pipeOnDrain(src) {
15107 return function () {
15108 var state = src._readableState;
15109 debug('pipeOnDrain', state.awaitDrain);
15110 if (state.awaitDrain) state.awaitDrain--;
15111 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
15112 state.flowing = true;
15113 flow(src);
15114 }
15115 };
15116}
15117
15118Readable.prototype.unpipe = function (dest) {
15119 var state = this._readableState;
15120 var unpipeInfo = { hasUnpiped: false };
15121
15122 // if we're not piping anywhere, then do nothing.
15123 if (state.pipesCount === 0) return this;
15124
15125 // just one destination. most common case.
15126 if (state.pipesCount === 1) {
15127 // passed in one, but it's not the right one.
15128 if (dest && dest !== state.pipes) return this;
15129
15130 if (!dest) dest = state.pipes;
15131
15132 // got a match.
15133 state.pipes = null;
15134 state.pipesCount = 0;
15135 state.flowing = false;
15136 if (dest) dest.emit('unpipe', this, unpipeInfo);
15137 return this;
15138 }
15139
15140 // slow case. multiple pipe destinations.
15141
15142 if (!dest) {
15143 // remove all.
15144 var dests = state.pipes;
15145 var len = state.pipesCount;
15146 state.pipes = null;
15147 state.pipesCount = 0;
15148 state.flowing = false;
15149
15150 for (var i = 0; i < len; i++) {
15151 dests[i].emit('unpipe', this, unpipeInfo);
15152 }return this;
15153 }
15154
15155 // try to find the right one.
15156 var index = indexOf(state.pipes, dest);
15157 if (index === -1) return this;
15158
15159 state.pipes.splice(index, 1);
15160 state.pipesCount -= 1;
15161 if (state.pipesCount === 1) state.pipes = state.pipes[0];
15162
15163 dest.emit('unpipe', this, unpipeInfo);
15164
15165 return this;
15166};
15167
15168// set up data events if they are asked for
15169// Ensure readable listeners eventually get something
15170Readable.prototype.on = function (ev, fn) {
15171 var res = Stream.prototype.on.call(this, ev, fn);
15172
15173 if (ev === 'data') {
15174 // Start flowing on next tick if stream isn't explicitly paused
15175 if (this._readableState.flowing !== false) this.resume();
15176 } else if (ev === 'readable') {
15177 var state = this._readableState;
15178 if (!state.endEmitted && !state.readableListening) {
15179 state.readableListening = state.needReadable = true;
15180 state.emittedReadable = false;
15181 if (!state.reading) {
15182 pna.nextTick(nReadingNextTick, this);
15183 } else if (state.length) {
15184 emitReadable(this);
15185 }
15186 }
15187 }
15188
15189 return res;
15190};
15191Readable.prototype.addListener = Readable.prototype.on;
15192
15193function nReadingNextTick(self) {
15194 debug('readable nexttick read 0');
15195 self.read(0);
15196}
15197
15198// pause() and resume() are remnants of the legacy readable stream API
15199// If the user uses them, then switch into old mode.
15200Readable.prototype.resume = function () {
15201 var state = this._readableState;
15202 if (!state.flowing) {
15203 debug('resume');
15204 state.flowing = true;
15205 resume(this, state);
15206 }
15207 return this;
15208};
15209
15210function resume(stream, state) {
15211 if (!state.resumeScheduled) {
15212 state.resumeScheduled = true;
15213 pna.nextTick(resume_, stream, state);
15214 }
15215}
15216
15217function resume_(stream, state) {
15218 if (!state.reading) {
15219 debug('resume read 0');
15220 stream.read(0);
15221 }
15222
15223 state.resumeScheduled = false;
15224 state.awaitDrain = 0;
15225 stream.emit('resume');
15226 flow(stream);
15227 if (state.flowing && !state.reading) stream.read(0);
15228}
15229
15230Readable.prototype.pause = function () {
15231 debug('call pause flowing=%j', this._readableState.flowing);
15232 if (false !== this._readableState.flowing) {
15233 debug('pause');
15234 this._readableState.flowing = false;
15235 this.emit('pause');
15236 }
15237 return this;
15238};
15239
15240function flow(stream) {
15241 var state = stream._readableState;
15242 debug('flow', state.flowing);
15243 while (state.flowing && stream.read() !== null) {}
15244}
15245
15246// wrap an old-style stream as the async data source.
15247// This is *not* part of the readable stream interface.
15248// It is an ugly unfortunate mess of history.
15249Readable.prototype.wrap = function (stream) {
15250 var _this = this;
15251
15252 var state = this._readableState;
15253 var paused = false;
15254
15255 stream.on('end', function () {
15256 debug('wrapped end');
15257 if (state.decoder && !state.ended) {
15258 var chunk = state.decoder.end();
15259 if (chunk && chunk.length) _this.push(chunk);
15260 }
15261
15262 _this.push(null);
15263 });
15264
15265 stream.on('data', function (chunk) {
15266 debug('wrapped data');
15267 if (state.decoder) chunk = state.decoder.write(chunk);
15268
15269 // don't skip over falsy values in objectMode
15270 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
15271
15272 var ret = _this.push(chunk);
15273 if (!ret) {
15274 paused = true;
15275 stream.pause();
15276 }
15277 });
15278
15279 // proxy all the other methods.
15280 // important when wrapping filters and duplexes.
15281 for (var i in stream) {
15282 if (this[i] === undefined && typeof stream[i] === 'function') {
15283 this[i] = function (method) {
15284 return function () {
15285 return stream[method].apply(stream, arguments);
15286 };
15287 }(i);
15288 }
15289 }
15290
15291 // proxy certain important events.
15292 for (var n = 0; n < kProxyEvents.length; n++) {
15293 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
15294 }
15295
15296 // when we try to consume some more bytes, simply unpause the
15297 // underlying stream.
15298 this._read = function (n) {
15299 debug('wrapped _read', n);
15300 if (paused) {
15301 paused = false;
15302 stream.resume();
15303 }
15304 };
15305
15306 return this;
15307};
15308
15309Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
15310 // making it explicit this property is not enumerable
15311 // because otherwise some prototype manipulation in
15312 // userland will fail
15313 enumerable: false,
15314 get: function () {
15315 return this._readableState.highWaterMark;
15316 }
15317});
15318
15319// exposed for testing purposes only.
15320Readable._fromList = fromList;
15321
15322// Pluck off n bytes from an array of buffers.
15323// Length is the combined lengths of all the buffers in the list.
15324// This function is designed to be inlinable, so please take care when making
15325// changes to the function body.
15326function fromList(n, state) {
15327 // nothing buffered
15328 if (state.length === 0) return null;
15329
15330 var ret;
15331 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
15332 // read it all, truncate the list
15333 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);
15334 state.buffer.clear();
15335 } else {
15336 // read part of list
15337 ret = fromListPartial(n, state.buffer, state.decoder);
15338 }
15339
15340 return ret;
15341}
15342
15343// Extracts only enough buffered data to satisfy the amount requested.
15344// This function is designed to be inlinable, so please take care when making
15345// changes to the function body.
15346function fromListPartial(n, list, hasStrings) {
15347 var ret;
15348 if (n < list.head.data.length) {
15349 // slice is the same for buffers and strings
15350 ret = list.head.data.slice(0, n);
15351 list.head.data = list.head.data.slice(n);
15352 } else if (n === list.head.data.length) {
15353 // first chunk is a perfect match
15354 ret = list.shift();
15355 } else {
15356 // result spans more than one buffer
15357 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
15358 }
15359 return ret;
15360}
15361
15362// Copies a specified amount of characters from the list of buffered data
15363// chunks.
15364// This function is designed to be inlinable, so please take care when making
15365// changes to the function body.
15366function copyFromBufferString(n, list) {
15367 var p = list.head;
15368 var c = 1;
15369 var ret = p.data;
15370 n -= ret.length;
15371 while (p = p.next) {
15372 var str = p.data;
15373 var nb = n > str.length ? str.length : n;
15374 if (nb === str.length) ret += str;else ret += str.slice(0, n);
15375 n -= nb;
15376 if (n === 0) {
15377 if (nb === str.length) {
15378 ++c;
15379 if (p.next) list.head = p.next;else list.head = list.tail = null;
15380 } else {
15381 list.head = p;
15382 p.data = str.slice(nb);
15383 }
15384 break;
15385 }
15386 ++c;
15387 }
15388 list.length -= c;
15389 return ret;
15390}
15391
15392// Copies a specified amount of bytes from the list of buffered data chunks.
15393// This function is designed to be inlinable, so please take care when making
15394// changes to the function body.
15395function copyFromBuffer(n, list) {
15396 var ret = Buffer.allocUnsafe(n);
15397 var p = list.head;
15398 var c = 1;
15399 p.data.copy(ret);
15400 n -= p.data.length;
15401 while (p = p.next) {
15402 var buf = p.data;
15403 var nb = n > buf.length ? buf.length : n;
15404 buf.copy(ret, ret.length - n, 0, nb);
15405 n -= nb;
15406 if (n === 0) {
15407 if (nb === buf.length) {
15408 ++c;
15409 if (p.next) list.head = p.next;else list.head = list.tail = null;
15410 } else {
15411 list.head = p;
15412 p.data = buf.slice(nb);
15413 }
15414 break;
15415 }
15416 ++c;
15417 }
15418 list.length -= c;
15419 return ret;
15420}
15421
15422function endReadable(stream) {
15423 var state = stream._readableState;
15424
15425 // If we get here before consuming all the bytes, then that is a
15426 // bug in node. Should never happen.
15427 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
15428
15429 if (!state.endEmitted) {
15430 state.ended = true;
15431 pna.nextTick(endReadableNT, state, stream);
15432 }
15433}
15434
15435function endReadableNT(state, stream) {
15436 // Check that we didn't get one last unshift.
15437 if (!state.endEmitted && state.length === 0) {
15438 state.endEmitted = true;
15439 stream.readable = false;
15440 stream.emit('end');
15441 }
15442}
15443
15444function indexOf(xs, x) {
15445 for (var i = 0, l = xs.length; i < l; i++) {
15446 if (xs[i] === x) return i;
15447 }
15448 return -1;
15449}
15450}).call(this)}).call(this,_dereq_(73),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
15451},{"100":100,"101":101,"11":11,"14":14,"26":26,"37":37,"72":72,"73":73,"86":86,"88":88,"93":93,"94":94,"95":95}],91:[function(_dereq_,module,exports){
15452// Copyright Joyent, Inc. and other Node contributors.
15453//
15454// Permission is hereby granted, free of charge, to any person obtaining a
15455// copy of this software and associated documentation files (the
15456// "Software"), to deal in the Software without restriction, including
15457// without limitation the rights to use, copy, modify, merge, publish,
15458// distribute, sublicense, and/or sell copies of the Software, and to permit
15459// persons to whom the Software is furnished to do so, subject to the
15460// following conditions:
15461//
15462// The above copyright notice and this permission notice shall be included
15463// in all copies or substantial portions of the Software.
15464//
15465// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15466// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15467// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15468// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15469// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15470// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15471// USE OR OTHER DEALINGS IN THE SOFTWARE.
15472
15473// a transform stream is a readable/writable stream where you do
15474// something with the data. Sometimes it's called a "filter",
15475// but that's not a great name for it, since that implies a thing where
15476// some bits pass through, and others are simply ignored. (That would
15477// be a valid example of a transform, of course.)
15478//
15479// While the output is causally related to the input, it's not a
15480// necessarily symmetric or synchronous transformation. For example,
15481// a zlib stream might take multiple plain-text writes(), and then
15482// emit a single compressed chunk some time in the future.
15483//
15484// Here's how this works:
15485//
15486// The Transform stream has all the aspects of the readable and writable
15487// stream classes. When you write(chunk), that calls _write(chunk,cb)
15488// internally, and returns false if there's a lot of pending writes
15489// buffered up. When you call read(), that calls _read(n) until
15490// there's enough pending readable data buffered up.
15491//
15492// In a transform stream, the written data is placed in a buffer. When
15493// _read(n) is called, it transforms the queued up data, calling the
15494// buffered _write cb's as it consumes chunks. If consuming a single
15495// written chunk would result in multiple output chunks, then the first
15496// outputted bit calls the readcb, and subsequent chunks just go into
15497// the read buffer, and will cause it to emit 'readable' if necessary.
15498//
15499// This way, back-pressure is actually determined by the reading side,
15500// since _read has to be called to start processing a new chunk. However,
15501// a pathological inflate type of transform can cause excessive buffering
15502// here. For example, imagine a stream where every byte of input is
15503// interpreted as an integer from 0-255, and then results in that many
15504// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
15505// 1kb of data being output. In this case, you could write a very small
15506// amount of input, and end up with a very large amount of output. In
15507// such a pathological inflating mechanism, there'd be no way to tell
15508// the system to stop doing the transform. A single 4MB write could
15509// cause the system to run out of memory.
15510//
15511// However, even in such a pathological case, only a single written chunk
15512// would be consumed, and then the rest would wait (un-transformed) until
15513// the results of the previous transformed chunk were consumed.
15514
15515'use strict';
15516
15517module.exports = Transform;
15518
15519var Duplex = _dereq_(88);
15520
15521/*<replacement>*/
15522var util = Object.create(_dereq_(14));
15523util.inherits = _dereq_(37);
15524/*</replacement>*/
15525
15526util.inherits(Transform, Duplex);
15527
15528function afterTransform(er, data) {
15529 var ts = this._transformState;
15530 ts.transforming = false;
15531
15532 var cb = ts.writecb;
15533
15534 if (!cb) {
15535 return this.emit('error', new Error('write callback called multiple times'));
15536 }
15537
15538 ts.writechunk = null;
15539 ts.writecb = null;
15540
15541 if (data != null) // single equals check for both `null` and `undefined`
15542 this.push(data);
15543
15544 cb(er);
15545
15546 var rs = this._readableState;
15547 rs.reading = false;
15548 if (rs.needReadable || rs.length < rs.highWaterMark) {
15549 this._read(rs.highWaterMark);
15550 }
15551}
15552
15553function Transform(options) {
15554 if (!(this instanceof Transform)) return new Transform(options);
15555
15556 Duplex.call(this, options);
15557
15558 this._transformState = {
15559 afterTransform: afterTransform.bind(this),
15560 needTransform: false,
15561 transforming: false,
15562 writecb: null,
15563 writechunk: null,
15564 writeencoding: null
15565 };
15566
15567 // start out asking for a readable event once data is transformed.
15568 this._readableState.needReadable = true;
15569
15570 // we have implemented the _read method, and done the other things
15571 // that Readable wants before the first _read call, so unset the
15572 // sync guard flag.
15573 this._readableState.sync = false;
15574
15575 if (options) {
15576 if (typeof options.transform === 'function') this._transform = options.transform;
15577
15578 if (typeof options.flush === 'function') this._flush = options.flush;
15579 }
15580
15581 // When the writable side finishes, then flush out anything remaining.
15582 this.on('prefinish', prefinish);
15583}
15584
15585function prefinish() {
15586 var _this = this;
15587
15588 if (typeof this._flush === 'function') {
15589 this._flush(function (er, data) {
15590 done(_this, er, data);
15591 });
15592 } else {
15593 done(this, null, null);
15594 }
15595}
15596
15597Transform.prototype.push = function (chunk, encoding) {
15598 this._transformState.needTransform = false;
15599 return Duplex.prototype.push.call(this, chunk, encoding);
15600};
15601
15602// This is the part where you do stuff!
15603// override this function in implementation classes.
15604// 'chunk' is an input chunk.
15605//
15606// Call `push(newChunk)` to pass along transformed output
15607// to the readable side. You may call 'push' zero or more times.
15608//
15609// Call `cb(err)` when you are done with this chunk. If you pass
15610// an error, then that'll put the hurt on the whole operation. If you
15611// never call cb(), then you'll never get another chunk.
15612Transform.prototype._transform = function (chunk, encoding, cb) {
15613 throw new Error('_transform() is not implemented');
15614};
15615
15616Transform.prototype._write = function (chunk, encoding, cb) {
15617 var ts = this._transformState;
15618 ts.writecb = cb;
15619 ts.writechunk = chunk;
15620 ts.writeencoding = encoding;
15621 if (!ts.transforming) {
15622 var rs = this._readableState;
15623 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
15624 }
15625};
15626
15627// Doesn't matter what the args are here.
15628// _transform does all the work.
15629// That we got here means that the readable side wants more data.
15630Transform.prototype._read = function (n) {
15631 var ts = this._transformState;
15632
15633 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
15634 ts.transforming = true;
15635 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
15636 } else {
15637 // mark that we need a transform, so that any data that comes in
15638 // will get processed, now that we've asked for it.
15639 ts.needTransform = true;
15640 }
15641};
15642
15643Transform.prototype._destroy = function (err, cb) {
15644 var _this2 = this;
15645
15646 Duplex.prototype._destroy.call(this, err, function (err2) {
15647 cb(err2);
15648 _this2.emit('close');
15649 });
15650};
15651
15652function done(stream, er, data) {
15653 if (er) return stream.emit('error', er);
15654
15655 if (data != null) // single equals check for both `null` and `undefined`
15656 stream.push(data);
15657
15658 // if there's nothing in the write buffer, then that means
15659 // that nothing more will ever be provided
15660 if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
15661
15662 if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
15663
15664 return stream.push(null);
15665}
15666},{"14":14,"37":37,"88":88}],92:[function(_dereq_,module,exports){
15667(function (process,global,setImmediate){(function (){
15668// Copyright Joyent, Inc. and other Node contributors.
15669//
15670// Permission is hereby granted, free of charge, to any person obtaining a
15671// copy of this software and associated documentation files (the
15672// "Software"), to deal in the Software without restriction, including
15673// without limitation the rights to use, copy, modify, merge, publish,
15674// distribute, sublicense, and/or sell copies of the Software, and to permit
15675// persons to whom the Software is furnished to do so, subject to the
15676// following conditions:
15677//
15678// The above copyright notice and this permission notice shall be included
15679// in all copies or substantial portions of the Software.
15680//
15681// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15682// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15683// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15684// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15685// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15686// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15687// USE OR OTHER DEALINGS IN THE SOFTWARE.
15688
15689// A bit simpler than readable streams.
15690// Implement an async ._write(chunk, encoding, cb), and it'll handle all
15691// the drain event emission and buffering.
15692
15693'use strict';
15694
15695/*<replacement>*/
15696
15697var pna = _dereq_(72);
15698/*</replacement>*/
15699
15700module.exports = Writable;
15701
15702/* <replacement> */
15703function WriteReq(chunk, encoding, cb) {
15704 this.chunk = chunk;
15705 this.encoding = encoding;
15706 this.callback = cb;
15707 this.next = null;
15708}
15709
15710// It seems a linked list but it is not
15711// there will be only 2 of these for each stream
15712function CorkedRequest(state) {
15713 var _this = this;
15714
15715 this.next = null;
15716 this.entry = null;
15717 this.finish = function () {
15718 onCorkedFinish(_this, state);
15719 };
15720}
15721/* </replacement> */
15722
15723/*<replacement>*/
15724var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
15725/*</replacement>*/
15726
15727/*<replacement>*/
15728var Duplex;
15729/*</replacement>*/
15730
15731Writable.WritableState = WritableState;
15732
15733/*<replacement>*/
15734var util = Object.create(_dereq_(14));
15735util.inherits = _dereq_(37);
15736/*</replacement>*/
15737
15738/*<replacement>*/
15739var internalUtil = {
15740 deprecate: _dereq_(121)
15741};
15742/*</replacement>*/
15743
15744/*<replacement>*/
15745var Stream = _dereq_(95);
15746/*</replacement>*/
15747
15748/*<replacement>*/
15749
15750var Buffer = _dereq_(100).Buffer;
15751var OurUint8Array = global.Uint8Array || function () {};
15752function _uint8ArrayToBuffer(chunk) {
15753 return Buffer.from(chunk);
15754}
15755function _isUint8Array(obj) {
15756 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
15757}
15758
15759/*</replacement>*/
15760
15761var destroyImpl = _dereq_(94);
15762
15763util.inherits(Writable, Stream);
15764
15765function nop() {}
15766
15767function WritableState(options, stream) {
15768 Duplex = Duplex || _dereq_(88);
15769
15770 options = options || {};
15771
15772 // Duplex streams are both readable and writable, but share
15773 // the same options object.
15774 // However, some cases require setting options to different
15775 // values for the readable and the writable sides of the duplex stream.
15776 // These options can be provided separately as readableXXX and writableXXX.
15777 var isDuplex = stream instanceof Duplex;
15778
15779 // object stream flag to indicate whether or not this stream
15780 // contains buffers or objects.
15781 this.objectMode = !!options.objectMode;
15782
15783 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
15784
15785 // the point at which write() starts returning false
15786 // Note: 0 is a valid value, means that we always return false if
15787 // the entire buffer is not flushed immediately on write()
15788 var hwm = options.highWaterMark;
15789 var writableHwm = options.writableHighWaterMark;
15790 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
15791
15792 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
15793
15794 // cast to ints.
15795 this.highWaterMark = Math.floor(this.highWaterMark);
15796
15797 // if _final has been called
15798 this.finalCalled = false;
15799
15800 // drain event flag.
15801 this.needDrain = false;
15802 // at the start of calling end()
15803 this.ending = false;
15804 // when end() has been called, and returned
15805 this.ended = false;
15806 // when 'finish' is emitted
15807 this.finished = false;
15808
15809 // has it been destroyed
15810 this.destroyed = false;
15811
15812 // should we decode strings into buffers before passing to _write?
15813 // this is here so that some node-core streams can optimize string
15814 // handling at a lower level.
15815 var noDecode = options.decodeStrings === false;
15816 this.decodeStrings = !noDecode;
15817
15818 // Crypto is kind of old and crusty. Historically, its default string
15819 // encoding is 'binary' so we have to make this configurable.
15820 // Everything else in the universe uses 'utf8', though.
15821 this.defaultEncoding = options.defaultEncoding || 'utf8';
15822
15823 // not an actual buffer we keep track of, but a measurement
15824 // of how much we're waiting to get pushed to some underlying
15825 // socket or file.
15826 this.length = 0;
15827
15828 // a flag to see when we're in the middle of a write.
15829 this.writing = false;
15830
15831 // when true all writes will be buffered until .uncork() call
15832 this.corked = 0;
15833
15834 // a flag to be able to tell if the onwrite cb is called immediately,
15835 // or on a later tick. We set this to true at first, because any
15836 // actions that shouldn't happen until "later" should generally also
15837 // not happen before the first write call.
15838 this.sync = true;
15839
15840 // a flag to know if we're processing previously buffered items, which
15841 // may call the _write() callback in the same tick, so that we don't
15842 // end up in an overlapped onwrite situation.
15843 this.bufferProcessing = false;
15844
15845 // the callback that's passed to _write(chunk,cb)
15846 this.onwrite = function (er) {
15847 onwrite(stream, er);
15848 };
15849
15850 // the callback that the user supplies to write(chunk,encoding,cb)
15851 this.writecb = null;
15852
15853 // the amount that is being written when _write is called.
15854 this.writelen = 0;
15855
15856 this.bufferedRequest = null;
15857 this.lastBufferedRequest = null;
15858
15859 // number of pending user-supplied write callbacks
15860 // this must be 0 before 'finish' can be emitted
15861 this.pendingcb = 0;
15862
15863 // emit prefinish if the only thing we're waiting for is _write cbs
15864 // This is relevant for synchronous Transform streams
15865 this.prefinished = false;
15866
15867 // True if the error was already emitted and should not be thrown again
15868 this.errorEmitted = false;
15869
15870 // count buffered requests
15871 this.bufferedRequestCount = 0;
15872
15873 // allocate the first CorkedRequest, there is always
15874 // one allocated and free to use, and we maintain at most two
15875 this.corkedRequestsFree = new CorkedRequest(this);
15876}
15877
15878WritableState.prototype.getBuffer = function getBuffer() {
15879 var current = this.bufferedRequest;
15880 var out = [];
15881 while (current) {
15882 out.push(current);
15883 current = current.next;
15884 }
15885 return out;
15886};
15887
15888(function () {
15889 try {
15890 Object.defineProperty(WritableState.prototype, 'buffer', {
15891 get: internalUtil.deprecate(function () {
15892 return this.getBuffer();
15893 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
15894 });
15895 } catch (_) {}
15896})();
15897
15898// Test _writableState for inheritance to account for Duplex streams,
15899// whose prototype chain only points to Readable.
15900var realHasInstance;
15901if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
15902 realHasInstance = Function.prototype[Symbol.hasInstance];
15903 Object.defineProperty(Writable, Symbol.hasInstance, {
15904 value: function (object) {
15905 if (realHasInstance.call(this, object)) return true;
15906 if (this !== Writable) return false;
15907
15908 return object && object._writableState instanceof WritableState;
15909 }
15910 });
15911} else {
15912 realHasInstance = function (object) {
15913 return object instanceof this;
15914 };
15915}
15916
15917function Writable(options) {
15918 Duplex = Duplex || _dereq_(88);
15919
15920 // Writable ctor is applied to Duplexes, too.
15921 // `realHasInstance` is necessary because using plain `instanceof`
15922 // would return false, as no `_writableState` property is attached.
15923
15924 // Trying to use the custom `instanceof` for Writable here will also break the
15925 // Node.js LazyTransform implementation, which has a non-trivial getter for
15926 // `_writableState` that would lead to infinite recursion.
15927 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
15928 return new Writable(options);
15929 }
15930
15931 this._writableState = new WritableState(options, this);
15932
15933 // legacy.
15934 this.writable = true;
15935
15936 if (options) {
15937 if (typeof options.write === 'function') this._write = options.write;
15938
15939 if (typeof options.writev === 'function') this._writev = options.writev;
15940
15941 if (typeof options.destroy === 'function') this._destroy = options.destroy;
15942
15943 if (typeof options.final === 'function') this._final = options.final;
15944 }
15945
15946 Stream.call(this);
15947}
15948
15949// Otherwise people can pipe Writable streams, which is just wrong.
15950Writable.prototype.pipe = function () {
15951 this.emit('error', new Error('Cannot pipe, not readable'));
15952};
15953
15954function writeAfterEnd(stream, cb) {
15955 var er = new Error('write after end');
15956 // TODO: defer error events consistently everywhere, not just the cb
15957 stream.emit('error', er);
15958 pna.nextTick(cb, er);
15959}
15960
15961// Checks that a user-supplied chunk is valid, especially for the particular
15962// mode the stream is in. Currently this means that `null` is never accepted
15963// and undefined/non-string values are only allowed in object mode.
15964function validChunk(stream, state, chunk, cb) {
15965 var valid = true;
15966 var er = false;
15967
15968 if (chunk === null) {
15969 er = new TypeError('May not write null values to stream');
15970 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
15971 er = new TypeError('Invalid non-string/buffer chunk');
15972 }
15973 if (er) {
15974 stream.emit('error', er);
15975 pna.nextTick(cb, er);
15976 valid = false;
15977 }
15978 return valid;
15979}
15980
15981Writable.prototype.write = function (chunk, encoding, cb) {
15982 var state = this._writableState;
15983 var ret = false;
15984 var isBuf = !state.objectMode && _isUint8Array(chunk);
15985
15986 if (isBuf && !Buffer.isBuffer(chunk)) {
15987 chunk = _uint8ArrayToBuffer(chunk);
15988 }
15989
15990 if (typeof encoding === 'function') {
15991 cb = encoding;
15992 encoding = null;
15993 }
15994
15995 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
15996
15997 if (typeof cb !== 'function') cb = nop;
15998
15999 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
16000 state.pendingcb++;
16001 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
16002 }
16003
16004 return ret;
16005};
16006
16007Writable.prototype.cork = function () {
16008 var state = this._writableState;
16009
16010 state.corked++;
16011};
16012
16013Writable.prototype.uncork = function () {
16014 var state = this._writableState;
16015
16016 if (state.corked) {
16017 state.corked--;
16018
16019 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
16020 }
16021};
16022
16023Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
16024 // node::ParseEncoding() requires lower case.
16025 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
16026 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);
16027 this._writableState.defaultEncoding = encoding;
16028 return this;
16029};
16030
16031function decodeChunk(state, chunk, encoding) {
16032 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
16033 chunk = Buffer.from(chunk, encoding);
16034 }
16035 return chunk;
16036}
16037
16038Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
16039 // making it explicit this property is not enumerable
16040 // because otherwise some prototype manipulation in
16041 // userland will fail
16042 enumerable: false,
16043 get: function () {
16044 return this._writableState.highWaterMark;
16045 }
16046});
16047
16048// if we're already writing something, then just put this
16049// in the queue, and wait our turn. Otherwise, call _write
16050// If we return false, then we need a drain event, so set that flag.
16051function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
16052 if (!isBuf) {
16053 var newChunk = decodeChunk(state, chunk, encoding);
16054 if (chunk !== newChunk) {
16055 isBuf = true;
16056 encoding = 'buffer';
16057 chunk = newChunk;
16058 }
16059 }
16060 var len = state.objectMode ? 1 : chunk.length;
16061
16062 state.length += len;
16063
16064 var ret = state.length < state.highWaterMark;
16065 // we must ensure that previous needDrain will not be reset to false.
16066 if (!ret) state.needDrain = true;
16067
16068 if (state.writing || state.corked) {
16069 var last = state.lastBufferedRequest;
16070 state.lastBufferedRequest = {
16071 chunk: chunk,
16072 encoding: encoding,
16073 isBuf: isBuf,
16074 callback: cb,
16075 next: null
16076 };
16077 if (last) {
16078 last.next = state.lastBufferedRequest;
16079 } else {
16080 state.bufferedRequest = state.lastBufferedRequest;
16081 }
16082 state.bufferedRequestCount += 1;
16083 } else {
16084 doWrite(stream, state, false, len, chunk, encoding, cb);
16085 }
16086
16087 return ret;
16088}
16089
16090function doWrite(stream, state, writev, len, chunk, encoding, cb) {
16091 state.writelen = len;
16092 state.writecb = cb;
16093 state.writing = true;
16094 state.sync = true;
16095 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
16096 state.sync = false;
16097}
16098
16099function onwriteError(stream, state, sync, er, cb) {
16100 --state.pendingcb;
16101
16102 if (sync) {
16103 // defer the callback if we are being called synchronously
16104 // to avoid piling up things on the stack
16105 pna.nextTick(cb, er);
16106 // this can emit finish, and it will always happen
16107 // after error
16108 pna.nextTick(finishMaybe, stream, state);
16109 stream._writableState.errorEmitted = true;
16110 stream.emit('error', er);
16111 } else {
16112 // the caller expect this to happen before if
16113 // it is async
16114 cb(er);
16115 stream._writableState.errorEmitted = true;
16116 stream.emit('error', er);
16117 // this can emit finish, but finish must
16118 // always follow error
16119 finishMaybe(stream, state);
16120 }
16121}
16122
16123function onwriteStateUpdate(state) {
16124 state.writing = false;
16125 state.writecb = null;
16126 state.length -= state.writelen;
16127 state.writelen = 0;
16128}
16129
16130function onwrite(stream, er) {
16131 var state = stream._writableState;
16132 var sync = state.sync;
16133 var cb = state.writecb;
16134
16135 onwriteStateUpdate(state);
16136
16137 if (er) onwriteError(stream, state, sync, er, cb);else {
16138 // Check if we're actually ready to finish, but don't emit yet
16139 var finished = needFinish(state);
16140
16141 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
16142 clearBuffer(stream, state);
16143 }
16144
16145 if (sync) {
16146 /*<replacement>*/
16147 asyncWrite(afterWrite, stream, state, finished, cb);
16148 /*</replacement>*/
16149 } else {
16150 afterWrite(stream, state, finished, cb);
16151 }
16152 }
16153}
16154
16155function afterWrite(stream, state, finished, cb) {
16156 if (!finished) onwriteDrain(stream, state);
16157 state.pendingcb--;
16158 cb();
16159 finishMaybe(stream, state);
16160}
16161
16162// Must force callback to be called on nextTick, so that we don't
16163// emit 'drain' before the write() consumer gets the 'false' return
16164// value, and has a chance to attach a 'drain' listener.
16165function onwriteDrain(stream, state) {
16166 if (state.length === 0 && state.needDrain) {
16167 state.needDrain = false;
16168 stream.emit('drain');
16169 }
16170}
16171
16172// if there's something in the buffer waiting, then process it
16173function clearBuffer(stream, state) {
16174 state.bufferProcessing = true;
16175 var entry = state.bufferedRequest;
16176
16177 if (stream._writev && entry && entry.next) {
16178 // Fast case, write everything using _writev()
16179 var l = state.bufferedRequestCount;
16180 var buffer = new Array(l);
16181 var holder = state.corkedRequestsFree;
16182 holder.entry = entry;
16183
16184 var count = 0;
16185 var allBuffers = true;
16186 while (entry) {
16187 buffer[count] = entry;
16188 if (!entry.isBuf) allBuffers = false;
16189 entry = entry.next;
16190 count += 1;
16191 }
16192 buffer.allBuffers = allBuffers;
16193
16194 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
16195
16196 // doWrite is almost always async, defer these to save a bit of time
16197 // as the hot path ends with doWrite
16198 state.pendingcb++;
16199 state.lastBufferedRequest = null;
16200 if (holder.next) {
16201 state.corkedRequestsFree = holder.next;
16202 holder.next = null;
16203 } else {
16204 state.corkedRequestsFree = new CorkedRequest(state);
16205 }
16206 state.bufferedRequestCount = 0;
16207 } else {
16208 // Slow case, write chunks one-by-one
16209 while (entry) {
16210 var chunk = entry.chunk;
16211 var encoding = entry.encoding;
16212 var cb = entry.callback;
16213 var len = state.objectMode ? 1 : chunk.length;
16214
16215 doWrite(stream, state, false, len, chunk, encoding, cb);
16216 entry = entry.next;
16217 state.bufferedRequestCount--;
16218 // if we didn't call the onwrite immediately, then
16219 // it means that we need to wait until it does.
16220 // also, that means that the chunk and cb are currently
16221 // being processed, so move the buffer counter past them.
16222 if (state.writing) {
16223 break;
16224 }
16225 }
16226
16227 if (entry === null) state.lastBufferedRequest = null;
16228 }
16229
16230 state.bufferedRequest = entry;
16231 state.bufferProcessing = false;
16232}
16233
16234Writable.prototype._write = function (chunk, encoding, cb) {
16235 cb(new Error('_write() is not implemented'));
16236};
16237
16238Writable.prototype._writev = null;
16239
16240Writable.prototype.end = function (chunk, encoding, cb) {
16241 var state = this._writableState;
16242
16243 if (typeof chunk === 'function') {
16244 cb = chunk;
16245 chunk = null;
16246 encoding = null;
16247 } else if (typeof encoding === 'function') {
16248 cb = encoding;
16249 encoding = null;
16250 }
16251
16252 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
16253
16254 // .end() fully uncorks
16255 if (state.corked) {
16256 state.corked = 1;
16257 this.uncork();
16258 }
16259
16260 // ignore unnecessary end() calls.
16261 if (!state.ending && !state.finished) endWritable(this, state, cb);
16262};
16263
16264function needFinish(state) {
16265 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
16266}
16267function callFinal(stream, state) {
16268 stream._final(function (err) {
16269 state.pendingcb--;
16270 if (err) {
16271 stream.emit('error', err);
16272 }
16273 state.prefinished = true;
16274 stream.emit('prefinish');
16275 finishMaybe(stream, state);
16276 });
16277}
16278function prefinish(stream, state) {
16279 if (!state.prefinished && !state.finalCalled) {
16280 if (typeof stream._final === 'function') {
16281 state.pendingcb++;
16282 state.finalCalled = true;
16283 pna.nextTick(callFinal, stream, state);
16284 } else {
16285 state.prefinished = true;
16286 stream.emit('prefinish');
16287 }
16288 }
16289}
16290
16291function finishMaybe(stream, state) {
16292 var need = needFinish(state);
16293 if (need) {
16294 prefinish(stream, state);
16295 if (state.pendingcb === 0) {
16296 state.finished = true;
16297 stream.emit('finish');
16298 }
16299 }
16300 return need;
16301}
16302
16303function endWritable(stream, state, cb) {
16304 state.ending = true;
16305 finishMaybe(stream, state);
16306 if (cb) {
16307 if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
16308 }
16309 state.ended = true;
16310 stream.writable = false;
16311}
16312
16313function onCorkedFinish(corkReq, state, err) {
16314 var entry = corkReq.entry;
16315 corkReq.entry = null;
16316 while (entry) {
16317 var cb = entry.callback;
16318 state.pendingcb--;
16319 cb(err);
16320 entry = entry.next;
16321 }
16322 if (state.corkedRequestsFree) {
16323 state.corkedRequestsFree.next = corkReq;
16324 } else {
16325 state.corkedRequestsFree = corkReq;
16326 }
16327}
16328
16329Object.defineProperty(Writable.prototype, 'destroyed', {
16330 get: function () {
16331 if (this._writableState === undefined) {
16332 return false;
16333 }
16334 return this._writableState.destroyed;
16335 },
16336 set: function (value) {
16337 // we ignore the value if the stream
16338 // has not been initialized yet
16339 if (!this._writableState) {
16340 return;
16341 }
16342
16343 // backward compatibility, the user is explicitly
16344 // managing destroyed
16345 this._writableState.destroyed = value;
16346 }
16347});
16348
16349Writable.prototype.destroy = destroyImpl.destroy;
16350Writable.prototype._undestroy = destroyImpl.undestroy;
16351Writable.prototype._destroy = function (err, cb) {
16352 this.end();
16353 cb(err);
16354};
16355}).call(this)}).call(this,_dereq_(73),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_(119).setImmediate)
16356},{"100":100,"119":119,"121":121,"14":14,"37":37,"72":72,"73":73,"88":88,"94":94,"95":95}],93:[function(_dereq_,module,exports){
16357'use strict';
16358
16359function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
16360
16361var Buffer = _dereq_(100).Buffer;
16362var util = _dereq_(11);
16363
16364function copyBuffer(src, target, offset) {
16365 src.copy(target, offset);
16366}
16367
16368module.exports = function () {
16369 function BufferList() {
16370 _classCallCheck(this, BufferList);
16371
16372 this.head = null;
16373 this.tail = null;
16374 this.length = 0;
16375 }
16376
16377 BufferList.prototype.push = function push(v) {
16378 var entry = { data: v, next: null };
16379 if (this.length > 0) this.tail.next = entry;else this.head = entry;
16380 this.tail = entry;
16381 ++this.length;
16382 };
16383
16384 BufferList.prototype.unshift = function unshift(v) {
16385 var entry = { data: v, next: this.head };
16386 if (this.length === 0) this.tail = entry;
16387 this.head = entry;
16388 ++this.length;
16389 };
16390
16391 BufferList.prototype.shift = function shift() {
16392 if (this.length === 0) return;
16393 var ret = this.head.data;
16394 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
16395 --this.length;
16396 return ret;
16397 };
16398
16399 BufferList.prototype.clear = function clear() {
16400 this.head = this.tail = null;
16401 this.length = 0;
16402 };
16403
16404 BufferList.prototype.join = function join(s) {
16405 if (this.length === 0) return '';
16406 var p = this.head;
16407 var ret = '' + p.data;
16408 while (p = p.next) {
16409 ret += s + p.data;
16410 }return ret;
16411 };
16412
16413 BufferList.prototype.concat = function concat(n) {
16414 if (this.length === 0) return Buffer.alloc(0);
16415 if (this.length === 1) return this.head.data;
16416 var ret = Buffer.allocUnsafe(n >>> 0);
16417 var p = this.head;
16418 var i = 0;
16419 while (p) {
16420 copyBuffer(p.data, ret, i);
16421 i += p.data.length;
16422 p = p.next;
16423 }
16424 return ret;
16425 };
16426
16427 return BufferList;
16428}();
16429
16430if (util && util.inspect && util.inspect.custom) {
16431 module.exports.prototype[util.inspect.custom] = function () {
16432 var obj = util.inspect({ length: this.length });
16433 return this.constructor.name + ' ' + obj;
16434 };
16435}
16436},{"100":100,"11":11}],94:[function(_dereq_,module,exports){
16437'use strict';
16438
16439/*<replacement>*/
16440
16441var pna = _dereq_(72);
16442/*</replacement>*/
16443
16444// undocumented cb() API, needed for core, not for public API
16445function destroy(err, cb) {
16446 var _this = this;
16447
16448 var readableDestroyed = this._readableState && this._readableState.destroyed;
16449 var writableDestroyed = this._writableState && this._writableState.destroyed;
16450
16451 if (readableDestroyed || writableDestroyed) {
16452 if (cb) {
16453 cb(err);
16454 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
16455 pna.nextTick(emitErrorNT, this, err);
16456 }
16457 return this;
16458 }
16459
16460 // we set destroyed to true before firing error callbacks in order
16461 // to make it re-entrance safe in case destroy() is called within callbacks
16462
16463 if (this._readableState) {
16464 this._readableState.destroyed = true;
16465 }
16466
16467 // if this is a duplex stream mark the writable part as destroyed as well
16468 if (this._writableState) {
16469 this._writableState.destroyed = true;
16470 }
16471
16472 this._destroy(err || null, function (err) {
16473 if (!cb && err) {
16474 pna.nextTick(emitErrorNT, _this, err);
16475 if (_this._writableState) {
16476 _this._writableState.errorEmitted = true;
16477 }
16478 } else if (cb) {
16479 cb(err);
16480 }
16481 });
16482
16483 return this;
16484}
16485
16486function undestroy() {
16487 if (this._readableState) {
16488 this._readableState.destroyed = false;
16489 this._readableState.reading = false;
16490 this._readableState.ended = false;
16491 this._readableState.endEmitted = false;
16492 }
16493
16494 if (this._writableState) {
16495 this._writableState.destroyed = false;
16496 this._writableState.ended = false;
16497 this._writableState.ending = false;
16498 this._writableState.finished = false;
16499 this._writableState.errorEmitted = false;
16500 }
16501}
16502
16503function emitErrorNT(self, err) {
16504 self.emit('error', err);
16505}
16506
16507module.exports = {
16508 destroy: destroy,
16509 undestroy: undestroy
16510};
16511},{"72":72}],95:[function(_dereq_,module,exports){
16512arguments[4][56][0].apply(exports,arguments)
16513},{"26":26,"56":56}],96:[function(_dereq_,module,exports){
16514module.exports = _dereq_(97).PassThrough
16515
16516},{"97":97}],97:[function(_dereq_,module,exports){
16517exports = module.exports = _dereq_(90);
16518exports.Stream = exports;
16519exports.Readable = exports;
16520exports.Writable = _dereq_(92);
16521exports.Duplex = _dereq_(88);
16522exports.Transform = _dereq_(91);
16523exports.PassThrough = _dereq_(89);
16524
16525},{"88":88,"89":89,"90":90,"91":91,"92":92}],98:[function(_dereq_,module,exports){
16526module.exports = _dereq_(97).Transform
16527
16528},{"97":97}],99:[function(_dereq_,module,exports){
16529module.exports = _dereq_(92);
16530
16531},{"92":92}],100:[function(_dereq_,module,exports){
16532/* eslint-disable node/no-deprecated-api */
16533var buffer = _dereq_(13)
16534var Buffer = buffer.Buffer
16535
16536// alternative to using Object.keys for old browsers
16537function copyProps (src, dst) {
16538 for (var key in src) {
16539 dst[key] = src[key]
16540 }
16541}
16542if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
16543 module.exports = buffer
16544} else {
16545 // Copy properties from require('buffer')
16546 copyProps(buffer, exports)
16547 exports.Buffer = SafeBuffer
16548}
16549
16550function SafeBuffer (arg, encodingOrOffset, length) {
16551 return Buffer(arg, encodingOrOffset, length)
16552}
16553
16554// Copy static methods from Buffer
16555copyProps(Buffer, SafeBuffer)
16556
16557SafeBuffer.from = function (arg, encodingOrOffset, length) {
16558 if (typeof arg === 'number') {
16559 throw new TypeError('Argument must not be a number')
16560 }
16561 return Buffer(arg, encodingOrOffset, length)
16562}
16563
16564SafeBuffer.alloc = function (size, fill, encoding) {
16565 if (typeof size !== 'number') {
16566 throw new TypeError('Argument must be a number')
16567 }
16568 var buf = Buffer(size)
16569 if (fill !== undefined) {
16570 if (typeof encoding === 'string') {
16571 buf.fill(fill, encoding)
16572 } else {
16573 buf.fill(fill)
16574 }
16575 } else {
16576 buf.fill(0)
16577 }
16578 return buf
16579}
16580
16581SafeBuffer.allocUnsafe = function (size) {
16582 if (typeof size !== 'number') {
16583 throw new TypeError('Argument must be a number')
16584 }
16585 return Buffer(size)
16586}
16587
16588SafeBuffer.allocUnsafeSlow = function (size) {
16589 if (typeof size !== 'number') {
16590 throw new TypeError('Argument must be a number')
16591 }
16592 return buffer.SlowBuffer(size)
16593}
16594
16595},{"13":13}],101:[function(_dereq_,module,exports){
16596// Copyright Joyent, Inc. and other Node contributors.
16597//
16598// Permission is hereby granted, free of charge, to any person obtaining a
16599// copy of this software and associated documentation files (the
16600// "Software"), to deal in the Software without restriction, including
16601// without limitation the rights to use, copy, modify, merge, publish,
16602// distribute, sublicense, and/or sell copies of the Software, and to permit
16603// persons to whom the Software is furnished to do so, subject to the
16604// following conditions:
16605//
16606// The above copyright notice and this permission notice shall be included
16607// in all copies or substantial portions of the Software.
16608//
16609// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16610// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16611// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
16612// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
16613// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16614// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
16615// USE OR OTHER DEALINGS IN THE SOFTWARE.
16616
16617'use strict';
16618
16619/*<replacement>*/
16620
16621var Buffer = _dereq_(100).Buffer;
16622/*</replacement>*/
16623
16624var isEncoding = Buffer.isEncoding || function (encoding) {
16625 encoding = '' + encoding;
16626 switch (encoding && encoding.toLowerCase()) {
16627 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':
16628 return true;
16629 default:
16630 return false;
16631 }
16632};
16633
16634function _normalizeEncoding(enc) {
16635 if (!enc) return 'utf8';
16636 var retried;
16637 while (true) {
16638 switch (enc) {
16639 case 'utf8':
16640 case 'utf-8':
16641 return 'utf8';
16642 case 'ucs2':
16643 case 'ucs-2':
16644 case 'utf16le':
16645 case 'utf-16le':
16646 return 'utf16le';
16647 case 'latin1':
16648 case 'binary':
16649 return 'latin1';
16650 case 'base64':
16651 case 'ascii':
16652 case 'hex':
16653 return enc;
16654 default:
16655 if (retried) return; // undefined
16656 enc = ('' + enc).toLowerCase();
16657 retried = true;
16658 }
16659 }
16660};
16661
16662// Do not cache `Buffer.isEncoding` when checking encoding names as some
16663// modules monkey-patch it to support additional encodings
16664function normalizeEncoding(enc) {
16665 var nenc = _normalizeEncoding(enc);
16666 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
16667 return nenc || enc;
16668}
16669
16670// StringDecoder provides an interface for efficiently splitting a series of
16671// buffers into a series of JS strings without breaking apart multi-byte
16672// characters.
16673exports.StringDecoder = StringDecoder;
16674function StringDecoder(encoding) {
16675 this.encoding = normalizeEncoding(encoding);
16676 var nb;
16677 switch (this.encoding) {
16678 case 'utf16le':
16679 this.text = utf16Text;
16680 this.end = utf16End;
16681 nb = 4;
16682 break;
16683 case 'utf8':
16684 this.fillLast = utf8FillLast;
16685 nb = 4;
16686 break;
16687 case 'base64':
16688 this.text = base64Text;
16689 this.end = base64End;
16690 nb = 3;
16691 break;
16692 default:
16693 this.write = simpleWrite;
16694 this.end = simpleEnd;
16695 return;
16696 }
16697 this.lastNeed = 0;
16698 this.lastTotal = 0;
16699 this.lastChar = Buffer.allocUnsafe(nb);
16700}
16701
16702StringDecoder.prototype.write = function (buf) {
16703 if (buf.length === 0) return '';
16704 var r;
16705 var i;
16706 if (this.lastNeed) {
16707 r = this.fillLast(buf);
16708 if (r === undefined) return '';
16709 i = this.lastNeed;
16710 this.lastNeed = 0;
16711 } else {
16712 i = 0;
16713 }
16714 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
16715 return r || '';
16716};
16717
16718StringDecoder.prototype.end = utf8End;
16719
16720// Returns only complete characters in a Buffer
16721StringDecoder.prototype.text = utf8Text;
16722
16723// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
16724StringDecoder.prototype.fillLast = function (buf) {
16725 if (this.lastNeed <= buf.length) {
16726 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
16727 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
16728 }
16729 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
16730 this.lastNeed -= buf.length;
16731};
16732
16733// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
16734// continuation byte. If an invalid byte is detected, -2 is returned.
16735function utf8CheckByte(byte) {
16736 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;
16737 return byte >> 6 === 0x02 ? -1 : -2;
16738}
16739
16740// Checks at most 3 bytes at the end of a Buffer in order to detect an
16741// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
16742// needed to complete the UTF-8 character (if applicable) are returned.
16743function utf8CheckIncomplete(self, buf, i) {
16744 var j = buf.length - 1;
16745 if (j < i) return 0;
16746 var nb = utf8CheckByte(buf[j]);
16747 if (nb >= 0) {
16748 if (nb > 0) self.lastNeed = nb - 1;
16749 return nb;
16750 }
16751 if (--j < i || nb === -2) return 0;
16752 nb = utf8CheckByte(buf[j]);
16753 if (nb >= 0) {
16754 if (nb > 0) self.lastNeed = nb - 2;
16755 return nb;
16756 }
16757 if (--j < i || nb === -2) return 0;
16758 nb = utf8CheckByte(buf[j]);
16759 if (nb >= 0) {
16760 if (nb > 0) {
16761 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
16762 }
16763 return nb;
16764 }
16765 return 0;
16766}
16767
16768// Validates as many continuation bytes for a multi-byte UTF-8 character as
16769// needed or are available. If we see a non-continuation byte where we expect
16770// one, we "replace" the validated continuation bytes we've seen so far with
16771// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
16772// behavior. The continuation byte check is included three times in the case
16773// where all of the continuation bytes for a character exist in the same buffer.
16774// It is also done this way as a slight performance increase instead of using a
16775// loop.
16776function utf8CheckExtraBytes(self, buf, p) {
16777 if ((buf[0] & 0xC0) !== 0x80) {
16778 self.lastNeed = 0;
16779 return '\ufffd';
16780 }
16781 if (self.lastNeed > 1 && buf.length > 1) {
16782 if ((buf[1] & 0xC0) !== 0x80) {
16783 self.lastNeed = 1;
16784 return '\ufffd';
16785 }
16786 if (self.lastNeed > 2 && buf.length > 2) {
16787 if ((buf[2] & 0xC0) !== 0x80) {
16788 self.lastNeed = 2;
16789 return '\ufffd';
16790 }
16791 }
16792 }
16793}
16794
16795// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
16796function utf8FillLast(buf) {
16797 var p = this.lastTotal - this.lastNeed;
16798 var r = utf8CheckExtraBytes(this, buf, p);
16799 if (r !== undefined) return r;
16800 if (this.lastNeed <= buf.length) {
16801 buf.copy(this.lastChar, p, 0, this.lastNeed);
16802 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
16803 }
16804 buf.copy(this.lastChar, p, 0, buf.length);
16805 this.lastNeed -= buf.length;
16806}
16807
16808// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
16809// partial character, the character's bytes are buffered until the required
16810// number of bytes are available.
16811function utf8Text(buf, i) {
16812 var total = utf8CheckIncomplete(this, buf, i);
16813 if (!this.lastNeed) return buf.toString('utf8', i);
16814 this.lastTotal = total;
16815 var end = buf.length - (total - this.lastNeed);
16816 buf.copy(this.lastChar, 0, end);
16817 return buf.toString('utf8', i, end);
16818}
16819
16820// For UTF-8, a replacement character is added when ending on a partial
16821// character.
16822function utf8End(buf) {
16823 var r = buf && buf.length ? this.write(buf) : '';
16824 if (this.lastNeed) return r + '\ufffd';
16825 return r;
16826}
16827
16828// UTF-16LE typically needs two bytes per character, but even if we have an even
16829// number of bytes available, we need to check if we end on a leading/high
16830// surrogate. In that case, we need to wait for the next two bytes in order to
16831// decode the last character properly.
16832function utf16Text(buf, i) {
16833 if ((buf.length - i) % 2 === 0) {
16834 var r = buf.toString('utf16le', i);
16835 if (r) {
16836 var c = r.charCodeAt(r.length - 1);
16837 if (c >= 0xD800 && c <= 0xDBFF) {
16838 this.lastNeed = 2;
16839 this.lastTotal = 4;
16840 this.lastChar[0] = buf[buf.length - 2];
16841 this.lastChar[1] = buf[buf.length - 1];
16842 return r.slice(0, -1);
16843 }
16844 }
16845 return r;
16846 }
16847 this.lastNeed = 1;
16848 this.lastTotal = 2;
16849 this.lastChar[0] = buf[buf.length - 1];
16850 return buf.toString('utf16le', i, buf.length - 1);
16851}
16852
16853// For UTF-16LE we do not explicitly append special replacement characters if we
16854// end on a partial character, we simply let v8 handle that.
16855function utf16End(buf) {
16856 var r = buf && buf.length ? this.write(buf) : '';
16857 if (this.lastNeed) {
16858 var end = this.lastTotal - this.lastNeed;
16859 return r + this.lastChar.toString('utf16le', 0, end);
16860 }
16861 return r;
16862}
16863
16864function base64Text(buf, i) {
16865 var n = (buf.length - i) % 3;
16866 if (n === 0) return buf.toString('base64', i);
16867 this.lastNeed = 3 - n;
16868 this.lastTotal = 3;
16869 if (n === 1) {
16870 this.lastChar[0] = buf[buf.length - 1];
16871 } else {
16872 this.lastChar[0] = buf[buf.length - 2];
16873 this.lastChar[1] = buf[buf.length - 1];
16874 }
16875 return buf.toString('base64', i, buf.length - n);
16876}
16877
16878function base64End(buf) {
16879 var r = buf && buf.length ? this.write(buf) : '';
16880 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
16881 return r;
16882}
16883
16884// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
16885function simpleWrite(buf) {
16886 return buf.toString(this.encoding);
16887}
16888
16889function simpleEnd(buf) {
16890 return buf && buf.length ? this.write(buf) : '';
16891}
16892},{"100":100}],102:[function(_dereq_,module,exports){
16893arguments[4][101][0].apply(exports,arguments)
16894},{"101":101,"83":83}],103:[function(_dereq_,module,exports){
16895arguments[4][43][0].apply(exports,arguments)
16896},{"43":43}],104:[function(_dereq_,module,exports){
16897arguments[4][44][0].apply(exports,arguments)
16898},{"106":106,"108":108,"37":37,"44":44,"73":73}],105:[function(_dereq_,module,exports){
16899arguments[4][45][0].apply(exports,arguments)
16900},{"107":107,"37":37,"45":45}],106:[function(_dereq_,module,exports){
16901arguments[4][46][0].apply(exports,arguments)
16902},{"102":102,"103":103,"104":104,"109":109,"11":11,"110":110,"111":111,"113":113,"115":115,"116":116,"13":13,"26":26,"37":37,"46":46,"73":73}],107:[function(_dereq_,module,exports){
16903arguments[4][47][0].apply(exports,arguments)
16904},{"103":103,"104":104,"37":37,"47":47}],108:[function(_dereq_,module,exports){
16905arguments[4][48][0].apply(exports,arguments)
16906},{"103":103,"104":104,"111":111,"115":115,"116":116,"121":121,"13":13,"37":37,"48":48,"73":73}],109:[function(_dereq_,module,exports){
16907arguments[4][49][0].apply(exports,arguments)
16908},{"112":112,"49":49,"73":73}],110:[function(_dereq_,module,exports){
16909arguments[4][50][0].apply(exports,arguments)
16910},{"11":11,"13":13,"50":50}],111:[function(_dereq_,module,exports){
16911arguments[4][51][0].apply(exports,arguments)
16912},{"51":51,"73":73}],112:[function(_dereq_,module,exports){
16913arguments[4][52][0].apply(exports,arguments)
16914},{"103":103,"52":52}],113:[function(_dereq_,module,exports){
16915arguments[4][53][0].apply(exports,arguments)
16916},{"53":53}],114:[function(_dereq_,module,exports){
16917arguments[4][54][0].apply(exports,arguments)
16918},{"103":103,"112":112,"54":54}],115:[function(_dereq_,module,exports){
16919arguments[4][55][0].apply(exports,arguments)
16920},{"103":103,"55":55}],116:[function(_dereq_,module,exports){
16921arguments[4][56][0].apply(exports,arguments)
16922},{"26":26,"56":56}],117:[function(_dereq_,module,exports){
16923arguments[4][57][0].apply(exports,arguments)
16924},{"104":104,"105":105,"106":106,"107":107,"108":108,"112":112,"114":114,"57":57}],118:[function(_dereq_,module,exports){
16925(function (process){(function (){
16926var Transform = _dereq_(117).Transform
16927 , inherits = _dereq_(37)
16928
16929function DestroyableTransform(opts) {
16930 Transform.call(this, opts)
16931 this._destroyed = false
16932}
16933
16934inherits(DestroyableTransform, Transform)
16935
16936DestroyableTransform.prototype.destroy = function(err) {
16937 if (this._destroyed) return
16938 this._destroyed = true
16939
16940 var self = this
16941 process.nextTick(function() {
16942 if (err)
16943 self.emit('error', err)
16944 self.emit('close')
16945 })
16946}
16947
16948// a noop _transform function
16949function noop (chunk, enc, callback) {
16950 callback(null, chunk)
16951}
16952
16953
16954// create a new export function, used by both the main export and
16955// the .ctor export, contains common logic for dealing with arguments
16956function through2 (construct) {
16957 return function (options, transform, flush) {
16958 if (typeof options == 'function') {
16959 flush = transform
16960 transform = options
16961 options = {}
16962 }
16963
16964 if (typeof transform != 'function')
16965 transform = noop
16966
16967 if (typeof flush != 'function')
16968 flush = null
16969
16970 return construct(options, transform, flush)
16971 }
16972}
16973
16974
16975// main export, just make me a transform stream!
16976module.exports = through2(function (options, transform, flush) {
16977 var t2 = new DestroyableTransform(options)
16978
16979 t2._transform = transform
16980
16981 if (flush)
16982 t2._flush = flush
16983
16984 return t2
16985})
16986
16987
16988// make me a reusable prototype that I can `new`, or implicitly `new`
16989// with a constructor call
16990module.exports.ctor = through2(function (options, transform, flush) {
16991 function Through2 (override) {
16992 if (!(this instanceof Through2))
16993 return new Through2(override)
16994
16995 this.options = Object.assign({}, options, override)
16996
16997 DestroyableTransform.call(this, this.options)
16998 }
16999
17000 inherits(Through2, DestroyableTransform)
17001
17002 Through2.prototype._transform = transform
17003
17004 if (flush)
17005 Through2.prototype._flush = flush
17006
17007 return Through2
17008})
17009
17010
17011module.exports.obj = through2(function (options, transform, flush) {
17012 var t2 = new DestroyableTransform(Object.assign({ objectMode: true, highWaterMark: 16 }, options))
17013
17014 t2._transform = transform
17015
17016 if (flush)
17017 t2._flush = flush
17018
17019 return t2
17020})
17021
17022}).call(this)}).call(this,_dereq_(73))
17023},{"117":117,"37":37,"73":73}],119:[function(_dereq_,module,exports){
17024(function (setImmediate,clearImmediate){(function (){
17025var nextTick = _dereq_(73).nextTick;
17026var apply = Function.prototype.apply;
17027var slice = Array.prototype.slice;
17028var immediateIds = {};
17029var nextImmediateId = 0;
17030
17031// DOM APIs, for completeness
17032
17033exports.setTimeout = function() {
17034 return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
17035};
17036exports.setInterval = function() {
17037 return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
17038};
17039exports.clearTimeout =
17040exports.clearInterval = function(timeout) { timeout.close(); };
17041
17042function Timeout(id, clearFn) {
17043 this._id = id;
17044 this._clearFn = clearFn;
17045}
17046Timeout.prototype.unref = Timeout.prototype.ref = function() {};
17047Timeout.prototype.close = function() {
17048 this._clearFn.call(window, this._id);
17049};
17050
17051// Does not start the time, just sets up the members needed.
17052exports.enroll = function(item, msecs) {
17053 clearTimeout(item._idleTimeoutId);
17054 item._idleTimeout = msecs;
17055};
17056
17057exports.unenroll = function(item) {
17058 clearTimeout(item._idleTimeoutId);
17059 item._idleTimeout = -1;
17060};
17061
17062exports._unrefActive = exports.active = function(item) {
17063 clearTimeout(item._idleTimeoutId);
17064
17065 var msecs = item._idleTimeout;
17066 if (msecs >= 0) {
17067 item._idleTimeoutId = setTimeout(function onTimeout() {
17068 if (item._onTimeout)
17069 item._onTimeout();
17070 }, msecs);
17071 }
17072};
17073
17074// That's not how node.js implements it but the exposed api is the same.
17075exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
17076 var id = nextImmediateId++;
17077 var args = arguments.length < 2 ? false : slice.call(arguments, 1);
17078
17079 immediateIds[id] = true;
17080
17081 nextTick(function onNextTick() {
17082 if (immediateIds[id]) {
17083 // fn.call() is faster so we optimize for the common use-case
17084 // @see http://jsperf.com/call-apply-segu
17085 if (args) {
17086 fn.apply(null, args);
17087 } else {
17088 fn.call(null);
17089 }
17090 // Prevent ids from leaking
17091 exports.clearImmediate(id);
17092 }
17093 });
17094
17095 return id;
17096};
17097
17098exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
17099 delete immediateIds[id];
17100};
17101}).call(this)}).call(this,_dereq_(119).setImmediate,_dereq_(119).clearImmediate)
17102},{"119":119,"73":73}],120:[function(_dereq_,module,exports){
17103'use strict';
17104
17105// Simple FIFO queue implementation to avoid having to do shift()
17106// on an array, which is slow.
17107
17108function Queue() {
17109 this.length = 0;
17110}
17111
17112Queue.prototype.push = function (item) {
17113 var node = {item: item};
17114 if (this.last) {
17115 this.last = this.last.next = node;
17116 } else {
17117 this.last = this.first = node;
17118 }
17119 this.length++;
17120};
17121
17122Queue.prototype.shift = function () {
17123 var node = this.first;
17124 if (node) {
17125 this.first = node.next;
17126 if (!(--this.length)) {
17127 this.last = undefined;
17128 }
17129 return node.item;
17130 }
17131};
17132
17133Queue.prototype.slice = function (start, end) {
17134 start = typeof start === 'undefined' ? 0 : start;
17135 end = typeof end === 'undefined' ? Infinity : end;
17136
17137 var output = [];
17138
17139 var i = 0;
17140 for (var node = this.first; node; node = node.next) {
17141 if (--end < 0) {
17142 break;
17143 } else if (++i > start) {
17144 output.push(node.item);
17145 }
17146 }
17147 return output;
17148}
17149
17150module.exports = Queue;
17151
17152},{}],121:[function(_dereq_,module,exports){
17153(function (global){(function (){
17154
17155/**
17156 * Module exports.
17157 */
17158
17159module.exports = deprecate;
17160
17161/**
17162 * Mark that a method should not be used.
17163 * Returns a modified function which warns once by default.
17164 *
17165 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
17166 *
17167 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
17168 * will throw an Error when invoked.
17169 *
17170 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
17171 * will invoke `console.trace()` instead of `console.error()`.
17172 *
17173 * @param {Function} fn - the function to deprecate
17174 * @param {String} msg - the string to print to the console when `fn` is invoked
17175 * @returns {Function} a new "deprecated" version of `fn`
17176 * @api public
17177 */
17178
17179function deprecate (fn, msg) {
17180 if (config('noDeprecation')) {
17181 return fn;
17182 }
17183
17184 var warned = false;
17185 function deprecated() {
17186 if (!warned) {
17187 if (config('throwDeprecation')) {
17188 throw new Error(msg);
17189 } else if (config('traceDeprecation')) {
17190 console.trace(msg);
17191 } else {
17192 console.warn(msg);
17193 }
17194 warned = true;
17195 }
17196 return fn.apply(this, arguments);
17197 }
17198
17199 return deprecated;
17200}
17201
17202/**
17203 * Checks `localStorage` for boolean values for the given `name`.
17204 *
17205 * @param {String} name
17206 * @returns {Boolean}
17207 * @api private
17208 */
17209
17210function config (name) {
17211 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
17212 try {
17213 if (!global.localStorage) return false;
17214 } catch (_) {
17215 return false;
17216 }
17217 var val = global.localStorage[name];
17218 if (null == val) return false;
17219 return String(val).toLowerCase() === 'true';
17220}
17221
17222}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
17223},{}],122:[function(_dereq_,module,exports){
17224arguments[4][7][0].apply(exports,arguments)
17225},{"7":7}],123:[function(_dereq_,module,exports){
17226arguments[4][8][0].apply(exports,arguments)
17227},{"8":8}],124:[function(_dereq_,module,exports){
17228arguments[4][9][0].apply(exports,arguments)
17229},{"122":122,"123":123,"73":73,"9":9}],125:[function(_dereq_,module,exports){
17230"use strict";
17231
17232Object.defineProperty(exports, "__esModule", {
17233 value: true
17234});
17235Object.defineProperty(exports, "v1", {
17236 enumerable: true,
17237 get: function () {
17238 return _v.default;
17239 }
17240});
17241Object.defineProperty(exports, "v3", {
17242 enumerable: true,
17243 get: function () {
17244 return _v2.default;
17245 }
17246});
17247Object.defineProperty(exports, "v4", {
17248 enumerable: true,
17249 get: function () {
17250 return _v3.default;
17251 }
17252});
17253Object.defineProperty(exports, "v5", {
17254 enumerable: true,
17255 get: function () {
17256 return _v4.default;
17257 }
17258});
17259Object.defineProperty(exports, "NIL", {
17260 enumerable: true,
17261 get: function () {
17262 return _nil.default;
17263 }
17264});
17265Object.defineProperty(exports, "version", {
17266 enumerable: true,
17267 get: function () {
17268 return _version.default;
17269 }
17270});
17271Object.defineProperty(exports, "validate", {
17272 enumerable: true,
17273 get: function () {
17274 return _validate.default;
17275 }
17276});
17277Object.defineProperty(exports, "stringify", {
17278 enumerable: true,
17279 get: function () {
17280 return _stringify.default;
17281 }
17282});
17283Object.defineProperty(exports, "parse", {
17284 enumerable: true,
17285 get: function () {
17286 return _parse.default;
17287 }
17288});
17289
17290var _v = _interopRequireDefault(_dereq_(133));
17291
17292var _v2 = _interopRequireDefault(_dereq_(134));
17293
17294var _v3 = _interopRequireDefault(_dereq_(136));
17295
17296var _v4 = _interopRequireDefault(_dereq_(137));
17297
17298var _nil = _interopRequireDefault(_dereq_(127));
17299
17300var _version = _interopRequireDefault(_dereq_(139));
17301
17302var _validate = _interopRequireDefault(_dereq_(138));
17303
17304var _stringify = _interopRequireDefault(_dereq_(132));
17305
17306var _parse = _interopRequireDefault(_dereq_(128));
17307
17308function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17309},{"127":127,"128":128,"132":132,"133":133,"134":134,"136":136,"137":137,"138":138,"139":139}],126:[function(_dereq_,module,exports){
17310"use strict";
17311
17312Object.defineProperty(exports, "__esModule", {
17313 value: true
17314});
17315exports.default = void 0;
17316
17317/*
17318 * Browser-compatible JavaScript MD5
17319 *
17320 * Modification of JavaScript MD5
17321 * https://github.com/blueimp/JavaScript-MD5
17322 *
17323 * Copyright 2011, Sebastian Tschan
17324 * https://blueimp.net
17325 *
17326 * Licensed under the MIT license:
17327 * https://opensource.org/licenses/MIT
17328 *
17329 * Based on
17330 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
17331 * Digest Algorithm, as defined in RFC 1321.
17332 * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
17333 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
17334 * Distributed under the BSD License
17335 * See http://pajhome.org.uk/crypt/md5 for more info.
17336 */
17337function md5(bytes) {
17338 if (typeof bytes === 'string') {
17339 const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
17340
17341 bytes = new Uint8Array(msg.length);
17342
17343 for (let i = 0; i < msg.length; ++i) {
17344 bytes[i] = msg.charCodeAt(i);
17345 }
17346 }
17347
17348 return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));
17349}
17350/*
17351 * Convert an array of little-endian words to an array of bytes
17352 */
17353
17354
17355function md5ToHexEncodedArray(input) {
17356 const output = [];
17357 const length32 = input.length * 32;
17358 const hexTab = '0123456789abcdef';
17359
17360 for (let i = 0; i < length32; i += 8) {
17361 const x = input[i >> 5] >>> i % 32 & 0xff;
17362 const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);
17363 output.push(hex);
17364 }
17365
17366 return output;
17367}
17368/**
17369 * Calculate output length with padding and bit length
17370 */
17371
17372
17373function getOutputLength(inputLength8) {
17374 return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
17375}
17376/*
17377 * Calculate the MD5 of an array of little-endian words, and a bit length.
17378 */
17379
17380
17381function wordsToMd5(x, len) {
17382 /* append padding */
17383 x[len >> 5] |= 0x80 << len % 32;
17384 x[getOutputLength(len) - 1] = len;
17385 let a = 1732584193;
17386 let b = -271733879;
17387 let c = -1732584194;
17388 let d = 271733878;
17389
17390 for (let i = 0; i < x.length; i += 16) {
17391 const olda = a;
17392 const oldb = b;
17393 const oldc = c;
17394 const oldd = d;
17395 a = md5ff(a, b, c, d, x[i], 7, -680876936);
17396 d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
17397 c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
17398 b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
17399 a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
17400 d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
17401 c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
17402 b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
17403 a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
17404 d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
17405 c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
17406 b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
17407 a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
17408 d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
17409 c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
17410 b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
17411 a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
17412 d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
17413 c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
17414 b = md5gg(b, c, d, a, x[i], 20, -373897302);
17415 a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
17416 d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
17417 c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
17418 b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
17419 a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
17420 d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
17421 c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
17422 b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
17423 a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
17424 d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
17425 c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
17426 b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
17427 a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
17428 d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
17429 c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
17430 b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
17431 a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
17432 d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
17433 c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
17434 b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
17435 a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
17436 d = md5hh(d, a, b, c, x[i], 11, -358537222);
17437 c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
17438 b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
17439 a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
17440 d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
17441 c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
17442 b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
17443 a = md5ii(a, b, c, d, x[i], 6, -198630844);
17444 d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
17445 c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
17446 b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
17447 a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
17448 d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
17449 c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
17450 b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
17451 a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
17452 d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
17453 c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
17454 b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
17455 a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
17456 d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
17457 c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
17458 b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
17459 a = safeAdd(a, olda);
17460 b = safeAdd(b, oldb);
17461 c = safeAdd(c, oldc);
17462 d = safeAdd(d, oldd);
17463 }
17464
17465 return [a, b, c, d];
17466}
17467/*
17468 * Convert an array bytes to an array of little-endian words
17469 * Characters >255 have their high-byte silently ignored.
17470 */
17471
17472
17473function bytesToWords(input) {
17474 if (input.length === 0) {
17475 return [];
17476 }
17477
17478 const length8 = input.length * 8;
17479 const output = new Uint32Array(getOutputLength(length8));
17480
17481 for (let i = 0; i < length8; i += 8) {
17482 output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;
17483 }
17484
17485 return output;
17486}
17487/*
17488 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
17489 * to work around bugs in some JS interpreters.
17490 */
17491
17492
17493function safeAdd(x, y) {
17494 const lsw = (x & 0xffff) + (y & 0xffff);
17495 const msw = (x >> 16) + (y >> 16) + (lsw >> 16);
17496 return msw << 16 | lsw & 0xffff;
17497}
17498/*
17499 * Bitwise rotate a 32-bit number to the left.
17500 */
17501
17502
17503function bitRotateLeft(num, cnt) {
17504 return num << cnt | num >>> 32 - cnt;
17505}
17506/*
17507 * These functions implement the four basic operations the algorithm uses.
17508 */
17509
17510
17511function md5cmn(q, a, b, x, s, t) {
17512 return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
17513}
17514
17515function md5ff(a, b, c, d, x, s, t) {
17516 return md5cmn(b & c | ~b & d, a, b, x, s, t);
17517}
17518
17519function md5gg(a, b, c, d, x, s, t) {
17520 return md5cmn(b & d | c & ~d, a, b, x, s, t);
17521}
17522
17523function md5hh(a, b, c, d, x, s, t) {
17524 return md5cmn(b ^ c ^ d, a, b, x, s, t);
17525}
17526
17527function md5ii(a, b, c, d, x, s, t) {
17528 return md5cmn(c ^ (b | ~d), a, b, x, s, t);
17529}
17530
17531var _default = md5;
17532exports.default = _default;
17533},{}],127:[function(_dereq_,module,exports){
17534"use strict";
17535
17536Object.defineProperty(exports, "__esModule", {
17537 value: true
17538});
17539exports.default = void 0;
17540var _default = '00000000-0000-0000-0000-000000000000';
17541exports.default = _default;
17542},{}],128:[function(_dereq_,module,exports){
17543"use strict";
17544
17545Object.defineProperty(exports, "__esModule", {
17546 value: true
17547});
17548exports.default = void 0;
17549
17550var _validate = _interopRequireDefault(_dereq_(138));
17551
17552function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17553
17554function parse(uuid) {
17555 if (!(0, _validate.default)(uuid)) {
17556 throw TypeError('Invalid UUID');
17557 }
17558
17559 let v;
17560 const arr = new Uint8Array(16); // Parse ########-....-....-....-............
17561
17562 arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
17563 arr[1] = v >>> 16 & 0xff;
17564 arr[2] = v >>> 8 & 0xff;
17565 arr[3] = v & 0xff; // Parse ........-####-....-....-............
17566
17567 arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
17568 arr[5] = v & 0xff; // Parse ........-....-####-....-............
17569
17570 arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
17571 arr[7] = v & 0xff; // Parse ........-....-....-####-............
17572
17573 arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
17574 arr[9] = v & 0xff; // Parse ........-....-....-....-############
17575 // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
17576
17577 arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
17578 arr[11] = v / 0x100000000 & 0xff;
17579 arr[12] = v >>> 24 & 0xff;
17580 arr[13] = v >>> 16 & 0xff;
17581 arr[14] = v >>> 8 & 0xff;
17582 arr[15] = v & 0xff;
17583 return arr;
17584}
17585
17586var _default = parse;
17587exports.default = _default;
17588},{"138":138}],129:[function(_dereq_,module,exports){
17589"use strict";
17590
17591Object.defineProperty(exports, "__esModule", {
17592 value: true
17593});
17594exports.default = void 0;
17595var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
17596exports.default = _default;
17597},{}],130:[function(_dereq_,module,exports){
17598"use strict";
17599
17600Object.defineProperty(exports, "__esModule", {
17601 value: true
17602});
17603exports.default = rng;
17604// Unique ID creation requires a high quality random # generator. In the browser we therefore
17605// require the crypto API and do not support built-in fallback to lower quality random number
17606// generators (like Math.random()).
17607let getRandomValues;
17608const rnds8 = new Uint8Array(16);
17609
17610function rng() {
17611 // lazy load so that environments that need to polyfill have a chance to do so
17612 if (!getRandomValues) {
17613 // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
17614 // find the complete implementation of crypto (msCrypto) on IE11.
17615 getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
17616
17617 if (!getRandomValues) {
17618 throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
17619 }
17620 }
17621
17622 return getRandomValues(rnds8);
17623}
17624},{}],131:[function(_dereq_,module,exports){
17625"use strict";
17626
17627Object.defineProperty(exports, "__esModule", {
17628 value: true
17629});
17630exports.default = void 0;
17631
17632// Adapted from Chris Veness' SHA1 code at
17633// http://www.movable-type.co.uk/scripts/sha1.html
17634function f(s, x, y, z) {
17635 switch (s) {
17636 case 0:
17637 return x & y ^ ~x & z;
17638
17639 case 1:
17640 return x ^ y ^ z;
17641
17642 case 2:
17643 return x & y ^ x & z ^ y & z;
17644
17645 case 3:
17646 return x ^ y ^ z;
17647 }
17648}
17649
17650function ROTL(x, n) {
17651 return x << n | x >>> 32 - n;
17652}
17653
17654function sha1(bytes) {
17655 const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
17656 const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
17657
17658 if (typeof bytes === 'string') {
17659 const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
17660
17661 bytes = [];
17662
17663 for (let i = 0; i < msg.length; ++i) {
17664 bytes.push(msg.charCodeAt(i));
17665 }
17666 } else if (!Array.isArray(bytes)) {
17667 // Convert Array-like to Array
17668 bytes = Array.prototype.slice.call(bytes);
17669 }
17670
17671 bytes.push(0x80);
17672 const l = bytes.length / 4 + 2;
17673 const N = Math.ceil(l / 16);
17674 const M = new Array(N);
17675
17676 for (let i = 0; i < N; ++i) {
17677 const arr = new Uint32Array(16);
17678
17679 for (let j = 0; j < 16; ++j) {
17680 arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3];
17681 }
17682
17683 M[i] = arr;
17684 }
17685
17686 M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
17687 M[N - 1][14] = Math.floor(M[N - 1][14]);
17688 M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;
17689
17690 for (let i = 0; i < N; ++i) {
17691 const W = new Uint32Array(80);
17692
17693 for (let t = 0; t < 16; ++t) {
17694 W[t] = M[i][t];
17695 }
17696
17697 for (let t = 16; t < 80; ++t) {
17698 W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);
17699 }
17700
17701 let a = H[0];
17702 let b = H[1];
17703 let c = H[2];
17704 let d = H[3];
17705 let e = H[4];
17706
17707 for (let t = 0; t < 80; ++t) {
17708 const s = Math.floor(t / 20);
17709 const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0;
17710 e = d;
17711 d = c;
17712 c = ROTL(b, 30) >>> 0;
17713 b = a;
17714 a = T;
17715 }
17716
17717 H[0] = H[0] + a >>> 0;
17718 H[1] = H[1] + b >>> 0;
17719 H[2] = H[2] + c >>> 0;
17720 H[3] = H[3] + d >>> 0;
17721 H[4] = H[4] + e >>> 0;
17722 }
17723
17724 return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];
17725}
17726
17727var _default = sha1;
17728exports.default = _default;
17729},{}],132:[function(_dereq_,module,exports){
17730"use strict";
17731
17732Object.defineProperty(exports, "__esModule", {
17733 value: true
17734});
17735exports.default = void 0;
17736
17737var _validate = _interopRequireDefault(_dereq_(138));
17738
17739function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17740
17741/**
17742 * Convert array of 16 byte values to UUID string format of the form:
17743 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
17744 */
17745const byteToHex = [];
17746
17747for (let i = 0; i < 256; ++i) {
17748 byteToHex.push((i + 0x100).toString(16).substr(1));
17749}
17750
17751function stringify(arr, offset = 0) {
17752 // Note: Be careful editing this code! It's been tuned for performance
17753 // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
17754 const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
17755 // of the following:
17756 // - One or more input array values don't map to a hex octet (leading to
17757 // "undefined" in the uuid)
17758 // - Invalid input values for the RFC `version` or `variant` fields
17759
17760 if (!(0, _validate.default)(uuid)) {
17761 throw TypeError('Stringified UUID is invalid');
17762 }
17763
17764 return uuid;
17765}
17766
17767var _default = stringify;
17768exports.default = _default;
17769},{"138":138}],133:[function(_dereq_,module,exports){
17770"use strict";
17771
17772Object.defineProperty(exports, "__esModule", {
17773 value: true
17774});
17775exports.default = void 0;
17776
17777var _rng = _interopRequireDefault(_dereq_(130));
17778
17779var _stringify = _interopRequireDefault(_dereq_(132));
17780
17781function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17782
17783// **`v1()` - Generate time-based UUID**
17784//
17785// Inspired by https://github.com/LiosK/UUID.js
17786// and http://docs.python.org/library/uuid.html
17787let _nodeId;
17788
17789let _clockseq; // Previous uuid creation time
17790
17791
17792let _lastMSecs = 0;
17793let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details
17794
17795function v1(options, buf, offset) {
17796 let i = buf && offset || 0;
17797 const b = buf || new Array(16);
17798 options = options || {};
17799 let node = options.node || _nodeId;
17800 let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not
17801 // specified. We do this lazily to minimize issues related to insufficient
17802 // system entropy. See #189
17803
17804 if (node == null || clockseq == null) {
17805 const seedBytes = options.random || (options.rng || _rng.default)();
17806
17807 if (node == null) {
17808 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
17809 node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
17810 }
17811
17812 if (clockseq == null) {
17813 // Per 4.2.2, randomize (14 bit) clockseq
17814 clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
17815 }
17816 } // UUID timestamps are 100 nano-second units since the Gregorian epoch,
17817 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
17818 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
17819 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
17820
17821
17822 let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock
17823 // cycle to simulate higher resolution clock
17824
17825 let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)
17826
17827 const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression
17828
17829 if (dt < 0 && options.clockseq === undefined) {
17830 clockseq = clockseq + 1 & 0x3fff;
17831 } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
17832 // time interval
17833
17834
17835 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
17836 nsecs = 0;
17837 } // Per 4.2.1.2 Throw error if too many uuids are requested
17838
17839
17840 if (nsecs >= 10000) {
17841 throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
17842 }
17843
17844 _lastMSecs = msecs;
17845 _lastNSecs = nsecs;
17846 _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
17847
17848 msecs += 12219292800000; // `time_low`
17849
17850 const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
17851 b[i++] = tl >>> 24 & 0xff;
17852 b[i++] = tl >>> 16 & 0xff;
17853 b[i++] = tl >>> 8 & 0xff;
17854 b[i++] = tl & 0xff; // `time_mid`
17855
17856 const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
17857 b[i++] = tmh >>> 8 & 0xff;
17858 b[i++] = tmh & 0xff; // `time_high_and_version`
17859
17860 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
17861
17862 b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
17863
17864 b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`
17865
17866 b[i++] = clockseq & 0xff; // `node`
17867
17868 for (let n = 0; n < 6; ++n) {
17869 b[i + n] = node[n];
17870 }
17871
17872 return buf || (0, _stringify.default)(b);
17873}
17874
17875var _default = v1;
17876exports.default = _default;
17877},{"130":130,"132":132}],134:[function(_dereq_,module,exports){
17878"use strict";
17879
17880Object.defineProperty(exports, "__esModule", {
17881 value: true
17882});
17883exports.default = void 0;
17884
17885var _v = _interopRequireDefault(_dereq_(135));
17886
17887var _md = _interopRequireDefault(_dereq_(126));
17888
17889function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17890
17891const v3 = (0, _v.default)('v3', 0x30, _md.default);
17892var _default = v3;
17893exports.default = _default;
17894},{"126":126,"135":135}],135:[function(_dereq_,module,exports){
17895"use strict";
17896
17897Object.defineProperty(exports, "__esModule", {
17898 value: true
17899});
17900exports.default = _default;
17901exports.URL = exports.DNS = void 0;
17902
17903var _stringify = _interopRequireDefault(_dereq_(132));
17904
17905var _parse = _interopRequireDefault(_dereq_(128));
17906
17907function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17908
17909function stringToBytes(str) {
17910 str = unescape(encodeURIComponent(str)); // UTF8 escape
17911
17912 const bytes = [];
17913
17914 for (let i = 0; i < str.length; ++i) {
17915 bytes.push(str.charCodeAt(i));
17916 }
17917
17918 return bytes;
17919}
17920
17921const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
17922exports.DNS = DNS;
17923const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
17924exports.URL = URL;
17925
17926function _default(name, version, hashfunc) {
17927 function generateUUID(value, namespace, buf, offset) {
17928 if (typeof value === 'string') {
17929 value = stringToBytes(value);
17930 }
17931
17932 if (typeof namespace === 'string') {
17933 namespace = (0, _parse.default)(namespace);
17934 }
17935
17936 if (namespace.length !== 16) {
17937 throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
17938 } // Compute hash of namespace and value, Per 4.3
17939 // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
17940 // hashfunc([...namespace, ... value])`
17941
17942
17943 let bytes = new Uint8Array(16 + value.length);
17944 bytes.set(namespace);
17945 bytes.set(value, namespace.length);
17946 bytes = hashfunc(bytes);
17947 bytes[6] = bytes[6] & 0x0f | version;
17948 bytes[8] = bytes[8] & 0x3f | 0x80;
17949
17950 if (buf) {
17951 offset = offset || 0;
17952
17953 for (let i = 0; i < 16; ++i) {
17954 buf[offset + i] = bytes[i];
17955 }
17956
17957 return buf;
17958 }
17959
17960 return (0, _stringify.default)(bytes);
17961 } // Function#name is not settable on some platforms (#270)
17962
17963
17964 try {
17965 generateUUID.name = name; // eslint-disable-next-line no-empty
17966 } catch (err) {} // For CommonJS default export support
17967
17968
17969 generateUUID.DNS = DNS;
17970 generateUUID.URL = URL;
17971 return generateUUID;
17972}
17973},{"128":128,"132":132}],136:[function(_dereq_,module,exports){
17974"use strict";
17975
17976Object.defineProperty(exports, "__esModule", {
17977 value: true
17978});
17979exports.default = void 0;
17980
17981var _rng = _interopRequireDefault(_dereq_(130));
17982
17983var _stringify = _interopRequireDefault(_dereq_(132));
17984
17985function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17986
17987function v4(options, buf, offset) {
17988 options = options || {};
17989
17990 const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
17991
17992
17993 rnds[6] = rnds[6] & 0x0f | 0x40;
17994 rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
17995
17996 if (buf) {
17997 offset = offset || 0;
17998
17999 for (let i = 0; i < 16; ++i) {
18000 buf[offset + i] = rnds[i];
18001 }
18002
18003 return buf;
18004 }
18005
18006 return (0, _stringify.default)(rnds);
18007}
18008
18009var _default = v4;
18010exports.default = _default;
18011},{"130":130,"132":132}],137:[function(_dereq_,module,exports){
18012"use strict";
18013
18014Object.defineProperty(exports, "__esModule", {
18015 value: true
18016});
18017exports.default = void 0;
18018
18019var _v = _interopRequireDefault(_dereq_(135));
18020
18021var _sha = _interopRequireDefault(_dereq_(131));
18022
18023function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18024
18025const v5 = (0, _v.default)('v5', 0x50, _sha.default);
18026var _default = v5;
18027exports.default = _default;
18028},{"131":131,"135":135}],138:[function(_dereq_,module,exports){
18029"use strict";
18030
18031Object.defineProperty(exports, "__esModule", {
18032 value: true
18033});
18034exports.default = void 0;
18035
18036var _regex = _interopRequireDefault(_dereq_(129));
18037
18038function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18039
18040function validate(uuid) {
18041 return typeof uuid === 'string' && _regex.default.test(uuid);
18042}
18043
18044var _default = validate;
18045exports.default = _default;
18046},{"129":129}],139:[function(_dereq_,module,exports){
18047"use strict";
18048
18049Object.defineProperty(exports, "__esModule", {
18050 value: true
18051});
18052exports.default = void 0;
18053
18054var _validate = _interopRequireDefault(_dereq_(138));
18055
18056function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18057
18058function version(uuid) {
18059 if (!(0, _validate.default)(uuid)) {
18060 throw TypeError('Invalid UUID');
18061 }
18062
18063 return parseInt(uuid.substr(14, 1), 16);
18064}
18065
18066var _default = version;
18067exports.default = _default;
18068},{"138":138}],140:[function(_dereq_,module,exports){
18069'use strict';
18070
18071/**
18072 * Stringify/parse functions that don't operate
18073 * recursively, so they avoid call stack exceeded
18074 * errors.
18075 */
18076exports.stringify = function stringify(input) {
18077 var queue = [];
18078 queue.push({obj: input});
18079
18080 var res = '';
18081 var next, obj, prefix, val, i, arrayPrefix, keys, k, key, value, objPrefix;
18082 while ((next = queue.pop())) {
18083 obj = next.obj;
18084 prefix = next.prefix || '';
18085 val = next.val || '';
18086 res += prefix;
18087 if (val) {
18088 res += val;
18089 } else if (typeof obj !== 'object') {
18090 res += typeof obj === 'undefined' ? null : JSON.stringify(obj);
18091 } else if (obj === null) {
18092 res += 'null';
18093 } else if (Array.isArray(obj)) {
18094 queue.push({val: ']'});
18095 for (i = obj.length - 1; i >= 0; i--) {
18096 arrayPrefix = i === 0 ? '' : ',';
18097 queue.push({obj: obj[i], prefix: arrayPrefix});
18098 }
18099 queue.push({val: '['});
18100 } else { // object
18101 keys = [];
18102 for (k in obj) {
18103 if (obj.hasOwnProperty(k)) {
18104 keys.push(k);
18105 }
18106 }
18107 queue.push({val: '}'});
18108 for (i = keys.length - 1; i >= 0; i--) {
18109 key = keys[i];
18110 value = obj[key];
18111 objPrefix = (i > 0 ? ',' : '');
18112 objPrefix += JSON.stringify(key) + ':';
18113 queue.push({obj: value, prefix: objPrefix});
18114 }
18115 queue.push({val: '{'});
18116 }
18117 }
18118 return res;
18119};
18120
18121// Convenience function for the parse function.
18122// This pop function is basically copied from
18123// pouchCollate.parseIndexableString
18124function pop(obj, stack, metaStack) {
18125 var lastMetaElement = metaStack[metaStack.length - 1];
18126 if (obj === lastMetaElement.element) {
18127 // popping a meta-element, e.g. an object whose value is another object
18128 metaStack.pop();
18129 lastMetaElement = metaStack[metaStack.length - 1];
18130 }
18131 var element = lastMetaElement.element;
18132 var lastElementIndex = lastMetaElement.index;
18133 if (Array.isArray(element)) {
18134 element.push(obj);
18135 } else if (lastElementIndex === stack.length - 2) { // obj with key+value
18136 var key = stack.pop();
18137 element[key] = obj;
18138 } else {
18139 stack.push(obj); // obj with key only
18140 }
18141}
18142
18143exports.parse = function (str) {
18144 var stack = [];
18145 var metaStack = []; // stack for arrays and objects
18146 var i = 0;
18147 var collationIndex,parsedNum,numChar;
18148 var parsedString,lastCh,numConsecutiveSlashes,ch;
18149 var arrayElement, objElement;
18150 while (true) {
18151 collationIndex = str[i++];
18152 if (collationIndex === '}' ||
18153 collationIndex === ']' ||
18154 typeof collationIndex === 'undefined') {
18155 if (stack.length === 1) {
18156 return stack.pop();
18157 } else {
18158 pop(stack.pop(), stack, metaStack);
18159 continue;
18160 }
18161 }
18162 switch (collationIndex) {
18163 case ' ':
18164 case '\t':
18165 case '\n':
18166 case ':':
18167 case ',':
18168 break;
18169 case 'n':
18170 i += 3; // 'ull'
18171 pop(null, stack, metaStack);
18172 break;
18173 case 't':
18174 i += 3; // 'rue'
18175 pop(true, stack, metaStack);
18176 break;
18177 case 'f':
18178 i += 4; // 'alse'
18179 pop(false, stack, metaStack);
18180 break;
18181 case '0':
18182 case '1':
18183 case '2':
18184 case '3':
18185 case '4':
18186 case '5':
18187 case '6':
18188 case '7':
18189 case '8':
18190 case '9':
18191 case '-':
18192 parsedNum = '';
18193 i--;
18194 while (true) {
18195 numChar = str[i++];
18196 if (/[\d\.\-e\+]/.test(numChar)) {
18197 parsedNum += numChar;
18198 } else {
18199 i--;
18200 break;
18201 }
18202 }
18203 pop(parseFloat(parsedNum), stack, metaStack);
18204 break;
18205 case '"':
18206 parsedString = '';
18207 lastCh = void 0;
18208 numConsecutiveSlashes = 0;
18209 while (true) {
18210 ch = str[i++];
18211 if (ch !== '"' || (lastCh === '\\' &&
18212 numConsecutiveSlashes % 2 === 1)) {
18213 parsedString += ch;
18214 lastCh = ch;
18215 if (lastCh === '\\') {
18216 numConsecutiveSlashes++;
18217 } else {
18218 numConsecutiveSlashes = 0;
18219 }
18220 } else {
18221 break;
18222 }
18223 }
18224 pop(JSON.parse('"' + parsedString + '"'), stack, metaStack);
18225 break;
18226 case '[':
18227 arrayElement = { element: [], index: stack.length };
18228 stack.push(arrayElement.element);
18229 metaStack.push(arrayElement);
18230 break;
18231 case '{':
18232 objElement = { element: {}, index: stack.length };
18233 stack.push(objElement.element);
18234 metaStack.push(objElement);
18235 break;
18236 default:
18237 throw new Error(
18238 'unexpectedly reached end of input: ' + collationIndex);
18239 }
18240 }
18241};
18242
18243},{}],141:[function(_dereq_,module,exports){
18244module.exports = extend
18245
18246var hasOwnProperty = Object.prototype.hasOwnProperty;
18247
18248function extend() {
18249 var target = {}
18250
18251 for (var i = 0; i < arguments.length; i++) {
18252 var source = arguments[i]
18253
18254 for (var key in source) {
18255 if (hasOwnProperty.call(source, key)) {
18256 target[key] = source[key]
18257 }
18258 }
18259 }
18260
18261 return target
18262}
18263
18264},{}],142:[function(_dereq_,module,exports){
18265module.exports = extend
18266
18267var hasOwnProperty = Object.prototype.hasOwnProperty;
18268
18269function extend(target) {
18270 for (var i = 1; i < arguments.length; i++) {
18271 var source = arguments[i]
18272
18273 for (var key in source) {
18274 if (hasOwnProperty.call(source, key)) {
18275 target[key] = source[key]
18276 }
18277 }
18278 }
18279
18280 return target
18281}
18282
18283},{}],143:[function(_dereq_,module,exports){
18284'use strict';
18285
18286function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
18287
18288var immediate = _interopDefault(_dereq_(31));
18289var uuid = _dereq_(125);
18290var Md5 = _interopDefault(_dereq_(84));
18291var levelup = _interopDefault(_dereq_(61));
18292var ltgt = _interopDefault(_dereq_(70));
18293var EventEmitter = _interopDefault(_dereq_(26));
18294var Codec = _interopDefault(_dereq_(39));
18295var ReadableStreamCore = _interopDefault(_dereq_(82));
18296var inherits = _interopDefault(_dereq_(37));
18297var through2 = _dereq_(118);
18298var getArguments = _interopDefault(_dereq_(5));
18299var Deque = _interopDefault(_dereq_(23));
18300var bufferFrom = _interopDefault(_dereq_(12));
18301var vuvuzela = _interopDefault(_dereq_(140));
18302var localstoragedown = _interopDefault(_dereq_(63));
18303
18304function isBinaryObject(object) {
18305 return (typeof ArrayBuffer !== 'undefined' && object instanceof ArrayBuffer) ||
18306 (typeof Blob !== 'undefined' && object instanceof Blob);
18307}
18308
18309function cloneArrayBuffer(buff) {
18310 if (typeof buff.slice === 'function') {
18311 return buff.slice(0);
18312 }
18313 // IE10-11 slice() polyfill
18314 var target = new ArrayBuffer(buff.byteLength);
18315 var targetArray = new Uint8Array(target);
18316 var sourceArray = new Uint8Array(buff);
18317 targetArray.set(sourceArray);
18318 return target;
18319}
18320
18321function cloneBinaryObject(object) {
18322 if (object instanceof ArrayBuffer) {
18323 return cloneArrayBuffer(object);
18324 }
18325 var size = object.size;
18326 var type = object.type;
18327 // Blob
18328 if (typeof object.slice === 'function') {
18329 return object.slice(0, size, type);
18330 }
18331 // PhantomJS slice() replacement
18332 return object.webkitSlice(0, size, type);
18333}
18334
18335// most of this is borrowed from lodash.isPlainObject:
18336// https://github.com/fis-components/lodash.isplainobject/
18337// blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js
18338
18339var funcToString = Function.prototype.toString;
18340var objectCtorString = funcToString.call(Object);
18341
18342function isPlainObject(value) {
18343 var proto = Object.getPrototypeOf(value);
18344 /* istanbul ignore if */
18345 if (proto === null) { // not sure when this happens, but I guess it can
18346 return true;
18347 }
18348 var Ctor = proto.constructor;
18349 return (typeof Ctor == 'function' &&
18350 Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
18351}
18352
18353function clone(object) {
18354 var newObject;
18355 var i;
18356 var len;
18357
18358 if (!object || typeof object !== 'object') {
18359 return object;
18360 }
18361
18362 if (Array.isArray(object)) {
18363 newObject = [];
18364 for (i = 0, len = object.length; i < len; i++) {
18365 newObject[i] = clone(object[i]);
18366 }
18367 return newObject;
18368 }
18369
18370 // special case: to avoid inconsistencies between IndexedDB
18371 // and other backends, we automatically stringify Dates
18372 if (object instanceof Date && isFinite(object)) {
18373 return object.toISOString();
18374 }
18375
18376 if (isBinaryObject(object)) {
18377 return cloneBinaryObject(object);
18378 }
18379
18380 if (!isPlainObject(object)) {
18381 return object; // don't clone objects like Workers
18382 }
18383
18384 newObject = {};
18385 for (i in object) {
18386 /* istanbul ignore else */
18387 if (Object.prototype.hasOwnProperty.call(object, i)) {
18388 var value = clone(object[i]);
18389 if (typeof value !== 'undefined') {
18390 newObject[i] = value;
18391 }
18392 }
18393 }
18394 return newObject;
18395}
18396
18397function mangle(key) {
18398 return '$' + key;
18399}
18400function unmangle(key) {
18401 return key.substring(1);
18402}
18403function Map$1() {
18404 this._store = {};
18405}
18406Map$1.prototype.get = function (key) {
18407 var mangled = mangle(key);
18408 return this._store[mangled];
18409};
18410Map$1.prototype.set = function (key, value) {
18411 var mangled = mangle(key);
18412 this._store[mangled] = value;
18413 return true;
18414};
18415Map$1.prototype.has = function (key) {
18416 var mangled = mangle(key);
18417 return mangled in this._store;
18418};
18419Map$1.prototype.keys = function () {
18420 return Object.keys(this._store).map(k => unmangle(k));
18421};
18422Map$1.prototype["delete"] = function (key) {
18423 var mangled = mangle(key);
18424 var res = mangled in this._store;
18425 delete this._store[mangled];
18426 return res;
18427};
18428Map$1.prototype.forEach = function (cb) {
18429 var keys = Object.keys(this._store);
18430 for (var i = 0, len = keys.length; i < len; i++) {
18431 var key = keys[i];
18432 var value = this._store[key];
18433 key = unmangle(key);
18434 cb(value, key);
18435 }
18436};
18437Object.defineProperty(Map$1.prototype, 'size', {
18438 get: function () {
18439 return Object.keys(this._store).length;
18440 }
18441});
18442
18443function Set$1(array) {
18444 this._store = new Map$1();
18445
18446 // init with an array
18447 if (array && Array.isArray(array)) {
18448 for (var i = 0, len = array.length; i < len; i++) {
18449 this.add(array[i]);
18450 }
18451 }
18452}
18453Set$1.prototype.add = function (key) {
18454 return this._store.set(key, true);
18455};
18456Set$1.prototype.has = function (key) {
18457 return this._store.has(key);
18458};
18459Set$1.prototype.forEach = function (cb) {
18460 this._store.forEach(function (value, key) {
18461 cb(key);
18462 });
18463};
18464Object.defineProperty(Set$1.prototype, 'size', {
18465 get: function () {
18466 return this._store.size;
18467 }
18468});
18469
18470// Based on https://kangax.github.io/compat-table/es6/ we can sniff out
18471// incomplete Map/Set implementations which would otherwise cause our tests to fail.
18472// Notably they fail in IE11 and iOS 8.4, which this prevents.
18473function supportsMapAndSet() {
18474 if (typeof Symbol === 'undefined' || typeof Map === 'undefined' || typeof Set === 'undefined') {
18475 return false;
18476 }
18477 var prop = Object.getOwnPropertyDescriptor(Map, Symbol.species);
18478 return prop && 'get' in prop && Map[Symbol.species] === Map;
18479}
18480
18481// based on https://github.com/montagejs/collections
18482
18483var ExportedSet;
18484var ExportedMap;
18485
18486{
18487 if (supportsMapAndSet()) { // prefer built-in Map/Set
18488 ExportedSet = Set;
18489 ExportedMap = Map;
18490 } else { // fall back to our polyfill
18491 ExportedSet = Set$1;
18492 ExportedMap = Map$1;
18493 }
18494}
18495
18496// like underscore/lodash _.pick()
18497function pick(obj, arr) {
18498 var res = {};
18499 for (var i = 0, len = arr.length; i < len; i++) {
18500 var prop = arr[i];
18501 if (prop in obj) {
18502 res[prop] = obj[prop];
18503 }
18504 }
18505 return res;
18506}
18507
18508var hasLocal;
18509
18510try {
18511 localStorage.setItem('_pouch_check_localstorage', 1);
18512 hasLocal = !!localStorage.getItem('_pouch_check_localstorage');
18513} catch (e) {
18514 hasLocal = false;
18515}
18516
18517function hasLocalStorage() {
18518 return hasLocal;
18519}
18520
18521// Custom nextTick() shim for browsers. In node, this will just be process.nextTick(). We
18522
18523inherits(Changes, EventEmitter);
18524
18525/* istanbul ignore next */
18526function attachBrowserEvents(self) {
18527 if (hasLocalStorage()) {
18528 addEventListener("storage", function (e) {
18529 self.emit(e.key);
18530 });
18531 }
18532}
18533
18534function Changes() {
18535 EventEmitter.call(this);
18536 this._listeners = {};
18537
18538 attachBrowserEvents(this);
18539}
18540Changes.prototype.addListener = function (dbName, id, db, opts) {
18541 /* istanbul ignore if */
18542 if (this._listeners[id]) {
18543 return;
18544 }
18545 var self = this;
18546 var inprogress = false;
18547 function eventFunction() {
18548 /* istanbul ignore if */
18549 if (!self._listeners[id]) {
18550 return;
18551 }
18552 if (inprogress) {
18553 inprogress = 'waiting';
18554 return;
18555 }
18556 inprogress = true;
18557 var changesOpts = pick(opts, [
18558 'style', 'include_docs', 'attachments', 'conflicts', 'filter',
18559 'doc_ids', 'view', 'since', 'query_params', 'binary', 'return_docs'
18560 ]);
18561
18562 /* istanbul ignore next */
18563 function onError() {
18564 inprogress = false;
18565 }
18566
18567 db.changes(changesOpts).on('change', function (c) {
18568 if (c.seq > opts.since && !opts.cancelled) {
18569 opts.since = c.seq;
18570 opts.onChange(c);
18571 }
18572 }).on('complete', function () {
18573 if (inprogress === 'waiting') {
18574 immediate(eventFunction);
18575 }
18576 inprogress = false;
18577 }).on('error', onError);
18578 }
18579 this._listeners[id] = eventFunction;
18580 this.on(dbName, eventFunction);
18581};
18582
18583Changes.prototype.removeListener = function (dbName, id) {
18584 /* istanbul ignore if */
18585 if (!(id in this._listeners)) {
18586 return;
18587 }
18588 EventEmitter.prototype.removeListener.call(this, dbName,
18589 this._listeners[id]);
18590 delete this._listeners[id];
18591};
18592
18593
18594/* istanbul ignore next */
18595Changes.prototype.notifyLocalWindows = function (dbName) {
18596 //do a useless change on a storage thing
18597 //in order to get other windows's listeners to activate
18598 if (hasLocalStorage()) {
18599 localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a";
18600 }
18601};
18602
18603Changes.prototype.notify = function (dbName) {
18604 this.emit(dbName);
18605 this.notifyLocalWindows(dbName);
18606};
18607
18608function guardedConsole(method) {
18609 /* istanbul ignore else */
18610 if (typeof console !== 'undefined' && typeof console[method] === 'function') {
18611 var args = Array.prototype.slice.call(arguments, 1);
18612 console[method].apply(console, args);
18613 }
18614}
18615
18616var assign;
18617{
18618 if (typeof Object.assign === 'function') {
18619 assign = Object.assign;
18620 } else {
18621 // lite Object.assign polyfill based on
18622 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
18623 assign = function (target) {
18624 var to = Object(target);
18625
18626 for (var index = 1; index < arguments.length; index++) {
18627 var nextSource = arguments[index];
18628
18629 if (nextSource != null) { // Skip over if undefined or null
18630 for (var nextKey in nextSource) {
18631 // Avoid bugs when hasOwnProperty is shadowed
18632 if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
18633 to[nextKey] = nextSource[nextKey];
18634 }
18635 }
18636 }
18637 }
18638 return to;
18639 };
18640 }
18641}
18642
18643var $inject_Object_assign = assign;
18644
18645inherits(PouchError, Error);
18646
18647function PouchError(status, error, reason) {
18648 Error.call(this, reason);
18649 this.status = status;
18650 this.name = error;
18651 this.message = reason;
18652 this.error = true;
18653}
18654
18655PouchError.prototype.toString = function () {
18656 return JSON.stringify({
18657 status: this.status,
18658 name: this.name,
18659 message: this.message,
18660 reason: this.reason
18661 });
18662};
18663
18664var UNAUTHORIZED = new PouchError(401, 'unauthorized', "Name or password is incorrect.");
18665var MISSING_BULK_DOCS = new PouchError(400, 'bad_request', "Missing JSON list of 'docs'");
18666var MISSING_DOC = new PouchError(404, 'not_found', 'missing');
18667var REV_CONFLICT = new PouchError(409, 'conflict', 'Document update conflict');
18668var INVALID_ID = new PouchError(400, 'bad_request', '_id field must contain a string');
18669var MISSING_ID = new PouchError(412, 'missing_id', '_id is required for puts');
18670var RESERVED_ID = new PouchError(400, 'bad_request', 'Only reserved document ids may start with underscore.');
18671var NOT_OPEN = new PouchError(412, 'precondition_failed', 'Database not open');
18672var UNKNOWN_ERROR = new PouchError(500, 'unknown_error', 'Database encountered an unknown error');
18673var BAD_ARG = new PouchError(500, 'badarg', 'Some query argument is invalid');
18674var INVALID_REQUEST = new PouchError(400, 'invalid_request', 'Request was invalid');
18675var QUERY_PARSE_ERROR = new PouchError(400, 'query_parse_error', 'Some query parameter is invalid');
18676var DOC_VALIDATION = new PouchError(500, 'doc_validation', 'Bad special document member');
18677var BAD_REQUEST = new PouchError(400, 'bad_request', 'Something wrong with the request');
18678var NOT_AN_OBJECT = new PouchError(400, 'bad_request', 'Document must be a JSON object');
18679var DB_MISSING = new PouchError(404, 'not_found', 'Database not found');
18680var IDB_ERROR = new PouchError(500, 'indexed_db_went_bad', 'unknown');
18681var WSQ_ERROR = new PouchError(500, 'web_sql_went_bad', 'unknown');
18682var LDB_ERROR = new PouchError(500, 'levelDB_went_went_bad', 'unknown');
18683var FORBIDDEN = new PouchError(403, 'forbidden', 'Forbidden by design doc validate_doc_update function');
18684var INVALID_REV = new PouchError(400, 'bad_request', 'Invalid rev format');
18685var FILE_EXISTS = new PouchError(412, 'file_exists', 'The database could not be created, the file already exists.');
18686var MISSING_STUB = new PouchError(412, 'missing_stub', 'A pre-existing attachment stub wasn\'t found');
18687var INVALID_URL = new PouchError(413, 'invalid_url', 'Provided URL is invalid');
18688
18689function createError(error, reason) {
18690 function CustomPouchError(reason) {
18691 // inherit error properties from our parent error manually
18692 // so as to allow proper JSON parsing.
18693 /* jshint ignore:start */
18694 var names = Object.getOwnPropertyNames(error);
18695 for (var i = 0, len = names.length; i < len; i++) {
18696 if (typeof error[names[i]] !== 'function') {
18697 this[names[i]] = error[names[i]];
18698 }
18699 }
18700
18701 if (this.stack === undefined) {
18702 this.stack = (new Error()).stack;
18703 }
18704
18705 /* jshint ignore:end */
18706 if (reason !== undefined) {
18707 this.reason = reason;
18708 }
18709 }
18710 CustomPouchError.prototype = PouchError.prototype;
18711 return new CustomPouchError(reason);
18712}
18713
18714function tryFilter(filter, doc, req) {
18715 try {
18716 return !filter(doc, req);
18717 } catch (err) {
18718 var msg = 'Filter function threw: ' + err.toString();
18719 return createError(BAD_REQUEST, msg);
18720 }
18721}
18722
18723function filterChange(opts) {
18724 var req = {};
18725 var hasFilter = opts.filter && typeof opts.filter === 'function';
18726 req.query = opts.query_params;
18727
18728 return function filter(change) {
18729 if (!change.doc) {
18730 // CSG sends events on the changes feed that don't have documents,
18731 // this hack makes a whole lot of existing code robust.
18732 change.doc = {};
18733 }
18734
18735 var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req);
18736
18737 if (typeof filterReturn === 'object') {
18738 return filterReturn;
18739 }
18740
18741 if (filterReturn) {
18742 return false;
18743 }
18744
18745 if (!opts.include_docs) {
18746 delete change.doc;
18747 } else if (!opts.attachments) {
18748 for (var att in change.doc._attachments) {
18749 /* istanbul ignore else */
18750 if (Object.prototype.hasOwnProperty.call(change.doc._attachments, att)) {
18751 change.doc._attachments[att].stub = true;
18752 }
18753 }
18754 }
18755 return true;
18756 };
18757}
18758
18759// shim for Function.prototype.name,
18760// for browsers that don't support it like IE
18761
18762/* istanbul ignore next */
18763function f() {}
18764
18765var hasName = f.name;
18766var res;
18767
18768// We dont run coverage in IE
18769/* istanbul ignore else */
18770if (hasName) {
18771 res = function (fun) {
18772 return fun.name;
18773 };
18774} else {
18775 res = function (fun) {
18776 var match = fun.toString().match(/^\s*function\s*(?:(\S+)\s*)?\(/);
18777 if (match && match[1]) {
18778 return match[1];
18779 }
18780 else {
18781 return '';
18782 }
18783 };
18784}
18785
18786var functionName = res;
18787
18788// Determine id an ID is valid
18789// - invalid IDs begin with an underescore that does not begin '_design' or
18790// '_local'
18791// - any other string value is a valid id
18792// Returns the specific error object for each case
18793function invalidIdError(id) {
18794 var err;
18795 if (!id) {
18796 err = createError(MISSING_ID);
18797 } else if (typeof id !== 'string') {
18798 err = createError(INVALID_ID);
18799 } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {
18800 err = createError(RESERVED_ID);
18801 }
18802 if (err) {
18803 throw err;
18804 }
18805}
18806
18807// Checks if a PouchDB object is "remote" or not. This is
18808
18809// originally parseUri 1.2.2, now patched by us
18810
18811// Based on https://github.com/alexdavid/scope-eval v0.0.3
18812
18813var thisAtob = function (str) {
18814 return atob(str);
18815};
18816
18817var thisBtoa = function (str) {
18818 return btoa(str);
18819};
18820
18821// Abstracts constructing a Blob object, so it also works in older
18822// browsers that don't support the native Blob constructor (e.g.
18823// old QtWebKit versions, Android < 4.4).
18824function createBlob(parts, properties) {
18825 /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
18826 parts = parts || [];
18827 properties = properties || {};
18828 try {
18829 return new Blob(parts, properties);
18830 } catch (e) {
18831 if (e.name !== "TypeError") {
18832 throw e;
18833 }
18834 var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
18835 typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
18836 typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
18837 WebKitBlobBuilder;
18838 var builder = new Builder();
18839 for (var i = 0; i < parts.length; i += 1) {
18840 builder.append(parts[i]);
18841 }
18842 return builder.getBlob(properties.type);
18843 }
18844}
18845
18846// From http://stackoverflow.com/questions/14967647/ (continues on next line)
18847// encode-decode-image-with-base64-breaks-image (2013-04-21)
18848function binaryStringToArrayBuffer(bin) {
18849 var length = bin.length;
18850 var buf = new ArrayBuffer(length);
18851 var arr = new Uint8Array(buf);
18852 for (var i = 0; i < length; i++) {
18853 arr[i] = bin.charCodeAt(i);
18854 }
18855 return buf;
18856}
18857
18858function binStringToBluffer(binString, type) {
18859 return createBlob([binaryStringToArrayBuffer(binString)], {type: type});
18860}
18861
18862//Can't find original post, but this is close
18863//http://stackoverflow.com/questions/6965107/ (continues on next line)
18864//converting-between-strings-and-arraybuffers
18865function arrayBufferToBinaryString(buffer) {
18866 var binary = '';
18867 var bytes = new Uint8Array(buffer);
18868 var length = bytes.byteLength;
18869 for (var i = 0; i < length; i++) {
18870 binary += String.fromCharCode(bytes[i]);
18871 }
18872 return binary;
18873}
18874
18875// shim for browsers that don't support it
18876function readAsBinaryString(blob, callback) {
18877 var reader = new FileReader();
18878 var hasBinaryString = typeof reader.readAsBinaryString === 'function';
18879 reader.onloadend = function (e) {
18880 var result = e.target.result || '';
18881 if (hasBinaryString) {
18882 return callback(result);
18883 }
18884 callback(arrayBufferToBinaryString(result));
18885 };
18886 if (hasBinaryString) {
18887 reader.readAsBinaryString(blob);
18888 } else {
18889 reader.readAsArrayBuffer(blob);
18890 }
18891}
18892
18893// simplified API. universal browser support is assumed
18894function readAsArrayBuffer(blob, callback) {
18895 var reader = new FileReader();
18896 reader.onloadend = function (e) {
18897 var result = e.target.result || new ArrayBuffer(0);
18898 callback(result);
18899 };
18900 reader.readAsArrayBuffer(blob);
18901}
18902
18903// this is not used in the browser
18904
18905var setImmediateShim = self.setImmediate || self.setTimeout;
18906var MD5_CHUNK_SIZE = 32768;
18907
18908function rawToBase64(raw) {
18909 return thisBtoa(raw);
18910}
18911
18912function sliceBlob(blob, start, end) {
18913 if (blob.webkitSlice) {
18914 return blob.webkitSlice(start, end);
18915 }
18916 return blob.slice(start, end);
18917}
18918
18919function appendBlob(buffer, blob, start, end, callback) {
18920 if (start > 0 || end < blob.size) {
18921 // only slice blob if we really need to
18922 blob = sliceBlob(blob, start, end);
18923 }
18924 readAsArrayBuffer(blob, function (arrayBuffer) {
18925 buffer.append(arrayBuffer);
18926 callback();
18927 });
18928}
18929
18930function appendString(buffer, string, start, end, callback) {
18931 if (start > 0 || end < string.length) {
18932 // only create a substring if we really need to
18933 string = string.substring(start, end);
18934 }
18935 buffer.appendBinary(string);
18936 callback();
18937}
18938
18939function binaryMd5(data, callback) {
18940 var inputIsString = typeof data === 'string';
18941 var len = inputIsString ? data.length : data.size;
18942 var chunkSize = Math.min(MD5_CHUNK_SIZE, len);
18943 var chunks = Math.ceil(len / chunkSize);
18944 var currentChunk = 0;
18945 var buffer = inputIsString ? new Md5() : new Md5.ArrayBuffer();
18946
18947 var append = inputIsString ? appendString : appendBlob;
18948
18949 function next() {
18950 setImmediateShim(loadNextChunk);
18951 }
18952
18953 function done() {
18954 var raw = buffer.end(true);
18955 var base64 = rawToBase64(raw);
18956 callback(base64);
18957 buffer.destroy();
18958 }
18959
18960 function loadNextChunk() {
18961 var start = currentChunk * chunkSize;
18962 var end = start + chunkSize;
18963 currentChunk++;
18964 if (currentChunk < chunks) {
18965 append(buffer, data, start, end, next);
18966 } else {
18967 append(buffer, data, start, end, done);
18968 }
18969 }
18970 loadNextChunk();
18971}
18972
18973function stringMd5(string) {
18974 return Md5.hash(string);
18975}
18976
18977/**
18978 * Creates a new revision string that does NOT include the revision height
18979 * For example '56649f1b0506c6ca9fda0746eb0cacdf'
18980 */
18981function rev$$1(doc, deterministic_revs) {
18982 if (!deterministic_revs) {
18983 return uuid.v4().replace(/-/g, '').toLowerCase();
18984 }
18985
18986 var mutateableDoc = $inject_Object_assign({}, doc);
18987 delete mutateableDoc._rev_tree;
18988 return stringMd5(JSON.stringify(mutateableDoc));
18989}
18990
18991var uuid$1 = uuid.v4; // mimic old import, only v4 is ever used elsewhere
18992
18993function isFunction(f) {
18994 return 'function' === typeof f;
18995}
18996
18997function getPrefix(db) {
18998 if (isFunction(db.prefix)) {
18999 return db.prefix();
19000 }
19001 return db;
19002}
19003
19004function clone$1(_obj) {
19005 var obj = {};
19006 for (var k in _obj) {
19007 obj[k] = _obj[k];
19008 }
19009 return obj;
19010}
19011
19012function nut(db, precodec, codec) {
19013 function encodePrefix(prefix, key, opts1, opts2) {
19014 return precodec.encode([ prefix, codec.encodeKey(key, opts1, opts2 ) ]);
19015 }
19016
19017 function addEncodings(op, prefix) {
19018 if (prefix && prefix.options) {
19019 op.keyEncoding =
19020 op.keyEncoding || prefix.options.keyEncoding;
19021 op.valueEncoding =
19022 op.valueEncoding || prefix.options.valueEncoding;
19023 }
19024 return op;
19025 }
19026
19027 db.open(function () { /* no-op */});
19028
19029 return {
19030 apply: function (ops, opts, cb) {
19031 opts = opts || {};
19032
19033 var batch = [];
19034 var i = -1;
19035 var len = ops.length;
19036
19037 while (++i < len) {
19038 var op = ops[i];
19039 addEncodings(op, op.prefix);
19040 op.prefix = getPrefix(op.prefix);
19041 batch.push({
19042 key: encodePrefix(op.prefix, op.key, opts, op),
19043 value: op.type !== 'del' && codec.encodeValue(op.value, opts, op),
19044 type: op.type
19045 });
19046 }
19047 db.db.batch(batch, opts, cb);
19048 },
19049 get: function (key, prefix, opts, cb) {
19050 opts.asBuffer = codec.valueAsBuffer(opts);
19051 return db.db.get(
19052 encodePrefix(prefix, key, opts),
19053 opts,
19054 function (err, value) {
19055 if (err) {
19056 cb(err);
19057 } else {
19058 cb(null, codec.decodeValue(value, opts));
19059 }
19060 }
19061 );
19062 },
19063 createDecoder: function (opts) {
19064 return function (key, value) {
19065 return {
19066 key: codec.decodeKey(precodec.decode(key)[1], opts),
19067 value: codec.decodeValue(value, opts)
19068 };
19069 };
19070 },
19071 isClosed: function isClosed() {
19072 return db.isClosed();
19073 },
19074 close: function close(cb) {
19075 return db.close(cb);
19076 },
19077 iterator: function (_opts) {
19078 var opts = clone$1(_opts || {});
19079 var prefix = _opts.prefix || [];
19080
19081 function encodeKey(key) {
19082 return encodePrefix(prefix, key, opts, {});
19083 }
19084
19085 ltgt.toLtgt(_opts, opts, encodeKey, precodec.lowerBound, precodec.upperBound);
19086
19087 // if these legacy values are in the options, remove them
19088
19089 opts.prefix = null;
19090
19091 //************************************************
19092 //hard coded defaults, for now...
19093 //TODO: pull defaults and encoding out of levelup.
19094 opts.keyAsBuffer = opts.valueAsBuffer = false;
19095 //************************************************
19096
19097
19098 //this is vital, otherwise limit: undefined will
19099 //create an empty stream.
19100 /* istanbul ignore next */
19101 if ('number' !== typeof opts.limit) {
19102 opts.limit = -1;
19103 }
19104
19105 opts.keyAsBuffer = precodec.buffer;
19106 opts.valueAsBuffer = codec.valueAsBuffer(opts);
19107
19108 function wrapIterator(iterator) {
19109 return {
19110 next: function (cb) {
19111 return iterator.next(cb);
19112 },
19113 end: function (cb) {
19114 iterator.end(cb);
19115 }
19116 };
19117 }
19118
19119 return wrapIterator(db.db.iterator(opts));
19120 }
19121 };
19122}
19123
19124function NotFoundError() {
19125 Error.call(this);
19126}
19127
19128inherits(NotFoundError, Error);
19129
19130NotFoundError.prototype.name = 'NotFoundError';
19131
19132var EventEmitter$1 = EventEmitter.EventEmitter;
19133var version = "6.5.4";
19134
19135var NOT_FOUND_ERROR = new NotFoundError();
19136
19137var sublevel = function (nut, prefix, createStream, options) {
19138 var emitter = new EventEmitter$1();
19139 emitter.sublevels = {};
19140 emitter.options = options;
19141
19142 emitter.version = version;
19143
19144 emitter.methods = {};
19145 prefix = prefix || [];
19146
19147 function mergeOpts(opts) {
19148 var o = {};
19149 var k;
19150 if (options) {
19151 for (k in options) {
19152 if (typeof options[k] !== 'undefined') {
19153 o[k] = options[k];
19154 }
19155 }
19156 }
19157 if (opts) {
19158 for (k in opts) {
19159 if (typeof opts[k] !== 'undefined') {
19160 o[k] = opts[k];
19161 }
19162 }
19163 }
19164 return o;
19165 }
19166
19167 emitter.put = function (key, value, opts, cb) {
19168 if ('function' === typeof opts) {
19169 cb = opts;
19170 opts = {};
19171 }
19172
19173 nut.apply([{
19174 key: key, value: value,
19175 prefix: prefix.slice(), type: 'put'
19176 }], mergeOpts(opts), function (err) {
19177 /* istanbul ignore next */
19178 if (err) {
19179 return cb(err);
19180 }
19181 emitter.emit('put', key, value);
19182 cb(null);
19183 });
19184 };
19185
19186 emitter.prefix = function () {
19187 return prefix.slice();
19188 };
19189
19190 emitter.batch = function (ops, opts, cb) {
19191 if ('function' === typeof opts) {
19192 cb = opts;
19193 opts = {};
19194 }
19195
19196 ops = ops.map(function (op) {
19197 return {
19198 key: op.key,
19199 value: op.value,
19200 prefix: op.prefix || prefix,
19201 keyEncoding: op.keyEncoding, // *
19202 valueEncoding: op.valueEncoding, // * (TODO: encodings on sublevel)
19203 type: op.type
19204 };
19205 });
19206
19207 nut.apply(ops, mergeOpts(opts), function (err) {
19208 /* istanbul ignore next */
19209 if (err) {
19210 return cb(err);
19211 }
19212 emitter.emit('batch', ops);
19213 cb(null);
19214 });
19215 };
19216
19217 emitter.get = function (key, opts, cb) {
19218 /* istanbul ignore else */
19219 if ('function' === typeof opts) {
19220 cb = opts;
19221 opts = {};
19222 }
19223 nut.get(key, prefix, mergeOpts(opts), function (err, value) {
19224 if (err) {
19225 cb(NOT_FOUND_ERROR);
19226 } else {
19227 cb(null, value);
19228 }
19229 });
19230 };
19231
19232 emitter.sublevel = function (name, opts) {
19233 return emitter.sublevels[name] =
19234 emitter.sublevels[name] || sublevel(nut, prefix.concat(name), createStream, mergeOpts(opts));
19235 };
19236
19237 emitter.readStream = emitter.createReadStream = function (opts) {
19238 opts = mergeOpts(opts);
19239 opts.prefix = prefix;
19240 var stream;
19241 var it = nut.iterator(opts);
19242
19243 stream = createStream(opts, nut.createDecoder(opts));
19244 stream.setIterator(it);
19245
19246 return stream;
19247 };
19248
19249 emitter.close = function (cb) {
19250 nut.close(cb);
19251 };
19252
19253 emitter.isOpen = nut.isOpen;
19254 emitter.isClosed = nut.isClosed;
19255
19256 return emitter;
19257};
19258
19259/* Copyright (c) 2012-2014 LevelUP contributors
19260 * See list at <https://github.com/rvagg/node-levelup#contributing>
19261 * MIT License <https://github.com/rvagg/node-levelup/blob/master/LICENSE.md>
19262 */
19263
19264var Readable = ReadableStreamCore.Readable;
19265
19266function ReadStream(options, makeData) {
19267 if (!(this instanceof ReadStream)) {
19268 return new ReadStream(options, makeData);
19269 }
19270
19271 Readable.call(this, { objectMode: true, highWaterMark: options.highWaterMark });
19272
19273 // purely to keep `db` around until we're done so it's not GCed if the user doesn't keep a ref
19274
19275 this._waiting = false;
19276 this._options = options;
19277 this._makeData = makeData;
19278}
19279
19280inherits(ReadStream, Readable);
19281
19282ReadStream.prototype.setIterator = function (it) {
19283 this._iterator = it;
19284 /* istanbul ignore if */
19285 if (this._destroyed) {
19286 return it.end(function () {});
19287 }
19288 /* istanbul ignore if */
19289 if (this._waiting) {
19290 this._waiting = false;
19291 return this._read();
19292 }
19293 return this;
19294};
19295
19296ReadStream.prototype._read = function read() {
19297 var self = this;
19298 /* istanbul ignore if */
19299 if (self._destroyed) {
19300 return;
19301 }
19302 /* istanbul ignore if */
19303 if (!self._iterator) {
19304 return this._waiting = true;
19305 }
19306
19307 self._iterator.next(function (err, key, value) {
19308 if (err || (key === undefined && value === undefined)) {
19309 if (!err && !self._destroyed) {
19310 self.push(null);
19311 }
19312 return self._cleanup(err);
19313 }
19314
19315
19316 value = self._makeData(key, value);
19317 if (!self._destroyed) {
19318 self.push(value);
19319 }
19320 });
19321};
19322
19323ReadStream.prototype._cleanup = function (err) {
19324 if (this._destroyed) {
19325 return;
19326 }
19327
19328 this._destroyed = true;
19329
19330 var self = this;
19331 /* istanbul ignore if */
19332 if (err && err.message !== 'iterator has ended') {
19333 self.emit('error', err);
19334 }
19335
19336 /* istanbul ignore else */
19337 if (self._iterator) {
19338 self._iterator.end(function () {
19339 self._iterator = null;
19340 self.emit('close');
19341 });
19342 } else {
19343 self.emit('close');
19344 }
19345};
19346
19347ReadStream.prototype.destroy = function () {
19348 this._cleanup();
19349};
19350
19351var precodec = {
19352 encode: function (decodedKey) {
19353 return '\xff' + decodedKey[0] + '\xff' + decodedKey[1];
19354 },
19355 decode: function (encodedKeyAsBuffer) {
19356 var str = encodedKeyAsBuffer.toString();
19357 var idx = str.indexOf('\xff', 1);
19358 return [str.substring(1, idx), str.substring(idx + 1)];
19359 },
19360 lowerBound: '\x00',
19361 upperBound: '\xff'
19362};
19363
19364var codec = new Codec();
19365
19366function sublevelPouch(db) {
19367 return sublevel(nut(db, precodec, codec), [], ReadStream, db.options);
19368}
19369
19370function allDocsKeysQuery(api, opts) {
19371 var keys = opts.keys;
19372 var finalResults = {
19373 offset: opts.skip
19374 };
19375 return Promise.all(keys.map(function (key) {
19376 var subOpts = $inject_Object_assign({key: key, deleted: 'ok'}, opts);
19377 ['limit', 'skip', 'keys'].forEach(function (optKey) {
19378 delete subOpts[optKey];
19379 });
19380 return new Promise(function (resolve, reject) {
19381 api._allDocs(subOpts, function (err, res) {
19382 /* istanbul ignore if */
19383 if (err) {
19384 return reject(err);
19385 }
19386 /* istanbul ignore if */
19387 if (opts.update_seq && res.update_seq !== undefined) {
19388 finalResults.update_seq = res.update_seq;
19389 }
19390 finalResults.total_rows = res.total_rows;
19391 resolve(res.rows[0] || {key: key, error: 'not_found'});
19392 });
19393 });
19394 })).then(function (results) {
19395 finalResults.rows = results;
19396 return finalResults;
19397 });
19398}
19399
19400function toObject(array) {
19401 return array.reduce(function (obj, item) {
19402 obj[item] = true;
19403 return obj;
19404 }, {});
19405}
19406// List of top level reserved words for doc
19407var reservedWords = toObject([
19408 '_id',
19409 '_rev',
19410 '_access',
19411 '_attachments',
19412 '_deleted',
19413 '_revisions',
19414 '_revs_info',
19415 '_conflicts',
19416 '_deleted_conflicts',
19417 '_local_seq',
19418 '_rev_tree',
19419 // replication documents
19420 '_replication_id',
19421 '_replication_state',
19422 '_replication_state_time',
19423 '_replication_state_reason',
19424 '_replication_stats',
19425 // Specific to Couchbase Sync Gateway
19426 '_removed'
19427]);
19428
19429// List of reserved words that should end up in the document
19430var dataWords = toObject([
19431 '_access',
19432 '_attachments',
19433 // replication documents
19434 '_replication_id',
19435 '_replication_state',
19436 '_replication_state_time',
19437 '_replication_state_reason',
19438 '_replication_stats'
19439]);
19440
19441function parseRevisionInfo(rev) {
19442 if (!/^\d+-/.test(rev)) {
19443 return createError(INVALID_REV);
19444 }
19445 var idx = rev.indexOf('-');
19446 var left = rev.substring(0, idx);
19447 var right = rev.substring(idx + 1);
19448 return {
19449 prefix: parseInt(left, 10),
19450 id: right
19451 };
19452}
19453
19454function makeRevTreeFromRevisions(revisions, opts) {
19455 var pos = revisions.start - revisions.ids.length + 1;
19456
19457 var revisionIds = revisions.ids;
19458 var ids = [revisionIds[0], opts, []];
19459
19460 for (var i = 1, len = revisionIds.length; i < len; i++) {
19461 ids = [revisionIds[i], {status: 'missing'}, [ids]];
19462 }
19463
19464 return [{
19465 pos: pos,
19466 ids: ids
19467 }];
19468}
19469
19470// Preprocess documents, parse their revisions, assign an id and a
19471// revision for new writes that are missing them, etc
19472function parseDoc(doc, newEdits, dbOpts) {
19473 if (!dbOpts) {
19474 dbOpts = {
19475 deterministic_revs: true
19476 };
19477 }
19478
19479 var nRevNum;
19480 var newRevId;
19481 var revInfo;
19482 var opts = {status: 'available'};
19483 if (doc._deleted) {
19484 opts.deleted = true;
19485 }
19486
19487 if (newEdits) {
19488 if (!doc._id) {
19489 doc._id = uuid$1();
19490 }
19491 newRevId = rev$$1(doc, dbOpts.deterministic_revs);
19492 if (doc._rev) {
19493 revInfo = parseRevisionInfo(doc._rev);
19494 if (revInfo.error) {
19495 return revInfo;
19496 }
19497 doc._rev_tree = [{
19498 pos: revInfo.prefix,
19499 ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]]
19500 }];
19501 nRevNum = revInfo.prefix + 1;
19502 } else {
19503 doc._rev_tree = [{
19504 pos: 1,
19505 ids : [newRevId, opts, []]
19506 }];
19507 nRevNum = 1;
19508 }
19509 } else {
19510 if (doc._revisions) {
19511 doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts);
19512 nRevNum = doc._revisions.start;
19513 newRevId = doc._revisions.ids[0];
19514 }
19515 if (!doc._rev_tree) {
19516 revInfo = parseRevisionInfo(doc._rev);
19517 if (revInfo.error) {
19518 return revInfo;
19519 }
19520 nRevNum = revInfo.prefix;
19521 newRevId = revInfo.id;
19522 doc._rev_tree = [{
19523 pos: nRevNum,
19524 ids: [newRevId, opts, []]
19525 }];
19526 }
19527 }
19528
19529 invalidIdError(doc._id);
19530
19531 doc._rev = nRevNum + '-' + newRevId;
19532
19533 var result = {metadata : {}, data : {}};
19534 for (var key in doc) {
19535 /* istanbul ignore else */
19536 if (Object.prototype.hasOwnProperty.call(doc, key)) {
19537 var specialKey = key[0] === '_';
19538 if (specialKey && !reservedWords[key]) {
19539 var error = createError(DOC_VALIDATION, key);
19540 error.message = DOC_VALIDATION.message + ': ' + key;
19541 throw error;
19542 } else if (specialKey && !dataWords[key]) {
19543 result.metadata[key.slice(1)] = doc[key];
19544 } else {
19545 result.data[key] = doc[key];
19546 }
19547 }
19548 }
19549 return result;
19550}
19551
19552// We fetch all leafs of the revision tree, and sort them based on tree length
19553// and whether they were deleted, undeleted documents with the longest revision
19554// tree (most edits) win
19555// The final sort algorithm is slightly documented in a sidebar here:
19556// http://guide.couchdb.org/draft/conflicts.html
19557function winningRev(metadata) {
19558 var winningId;
19559 var winningPos;
19560 var winningDeleted;
19561 var toVisit = metadata.rev_tree.slice();
19562 var node;
19563 while ((node = toVisit.pop())) {
19564 var tree = node.ids;
19565 var branches = tree[2];
19566 var pos = node.pos;
19567 if (branches.length) { // non-leaf
19568 for (var i = 0, len = branches.length; i < len; i++) {
19569 toVisit.push({pos: pos + 1, ids: branches[i]});
19570 }
19571 continue;
19572 }
19573 var deleted = !!tree[1].deleted;
19574 var id = tree[0];
19575 // sort by deleted, then pos, then id
19576 if (!winningId || (winningDeleted !== deleted ? winningDeleted :
19577 winningPos !== pos ? winningPos < pos : winningId < id)) {
19578 winningId = id;
19579 winningPos = pos;
19580 winningDeleted = deleted;
19581 }
19582 }
19583
19584 return winningPos + '-' + winningId;
19585}
19586
19587// Pretty much all below can be combined into a higher order function to
19588// traverse revisions
19589// The return value from the callback will be passed as context to all
19590// children of that node
19591function traverseRevTree(revs, callback) {
19592 var toVisit = revs.slice();
19593
19594 var node;
19595 while ((node = toVisit.pop())) {
19596 var pos = node.pos;
19597 var tree = node.ids;
19598 var branches = tree[2];
19599 var newCtx =
19600 callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]);
19601 for (var i = 0, len = branches.length; i < len; i++) {
19602 toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx});
19603 }
19604 }
19605}
19606
19607function sortByPos(a, b) {
19608 return a.pos - b.pos;
19609}
19610
19611function collectLeaves(revs) {
19612 var leaves = [];
19613 traverseRevTree(revs, function (isLeaf, pos, id, acc, opts) {
19614 if (isLeaf) {
19615 leaves.push({rev: pos + "-" + id, pos: pos, opts: opts});
19616 }
19617 });
19618 leaves.sort(sortByPos).reverse();
19619 for (var i = 0, len = leaves.length; i < len; i++) {
19620 delete leaves[i].pos;
19621 }
19622 return leaves;
19623}
19624
19625// returns revs of all conflicts that is leaves such that
19626// 1. are not deleted and
19627// 2. are different than winning revision
19628function collectConflicts(metadata) {
19629 var win = winningRev(metadata);
19630 var leaves = collectLeaves(metadata.rev_tree);
19631 var conflicts = [];
19632 for (var i = 0, len = leaves.length; i < len; i++) {
19633 var leaf = leaves[i];
19634 if (leaf.rev !== win && !leaf.opts.deleted) {
19635 conflicts.push(leaf.rev);
19636 }
19637 }
19638 return conflicts;
19639}
19640
19641// compact a tree by marking its non-leafs as missing,
19642// and return a list of revs to delete
19643function compactTree(metadata) {
19644 var revs = [];
19645 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
19646 revHash, ctx, opts) {
19647 if (opts.status === 'available' && !isLeaf) {
19648 revs.push(pos + '-' + revHash);
19649 opts.status = 'missing';
19650 }
19651 });
19652 return revs;
19653}
19654
19655// build up a list of all the paths to the leafs in this revision tree
19656function rootToLeaf(revs) {
19657 var paths = [];
19658 var toVisit = revs.slice();
19659 var node;
19660 while ((node = toVisit.pop())) {
19661 var pos = node.pos;
19662 var tree = node.ids;
19663 var id = tree[0];
19664 var opts = tree[1];
19665 var branches = tree[2];
19666 var isLeaf = branches.length === 0;
19667
19668 var history = node.history ? node.history.slice() : [];
19669 history.push({id: id, opts: opts});
19670 if (isLeaf) {
19671 paths.push({pos: (pos + 1 - history.length), ids: history});
19672 }
19673 for (var i = 0, len = branches.length; i < len; i++) {
19674 toVisit.push({pos: pos + 1, ids: branches[i], history: history});
19675 }
19676 }
19677 return paths.reverse();
19678}
19679
19680// for a better overview of what this is doing, read:
19681
19682function sortByPos$1(a, b) {
19683 return a.pos - b.pos;
19684}
19685
19686// classic binary search
19687function binarySearch(arr, item, comparator) {
19688 var low = 0;
19689 var high = arr.length;
19690 var mid;
19691 while (low < high) {
19692 mid = (low + high) >>> 1;
19693 if (comparator(arr[mid], item) < 0) {
19694 low = mid + 1;
19695 } else {
19696 high = mid;
19697 }
19698 }
19699 return low;
19700}
19701
19702// assuming the arr is sorted, insert the item in the proper place
19703function insertSorted(arr, item, comparator) {
19704 var idx = binarySearch(arr, item, comparator);
19705 arr.splice(idx, 0, item);
19706}
19707
19708// Turn a path as a flat array into a tree with a single branch.
19709// If any should be stemmed from the beginning of the array, that's passed
19710// in as the second argument
19711function pathToTree(path, numStemmed) {
19712 var root;
19713 var leaf;
19714 for (var i = numStemmed, len = path.length; i < len; i++) {
19715 var node = path[i];
19716 var currentLeaf = [node.id, node.opts, []];
19717 if (leaf) {
19718 leaf[2].push(currentLeaf);
19719 leaf = currentLeaf;
19720 } else {
19721 root = leaf = currentLeaf;
19722 }
19723 }
19724 return root;
19725}
19726
19727// compare the IDs of two trees
19728function compareTree(a, b) {
19729 return a[0] < b[0] ? -1 : 1;
19730}
19731
19732// Merge two trees together
19733// The roots of tree1 and tree2 must be the same revision
19734function mergeTree(in_tree1, in_tree2) {
19735 var queue = [{tree1: in_tree1, tree2: in_tree2}];
19736 var conflicts = false;
19737 while (queue.length > 0) {
19738 var item = queue.pop();
19739 var tree1 = item.tree1;
19740 var tree2 = item.tree2;
19741
19742 if (tree1[1].status || tree2[1].status) {
19743 tree1[1].status =
19744 (tree1[1].status === 'available' ||
19745 tree2[1].status === 'available') ? 'available' : 'missing';
19746 }
19747
19748 for (var i = 0; i < tree2[2].length; i++) {
19749 if (!tree1[2][0]) {
19750 conflicts = 'new_leaf';
19751 tree1[2][0] = tree2[2][i];
19752 continue;
19753 }
19754
19755 var merged = false;
19756 for (var j = 0; j < tree1[2].length; j++) {
19757 if (tree1[2][j][0] === tree2[2][i][0]) {
19758 queue.push({tree1: tree1[2][j], tree2: tree2[2][i]});
19759 merged = true;
19760 }
19761 }
19762 if (!merged) {
19763 conflicts = 'new_branch';
19764 insertSorted(tree1[2], tree2[2][i], compareTree);
19765 }
19766 }
19767 }
19768 return {conflicts: conflicts, tree: in_tree1};
19769}
19770
19771function doMerge(tree, path, dontExpand) {
19772 var restree = [];
19773 var conflicts = false;
19774 var merged = false;
19775 var res;
19776
19777 if (!tree.length) {
19778 return {tree: [path], conflicts: 'new_leaf'};
19779 }
19780
19781 for (var i = 0, len = tree.length; i < len; i++) {
19782 var branch = tree[i];
19783 if (branch.pos === path.pos && branch.ids[0] === path.ids[0]) {
19784 // Paths start at the same position and have the same root, so they need
19785 // merged
19786 res = mergeTree(branch.ids, path.ids);
19787 restree.push({pos: branch.pos, ids: res.tree});
19788 conflicts = conflicts || res.conflicts;
19789 merged = true;
19790 } else if (dontExpand !== true) {
19791 // The paths start at a different position, take the earliest path and
19792 // traverse up until it as at the same point from root as the path we
19793 // want to merge. If the keys match we return the longer path with the
19794 // other merged After stemming we dont want to expand the trees
19795
19796 var t1 = branch.pos < path.pos ? branch : path;
19797 var t2 = branch.pos < path.pos ? path : branch;
19798 var diff = t2.pos - t1.pos;
19799
19800 var candidateParents = [];
19801
19802 var trees = [];
19803 trees.push({ids: t1.ids, diff: diff, parent: null, parentIdx: null});
19804 while (trees.length > 0) {
19805 var item = trees.pop();
19806 if (item.diff === 0) {
19807 if (item.ids[0] === t2.ids[0]) {
19808 candidateParents.push(item);
19809 }
19810 continue;
19811 }
19812 var elements = item.ids[2];
19813 for (var j = 0, elementsLen = elements.length; j < elementsLen; j++) {
19814 trees.push({
19815 ids: elements[j],
19816 diff: item.diff - 1,
19817 parent: item.ids,
19818 parentIdx: j
19819 });
19820 }
19821 }
19822
19823 var el = candidateParents[0];
19824
19825 if (!el) {
19826 restree.push(branch);
19827 } else {
19828 res = mergeTree(el.ids, t2.ids);
19829 el.parent[2][el.parentIdx] = res.tree;
19830 restree.push({pos: t1.pos, ids: t1.ids});
19831 conflicts = conflicts || res.conflicts;
19832 merged = true;
19833 }
19834 } else {
19835 restree.push(branch);
19836 }
19837 }
19838
19839 // We didnt find
19840 if (!merged) {
19841 restree.push(path);
19842 }
19843
19844 restree.sort(sortByPos$1);
19845
19846 return {
19847 tree: restree,
19848 conflicts: conflicts || 'internal_node'
19849 };
19850}
19851
19852// To ensure we dont grow the revision tree infinitely, we stem old revisions
19853function stem(tree, depth) {
19854 // First we break out the tree into a complete list of root to leaf paths
19855 var paths = rootToLeaf(tree);
19856 var stemmedRevs;
19857
19858 var result;
19859 for (var i = 0, len = paths.length; i < len; i++) {
19860 // Then for each path, we cut off the start of the path based on the
19861 // `depth` to stem to, and generate a new set of flat trees
19862 var path = paths[i];
19863 var stemmed = path.ids;
19864 var node;
19865 if (stemmed.length > depth) {
19866 // only do the stemming work if we actually need to stem
19867 if (!stemmedRevs) {
19868 stemmedRevs = {}; // avoid allocating this object unnecessarily
19869 }
19870 var numStemmed = stemmed.length - depth;
19871 node = {
19872 pos: path.pos + numStemmed,
19873 ids: pathToTree(stemmed, numStemmed)
19874 };
19875
19876 for (var s = 0; s < numStemmed; s++) {
19877 var rev = (path.pos + s) + '-' + stemmed[s].id;
19878 stemmedRevs[rev] = true;
19879 }
19880 } else { // no need to actually stem
19881 node = {
19882 pos: path.pos,
19883 ids: pathToTree(stemmed, 0)
19884 };
19885 }
19886
19887 // Then we remerge all those flat trees together, ensuring that we dont
19888 // connect trees that would go beyond the depth limit
19889 if (result) {
19890 result = doMerge(result, node, true).tree;
19891 } else {
19892 result = [node];
19893 }
19894 }
19895
19896 // this is memory-heavy per Chrome profiler, avoid unless we actually stemmed
19897 if (stemmedRevs) {
19898 traverseRevTree(result, function (isLeaf, pos, revHash) {
19899 // some revisions may have been removed in a branch but not in another
19900 delete stemmedRevs[pos + '-' + revHash];
19901 });
19902 }
19903
19904 return {
19905 tree: result,
19906 revs: stemmedRevs ? Object.keys(stemmedRevs) : []
19907 };
19908}
19909
19910function merge(tree, path, depth) {
19911 var newTree = doMerge(tree, path);
19912 var stemmed = stem(newTree.tree, depth);
19913 return {
19914 tree: stemmed.tree,
19915 stemmedRevs: stemmed.revs,
19916 conflicts: newTree.conflicts
19917 };
19918}
19919
19920// return true if a rev exists in the rev tree, false otherwise
19921function revExists(revs, rev) {
19922 var toVisit = revs.slice();
19923 var splitRev = rev.split('-');
19924 var targetPos = parseInt(splitRev[0], 10);
19925 var targetId = splitRev[1];
19926
19927 var node;
19928 while ((node = toVisit.pop())) {
19929 if (node.pos === targetPos && node.ids[0] === targetId) {
19930 return true;
19931 }
19932 var branches = node.ids[2];
19933 for (var i = 0, len = branches.length; i < len; i++) {
19934 toVisit.push({pos: node.pos + 1, ids: branches[i]});
19935 }
19936 }
19937 return false;
19938}
19939
19940function getTrees(node) {
19941 return node.ids;
19942}
19943
19944// check if a specific revision of a doc has been deleted
19945// - metadata: the metadata object from the doc store
19946// - rev: (optional) the revision to check. defaults to winning revision
19947function isDeleted(metadata, rev) {
19948 if (!rev) {
19949 rev = winningRev(metadata);
19950 }
19951 var id = rev.substring(rev.indexOf('-') + 1);
19952 var toVisit = metadata.rev_tree.map(getTrees);
19953
19954 var tree;
19955 while ((tree = toVisit.pop())) {
19956 if (tree[0] === id) {
19957 return !!tree[1].deleted;
19958 }
19959 toVisit = toVisit.concat(tree[2]);
19960 }
19961}
19962
19963function isLocalId(id) {
19964 return (/^_local/).test(id);
19965}
19966
19967// returns the current leaf node for a given revision
19968function latest(rev, metadata) {
19969 var toVisit = metadata.rev_tree.slice();
19970 var node;
19971 while ((node = toVisit.pop())) {
19972 var pos = node.pos;
19973 var tree = node.ids;
19974 var id = tree[0];
19975 var opts = tree[1];
19976 var branches = tree[2];
19977 var isLeaf = branches.length === 0;
19978
19979 var history = node.history ? node.history.slice() : [];
19980 history.push({id: id, pos: pos, opts: opts});
19981
19982 if (isLeaf) {
19983 for (var i = 0, len = history.length; i < len; i++) {
19984 var historyNode = history[i];
19985 var historyRev = historyNode.pos + '-' + historyNode.id;
19986
19987 if (historyRev === rev) {
19988 // return the rev of this leaf
19989 return pos + '-' + id;
19990 }
19991 }
19992 }
19993
19994 for (var j = 0, l = branches.length; j < l; j++) {
19995 toVisit.push({pos: pos + 1, ids: branches[j], history: history});
19996 }
19997 }
19998
19999 /* istanbul ignore next */
20000 throw new Error('Unable to resolve latest revision for id ' + metadata.id + ', rev ' + rev);
20001}
20002
20003function updateDoc(revLimit, prev, docInfo, results,
20004 i, cb, writeDoc, newEdits) {
20005
20006 if (revExists(prev.rev_tree, docInfo.metadata.rev) && !newEdits) {
20007 results[i] = docInfo;
20008 return cb();
20009 }
20010
20011 // sometimes this is pre-calculated. historically not always
20012 var previousWinningRev = prev.winningRev || winningRev(prev);
20013 var previouslyDeleted = 'deleted' in prev ? prev.deleted :
20014 isDeleted(prev, previousWinningRev);
20015 var deleted = 'deleted' in docInfo.metadata ? docInfo.metadata.deleted :
20016 isDeleted(docInfo.metadata);
20017 var isRoot = /^1-/.test(docInfo.metadata.rev);
20018
20019 if (previouslyDeleted && !deleted && newEdits && isRoot) {
20020 var newDoc = docInfo.data;
20021 newDoc._rev = previousWinningRev;
20022 newDoc._id = docInfo.metadata.id;
20023 docInfo = parseDoc(newDoc, newEdits);
20024 }
20025
20026 var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit);
20027
20028 var inConflict = newEdits && ((
20029 (previouslyDeleted && deleted && merged.conflicts !== 'new_leaf') ||
20030 (!previouslyDeleted && merged.conflicts !== 'new_leaf') ||
20031 (previouslyDeleted && !deleted && merged.conflicts === 'new_branch')));
20032
20033 if (inConflict) {
20034 var err = createError(REV_CONFLICT);
20035 results[i] = err;
20036 return cb();
20037 }
20038
20039 var newRev = docInfo.metadata.rev;
20040 docInfo.metadata.rev_tree = merged.tree;
20041 docInfo.stemmedRevs = merged.stemmedRevs || [];
20042 /* istanbul ignore else */
20043 if (prev.rev_map) {
20044 docInfo.metadata.rev_map = prev.rev_map; // used only by leveldb
20045 }
20046
20047 // recalculate
20048 var winningRev$$1 = winningRev(docInfo.metadata);
20049 var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev$$1);
20050
20051 // calculate the total number of documents that were added/removed,
20052 // from the perspective of total_rows/doc_count
20053 var delta = (previouslyDeleted === winningRevIsDeleted) ? 0 :
20054 previouslyDeleted < winningRevIsDeleted ? -1 : 1;
20055
20056 var newRevIsDeleted;
20057 if (newRev === winningRev$$1) {
20058 // if the new rev is the same as the winning rev, we can reuse that value
20059 newRevIsDeleted = winningRevIsDeleted;
20060 } else {
20061 // if they're not the same, then we need to recalculate
20062 newRevIsDeleted = isDeleted(docInfo.metadata, newRev);
20063 }
20064
20065 writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
20066 true, delta, i, cb);
20067}
20068
20069function rootIsMissing(docInfo) {
20070 return docInfo.metadata.rev_tree[0].ids[1].status === 'missing';
20071}
20072
20073function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results,
20074 writeDoc, opts, overallCallback) {
20075
20076 // Default to 1000 locally
20077 revLimit = revLimit || 1000;
20078
20079 function insertDoc(docInfo, resultsIdx, callback) {
20080 // Cant insert new deleted documents
20081 var winningRev$$1 = winningRev(docInfo.metadata);
20082 var deleted = isDeleted(docInfo.metadata, winningRev$$1);
20083 if ('was_delete' in opts && deleted) {
20084 results[resultsIdx] = createError(MISSING_DOC, 'deleted');
20085 return callback();
20086 }
20087
20088 // 4712 - detect whether a new document was inserted with a _rev
20089 var inConflict = newEdits && rootIsMissing(docInfo);
20090
20091 if (inConflict) {
20092 var err = createError(REV_CONFLICT);
20093 results[resultsIdx] = err;
20094 return callback();
20095 }
20096
20097 var delta = deleted ? 0 : 1;
20098
20099 writeDoc(docInfo, winningRev$$1, deleted, deleted, false,
20100 delta, resultsIdx, callback);
20101 }
20102
20103 var newEdits = opts.new_edits;
20104 var idsToDocs = new ExportedMap();
20105
20106 var docsDone = 0;
20107 var docsToDo = docInfos.length;
20108
20109 function checkAllDocsDone() {
20110 if (++docsDone === docsToDo && overallCallback) {
20111 overallCallback();
20112 }
20113 }
20114
20115 docInfos.forEach(function (currentDoc, resultsIdx) {
20116
20117 if (currentDoc._id && isLocalId(currentDoc._id)) {
20118 var fun = currentDoc._deleted ? '_removeLocal' : '_putLocal';
20119 api[fun](currentDoc, {ctx: tx}, function (err, res) {
20120 results[resultsIdx] = err || res;
20121 checkAllDocsDone();
20122 });
20123 return;
20124 }
20125
20126 var id = currentDoc.metadata.id;
20127 if (idsToDocs.has(id)) {
20128 docsToDo--; // duplicate
20129 idsToDocs.get(id).push([currentDoc, resultsIdx]);
20130 } else {
20131 idsToDocs.set(id, [[currentDoc, resultsIdx]]);
20132 }
20133 });
20134
20135 // in the case of new_edits, the user can provide multiple docs
20136 // with the same id. these need to be processed sequentially
20137 idsToDocs.forEach(function (docs, id) {
20138 var numDone = 0;
20139
20140 function docWritten() {
20141 if (++numDone < docs.length) {
20142 nextDoc();
20143 } else {
20144 checkAllDocsDone();
20145 }
20146 }
20147 function nextDoc() {
20148 var value = docs[numDone];
20149 var currentDoc = value[0];
20150 var resultsIdx = value[1];
20151
20152 if (fetchedDocs.has(id)) {
20153 updateDoc(revLimit, fetchedDocs.get(id), currentDoc, results,
20154 resultsIdx, docWritten, writeDoc, newEdits);
20155 } else {
20156 // Ensure stemming applies to new writes as well
20157 var merged = merge([], currentDoc.metadata.rev_tree[0], revLimit);
20158 currentDoc.metadata.rev_tree = merged.tree;
20159 currentDoc.stemmedRevs = merged.stemmedRevs || [];
20160 insertDoc(currentDoc, resultsIdx, docWritten);
20161 }
20162 }
20163 nextDoc();
20164 });
20165}
20166
20167function safeJsonParse(str) {
20168 // This try/catch guards against stack overflow errors.
20169 // JSON.parse() is faster than vuvuzela.parse() but vuvuzela
20170 // cannot overflow.
20171 try {
20172 return JSON.parse(str);
20173 } catch (e) {
20174 /* istanbul ignore next */
20175 return vuvuzela.parse(str);
20176 }
20177}
20178
20179function safeJsonStringify(json) {
20180 try {
20181 return JSON.stringify(json);
20182 } catch (e) {
20183 /* istanbul ignore next */
20184 return vuvuzela.stringify(json);
20185 }
20186}
20187
20188function readAsBlobOrBuffer(storedObject, type) {
20189 // In the browser, we've stored a binary string. This now comes back as a
20190 // browserified Node-style Buffer (implemented as a typed array),
20191 // but we want a Blob instead.
20192 var byteArray = new Uint8Array(storedObject);
20193 return createBlob([byteArray], {type: type});
20194}
20195
20196// In the browser, we store a binary string
20197function prepareAttachmentForStorage(attData, cb) {
20198 readAsBinaryString(attData, cb);
20199}
20200
20201function createEmptyBlobOrBuffer(type) {
20202 return createBlob([''], {type: type});
20203}
20204
20205function getCacheFor(transaction, store) {
20206 var prefix = store.prefix()[0];
20207 var cache = transaction._cache;
20208 var subCache = cache.get(prefix);
20209 if (!subCache) {
20210 subCache = new ExportedMap();
20211 cache.set(prefix, subCache);
20212 }
20213 return subCache;
20214}
20215
20216function LevelTransaction() {
20217 this._batch = [];
20218 this._cache = new ExportedMap();
20219}
20220
20221LevelTransaction.prototype.get = function (store, key, callback) {
20222 var cache = getCacheFor(this, store);
20223 var exists = cache.get(key);
20224 if (exists) {
20225 return immediate(function () {
20226 callback(null, exists);
20227 });
20228 } else if (exists === null) { // deleted marker
20229 /* istanbul ignore next */
20230 return immediate(function () {
20231 callback({name: 'NotFoundError'});
20232 });
20233 }
20234 store.get(key, function (err, res) {
20235 if (err) {
20236 /* istanbul ignore else */
20237 if (err.name === 'NotFoundError') {
20238 cache.set(key, null);
20239 }
20240 return callback(err);
20241 }
20242 cache.set(key, res);
20243 callback(null, res);
20244 });
20245};
20246
20247LevelTransaction.prototype.batch = function (batch) {
20248 for (var i = 0, len = batch.length; i < len; i++) {
20249 var operation = batch[i];
20250
20251 var cache = getCacheFor(this, operation.prefix);
20252
20253 if (operation.type === 'put') {
20254 cache.set(operation.key, operation.value);
20255 } else {
20256 cache.set(operation.key, null);
20257 }
20258 }
20259 this._batch = this._batch.concat(batch);
20260};
20261
20262LevelTransaction.prototype.execute = function (db, callback) {
20263
20264 var keys = new ExportedSet();
20265 var uniqBatches = [];
20266
20267 // remove duplicates; last one wins
20268 for (var i = this._batch.length - 1; i >= 0; i--) {
20269 var operation = this._batch[i];
20270 var lookupKey = operation.prefix.prefix()[0] + '\xff' + operation.key;
20271 if (keys.has(lookupKey)) {
20272 continue;
20273 }
20274 keys.add(lookupKey);
20275 uniqBatches.push(operation);
20276 }
20277
20278 db.batch(uniqBatches, callback);
20279};
20280
20281var DOC_STORE = 'document-store';
20282var BY_SEQ_STORE = 'by-sequence';
20283var ATTACHMENT_STORE = 'attach-store';
20284var BINARY_STORE = 'attach-binary-store';
20285var LOCAL_STORE = 'local-store';
20286var META_STORE = 'meta-store';
20287
20288// leveldb barks if we try to open a db multiple times
20289// so we cache opened connections here for initstore()
20290var dbStores = new ExportedMap();
20291
20292// store the value of update_seq in the by-sequence store the key name will
20293// never conflict, since the keys in the by-sequence store are integers
20294var UPDATE_SEQ_KEY = '_local_last_update_seq';
20295var DOC_COUNT_KEY = '_local_doc_count';
20296var UUID_KEY = '_local_uuid';
20297
20298var MD5_PREFIX = 'md5-';
20299
20300var safeJsonEncoding = {
20301 encode: safeJsonStringify,
20302 decode: safeJsonParse,
20303 buffer: false,
20304 type: 'cheap-json'
20305};
20306
20307var levelChanges = new Changes();
20308
20309// winningRev and deleted are performance-killers, but
20310// in newer versions of PouchDB, they are cached on the metadata
20311function getWinningRev(metadata) {
20312 return 'winningRev' in metadata ?
20313 metadata.winningRev : winningRev(metadata);
20314}
20315
20316function getIsDeleted(metadata, winningRev$$1) {
20317 return 'deleted' in metadata ?
20318 metadata.deleted : isDeleted(metadata, winningRev$$1);
20319}
20320
20321function fetchAttachment(att, stores, opts) {
20322 var type = att.content_type;
20323 return new Promise(function (resolve, reject) {
20324 stores.binaryStore.get(att.digest, function (err, buffer) {
20325 var data;
20326 if (err) {
20327 /* istanbul ignore if */
20328 if (err.name !== 'NotFoundError') {
20329 return reject(err);
20330 } else {
20331 // empty
20332 if (!opts.binary) {
20333 data = '';
20334 } else {
20335 data = binStringToBluffer('', type);
20336 }
20337 }
20338 } else { // non-empty
20339 if (opts.binary) {
20340 data = readAsBlobOrBuffer(buffer, type);
20341 } else {
20342 data = buffer.toString('base64');
20343 }
20344 }
20345 delete att.stub;
20346 delete att.length;
20347 att.data = data;
20348 resolve();
20349 });
20350 });
20351}
20352
20353function fetchAttachments(results, stores, opts) {
20354 var atts = [];
20355 results.forEach(function (row) {
20356 if (!(row.doc && row.doc._attachments)) {
20357 return;
20358 }
20359 var attNames = Object.keys(row.doc._attachments);
20360 attNames.forEach(function (attName) {
20361 var att = row.doc._attachments[attName];
20362 if (!('data' in att)) {
20363 atts.push(att);
20364 }
20365 });
20366 });
20367
20368 return Promise.all(atts.map(function (att) {
20369 return fetchAttachment(att, stores, opts);
20370 }));
20371}
20372
20373function LevelPouch(opts, callback) {
20374 opts = clone(opts);
20375 var api = this;
20376 var instanceId;
20377 var stores = {};
20378 var revLimit = opts.revs_limit;
20379 var db;
20380 var name = opts.name;
20381 // TODO: this is undocumented and unused probably
20382 /* istanbul ignore else */
20383 if (typeof opts.createIfMissing === 'undefined') {
20384 opts.createIfMissing = true;
20385 }
20386
20387 var leveldown = opts.db;
20388
20389 var dbStore;
20390 var leveldownName = functionName(leveldown);
20391 if (dbStores.has(leveldownName)) {
20392 dbStore = dbStores.get(leveldownName);
20393 } else {
20394 dbStore = new ExportedMap();
20395 dbStores.set(leveldownName, dbStore);
20396 }
20397 if (dbStore.has(name)) {
20398 db = dbStore.get(name);
20399 afterDBCreated();
20400 } else {
20401 dbStore.set(name, sublevelPouch(levelup(leveldown(name), opts, function (err) {
20402 /* istanbul ignore if */
20403 if (err) {
20404 dbStore["delete"](name);
20405 return callback(err);
20406 }
20407 db = dbStore.get(name);
20408 db._docCount = -1;
20409 db._queue = new Deque();
20410 /* istanbul ignore else */
20411 if (typeof opts.migrate === 'object') { // migration for leveldown
20412 opts.migrate.doMigrationOne(name, db, afterDBCreated);
20413 } else {
20414 afterDBCreated();
20415 }
20416 })));
20417 }
20418
20419 function afterDBCreated() {
20420 stores.docStore = db.sublevel(DOC_STORE, {valueEncoding: safeJsonEncoding});
20421 stores.bySeqStore = db.sublevel(BY_SEQ_STORE, {valueEncoding: 'json'});
20422 stores.attachmentStore =
20423 db.sublevel(ATTACHMENT_STORE, {valueEncoding: 'json'});
20424 stores.binaryStore = db.sublevel(BINARY_STORE, {valueEncoding: 'binary'});
20425 stores.localStore = db.sublevel(LOCAL_STORE, {valueEncoding: 'json'});
20426 stores.metaStore = db.sublevel(META_STORE, {valueEncoding: 'json'});
20427 /* istanbul ignore else */
20428 if (typeof opts.migrate === 'object') { // migration for leveldown
20429 opts.migrate.doMigrationTwo(db, stores, afterLastMigration);
20430 } else {
20431 afterLastMigration();
20432 }
20433 }
20434
20435 function afterLastMigration() {
20436 stores.metaStore.get(UPDATE_SEQ_KEY, function (err, value) {
20437 if (typeof db._updateSeq === 'undefined') {
20438 db._updateSeq = value || 0;
20439 }
20440 stores.metaStore.get(DOC_COUNT_KEY, function (err, value) {
20441 db._docCount = !err ? value : 0;
20442 stores.metaStore.get(UUID_KEY, function (err, value) {
20443 instanceId = !err ? value : uuid$1();
20444 stores.metaStore.put(UUID_KEY, instanceId, function () {
20445 immediate(function () {
20446 callback(null, api);
20447 });
20448 });
20449 });
20450 });
20451 });
20452 }
20453
20454 function countDocs(callback) {
20455 /* istanbul ignore if */
20456 if (db.isClosed()) {
20457 return callback(new Error('database is closed'));
20458 }
20459 return callback(null, db._docCount); // use cached value
20460 }
20461
20462 api._remote = false;
20463 /* istanbul ignore next */
20464 api.type = function () {
20465 return 'leveldb';
20466 };
20467
20468 api._id = function (callback) {
20469 callback(null, instanceId);
20470 };
20471
20472 api._info = function (callback) {
20473 var res = {
20474 doc_count: db._docCount,
20475 update_seq: db._updateSeq,
20476 backend_adapter: functionName(leveldown)
20477 };
20478 return immediate(function () {
20479 callback(null, res);
20480 });
20481 };
20482
20483 function tryCode(fun, args) {
20484 try {
20485 fun.apply(null, args);
20486 } catch (err) {
20487 args[args.length - 1](err);
20488 }
20489 }
20490
20491 function executeNext() {
20492 var firstTask = db._queue.peekFront();
20493
20494 if (firstTask.type === 'read') {
20495 runReadOperation(firstTask);
20496 } else { // write, only do one at a time
20497 runWriteOperation(firstTask);
20498 }
20499 }
20500
20501 function runReadOperation(firstTask) {
20502 // do multiple reads at once simultaneously, because it's safe
20503
20504 var readTasks = [firstTask];
20505 var i = 1;
20506 var nextTask = db._queue.get(i);
20507 while (typeof nextTask !== 'undefined' && nextTask.type === 'read') {
20508 readTasks.push(nextTask);
20509 i++;
20510 nextTask = db._queue.get(i);
20511 }
20512
20513 var numDone = 0;
20514
20515 readTasks.forEach(function (readTask) {
20516 var args = readTask.args;
20517 var callback = args[args.length - 1];
20518 args[args.length - 1] = getArguments(function (cbArgs) {
20519 callback.apply(null, cbArgs);
20520 if (++numDone === readTasks.length) {
20521 immediate(function () {
20522 // all read tasks have finished
20523 readTasks.forEach(function () {
20524 db._queue.shift();
20525 });
20526 if (db._queue.length) {
20527 executeNext();
20528 }
20529 });
20530 }
20531 });
20532 tryCode(readTask.fun, args);
20533 });
20534 }
20535
20536 function runWriteOperation(firstTask) {
20537 var args = firstTask.args;
20538 var callback = args[args.length - 1];
20539 args[args.length - 1] = getArguments(function (cbArgs) {
20540 callback.apply(null, cbArgs);
20541 immediate(function () {
20542 db._queue.shift();
20543 if (db._queue.length) {
20544 executeNext();
20545 }
20546 });
20547 });
20548 tryCode(firstTask.fun, args);
20549 }
20550
20551 // all read/write operations to the database are done in a queue,
20552 // similar to how websql/idb works. this avoids problems such
20553 // as e.g. compaction needing to have a lock on the database while
20554 // it updates stuff. in the future we can revisit this.
20555 function writeLock(fun) {
20556 return getArguments(function (args) {
20557 db._queue.push({
20558 fun: fun,
20559 args: args,
20560 type: 'write'
20561 });
20562
20563 if (db._queue.length === 1) {
20564 immediate(executeNext);
20565 }
20566 });
20567 }
20568
20569 // same as the writelock, but multiple can run at once
20570 function readLock(fun) {
20571 return getArguments(function (args) {
20572 db._queue.push({
20573 fun: fun,
20574 args: args,
20575 type: 'read'
20576 });
20577
20578 if (db._queue.length === 1) {
20579 immediate(executeNext);
20580 }
20581 });
20582 }
20583
20584 function formatSeq(n) {
20585 return ('0000000000000000' + n).slice(-16);
20586 }
20587
20588 function parseSeq(s) {
20589 return parseInt(s, 10);
20590 }
20591
20592 api._get = readLock(function (id, opts, callback) {
20593 opts = clone(opts);
20594
20595 stores.docStore.get(id, function (err, metadata) {
20596
20597 if (err || !metadata) {
20598 return callback(createError(MISSING_DOC, 'missing'));
20599 }
20600
20601 var rev;
20602 if (!opts.rev) {
20603 rev = getWinningRev(metadata);
20604 var deleted = getIsDeleted(metadata, rev);
20605 if (deleted) {
20606 return callback(createError(MISSING_DOC, "deleted"));
20607 }
20608 } else {
20609 rev = opts.latest ? latest(opts.rev, metadata) : opts.rev;
20610 }
20611
20612 var seq = metadata.rev_map[rev];
20613
20614 stores.bySeqStore.get(formatSeq(seq), function (err, doc) {
20615 if (!doc) {
20616 return callback(createError(MISSING_DOC));
20617 }
20618 /* istanbul ignore if */
20619 if ('_id' in doc && doc._id !== metadata.id) {
20620 // this failing implies something very wrong
20621 return callback(new Error('wrong doc returned'));
20622 }
20623 doc._id = metadata.id;
20624 if ('_rev' in doc) {
20625 /* istanbul ignore if */
20626 if (doc._rev !== rev) {
20627 // this failing implies something very wrong
20628 return callback(new Error('wrong doc returned'));
20629 }
20630 } else {
20631 // we didn't always store this
20632 doc._rev = rev;
20633 }
20634 return callback(null, {doc: doc, metadata: metadata});
20635 });
20636 });
20637 });
20638
20639 // not technically part of the spec, but if putAttachment has its own
20640 // method...
20641 api._getAttachment = function (docId, attachId, attachment, opts, callback) {
20642 var digest = attachment.digest;
20643 var type = attachment.content_type;
20644
20645 stores.binaryStore.get(digest, function (err, attach) {
20646 if (err) {
20647 /* istanbul ignore if */
20648 if (err.name !== 'NotFoundError') {
20649 return callback(err);
20650 }
20651 // Empty attachment
20652 return callback(null, opts.binary ? createEmptyBlobOrBuffer(type) : '');
20653 }
20654
20655 if (opts.binary) {
20656 callback(null, readAsBlobOrBuffer(attach, type));
20657 } else {
20658 callback(null, attach.toString('base64'));
20659 }
20660 });
20661 };
20662
20663 api._bulkDocs = writeLock(function (req, opts, callback) {
20664 var newEdits = opts.new_edits;
20665 var results = new Array(req.docs.length);
20666 var fetchedDocs = new ExportedMap();
20667 var stemmedRevs = new ExportedMap();
20668
20669 var txn = new LevelTransaction();
20670 var docCountDelta = 0;
20671 var newUpdateSeq = db._updateSeq;
20672
20673 // parse the docs and give each a sequence number
20674 var userDocs = req.docs;
20675 var docInfos = userDocs.map(function (doc) {
20676 if (doc._id && isLocalId(doc._id)) {
20677 return doc;
20678 }
20679 var newDoc = parseDoc(doc, newEdits, api.__opts);
20680
20681 if (newDoc.metadata && !newDoc.metadata.rev_map) {
20682 newDoc.metadata.rev_map = {};
20683 }
20684
20685 return newDoc;
20686 });
20687 var infoErrors = docInfos.filter(function (doc) {
20688 return doc.error;
20689 });
20690
20691 if (infoErrors.length) {
20692 return callback(infoErrors[0]);
20693 }
20694
20695 // verify any stub attachments as a precondition test
20696
20697 function verifyAttachment(digest, callback) {
20698 txn.get(stores.attachmentStore, digest, function (levelErr) {
20699 if (levelErr) {
20700 var err = createError(MISSING_STUB,
20701 'unknown stub attachment with digest ' +
20702 digest);
20703 callback(err);
20704 } else {
20705 callback();
20706 }
20707 });
20708 }
20709
20710 function verifyAttachments(finish) {
20711 var digests = [];
20712 userDocs.forEach(function (doc) {
20713 if (doc && doc._attachments) {
20714 Object.keys(doc._attachments).forEach(function (filename) {
20715 var att = doc._attachments[filename];
20716 if (att.stub) {
20717 digests.push(att.digest);
20718 }
20719 });
20720 }
20721 });
20722 if (!digests.length) {
20723 return finish();
20724 }
20725 var numDone = 0;
20726 var err;
20727
20728 digests.forEach(function (digest) {
20729 verifyAttachment(digest, function (attErr) {
20730 if (attErr && !err) {
20731 err = attErr;
20732 }
20733
20734 if (++numDone === digests.length) {
20735 finish(err);
20736 }
20737 });
20738 });
20739 }
20740
20741 function fetchExistingDocs(finish) {
20742 var numDone = 0;
20743 var overallErr;
20744 function checkDone() {
20745 if (++numDone === userDocs.length) {
20746 return finish(overallErr);
20747 }
20748 }
20749
20750 userDocs.forEach(function (doc) {
20751 if (doc._id && isLocalId(doc._id)) {
20752 // skip local docs
20753 return checkDone();
20754 }
20755 txn.get(stores.docStore, doc._id, function (err, info) {
20756 if (err) {
20757 /* istanbul ignore if */
20758 if (err.name !== 'NotFoundError') {
20759 overallErr = err;
20760 }
20761 } else {
20762 fetchedDocs.set(doc._id, info);
20763 }
20764 checkDone();
20765 });
20766 });
20767 }
20768
20769 function compact(revsMap, callback) {
20770 var promise = Promise.resolve();
20771 revsMap.forEach(function (revs, docId) {
20772 // TODO: parallelize, for now need to be sequential to
20773 // pass orphaned attachment tests
20774 promise = promise.then(function () {
20775 return new Promise(function (resolve, reject) {
20776 api._doCompactionNoLock(docId, revs, {ctx: txn}, function (err) {
20777 /* istanbul ignore if */
20778 if (err) {
20779 return reject(err);
20780 }
20781 resolve();
20782 });
20783 });
20784 });
20785 });
20786
20787 promise.then(function () {
20788 callback();
20789 }, callback);
20790 }
20791
20792 function autoCompact(callback) {
20793 var revsMap = new ExportedMap();
20794 fetchedDocs.forEach(function (metadata, docId) {
20795 revsMap.set(docId, compactTree(metadata));
20796 });
20797 compact(revsMap, callback);
20798 }
20799
20800 function finish() {
20801 compact(stemmedRevs, function (error) {
20802 /* istanbul ignore if */
20803 if (error) {
20804 complete(error);
20805 }
20806 if (api.auto_compaction) {
20807 return autoCompact(complete);
20808 }
20809 complete();
20810 });
20811 }
20812
20813 function writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
20814 isUpdate, delta, resultsIdx, callback2) {
20815 docCountDelta += delta;
20816
20817 var err = null;
20818 var recv = 0;
20819
20820 docInfo.metadata.winningRev = winningRev$$1;
20821 docInfo.metadata.deleted = winningRevIsDeleted;
20822
20823 docInfo.data._id = docInfo.metadata.id;
20824 docInfo.data._rev = docInfo.metadata.rev;
20825
20826 if (newRevIsDeleted) {
20827 docInfo.data._deleted = true;
20828 }
20829
20830 if (docInfo.stemmedRevs.length) {
20831 stemmedRevs.set(docInfo.metadata.id, docInfo.stemmedRevs);
20832 }
20833
20834 var attachments = docInfo.data._attachments ?
20835 Object.keys(docInfo.data._attachments) :
20836 [];
20837
20838 function attachmentSaved(attachmentErr) {
20839 recv++;
20840 if (!err) {
20841 /* istanbul ignore if */
20842 if (attachmentErr) {
20843 err = attachmentErr;
20844 callback2(err);
20845 } else if (recv === attachments.length) {
20846 finish();
20847 }
20848 }
20849 }
20850
20851 function onMD5Load(doc, key, data, attachmentSaved) {
20852 return function (result) {
20853 saveAttachment(doc, MD5_PREFIX + result, key, data, attachmentSaved);
20854 };
20855 }
20856
20857 function doMD5(doc, key, attachmentSaved) {
20858 return function (data) {
20859 binaryMd5(data, onMD5Load(doc, key, data, attachmentSaved));
20860 };
20861 }
20862
20863 for (var i = 0; i < attachments.length; i++) {
20864 var key = attachments[i];
20865 var att = docInfo.data._attachments[key];
20866
20867 if (att.stub) {
20868 // still need to update the refs mapping
20869 var id = docInfo.data._id;
20870 var rev = docInfo.data._rev;
20871 saveAttachmentRefs(id, rev, att.digest, attachmentSaved);
20872 continue;
20873 }
20874 var data;
20875 if (typeof att.data === 'string') {
20876 // input is assumed to be a base64 string
20877 try {
20878 data = thisAtob(att.data);
20879 } catch (e) {
20880 callback(createError(BAD_ARG,
20881 'Attachment is not a valid base64 string'));
20882 return;
20883 }
20884 doMD5(docInfo, key, attachmentSaved)(data);
20885 } else {
20886 prepareAttachmentForStorage(att.data,
20887 doMD5(docInfo, key, attachmentSaved));
20888 }
20889 }
20890
20891 function finish() {
20892 var seq = docInfo.metadata.rev_map[docInfo.metadata.rev];
20893 /* istanbul ignore if */
20894 if (seq) {
20895 // check that there aren't any existing revisions with the same
20896 // revision id, else we shouldn't do anything
20897 return callback2();
20898 }
20899 seq = ++newUpdateSeq;
20900 docInfo.metadata.rev_map[docInfo.metadata.rev] =
20901 docInfo.metadata.seq = seq;
20902 var seqKey = formatSeq(seq);
20903 var batch = [{
20904 key: seqKey,
20905 value: docInfo.data,
20906 prefix: stores.bySeqStore,
20907 type: 'put'
20908 }, {
20909 key: docInfo.metadata.id,
20910 value: docInfo.metadata,
20911 prefix: stores.docStore,
20912 type: 'put'
20913 }];
20914 txn.batch(batch);
20915 results[resultsIdx] = {
20916 ok: true,
20917 id: docInfo.metadata.id,
20918 rev: docInfo.metadata.rev
20919 };
20920 fetchedDocs.set(docInfo.metadata.id, docInfo.metadata);
20921 callback2();
20922 }
20923
20924 if (!attachments.length) {
20925 finish();
20926 }
20927 }
20928
20929 // attachments are queued per-digest, otherwise the refs could be
20930 // overwritten by concurrent writes in the same bulkDocs session
20931 var attachmentQueues = {};
20932
20933 function saveAttachmentRefs(id, rev, digest, callback) {
20934
20935 function fetchAtt() {
20936 return new Promise(function (resolve, reject) {
20937 txn.get(stores.attachmentStore, digest, function (err, oldAtt) {
20938 /* istanbul ignore if */
20939 if (err && err.name !== 'NotFoundError') {
20940 return reject(err);
20941 }
20942 resolve(oldAtt);
20943 });
20944 });
20945 }
20946
20947 function saveAtt(oldAtt) {
20948 var ref = [id, rev].join('@');
20949 var newAtt = {};
20950
20951 if (oldAtt) {
20952 if (oldAtt.refs) {
20953 // only update references if this attachment already has them
20954 // since we cannot migrate old style attachments here without
20955 // doing a full db scan for references
20956 newAtt.refs = oldAtt.refs;
20957 newAtt.refs[ref] = true;
20958 }
20959 } else {
20960 newAtt.refs = {};
20961 newAtt.refs[ref] = true;
20962 }
20963
20964 return new Promise(function (resolve) {
20965 txn.batch([{
20966 type: 'put',
20967 prefix: stores.attachmentStore,
20968 key: digest,
20969 value: newAtt
20970 }]);
20971 resolve(!oldAtt);
20972 });
20973 }
20974
20975 // put attachments in a per-digest queue, to avoid two docs with the same
20976 // attachment overwriting each other
20977 var queue = attachmentQueues[digest] || Promise.resolve();
20978 attachmentQueues[digest] = queue.then(function () {
20979 return fetchAtt().then(saveAtt).then(function (isNewAttachment) {
20980 callback(null, isNewAttachment);
20981 }, callback);
20982 });
20983 }
20984
20985 function saveAttachment(docInfo, digest, key, data, callback) {
20986 var att = docInfo.data._attachments[key];
20987 delete att.data;
20988 att.digest = digest;
20989 att.length = data.length;
20990 var id = docInfo.metadata.id;
20991 var rev = docInfo.metadata.rev;
20992 att.revpos = parseInt(rev, 10);
20993
20994 saveAttachmentRefs(id, rev, digest, function (err, isNewAttachment) {
20995 /* istanbul ignore if */
20996 if (err) {
20997 return callback(err);
20998 }
20999 // do not try to store empty attachments
21000 if (data.length === 0) {
21001 return callback(err);
21002 }
21003 if (!isNewAttachment) {
21004 // small optimization - don't bother writing it again
21005 return callback(err);
21006 }
21007 txn.batch([{
21008 type: 'put',
21009 prefix: stores.binaryStore,
21010 key: digest,
21011 value: bufferFrom(data, 'binary')
21012 }]);
21013 callback();
21014 });
21015 }
21016
21017 function complete(err) {
21018 /* istanbul ignore if */
21019 if (err) {
21020 return immediate(function () {
21021 callback(err);
21022 });
21023 }
21024 txn.batch([
21025 {
21026 prefix: stores.metaStore,
21027 type: 'put',
21028 key: UPDATE_SEQ_KEY,
21029 value: newUpdateSeq
21030 },
21031 {
21032 prefix: stores.metaStore,
21033 type: 'put',
21034 key: DOC_COUNT_KEY,
21035 value: db._docCount + docCountDelta
21036 }
21037 ]);
21038 txn.execute(db, function (err) {
21039 /* istanbul ignore if */
21040 if (err) {
21041 return callback(err);
21042 }
21043 db._docCount += docCountDelta;
21044 db._updateSeq = newUpdateSeq;
21045 levelChanges.notify(name);
21046 immediate(function () {
21047 callback(null, results);
21048 });
21049 });
21050 }
21051
21052 if (!docInfos.length) {
21053 return callback(null, []);
21054 }
21055
21056 verifyAttachments(function (err) {
21057 if (err) {
21058 return callback(err);
21059 }
21060 fetchExistingDocs(function (err) {
21061 /* istanbul ignore if */
21062 if (err) {
21063 return callback(err);
21064 }
21065 processDocs(revLimit, docInfos, api, fetchedDocs, txn, results,
21066 writeDoc, opts, finish);
21067 });
21068 });
21069 });
21070 api._allDocs = function (opts, callback) {
21071 if ('keys' in opts) {
21072 return allDocsKeysQuery(this, opts);
21073 }
21074 return readLock(function (opts, callback) {
21075 opts = clone(opts);
21076 countDocs(function (err, docCount) {
21077 /* istanbul ignore if */
21078 if (err) {
21079 return callback(err);
21080 }
21081 var readstreamOpts = {};
21082 var skip = opts.skip || 0;
21083 if (opts.startkey) {
21084 readstreamOpts.gte = opts.startkey;
21085 }
21086 if (opts.endkey) {
21087 readstreamOpts.lte = opts.endkey;
21088 }
21089 if (opts.key) {
21090 readstreamOpts.gte = readstreamOpts.lte = opts.key;
21091 }
21092 if (opts.descending) {
21093 readstreamOpts.reverse = true;
21094 // switch start and ends
21095 var tmp = readstreamOpts.lte;
21096 readstreamOpts.lte = readstreamOpts.gte;
21097 readstreamOpts.gte = tmp;
21098 }
21099 var limit;
21100 if (typeof opts.limit === 'number') {
21101 limit = opts.limit;
21102 }
21103 if (limit === 0 ||
21104 ('gte' in readstreamOpts && 'lte' in readstreamOpts &&
21105 readstreamOpts.gte > readstreamOpts.lte)) {
21106 // should return 0 results when start is greater than end.
21107 // normally level would "fix" this for us by reversing the order,
21108 // so short-circuit instead
21109 var returnVal = {
21110 total_rows: docCount,
21111 offset: opts.skip,
21112 rows: []
21113 };
21114 /* istanbul ignore if */
21115 if (opts.update_seq) {
21116 returnVal.update_seq = db._updateSeq;
21117 }
21118 return callback(null, returnVal);
21119 }
21120 var results = [];
21121 var docstream = stores.docStore.readStream(readstreamOpts);
21122
21123 var throughStream = through2.obj(function (entry, _, next) {
21124 var metadata = entry.value;
21125 // winningRev and deleted are performance-killers, but
21126 // in newer versions of PouchDB, they are cached on the metadata
21127 var winningRev$$1 = getWinningRev(metadata);
21128 var deleted = getIsDeleted(metadata, winningRev$$1);
21129 if (!deleted) {
21130 if (skip-- > 0) {
21131 next();
21132 return;
21133 } else if (typeof limit === 'number' && limit-- <= 0) {
21134 docstream.unpipe();
21135 docstream.destroy();
21136 next();
21137 return;
21138 }
21139 } else if (opts.deleted !== 'ok') {
21140 next();
21141 return;
21142 }
21143 function allDocsInner(data) {
21144 var doc = {
21145 id: metadata.id,
21146 key: metadata.id,
21147 value: {
21148 rev: winningRev$$1
21149 }
21150 };
21151 if (opts.include_docs) {
21152 doc.doc = data;
21153 doc.doc._rev = doc.value.rev;
21154 if (opts.conflicts) {
21155 var conflicts = collectConflicts(metadata);
21156 if (conflicts.length) {
21157 doc.doc._conflicts = conflicts;
21158 }
21159 }
21160 for (var att in doc.doc._attachments) {
21161 if (Object.prototype.hasOwnProperty.call(doc.doc._attachments, att)) {
21162 doc.doc._attachments[att].stub = true;
21163 }
21164 }
21165 }
21166 if (opts.inclusive_end === false && metadata.id === opts.endkey) {
21167 return next();
21168 } else if (deleted) {
21169 if (opts.deleted === 'ok') {
21170 doc.value.deleted = true;
21171 doc.doc = null;
21172 } else {
21173 /* istanbul ignore next */
21174 return next();
21175 }
21176 }
21177 results.push(doc);
21178 next();
21179 }
21180 if (opts.include_docs) {
21181 var seq = metadata.rev_map[winningRev$$1];
21182 stores.bySeqStore.get(formatSeq(seq), function (err, data) {
21183 allDocsInner(data);
21184 });
21185 }
21186 else {
21187 allDocsInner();
21188 }
21189 }, function (next) {
21190 Promise.resolve().then(function () {
21191 if (opts.include_docs && opts.attachments) {
21192 return fetchAttachments(results, stores, opts);
21193 }
21194 }).then(function () {
21195 var returnVal = {
21196 total_rows: docCount,
21197 offset: opts.skip,
21198 rows: results
21199 };
21200
21201 /* istanbul ignore if */
21202 if (opts.update_seq) {
21203 returnVal.update_seq = db._updateSeq;
21204 }
21205 callback(null, returnVal);
21206 }, callback);
21207 next();
21208 }).on('unpipe', function () {
21209 throughStream.end();
21210 });
21211
21212 docstream.on('error', callback);
21213
21214 docstream.pipe(throughStream);
21215 });
21216 })(opts, callback);
21217 };
21218
21219 api._changes = function (opts) {
21220 opts = clone(opts);
21221
21222 if (opts.continuous) {
21223 var id = name + ':' + uuid$1();
21224 levelChanges.addListener(name, id, api, opts);
21225 levelChanges.notify(name);
21226 return {
21227 cancel: function () {
21228 levelChanges.removeListener(name, id);
21229 }
21230 };
21231 }
21232
21233 var descending = opts.descending;
21234 var results = [];
21235 var lastSeq = opts.since || 0;
21236 var called = 0;
21237 var streamOpts = {
21238 reverse: descending
21239 };
21240 var limit;
21241 if ('limit' in opts && opts.limit > 0) {
21242 limit = opts.limit;
21243 }
21244 if (!streamOpts.reverse) {
21245 streamOpts.start = formatSeq(opts.since || 0);
21246 }
21247
21248 var docIds = opts.doc_ids && new ExportedSet(opts.doc_ids);
21249 var filter = filterChange(opts);
21250 var docIdsToMetadata = new ExportedMap();
21251
21252 function complete() {
21253 opts.done = true;
21254 if (opts.return_docs && opts.limit) {
21255 /* istanbul ignore if */
21256 if (opts.limit < results.length) {
21257 results.length = opts.limit;
21258 }
21259 }
21260 changeStream.unpipe(throughStream);
21261 changeStream.destroy();
21262 if (!opts.continuous && !opts.cancelled) {
21263 if (opts.include_docs && opts.attachments && opts.return_docs) {
21264 fetchAttachments(results, stores, opts).then(function () {
21265 opts.complete(null, {results: results, last_seq: lastSeq});
21266 });
21267 } else {
21268 opts.complete(null, {results: results, last_seq: lastSeq});
21269 }
21270 }
21271 }
21272 var changeStream = stores.bySeqStore.readStream(streamOpts);
21273 var throughStream = through2.obj(function (data, _, next) {
21274 if (limit && called >= limit) {
21275 complete();
21276 return next();
21277 }
21278 if (opts.cancelled || opts.done) {
21279 return next();
21280 }
21281
21282 var seq = parseSeq(data.key);
21283 var doc = data.value;
21284
21285 if (seq === opts.since && !descending) {
21286 // couchdb ignores `since` if descending=true
21287 return next();
21288 }
21289
21290 if (docIds && !docIds.has(doc._id)) {
21291 return next();
21292 }
21293
21294 var metadata;
21295
21296 function onGetMetadata(metadata) {
21297 var winningRev$$1 = getWinningRev(metadata);
21298
21299 function onGetWinningDoc(winningDoc) {
21300
21301 var change = opts.processChange(winningDoc, metadata, opts);
21302 change.seq = metadata.seq;
21303
21304 var filtered = filter(change);
21305 if (typeof filtered === 'object') {
21306 return opts.complete(filtered);
21307 }
21308
21309 if (filtered) {
21310 called++;
21311
21312 if (opts.attachments && opts.include_docs) {
21313 // fetch attachment immediately for the benefit
21314 // of live listeners
21315 fetchAttachments([change], stores, opts).then(function () {
21316 opts.onChange(change);
21317 });
21318 } else {
21319 opts.onChange(change);
21320 }
21321
21322 if (opts.return_docs) {
21323 results.push(change);
21324 }
21325 }
21326 next();
21327 }
21328
21329 if (metadata.seq !== seq) {
21330 // some other seq is later
21331 return next();
21332 }
21333
21334 lastSeq = seq;
21335
21336 if (winningRev$$1 === doc._rev) {
21337 return onGetWinningDoc(doc);
21338 }
21339
21340 // fetch the winner
21341
21342 var winningSeq = metadata.rev_map[winningRev$$1];
21343
21344 stores.bySeqStore.get(formatSeq(winningSeq), function (err, doc) {
21345 onGetWinningDoc(doc);
21346 });
21347 }
21348
21349 metadata = docIdsToMetadata.get(doc._id);
21350 if (metadata) { // cached
21351 return onGetMetadata(metadata);
21352 }
21353 // metadata not cached, have to go fetch it
21354 stores.docStore.get(doc._id, function (err, metadata) {
21355 /* istanbul ignore if */
21356 if (opts.cancelled || opts.done || db.isClosed() ||
21357 isLocalId(metadata.id)) {
21358 return next();
21359 }
21360 docIdsToMetadata.set(doc._id, metadata);
21361 onGetMetadata(metadata);
21362 });
21363 }, function (next) {
21364 if (opts.cancelled) {
21365 return next();
21366 }
21367 if (opts.return_docs && opts.limit) {
21368 /* istanbul ignore if */
21369 if (opts.limit < results.length) {
21370 results.length = opts.limit;
21371 }
21372 }
21373
21374 next();
21375 }).on('unpipe', function () {
21376 throughStream.end();
21377 complete();
21378 });
21379 changeStream.pipe(throughStream);
21380 return {
21381 cancel: function () {
21382 opts.cancelled = true;
21383 complete();
21384 }
21385 };
21386 };
21387
21388 api._close = function (callback) {
21389 /* istanbul ignore if */
21390 if (db.isClosed()) {
21391 return callback(createError(NOT_OPEN));
21392 }
21393 db.close(function (err) {
21394 /* istanbul ignore if */
21395 if (err) {
21396 callback(err);
21397 } else {
21398 dbStore["delete"](name);
21399
21400 var adapterName = functionName(leveldown);
21401 var adapterStore = dbStores.get(adapterName);
21402 var keys = [...adapterStore.keys()].filter(k => k.includes("-mrview-"));
21403 keys.forEach(key => {
21404 var eventEmitter = adapterStore.get(key);
21405 eventEmitter.removeAllListeners();
21406 eventEmitter.close();
21407 adapterStore["delete"](key);
21408 });
21409
21410 callback();
21411 }
21412 });
21413 };
21414
21415 api._getRevisionTree = function (docId, callback) {
21416 stores.docStore.get(docId, function (err, metadata) {
21417 if (err) {
21418 callback(createError(MISSING_DOC));
21419 } else {
21420 callback(null, metadata.rev_tree);
21421 }
21422 });
21423 };
21424
21425 api._doCompaction = writeLock(function (docId, revs, opts, callback) {
21426 api._doCompactionNoLock(docId, revs, opts, callback);
21427 });
21428
21429 // the NoLock version is for use by bulkDocs
21430 api._doCompactionNoLock = function (docId, revs, opts, callback) {
21431 if (typeof opts === 'function') {
21432 callback = opts;
21433 opts = {};
21434 }
21435
21436 if (!revs.length) {
21437 return callback();
21438 }
21439 var txn = opts.ctx || new LevelTransaction();
21440
21441 txn.get(stores.docStore, docId, function (err, metadata) {
21442 /* istanbul ignore if */
21443 if (err) {
21444 return callback(err);
21445 }
21446 var seqs = revs.map(function (rev) {
21447 var seq = metadata.rev_map[rev];
21448 delete metadata.rev_map[rev];
21449 return seq;
21450 });
21451 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
21452 revHash, ctx, opts) {
21453 var rev = pos + '-' + revHash;
21454 if (revs.indexOf(rev) !== -1) {
21455 opts.status = 'missing';
21456 }
21457 });
21458
21459 var batch = [];
21460 batch.push({
21461 key: metadata.id,
21462 value: metadata,
21463 type: 'put',
21464 prefix: stores.docStore
21465 });
21466
21467 var digestMap = {};
21468 var numDone = 0;
21469 var overallErr;
21470 function checkDone(err) {
21471 /* istanbul ignore if */
21472 if (err) {
21473 overallErr = err;
21474 }
21475 if (++numDone === revs.length) { // done
21476 /* istanbul ignore if */
21477 if (overallErr) {
21478 return callback(overallErr);
21479 }
21480 deleteOrphanedAttachments();
21481 }
21482 }
21483
21484 function finish(err) {
21485 /* istanbul ignore if */
21486 if (err) {
21487 return callback(err);
21488 }
21489 txn.batch(batch);
21490 if (opts.ctx) {
21491 // don't execute immediately
21492 return callback();
21493 }
21494 txn.execute(db, callback);
21495 }
21496
21497 function deleteOrphanedAttachments() {
21498 var possiblyOrphanedAttachments = Object.keys(digestMap);
21499 if (!possiblyOrphanedAttachments.length) {
21500 return finish();
21501 }
21502 var numDone = 0;
21503 var overallErr;
21504 function checkDone(err) {
21505 /* istanbul ignore if */
21506 if (err) {
21507 overallErr = err;
21508 }
21509 if (++numDone === possiblyOrphanedAttachments.length) {
21510 finish(overallErr);
21511 }
21512 }
21513 var refsToDelete = new ExportedMap();
21514 revs.forEach(function (rev) {
21515 refsToDelete.set(docId + '@' + rev, true);
21516 });
21517 possiblyOrphanedAttachments.forEach(function (digest) {
21518 txn.get(stores.attachmentStore, digest, function (err, attData) {
21519 /* istanbul ignore if */
21520 if (err) {
21521 if (err.name === 'NotFoundError') {
21522 return checkDone();
21523 } else {
21524 return checkDone(err);
21525 }
21526 }
21527 var refs = Object.keys(attData.refs || {}).filter(function (ref) {
21528 return !refsToDelete.has(ref);
21529 });
21530 var newRefs = {};
21531 refs.forEach(function (ref) {
21532 newRefs[ref] = true;
21533 });
21534 if (refs.length) { // not orphaned
21535 batch.push({
21536 key: digest,
21537 type: 'put',
21538 value: {refs: newRefs},
21539 prefix: stores.attachmentStore
21540 });
21541 } else { // orphaned, can safely delete
21542 batch = batch.concat([{
21543 key: digest,
21544 type: 'del',
21545 prefix: stores.attachmentStore
21546 }, {
21547 key: digest,
21548 type: 'del',
21549 prefix: stores.binaryStore
21550 }]);
21551 }
21552 checkDone();
21553 });
21554 });
21555 }
21556
21557 seqs.forEach(function (seq) {
21558 batch.push({
21559 key: formatSeq(seq),
21560 type: 'del',
21561 prefix: stores.bySeqStore
21562 });
21563 txn.get(stores.bySeqStore, formatSeq(seq), function (err, doc) {
21564 /* istanbul ignore if */
21565 if (err) {
21566 if (err.name === 'NotFoundError') {
21567 return checkDone();
21568 } else {
21569 return checkDone(err);
21570 }
21571 }
21572 var atts = Object.keys(doc._attachments || {});
21573 atts.forEach(function (attName) {
21574 var digest = doc._attachments[attName].digest;
21575 digestMap[digest] = true;
21576 });
21577 checkDone();
21578 });
21579 });
21580 });
21581 };
21582
21583 api._getLocal = function (id, callback) {
21584 stores.localStore.get(id, function (err, doc) {
21585 if (err) {
21586 callback(createError(MISSING_DOC));
21587 } else {
21588 callback(null, doc);
21589 }
21590 });
21591 };
21592
21593 api._putLocal = function (doc, opts, callback) {
21594 if (typeof opts === 'function') {
21595 callback = opts;
21596 opts = {};
21597 }
21598 if (opts.ctx) {
21599 api._putLocalNoLock(doc, opts, callback);
21600 } else {
21601 api._putLocalWithLock(doc, opts, callback);
21602 }
21603 };
21604
21605 api._putLocalWithLock = writeLock(function (doc, opts, callback) {
21606 api._putLocalNoLock(doc, opts, callback);
21607 });
21608
21609 // the NoLock version is for use by bulkDocs
21610 api._putLocalNoLock = function (doc, opts, callback) {
21611 delete doc._revisions; // ignore this, trust the rev
21612 var oldRev = doc._rev;
21613 var id = doc._id;
21614
21615 var txn = opts.ctx || new LevelTransaction();
21616
21617 txn.get(stores.localStore, id, function (err, resp) {
21618 if (err && oldRev) {
21619 return callback(createError(REV_CONFLICT));
21620 }
21621 if (resp && resp._rev !== oldRev) {
21622 return callback(createError(REV_CONFLICT));
21623 }
21624 doc._rev =
21625 oldRev ? '0-' + (parseInt(oldRev.split('-')[1], 10) + 1) : '0-1';
21626 var batch = [
21627 {
21628 type: 'put',
21629 prefix: stores.localStore,
21630 key: id,
21631 value: doc
21632 }
21633 ];
21634
21635 txn.batch(batch);
21636 var ret = {ok: true, id: doc._id, rev: doc._rev};
21637
21638 if (opts.ctx) {
21639 // don't execute immediately
21640 return callback(null, ret);
21641 }
21642 txn.execute(db, function (err) {
21643 /* istanbul ignore if */
21644 if (err) {
21645 return callback(err);
21646 }
21647 callback(null, ret);
21648 });
21649 });
21650 };
21651
21652 api._removeLocal = function (doc, opts, callback) {
21653 if (typeof opts === 'function') {
21654 callback = opts;
21655 opts = {};
21656 }
21657 if (opts.ctx) {
21658 api._removeLocalNoLock(doc, opts, callback);
21659 } else {
21660 api._removeLocalWithLock(doc, opts, callback);
21661 }
21662 };
21663
21664 api._removeLocalWithLock = writeLock(function (doc, opts, callback) {
21665 api._removeLocalNoLock(doc, opts, callback);
21666 });
21667
21668 // the NoLock version is for use by bulkDocs
21669 api._removeLocalNoLock = function (doc, opts, callback) {
21670 var txn = opts.ctx || new LevelTransaction();
21671 txn.get(stores.localStore, doc._id, function (err, resp) {
21672 if (err) {
21673 /* istanbul ignore if */
21674 if (err.name !== 'NotFoundError') {
21675 return callback(err);
21676 } else {
21677 return callback(createError(MISSING_DOC));
21678 }
21679 }
21680 if (resp._rev !== doc._rev) {
21681 return callback(createError(REV_CONFLICT));
21682 }
21683 txn.batch([{
21684 prefix: stores.localStore,
21685 type: 'del',
21686 key: doc._id
21687 }]);
21688 var ret = {ok: true, id: doc._id, rev: '0-0'};
21689 if (opts.ctx) {
21690 // don't execute immediately
21691 return callback(null, ret);
21692 }
21693 txn.execute(db, function (err) {
21694 /* istanbul ignore if */
21695 if (err) {
21696 return callback(err);
21697 }
21698 callback(null, ret);
21699 });
21700 });
21701 };
21702
21703 // close and delete open leveldb stores
21704 api._destroy = function (opts, callback) {
21705 var dbStore;
21706 var leveldownName = functionName(leveldown);
21707 /* istanbul ignore else */
21708 if (dbStores.has(leveldownName)) {
21709 dbStore = dbStores.get(leveldownName);
21710 } else {
21711 return callDestroy(name, callback);
21712 }
21713
21714 /* istanbul ignore else */
21715 if (dbStore.has(name)) {
21716 levelChanges.removeAllListeners(name);
21717
21718 dbStore.get(name).close(function () {
21719 dbStore["delete"](name);
21720 callDestroy(name, callback);
21721 });
21722 } else {
21723 callDestroy(name, callback);
21724 }
21725 };
21726 function callDestroy(name, cb) {
21727 // May not exist if leveldown is backed by memory adapter
21728 /* istanbul ignore else */
21729 if ('destroy' in leveldown) {
21730 leveldown.destroy(name, cb);
21731 } else {
21732 cb(null);
21733 }
21734 }
21735}
21736
21737function LocalStoragePouch(opts, callback) {
21738 var _opts = $inject_Object_assign({
21739 db: localstoragedown
21740 }, opts);
21741
21742 LevelPouch.call(this, _opts, callback);
21743}
21744
21745// overrides for normal LevelDB behavior on Node
21746LocalStoragePouch.valid = function () {
21747 return typeof localStorage !== 'undefined';
21748};
21749LocalStoragePouch.use_prefix = true;
21750
21751function LocalStoragePouchPlugin (PouchDB) {
21752 PouchDB.adapter('localstorage', LocalStoragePouch, true);
21753}
21754
21755// this code only runs in the browser, as its own dist/ script
21756
21757if (typeof PouchDB === 'undefined') {
21758 guardedConsole('error', 'localstorage adapter plugin error: ' +
21759 'Cannot find global "PouchDB" object! ' +
21760 'Did you remember to include pouchdb.js?');
21761} else {
21762 PouchDB.plugin(LocalStoragePouchPlugin);
21763}
21764
21765},{"118":118,"12":12,"125":125,"140":140,"23":23,"26":26,"31":31,"37":37,"39":39,"5":5,"61":61,"63":63,"70":70,"82":82,"84":84}]},{},[143]);
21766
\No newline at end of file