UNPKG

738 kBJavaScriptView Raw
1// PouchDB localStorage plugin 9.0.0
2// Based on localstorage-down: https://github.com/No9/localstorage-down
3//
4// (c) 2012-2024 Dale Harvey and the PouchDB team
5// PouchDB may be freely distributed under the Apache license, version 2.0.
6// For all details and documentation:
7// http://pouchdb.com
8(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(_dereq_,module,exports){
9(function (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_('_process'))
92},{"_process":94}],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_('_process'))
145},{"_process":94}],3:[function(_dereq_,module,exports){
146(function (Buffer,process){(function (){
147/* Copyright (c) 2013 Rod Vagg, MIT License */
148
149var xtend = _dereq_('xtend')
150 , AbstractIterator = _dereq_('./abstract-iterator')
151 , AbstractChainedBatch = _dereq_('./abstract-chained-batch')
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_("../is-buffer/index.js")},_dereq_('_process'))
407},{"../is-buffer/index.js":54,"./abstract-chained-batch":1,"./abstract-iterator":2,"_process":94,"xtend":4}],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_('object.assign/polyfill')();
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_('util/');
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},{"object.assign/polyfill":92,"util/":145}],7:[function(_dereq_,module,exports){
957'use strict'
958
959exports.byteLength = byteLength
960exports.toByteArray = toByteArray
961exports.fromByteArray = fromByteArray
962
963var lookup = []
964var revLookup = []
965var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
966
967var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
968for (var i = 0, len = code.length; i < len; ++i) {
969 lookup[i] = code[i]
970 revLookup[code.charCodeAt(i)] = i
971}
972
973// Support decoding URL-safe base64 strings, as Node.js does.
974// See: https://en.wikipedia.org/wiki/Base64#URL_applications
975revLookup['-'.charCodeAt(0)] = 62
976revLookup['_'.charCodeAt(0)] = 63
977
978function getLens (b64) {
979 var len = b64.length
980
981 if (len % 4 > 0) {
982 throw new Error('Invalid string. Length must be a multiple of 4')
983 }
984
985 // Trim off extra bytes after placeholder bytes are found
986 // See: https://github.com/beatgammit/base64-js/issues/42
987 var validLen = b64.indexOf('=')
988 if (validLen === -1) validLen = len
989
990 var placeHoldersLen = validLen === len
991 ? 0
992 : 4 - (validLen % 4)
993
994 return [validLen, placeHoldersLen]
995}
996
997// base64 is 4/3 + up to two characters of the original data
998function byteLength (b64) {
999 var lens = getLens(b64)
1000 var validLen = lens[0]
1001 var placeHoldersLen = lens[1]
1002 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
1003}
1004
1005function _byteLength (b64, validLen, placeHoldersLen) {
1006 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
1007}
1008
1009function toByteArray (b64) {
1010 var tmp
1011 var lens = getLens(b64)
1012 var validLen = lens[0]
1013 var placeHoldersLen = lens[1]
1014
1015 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
1016
1017 var curByte = 0
1018
1019 // if there are placeholders, only get up to the last complete 4 chars
1020 var len = placeHoldersLen > 0
1021 ? validLen - 4
1022 : validLen
1023
1024 var i
1025 for (i = 0; i < len; i += 4) {
1026 tmp =
1027 (revLookup[b64.charCodeAt(i)] << 18) |
1028 (revLookup[b64.charCodeAt(i + 1)] << 12) |
1029 (revLookup[b64.charCodeAt(i + 2)] << 6) |
1030 revLookup[b64.charCodeAt(i + 3)]
1031 arr[curByte++] = (tmp >> 16) & 0xFF
1032 arr[curByte++] = (tmp >> 8) & 0xFF
1033 arr[curByte++] = tmp & 0xFF
1034 }
1035
1036 if (placeHoldersLen === 2) {
1037 tmp =
1038 (revLookup[b64.charCodeAt(i)] << 2) |
1039 (revLookup[b64.charCodeAt(i + 1)] >> 4)
1040 arr[curByte++] = tmp & 0xFF
1041 }
1042
1043 if (placeHoldersLen === 1) {
1044 tmp =
1045 (revLookup[b64.charCodeAt(i)] << 10) |
1046 (revLookup[b64.charCodeAt(i + 1)] << 4) |
1047 (revLookup[b64.charCodeAt(i + 2)] >> 2)
1048 arr[curByte++] = (tmp >> 8) & 0xFF
1049 arr[curByte++] = tmp & 0xFF
1050 }
1051
1052 return arr
1053}
1054
1055function tripletToBase64 (num) {
1056 return lookup[num >> 18 & 0x3F] +
1057 lookup[num >> 12 & 0x3F] +
1058 lookup[num >> 6 & 0x3F] +
1059 lookup[num & 0x3F]
1060}
1061
1062function encodeChunk (uint8, start, end) {
1063 var tmp
1064 var output = []
1065 for (var i = start; i < end; i += 3) {
1066 tmp =
1067 ((uint8[i] << 16) & 0xFF0000) +
1068 ((uint8[i + 1] << 8) & 0xFF00) +
1069 (uint8[i + 2] & 0xFF)
1070 output.push(tripletToBase64(tmp))
1071 }
1072 return output.join('')
1073}
1074
1075function fromByteArray (uint8) {
1076 var tmp
1077 var len = uint8.length
1078 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
1079 var parts = []
1080 var maxChunkLength = 16383 // must be multiple of 3
1081
1082 // go through the array every three bytes, we'll deal with trailing stuff later
1083 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
1084 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
1085 }
1086
1087 // pad the end with zeros, but make sure to not forget the extra bytes
1088 if (extraBytes === 1) {
1089 tmp = uint8[len - 1]
1090 parts.push(
1091 lookup[tmp >> 2] +
1092 lookup[(tmp << 4) & 0x3F] +
1093 '=='
1094 )
1095 } else if (extraBytes === 2) {
1096 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
1097 parts.push(
1098 lookup[tmp >> 10] +
1099 lookup[(tmp >> 4) & 0x3F] +
1100 lookup[(tmp << 2) & 0x3F] +
1101 '='
1102 )
1103 }
1104
1105 return parts.join('')
1106}
1107
1108},{}],8:[function(_dereq_,module,exports){
1109
1110},{}],9:[function(_dereq_,module,exports){
1111(function (Buffer){(function (){
1112/*!
1113 * The buffer module from node.js, for the browser.
1114 *
1115 * @author Feross Aboukhadijeh <https://feross.org>
1116 * @license MIT
1117 */
1118/* eslint-disable no-proto */
1119
1120'use strict'
1121
1122var base64 = _dereq_('base64-js')
1123var ieee754 = _dereq_('ieee754')
1124var customInspectSymbol =
1125 (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation
1126 ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation
1127 : null
1128
1129exports.Buffer = Buffer
1130exports.SlowBuffer = SlowBuffer
1131exports.INSPECT_MAX_BYTES = 50
1132
1133var K_MAX_LENGTH = 0x7fffffff
1134exports.kMaxLength = K_MAX_LENGTH
1135
1136/**
1137 * If `Buffer.TYPED_ARRAY_SUPPORT`:
1138 * === true Use Uint8Array implementation (fastest)
1139 * === false Print warning and recommend using `buffer` v4.x which has an Object
1140 * implementation (most compatible, even IE6)
1141 *
1142 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
1143 * Opera 11.6+, iOS 4.2+.
1144 *
1145 * We report that the browser does not support typed arrays if the are not subclassable
1146 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
1147 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
1148 * for __proto__ and has a buggy typed array implementation.
1149 */
1150Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
1151
1152if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
1153 typeof console.error === 'function') {
1154 console.error(
1155 'This browser lacks typed array (Uint8Array) support which is required by ' +
1156 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
1157 )
1158}
1159
1160function typedArraySupport () {
1161 // Can typed array instances can be augmented?
1162 try {
1163 var arr = new Uint8Array(1)
1164 var proto = { foo: function () { return 42 } }
1165 Object.setPrototypeOf(proto, Uint8Array.prototype)
1166 Object.setPrototypeOf(arr, proto)
1167 return arr.foo() === 42
1168 } catch (e) {
1169 return false
1170 }
1171}
1172
1173Object.defineProperty(Buffer.prototype, 'parent', {
1174 enumerable: true,
1175 get: function () {
1176 if (!Buffer.isBuffer(this)) return undefined
1177 return this.buffer
1178 }
1179})
1180
1181Object.defineProperty(Buffer.prototype, 'offset', {
1182 enumerable: true,
1183 get: function () {
1184 if (!Buffer.isBuffer(this)) return undefined
1185 return this.byteOffset
1186 }
1187})
1188
1189function createBuffer (length) {
1190 if (length > K_MAX_LENGTH) {
1191 throw new RangeError('The value "' + length + '" is invalid for option "size"')
1192 }
1193 // Return an augmented `Uint8Array` instance
1194 var buf = new Uint8Array(length)
1195 Object.setPrototypeOf(buf, Buffer.prototype)
1196 return buf
1197}
1198
1199/**
1200 * The Buffer constructor returns instances of `Uint8Array` that have their
1201 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
1202 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
1203 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
1204 * returns a single octet.
1205 *
1206 * The `Uint8Array` prototype remains unmodified.
1207 */
1208
1209function Buffer (arg, encodingOrOffset, length) {
1210 // Common case.
1211 if (typeof arg === 'number') {
1212 if (typeof encodingOrOffset === 'string') {
1213 throw new TypeError(
1214 'The "string" argument must be of type string. Received type number'
1215 )
1216 }
1217 return allocUnsafe(arg)
1218 }
1219 return from(arg, encodingOrOffset, length)
1220}
1221
1222Buffer.poolSize = 8192 // not used by this implementation
1223
1224function from (value, encodingOrOffset, length) {
1225 if (typeof value === 'string') {
1226 return fromString(value, encodingOrOffset)
1227 }
1228
1229 if (ArrayBuffer.isView(value)) {
1230 return fromArrayView(value)
1231 }
1232
1233 if (value == null) {
1234 throw new TypeError(
1235 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
1236 'or Array-like Object. Received type ' + (typeof value)
1237 )
1238 }
1239
1240 if (isInstance(value, ArrayBuffer) ||
1241 (value && isInstance(value.buffer, ArrayBuffer))) {
1242 return fromArrayBuffer(value, encodingOrOffset, length)
1243 }
1244
1245 if (typeof SharedArrayBuffer !== 'undefined' &&
1246 (isInstance(value, SharedArrayBuffer) ||
1247 (value && isInstance(value.buffer, SharedArrayBuffer)))) {
1248 return fromArrayBuffer(value, encodingOrOffset, length)
1249 }
1250
1251 if (typeof value === 'number') {
1252 throw new TypeError(
1253 'The "value" argument must not be of type number. Received type number'
1254 )
1255 }
1256
1257 var valueOf = value.valueOf && value.valueOf()
1258 if (valueOf != null && valueOf !== value) {
1259 return Buffer.from(valueOf, encodingOrOffset, length)
1260 }
1261
1262 var b = fromObject(value)
1263 if (b) return b
1264
1265 if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
1266 typeof value[Symbol.toPrimitive] === 'function') {
1267 return Buffer.from(
1268 value[Symbol.toPrimitive]('string'), encodingOrOffset, length
1269 )
1270 }
1271
1272 throw new TypeError(
1273 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
1274 'or Array-like Object. Received type ' + (typeof value)
1275 )
1276}
1277
1278/**
1279 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
1280 * if value is a number.
1281 * Buffer.from(str[, encoding])
1282 * Buffer.from(array)
1283 * Buffer.from(buffer)
1284 * Buffer.from(arrayBuffer[, byteOffset[, length]])
1285 **/
1286Buffer.from = function (value, encodingOrOffset, length) {
1287 return from(value, encodingOrOffset, length)
1288}
1289
1290// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
1291// https://github.com/feross/buffer/pull/148
1292Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)
1293Object.setPrototypeOf(Buffer, Uint8Array)
1294
1295function assertSize (size) {
1296 if (typeof size !== 'number') {
1297 throw new TypeError('"size" argument must be of type number')
1298 } else if (size < 0) {
1299 throw new RangeError('The value "' + size + '" is invalid for option "size"')
1300 }
1301}
1302
1303function alloc (size, fill, encoding) {
1304 assertSize(size)
1305 if (size <= 0) {
1306 return createBuffer(size)
1307 }
1308 if (fill !== undefined) {
1309 // Only pay attention to encoding if it's a string. This
1310 // prevents accidentally sending in a number that would
1311 // be interpreted as a start offset.
1312 return typeof encoding === 'string'
1313 ? createBuffer(size).fill(fill, encoding)
1314 : createBuffer(size).fill(fill)
1315 }
1316 return createBuffer(size)
1317}
1318
1319/**
1320 * Creates a new filled Buffer instance.
1321 * alloc(size[, fill[, encoding]])
1322 **/
1323Buffer.alloc = function (size, fill, encoding) {
1324 return alloc(size, fill, encoding)
1325}
1326
1327function allocUnsafe (size) {
1328 assertSize(size)
1329 return createBuffer(size < 0 ? 0 : checked(size) | 0)
1330}
1331
1332/**
1333 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
1334 * */
1335Buffer.allocUnsafe = function (size) {
1336 return allocUnsafe(size)
1337}
1338/**
1339 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
1340 */
1341Buffer.allocUnsafeSlow = function (size) {
1342 return allocUnsafe(size)
1343}
1344
1345function fromString (string, encoding) {
1346 if (typeof encoding !== 'string' || encoding === '') {
1347 encoding = 'utf8'
1348 }
1349
1350 if (!Buffer.isEncoding(encoding)) {
1351 throw new TypeError('Unknown encoding: ' + encoding)
1352 }
1353
1354 var length = byteLength(string, encoding) | 0
1355 var buf = createBuffer(length)
1356
1357 var actual = buf.write(string, encoding)
1358
1359 if (actual !== length) {
1360 // Writing a hex string, for example, that contains invalid characters will
1361 // cause everything after the first invalid character to be ignored. (e.g.
1362 // 'abxxcd' will be treated as 'ab')
1363 buf = buf.slice(0, actual)
1364 }
1365
1366 return buf
1367}
1368
1369function fromArrayLike (array) {
1370 var length = array.length < 0 ? 0 : checked(array.length) | 0
1371 var buf = createBuffer(length)
1372 for (var i = 0; i < length; i += 1) {
1373 buf[i] = array[i] & 255
1374 }
1375 return buf
1376}
1377
1378function fromArrayView (arrayView) {
1379 if (isInstance(arrayView, Uint8Array)) {
1380 var copy = new Uint8Array(arrayView)
1381 return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)
1382 }
1383 return fromArrayLike(arrayView)
1384}
1385
1386function fromArrayBuffer (array, byteOffset, length) {
1387 if (byteOffset < 0 || array.byteLength < byteOffset) {
1388 throw new RangeError('"offset" is outside of buffer bounds')
1389 }
1390
1391 if (array.byteLength < byteOffset + (length || 0)) {
1392 throw new RangeError('"length" is outside of buffer bounds')
1393 }
1394
1395 var buf
1396 if (byteOffset === undefined && length === undefined) {
1397 buf = new Uint8Array(array)
1398 } else if (length === undefined) {
1399 buf = new Uint8Array(array, byteOffset)
1400 } else {
1401 buf = new Uint8Array(array, byteOffset, length)
1402 }
1403
1404 // Return an augmented `Uint8Array` instance
1405 Object.setPrototypeOf(buf, Buffer.prototype)
1406
1407 return buf
1408}
1409
1410function fromObject (obj) {
1411 if (Buffer.isBuffer(obj)) {
1412 var len = checked(obj.length) | 0
1413 var buf = createBuffer(len)
1414
1415 if (buf.length === 0) {
1416 return buf
1417 }
1418
1419 obj.copy(buf, 0, 0, len)
1420 return buf
1421 }
1422
1423 if (obj.length !== undefined) {
1424 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
1425 return createBuffer(0)
1426 }
1427 return fromArrayLike(obj)
1428 }
1429
1430 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
1431 return fromArrayLike(obj.data)
1432 }
1433}
1434
1435function checked (length) {
1436 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
1437 // length is NaN (which is otherwise coerced to zero.)
1438 if (length >= K_MAX_LENGTH) {
1439 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
1440 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
1441 }
1442 return length | 0
1443}
1444
1445function SlowBuffer (length) {
1446 if (+length != length) { // eslint-disable-line eqeqeq
1447 length = 0
1448 }
1449 return Buffer.alloc(+length)
1450}
1451
1452Buffer.isBuffer = function isBuffer (b) {
1453 return b != null && b._isBuffer === true &&
1454 b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
1455}
1456
1457Buffer.compare = function compare (a, b) {
1458 if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
1459 if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
1460 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
1461 throw new TypeError(
1462 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
1463 )
1464 }
1465
1466 if (a === b) return 0
1467
1468 var x = a.length
1469 var y = b.length
1470
1471 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
1472 if (a[i] !== b[i]) {
1473 x = a[i]
1474 y = b[i]
1475 break
1476 }
1477 }
1478
1479 if (x < y) return -1
1480 if (y < x) return 1
1481 return 0
1482}
1483
1484Buffer.isEncoding = function isEncoding (encoding) {
1485 switch (String(encoding).toLowerCase()) {
1486 case 'hex':
1487 case 'utf8':
1488 case 'utf-8':
1489 case 'ascii':
1490 case 'latin1':
1491 case 'binary':
1492 case 'base64':
1493 case 'ucs2':
1494 case 'ucs-2':
1495 case 'utf16le':
1496 case 'utf-16le':
1497 return true
1498 default:
1499 return false
1500 }
1501}
1502
1503Buffer.concat = function concat (list, length) {
1504 if (!Array.isArray(list)) {
1505 throw new TypeError('"list" argument must be an Array of Buffers')
1506 }
1507
1508 if (list.length === 0) {
1509 return Buffer.alloc(0)
1510 }
1511
1512 var i
1513 if (length === undefined) {
1514 length = 0
1515 for (i = 0; i < list.length; ++i) {
1516 length += list[i].length
1517 }
1518 }
1519
1520 var buffer = Buffer.allocUnsafe(length)
1521 var pos = 0
1522 for (i = 0; i < list.length; ++i) {
1523 var buf = list[i]
1524 if (isInstance(buf, Uint8Array)) {
1525 if (pos + buf.length > buffer.length) {
1526 Buffer.from(buf).copy(buffer, pos)
1527 } else {
1528 Uint8Array.prototype.set.call(
1529 buffer,
1530 buf,
1531 pos
1532 )
1533 }
1534 } else if (!Buffer.isBuffer(buf)) {
1535 throw new TypeError('"list" argument must be an Array of Buffers')
1536 } else {
1537 buf.copy(buffer, pos)
1538 }
1539 pos += buf.length
1540 }
1541 return buffer
1542}
1543
1544function byteLength (string, encoding) {
1545 if (Buffer.isBuffer(string)) {
1546 return string.length
1547 }
1548 if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
1549 return string.byteLength
1550 }
1551 if (typeof string !== 'string') {
1552 throw new TypeError(
1553 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
1554 'Received type ' + typeof string
1555 )
1556 }
1557
1558 var len = string.length
1559 var mustMatch = (arguments.length > 2 && arguments[2] === true)
1560 if (!mustMatch && len === 0) return 0
1561
1562 // Use a for loop to avoid recursion
1563 var loweredCase = false
1564 for (;;) {
1565 switch (encoding) {
1566 case 'ascii':
1567 case 'latin1':
1568 case 'binary':
1569 return len
1570 case 'utf8':
1571 case 'utf-8':
1572 return utf8ToBytes(string).length
1573 case 'ucs2':
1574 case 'ucs-2':
1575 case 'utf16le':
1576 case 'utf-16le':
1577 return len * 2
1578 case 'hex':
1579 return len >>> 1
1580 case 'base64':
1581 return base64ToBytes(string).length
1582 default:
1583 if (loweredCase) {
1584 return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
1585 }
1586 encoding = ('' + encoding).toLowerCase()
1587 loweredCase = true
1588 }
1589 }
1590}
1591Buffer.byteLength = byteLength
1592
1593function slowToString (encoding, start, end) {
1594 var loweredCase = false
1595
1596 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
1597 // property of a typed array.
1598
1599 // This behaves neither like String nor Uint8Array in that we set start/end
1600 // to their upper/lower bounds if the value passed is out of range.
1601 // undefined is handled specially as per ECMA-262 6th Edition,
1602 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
1603 if (start === undefined || start < 0) {
1604 start = 0
1605 }
1606 // Return early if start > this.length. Done here to prevent potential uint32
1607 // coercion fail below.
1608 if (start > this.length) {
1609 return ''
1610 }
1611
1612 if (end === undefined || end > this.length) {
1613 end = this.length
1614 }
1615
1616 if (end <= 0) {
1617 return ''
1618 }
1619
1620 // Force coercion to uint32. This will also coerce falsey/NaN values to 0.
1621 end >>>= 0
1622 start >>>= 0
1623
1624 if (end <= start) {
1625 return ''
1626 }
1627
1628 if (!encoding) encoding = 'utf8'
1629
1630 while (true) {
1631 switch (encoding) {
1632 case 'hex':
1633 return hexSlice(this, start, end)
1634
1635 case 'utf8':
1636 case 'utf-8':
1637 return utf8Slice(this, start, end)
1638
1639 case 'ascii':
1640 return asciiSlice(this, start, end)
1641
1642 case 'latin1':
1643 case 'binary':
1644 return latin1Slice(this, start, end)
1645
1646 case 'base64':
1647 return base64Slice(this, start, end)
1648
1649 case 'ucs2':
1650 case 'ucs-2':
1651 case 'utf16le':
1652 case 'utf-16le':
1653 return utf16leSlice(this, start, end)
1654
1655 default:
1656 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1657 encoding = (encoding + '').toLowerCase()
1658 loweredCase = true
1659 }
1660 }
1661}
1662
1663// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
1664// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
1665// reliably in a browserify context because there could be multiple different
1666// copies of the 'buffer' package in use. This method works even for Buffer
1667// instances that were created from another copy of the `buffer` package.
1668// See: https://github.com/feross/buffer/issues/154
1669Buffer.prototype._isBuffer = true
1670
1671function swap (b, n, m) {
1672 var i = b[n]
1673 b[n] = b[m]
1674 b[m] = i
1675}
1676
1677Buffer.prototype.swap16 = function swap16 () {
1678 var len = this.length
1679 if (len % 2 !== 0) {
1680 throw new RangeError('Buffer size must be a multiple of 16-bits')
1681 }
1682 for (var i = 0; i < len; i += 2) {
1683 swap(this, i, i + 1)
1684 }
1685 return this
1686}
1687
1688Buffer.prototype.swap32 = function swap32 () {
1689 var len = this.length
1690 if (len % 4 !== 0) {
1691 throw new RangeError('Buffer size must be a multiple of 32-bits')
1692 }
1693 for (var i = 0; i < len; i += 4) {
1694 swap(this, i, i + 3)
1695 swap(this, i + 1, i + 2)
1696 }
1697 return this
1698}
1699
1700Buffer.prototype.swap64 = function swap64 () {
1701 var len = this.length
1702 if (len % 8 !== 0) {
1703 throw new RangeError('Buffer size must be a multiple of 64-bits')
1704 }
1705 for (var i = 0; i < len; i += 8) {
1706 swap(this, i, i + 7)
1707 swap(this, i + 1, i + 6)
1708 swap(this, i + 2, i + 5)
1709 swap(this, i + 3, i + 4)
1710 }
1711 return this
1712}
1713
1714Buffer.prototype.toString = function toString () {
1715 var length = this.length
1716 if (length === 0) return ''
1717 if (arguments.length === 0) return utf8Slice(this, 0, length)
1718 return slowToString.apply(this, arguments)
1719}
1720
1721Buffer.prototype.toLocaleString = Buffer.prototype.toString
1722
1723Buffer.prototype.equals = function equals (b) {
1724 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
1725 if (this === b) return true
1726 return Buffer.compare(this, b) === 0
1727}
1728
1729Buffer.prototype.inspect = function inspect () {
1730 var str = ''
1731 var max = exports.INSPECT_MAX_BYTES
1732 str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
1733 if (this.length > max) str += ' ... '
1734 return '<Buffer ' + str + '>'
1735}
1736if (customInspectSymbol) {
1737 Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect
1738}
1739
1740Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
1741 if (isInstance(target, Uint8Array)) {
1742 target = Buffer.from(target, target.offset, target.byteLength)
1743 }
1744 if (!Buffer.isBuffer(target)) {
1745 throw new TypeError(
1746 'The "target" argument must be one of type Buffer or Uint8Array. ' +
1747 'Received type ' + (typeof target)
1748 )
1749 }
1750
1751 if (start === undefined) {
1752 start = 0
1753 }
1754 if (end === undefined) {
1755 end = target ? target.length : 0
1756 }
1757 if (thisStart === undefined) {
1758 thisStart = 0
1759 }
1760 if (thisEnd === undefined) {
1761 thisEnd = this.length
1762 }
1763
1764 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
1765 throw new RangeError('out of range index')
1766 }
1767
1768 if (thisStart >= thisEnd && start >= end) {
1769 return 0
1770 }
1771 if (thisStart >= thisEnd) {
1772 return -1
1773 }
1774 if (start >= end) {
1775 return 1
1776 }
1777
1778 start >>>= 0
1779 end >>>= 0
1780 thisStart >>>= 0
1781 thisEnd >>>= 0
1782
1783 if (this === target) return 0
1784
1785 var x = thisEnd - thisStart
1786 var y = end - start
1787 var len = Math.min(x, y)
1788
1789 var thisCopy = this.slice(thisStart, thisEnd)
1790 var targetCopy = target.slice(start, end)
1791
1792 for (var i = 0; i < len; ++i) {
1793 if (thisCopy[i] !== targetCopy[i]) {
1794 x = thisCopy[i]
1795 y = targetCopy[i]
1796 break
1797 }
1798 }
1799
1800 if (x < y) return -1
1801 if (y < x) return 1
1802 return 0
1803}
1804
1805// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
1806// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
1807//
1808// Arguments:
1809// - buffer - a Buffer to search
1810// - val - a string, Buffer, or number
1811// - byteOffset - an index into `buffer`; will be clamped to an int32
1812// - encoding - an optional encoding, relevant is val is a string
1813// - dir - true for indexOf, false for lastIndexOf
1814function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
1815 // Empty buffer means no match
1816 if (buffer.length === 0) return -1
1817
1818 // Normalize byteOffset
1819 if (typeof byteOffset === 'string') {
1820 encoding = byteOffset
1821 byteOffset = 0
1822 } else if (byteOffset > 0x7fffffff) {
1823 byteOffset = 0x7fffffff
1824 } else if (byteOffset < -0x80000000) {
1825 byteOffset = -0x80000000
1826 }
1827 byteOffset = +byteOffset // Coerce to Number.
1828 if (numberIsNaN(byteOffset)) {
1829 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
1830 byteOffset = dir ? 0 : (buffer.length - 1)
1831 }
1832
1833 // Normalize byteOffset: negative offsets start from the end of the buffer
1834 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
1835 if (byteOffset >= buffer.length) {
1836 if (dir) return -1
1837 else byteOffset = buffer.length - 1
1838 } else if (byteOffset < 0) {
1839 if (dir) byteOffset = 0
1840 else return -1
1841 }
1842
1843 // Normalize val
1844 if (typeof val === 'string') {
1845 val = Buffer.from(val, encoding)
1846 }
1847
1848 // Finally, search either indexOf (if dir is true) or lastIndexOf
1849 if (Buffer.isBuffer(val)) {
1850 // Special case: looking for empty string/buffer always fails
1851 if (val.length === 0) {
1852 return -1
1853 }
1854 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
1855 } else if (typeof val === 'number') {
1856 val = val & 0xFF // Search for a byte value [0-255]
1857 if (typeof Uint8Array.prototype.indexOf === 'function') {
1858 if (dir) {
1859 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
1860 } else {
1861 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
1862 }
1863 }
1864 return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
1865 }
1866
1867 throw new TypeError('val must be string, number or Buffer')
1868}
1869
1870function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
1871 var indexSize = 1
1872 var arrLength = arr.length
1873 var valLength = val.length
1874
1875 if (encoding !== undefined) {
1876 encoding = String(encoding).toLowerCase()
1877 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
1878 encoding === 'utf16le' || encoding === 'utf-16le') {
1879 if (arr.length < 2 || val.length < 2) {
1880 return -1
1881 }
1882 indexSize = 2
1883 arrLength /= 2
1884 valLength /= 2
1885 byteOffset /= 2
1886 }
1887 }
1888
1889 function read (buf, i) {
1890 if (indexSize === 1) {
1891 return buf[i]
1892 } else {
1893 return buf.readUInt16BE(i * indexSize)
1894 }
1895 }
1896
1897 var i
1898 if (dir) {
1899 var foundIndex = -1
1900 for (i = byteOffset; i < arrLength; i++) {
1901 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
1902 if (foundIndex === -1) foundIndex = i
1903 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
1904 } else {
1905 if (foundIndex !== -1) i -= i - foundIndex
1906 foundIndex = -1
1907 }
1908 }
1909 } else {
1910 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
1911 for (i = byteOffset; i >= 0; i--) {
1912 var found = true
1913 for (var j = 0; j < valLength; j++) {
1914 if (read(arr, i + j) !== read(val, j)) {
1915 found = false
1916 break
1917 }
1918 }
1919 if (found) return i
1920 }
1921 }
1922
1923 return -1
1924}
1925
1926Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
1927 return this.indexOf(val, byteOffset, encoding) !== -1
1928}
1929
1930Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
1931 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
1932}
1933
1934Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
1935 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
1936}
1937
1938function hexWrite (buf, string, offset, length) {
1939 offset = Number(offset) || 0
1940 var remaining = buf.length - offset
1941 if (!length) {
1942 length = remaining
1943 } else {
1944 length = Number(length)
1945 if (length > remaining) {
1946 length = remaining
1947 }
1948 }
1949
1950 var strLen = string.length
1951
1952 if (length > strLen / 2) {
1953 length = strLen / 2
1954 }
1955 for (var i = 0; i < length; ++i) {
1956 var parsed = parseInt(string.substr(i * 2, 2), 16)
1957 if (numberIsNaN(parsed)) return i
1958 buf[offset + i] = parsed
1959 }
1960 return i
1961}
1962
1963function utf8Write (buf, string, offset, length) {
1964 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
1965}
1966
1967function asciiWrite (buf, string, offset, length) {
1968 return blitBuffer(asciiToBytes(string), buf, offset, length)
1969}
1970
1971function base64Write (buf, string, offset, length) {
1972 return blitBuffer(base64ToBytes(string), buf, offset, length)
1973}
1974
1975function ucs2Write (buf, string, offset, length) {
1976 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
1977}
1978
1979Buffer.prototype.write = function write (string, offset, length, encoding) {
1980 // Buffer#write(string)
1981 if (offset === undefined) {
1982 encoding = 'utf8'
1983 length = this.length
1984 offset = 0
1985 // Buffer#write(string, encoding)
1986 } else if (length === undefined && typeof offset === 'string') {
1987 encoding = offset
1988 length = this.length
1989 offset = 0
1990 // Buffer#write(string, offset[, length][, encoding])
1991 } else if (isFinite(offset)) {
1992 offset = offset >>> 0
1993 if (isFinite(length)) {
1994 length = length >>> 0
1995 if (encoding === undefined) encoding = 'utf8'
1996 } else {
1997 encoding = length
1998 length = undefined
1999 }
2000 } else {
2001 throw new Error(
2002 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
2003 )
2004 }
2005
2006 var remaining = this.length - offset
2007 if (length === undefined || length > remaining) length = remaining
2008
2009 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
2010 throw new RangeError('Attempt to write outside buffer bounds')
2011 }
2012
2013 if (!encoding) encoding = 'utf8'
2014
2015 var loweredCase = false
2016 for (;;) {
2017 switch (encoding) {
2018 case 'hex':
2019 return hexWrite(this, string, offset, length)
2020
2021 case 'utf8':
2022 case 'utf-8':
2023 return utf8Write(this, string, offset, length)
2024
2025 case 'ascii':
2026 case 'latin1':
2027 case 'binary':
2028 return asciiWrite(this, string, offset, length)
2029
2030 case 'base64':
2031 // Warning: maxLength not taken into account in base64Write
2032 return base64Write(this, string, offset, length)
2033
2034 case 'ucs2':
2035 case 'ucs-2':
2036 case 'utf16le':
2037 case 'utf-16le':
2038 return ucs2Write(this, string, offset, length)
2039
2040 default:
2041 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
2042 encoding = ('' + encoding).toLowerCase()
2043 loweredCase = true
2044 }
2045 }
2046}
2047
2048Buffer.prototype.toJSON = function toJSON () {
2049 return {
2050 type: 'Buffer',
2051 data: Array.prototype.slice.call(this._arr || this, 0)
2052 }
2053}
2054
2055function base64Slice (buf, start, end) {
2056 if (start === 0 && end === buf.length) {
2057 return base64.fromByteArray(buf)
2058 } else {
2059 return base64.fromByteArray(buf.slice(start, end))
2060 }
2061}
2062
2063function utf8Slice (buf, start, end) {
2064 end = Math.min(buf.length, end)
2065 var res = []
2066
2067 var i = start
2068 while (i < end) {
2069 var firstByte = buf[i]
2070 var codePoint = null
2071 var bytesPerSequence = (firstByte > 0xEF)
2072 ? 4
2073 : (firstByte > 0xDF)
2074 ? 3
2075 : (firstByte > 0xBF)
2076 ? 2
2077 : 1
2078
2079 if (i + bytesPerSequence <= end) {
2080 var secondByte, thirdByte, fourthByte, tempCodePoint
2081
2082 switch (bytesPerSequence) {
2083 case 1:
2084 if (firstByte < 0x80) {
2085 codePoint = firstByte
2086 }
2087 break
2088 case 2:
2089 secondByte = buf[i + 1]
2090 if ((secondByte & 0xC0) === 0x80) {
2091 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
2092 if (tempCodePoint > 0x7F) {
2093 codePoint = tempCodePoint
2094 }
2095 }
2096 break
2097 case 3:
2098 secondByte = buf[i + 1]
2099 thirdByte = buf[i + 2]
2100 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
2101 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
2102 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
2103 codePoint = tempCodePoint
2104 }
2105 }
2106 break
2107 case 4:
2108 secondByte = buf[i + 1]
2109 thirdByte = buf[i + 2]
2110 fourthByte = buf[i + 3]
2111 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
2112 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
2113 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
2114 codePoint = tempCodePoint
2115 }
2116 }
2117 }
2118 }
2119
2120 if (codePoint === null) {
2121 // we did not generate a valid codePoint so insert a
2122 // replacement char (U+FFFD) and advance only 1 byte
2123 codePoint = 0xFFFD
2124 bytesPerSequence = 1
2125 } else if (codePoint > 0xFFFF) {
2126 // encode to utf16 (surrogate pair dance)
2127 codePoint -= 0x10000
2128 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
2129 codePoint = 0xDC00 | codePoint & 0x3FF
2130 }
2131
2132 res.push(codePoint)
2133 i += bytesPerSequence
2134 }
2135
2136 return decodeCodePointsArray(res)
2137}
2138
2139// Based on http://stackoverflow.com/a/22747272/680742, the browser with
2140// the lowest limit is Chrome, with 0x10000 args.
2141// We go 1 magnitude less, for safety
2142var MAX_ARGUMENTS_LENGTH = 0x1000
2143
2144function decodeCodePointsArray (codePoints) {
2145 var len = codePoints.length
2146 if (len <= MAX_ARGUMENTS_LENGTH) {
2147 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
2148 }
2149
2150 // Decode in chunks to avoid "call stack size exceeded".
2151 var res = ''
2152 var i = 0
2153 while (i < len) {
2154 res += String.fromCharCode.apply(
2155 String,
2156 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
2157 )
2158 }
2159 return res
2160}
2161
2162function asciiSlice (buf, start, end) {
2163 var ret = ''
2164 end = Math.min(buf.length, end)
2165
2166 for (var i = start; i < end; ++i) {
2167 ret += String.fromCharCode(buf[i] & 0x7F)
2168 }
2169 return ret
2170}
2171
2172function latin1Slice (buf, start, end) {
2173 var ret = ''
2174 end = Math.min(buf.length, end)
2175
2176 for (var i = start; i < end; ++i) {
2177 ret += String.fromCharCode(buf[i])
2178 }
2179 return ret
2180}
2181
2182function hexSlice (buf, start, end) {
2183 var len = buf.length
2184
2185 if (!start || start < 0) start = 0
2186 if (!end || end < 0 || end > len) end = len
2187
2188 var out = ''
2189 for (var i = start; i < end; ++i) {
2190 out += hexSliceLookupTable[buf[i]]
2191 }
2192 return out
2193}
2194
2195function utf16leSlice (buf, start, end) {
2196 var bytes = buf.slice(start, end)
2197 var res = ''
2198 // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)
2199 for (var i = 0; i < bytes.length - 1; i += 2) {
2200 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
2201 }
2202 return res
2203}
2204
2205Buffer.prototype.slice = function slice (start, end) {
2206 var len = this.length
2207 start = ~~start
2208 end = end === undefined ? len : ~~end
2209
2210 if (start < 0) {
2211 start += len
2212 if (start < 0) start = 0
2213 } else if (start > len) {
2214 start = len
2215 }
2216
2217 if (end < 0) {
2218 end += len
2219 if (end < 0) end = 0
2220 } else if (end > len) {
2221 end = len
2222 }
2223
2224 if (end < start) end = start
2225
2226 var newBuf = this.subarray(start, end)
2227 // Return an augmented `Uint8Array` instance
2228 Object.setPrototypeOf(newBuf, Buffer.prototype)
2229
2230 return newBuf
2231}
2232
2233/*
2234 * Need to make sure that buffer isn't trying to write out of bounds.
2235 */
2236function checkOffset (offset, ext, length) {
2237 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
2238 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
2239}
2240
2241Buffer.prototype.readUintLE =
2242Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
2243 offset = offset >>> 0
2244 byteLength = byteLength >>> 0
2245 if (!noAssert) checkOffset(offset, byteLength, this.length)
2246
2247 var val = this[offset]
2248 var mul = 1
2249 var i = 0
2250 while (++i < byteLength && (mul *= 0x100)) {
2251 val += this[offset + i] * mul
2252 }
2253
2254 return val
2255}
2256
2257Buffer.prototype.readUintBE =
2258Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
2259 offset = offset >>> 0
2260 byteLength = byteLength >>> 0
2261 if (!noAssert) {
2262 checkOffset(offset, byteLength, this.length)
2263 }
2264
2265 var val = this[offset + --byteLength]
2266 var mul = 1
2267 while (byteLength > 0 && (mul *= 0x100)) {
2268 val += this[offset + --byteLength] * mul
2269 }
2270
2271 return val
2272}
2273
2274Buffer.prototype.readUint8 =
2275Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
2276 offset = offset >>> 0
2277 if (!noAssert) checkOffset(offset, 1, this.length)
2278 return this[offset]
2279}
2280
2281Buffer.prototype.readUint16LE =
2282Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
2283 offset = offset >>> 0
2284 if (!noAssert) checkOffset(offset, 2, this.length)
2285 return this[offset] | (this[offset + 1] << 8)
2286}
2287
2288Buffer.prototype.readUint16BE =
2289Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
2290 offset = offset >>> 0
2291 if (!noAssert) checkOffset(offset, 2, this.length)
2292 return (this[offset] << 8) | this[offset + 1]
2293}
2294
2295Buffer.prototype.readUint32LE =
2296Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
2297 offset = offset >>> 0
2298 if (!noAssert) checkOffset(offset, 4, this.length)
2299
2300 return ((this[offset]) |
2301 (this[offset + 1] << 8) |
2302 (this[offset + 2] << 16)) +
2303 (this[offset + 3] * 0x1000000)
2304}
2305
2306Buffer.prototype.readUint32BE =
2307Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
2308 offset = offset >>> 0
2309 if (!noAssert) checkOffset(offset, 4, this.length)
2310
2311 return (this[offset] * 0x1000000) +
2312 ((this[offset + 1] << 16) |
2313 (this[offset + 2] << 8) |
2314 this[offset + 3])
2315}
2316
2317Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
2318 offset = offset >>> 0
2319 byteLength = byteLength >>> 0
2320 if (!noAssert) checkOffset(offset, byteLength, this.length)
2321
2322 var val = this[offset]
2323 var mul = 1
2324 var i = 0
2325 while (++i < byteLength && (mul *= 0x100)) {
2326 val += this[offset + i] * mul
2327 }
2328 mul *= 0x80
2329
2330 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
2331
2332 return val
2333}
2334
2335Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
2336 offset = offset >>> 0
2337 byteLength = byteLength >>> 0
2338 if (!noAssert) checkOffset(offset, byteLength, this.length)
2339
2340 var i = byteLength
2341 var mul = 1
2342 var val = this[offset + --i]
2343 while (i > 0 && (mul *= 0x100)) {
2344 val += this[offset + --i] * mul
2345 }
2346 mul *= 0x80
2347
2348 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
2349
2350 return val
2351}
2352
2353Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
2354 offset = offset >>> 0
2355 if (!noAssert) checkOffset(offset, 1, this.length)
2356 if (!(this[offset] & 0x80)) return (this[offset])
2357 return ((0xff - this[offset] + 1) * -1)
2358}
2359
2360Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
2361 offset = offset >>> 0
2362 if (!noAssert) checkOffset(offset, 2, this.length)
2363 var val = this[offset] | (this[offset + 1] << 8)
2364 return (val & 0x8000) ? val | 0xFFFF0000 : val
2365}
2366
2367Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
2368 offset = offset >>> 0
2369 if (!noAssert) checkOffset(offset, 2, this.length)
2370 var val = this[offset + 1] | (this[offset] << 8)
2371 return (val & 0x8000) ? val | 0xFFFF0000 : val
2372}
2373
2374Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
2375 offset = offset >>> 0
2376 if (!noAssert) checkOffset(offset, 4, this.length)
2377
2378 return (this[offset]) |
2379 (this[offset + 1] << 8) |
2380 (this[offset + 2] << 16) |
2381 (this[offset + 3] << 24)
2382}
2383
2384Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
2385 offset = offset >>> 0
2386 if (!noAssert) checkOffset(offset, 4, this.length)
2387
2388 return (this[offset] << 24) |
2389 (this[offset + 1] << 16) |
2390 (this[offset + 2] << 8) |
2391 (this[offset + 3])
2392}
2393
2394Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
2395 offset = offset >>> 0
2396 if (!noAssert) checkOffset(offset, 4, this.length)
2397 return ieee754.read(this, offset, true, 23, 4)
2398}
2399
2400Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
2401 offset = offset >>> 0
2402 if (!noAssert) checkOffset(offset, 4, this.length)
2403 return ieee754.read(this, offset, false, 23, 4)
2404}
2405
2406Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
2407 offset = offset >>> 0
2408 if (!noAssert) checkOffset(offset, 8, this.length)
2409 return ieee754.read(this, offset, true, 52, 8)
2410}
2411
2412Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
2413 offset = offset >>> 0
2414 if (!noAssert) checkOffset(offset, 8, this.length)
2415 return ieee754.read(this, offset, false, 52, 8)
2416}
2417
2418function checkInt (buf, value, offset, ext, max, min) {
2419 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
2420 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
2421 if (offset + ext > buf.length) throw new RangeError('Index out of range')
2422}
2423
2424Buffer.prototype.writeUintLE =
2425Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
2426 value = +value
2427 offset = offset >>> 0
2428 byteLength = byteLength >>> 0
2429 if (!noAssert) {
2430 var maxBytes = Math.pow(2, 8 * byteLength) - 1
2431 checkInt(this, value, offset, byteLength, maxBytes, 0)
2432 }
2433
2434 var mul = 1
2435 var i = 0
2436 this[offset] = value & 0xFF
2437 while (++i < byteLength && (mul *= 0x100)) {
2438 this[offset + i] = (value / mul) & 0xFF
2439 }
2440
2441 return offset + byteLength
2442}
2443
2444Buffer.prototype.writeUintBE =
2445Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
2446 value = +value
2447 offset = offset >>> 0
2448 byteLength = byteLength >>> 0
2449 if (!noAssert) {
2450 var maxBytes = Math.pow(2, 8 * byteLength) - 1
2451 checkInt(this, value, offset, byteLength, maxBytes, 0)
2452 }
2453
2454 var i = byteLength - 1
2455 var mul = 1
2456 this[offset + i] = value & 0xFF
2457 while (--i >= 0 && (mul *= 0x100)) {
2458 this[offset + i] = (value / mul) & 0xFF
2459 }
2460
2461 return offset + byteLength
2462}
2463
2464Buffer.prototype.writeUint8 =
2465Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
2466 value = +value
2467 offset = offset >>> 0
2468 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
2469 this[offset] = (value & 0xff)
2470 return offset + 1
2471}
2472
2473Buffer.prototype.writeUint16LE =
2474Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
2475 value = +value
2476 offset = offset >>> 0
2477 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
2478 this[offset] = (value & 0xff)
2479 this[offset + 1] = (value >>> 8)
2480 return offset + 2
2481}
2482
2483Buffer.prototype.writeUint16BE =
2484Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
2485 value = +value
2486 offset = offset >>> 0
2487 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
2488 this[offset] = (value >>> 8)
2489 this[offset + 1] = (value & 0xff)
2490 return offset + 2
2491}
2492
2493Buffer.prototype.writeUint32LE =
2494Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
2495 value = +value
2496 offset = offset >>> 0
2497 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
2498 this[offset + 3] = (value >>> 24)
2499 this[offset + 2] = (value >>> 16)
2500 this[offset + 1] = (value >>> 8)
2501 this[offset] = (value & 0xff)
2502 return offset + 4
2503}
2504
2505Buffer.prototype.writeUint32BE =
2506Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
2507 value = +value
2508 offset = offset >>> 0
2509 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
2510 this[offset] = (value >>> 24)
2511 this[offset + 1] = (value >>> 16)
2512 this[offset + 2] = (value >>> 8)
2513 this[offset + 3] = (value & 0xff)
2514 return offset + 4
2515}
2516
2517Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
2518 value = +value
2519 offset = offset >>> 0
2520 if (!noAssert) {
2521 var limit = Math.pow(2, (8 * byteLength) - 1)
2522
2523 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2524 }
2525
2526 var i = 0
2527 var mul = 1
2528 var sub = 0
2529 this[offset] = value & 0xFF
2530 while (++i < byteLength && (mul *= 0x100)) {
2531 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
2532 sub = 1
2533 }
2534 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2535 }
2536
2537 return offset + byteLength
2538}
2539
2540Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
2541 value = +value
2542 offset = offset >>> 0
2543 if (!noAssert) {
2544 var limit = Math.pow(2, (8 * byteLength) - 1)
2545
2546 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2547 }
2548
2549 var i = byteLength - 1
2550 var mul = 1
2551 var sub = 0
2552 this[offset + i] = value & 0xFF
2553 while (--i >= 0 && (mul *= 0x100)) {
2554 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
2555 sub = 1
2556 }
2557 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2558 }
2559
2560 return offset + byteLength
2561}
2562
2563Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
2564 value = +value
2565 offset = offset >>> 0
2566 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
2567 if (value < 0) value = 0xff + value + 1
2568 this[offset] = (value & 0xff)
2569 return offset + 1
2570}
2571
2572Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
2573 value = +value
2574 offset = offset >>> 0
2575 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2576 this[offset] = (value & 0xff)
2577 this[offset + 1] = (value >>> 8)
2578 return offset + 2
2579}
2580
2581Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
2582 value = +value
2583 offset = offset >>> 0
2584 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2585 this[offset] = (value >>> 8)
2586 this[offset + 1] = (value & 0xff)
2587 return offset + 2
2588}
2589
2590Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
2591 value = +value
2592 offset = offset >>> 0
2593 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2594 this[offset] = (value & 0xff)
2595 this[offset + 1] = (value >>> 8)
2596 this[offset + 2] = (value >>> 16)
2597 this[offset + 3] = (value >>> 24)
2598 return offset + 4
2599}
2600
2601Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
2602 value = +value
2603 offset = offset >>> 0
2604 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2605 if (value < 0) value = 0xffffffff + value + 1
2606 this[offset] = (value >>> 24)
2607 this[offset + 1] = (value >>> 16)
2608 this[offset + 2] = (value >>> 8)
2609 this[offset + 3] = (value & 0xff)
2610 return offset + 4
2611}
2612
2613function checkIEEE754 (buf, value, offset, ext, max, min) {
2614 if (offset + ext > buf.length) throw new RangeError('Index out of range')
2615 if (offset < 0) throw new RangeError('Index out of range')
2616}
2617
2618function writeFloat (buf, value, offset, littleEndian, noAssert) {
2619 value = +value
2620 offset = offset >>> 0
2621 if (!noAssert) {
2622 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
2623 }
2624 ieee754.write(buf, value, offset, littleEndian, 23, 4)
2625 return offset + 4
2626}
2627
2628Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
2629 return writeFloat(this, value, offset, true, noAssert)
2630}
2631
2632Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
2633 return writeFloat(this, value, offset, false, noAssert)
2634}
2635
2636function writeDouble (buf, value, offset, littleEndian, noAssert) {
2637 value = +value
2638 offset = offset >>> 0
2639 if (!noAssert) {
2640 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
2641 }
2642 ieee754.write(buf, value, offset, littleEndian, 52, 8)
2643 return offset + 8
2644}
2645
2646Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
2647 return writeDouble(this, value, offset, true, noAssert)
2648}
2649
2650Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
2651 return writeDouble(this, value, offset, false, noAssert)
2652}
2653
2654// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
2655Buffer.prototype.copy = function copy (target, targetStart, start, end) {
2656 if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
2657 if (!start) start = 0
2658 if (!end && end !== 0) end = this.length
2659 if (targetStart >= target.length) targetStart = target.length
2660 if (!targetStart) targetStart = 0
2661 if (end > 0 && end < start) end = start
2662
2663 // Copy 0 bytes; we're done
2664 if (end === start) return 0
2665 if (target.length === 0 || this.length === 0) return 0
2666
2667 // Fatal error conditions
2668 if (targetStart < 0) {
2669 throw new RangeError('targetStart out of bounds')
2670 }
2671 if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
2672 if (end < 0) throw new RangeError('sourceEnd out of bounds')
2673
2674 // Are we oob?
2675 if (end > this.length) end = this.length
2676 if (target.length - targetStart < end - start) {
2677 end = target.length - targetStart + start
2678 }
2679
2680 var len = end - start
2681
2682 if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
2683 // Use built-in when available, missing from IE11
2684 this.copyWithin(targetStart, start, end)
2685 } else {
2686 Uint8Array.prototype.set.call(
2687 target,
2688 this.subarray(start, end),
2689 targetStart
2690 )
2691 }
2692
2693 return len
2694}
2695
2696// Usage:
2697// buffer.fill(number[, offset[, end]])
2698// buffer.fill(buffer[, offset[, end]])
2699// buffer.fill(string[, offset[, end]][, encoding])
2700Buffer.prototype.fill = function fill (val, start, end, encoding) {
2701 // Handle string cases:
2702 if (typeof val === 'string') {
2703 if (typeof start === 'string') {
2704 encoding = start
2705 start = 0
2706 end = this.length
2707 } else if (typeof end === 'string') {
2708 encoding = end
2709 end = this.length
2710 }
2711 if (encoding !== undefined && typeof encoding !== 'string') {
2712 throw new TypeError('encoding must be a string')
2713 }
2714 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
2715 throw new TypeError('Unknown encoding: ' + encoding)
2716 }
2717 if (val.length === 1) {
2718 var code = val.charCodeAt(0)
2719 if ((encoding === 'utf8' && code < 128) ||
2720 encoding === 'latin1') {
2721 // Fast path: If `val` fits into a single byte, use that numeric value.
2722 val = code
2723 }
2724 }
2725 } else if (typeof val === 'number') {
2726 val = val & 255
2727 } else if (typeof val === 'boolean') {
2728 val = Number(val)
2729 }
2730
2731 // Invalid ranges are not set to a default, so can range check early.
2732 if (start < 0 || this.length < start || this.length < end) {
2733 throw new RangeError('Out of range index')
2734 }
2735
2736 if (end <= start) {
2737 return this
2738 }
2739
2740 start = start >>> 0
2741 end = end === undefined ? this.length : end >>> 0
2742
2743 if (!val) val = 0
2744
2745 var i
2746 if (typeof val === 'number') {
2747 for (i = start; i < end; ++i) {
2748 this[i] = val
2749 }
2750 } else {
2751 var bytes = Buffer.isBuffer(val)
2752 ? val
2753 : Buffer.from(val, encoding)
2754 var len = bytes.length
2755 if (len === 0) {
2756 throw new TypeError('The value "' + val +
2757 '" is invalid for argument "value"')
2758 }
2759 for (i = 0; i < end - start; ++i) {
2760 this[i + start] = bytes[i % len]
2761 }
2762 }
2763
2764 return this
2765}
2766
2767// HELPER FUNCTIONS
2768// ================
2769
2770var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
2771
2772function base64clean (str) {
2773 // Node takes equal signs as end of the Base64 encoding
2774 str = str.split('=')[0]
2775 // Node strips out invalid characters like \n and \t from the string, base64-js does not
2776 str = str.trim().replace(INVALID_BASE64_RE, '')
2777 // Node converts strings with length < 2 to ''
2778 if (str.length < 2) return ''
2779 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
2780 while (str.length % 4 !== 0) {
2781 str = str + '='
2782 }
2783 return str
2784}
2785
2786function utf8ToBytes (string, units) {
2787 units = units || Infinity
2788 var codePoint
2789 var length = string.length
2790 var leadSurrogate = null
2791 var bytes = []
2792
2793 for (var i = 0; i < length; ++i) {
2794 codePoint = string.charCodeAt(i)
2795
2796 // is surrogate component
2797 if (codePoint > 0xD7FF && codePoint < 0xE000) {
2798 // last char was a lead
2799 if (!leadSurrogate) {
2800 // no lead yet
2801 if (codePoint > 0xDBFF) {
2802 // unexpected trail
2803 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2804 continue
2805 } else if (i + 1 === length) {
2806 // unpaired lead
2807 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2808 continue
2809 }
2810
2811 // valid lead
2812 leadSurrogate = codePoint
2813
2814 continue
2815 }
2816
2817 // 2 leads in a row
2818 if (codePoint < 0xDC00) {
2819 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2820 leadSurrogate = codePoint
2821 continue
2822 }
2823
2824 // valid surrogate pair
2825 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
2826 } else if (leadSurrogate) {
2827 // valid bmp char, but last char was a lead
2828 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2829 }
2830
2831 leadSurrogate = null
2832
2833 // encode utf8
2834 if (codePoint < 0x80) {
2835 if ((units -= 1) < 0) break
2836 bytes.push(codePoint)
2837 } else if (codePoint < 0x800) {
2838 if ((units -= 2) < 0) break
2839 bytes.push(
2840 codePoint >> 0x6 | 0xC0,
2841 codePoint & 0x3F | 0x80
2842 )
2843 } else if (codePoint < 0x10000) {
2844 if ((units -= 3) < 0) break
2845 bytes.push(
2846 codePoint >> 0xC | 0xE0,
2847 codePoint >> 0x6 & 0x3F | 0x80,
2848 codePoint & 0x3F | 0x80
2849 )
2850 } else if (codePoint < 0x110000) {
2851 if ((units -= 4) < 0) break
2852 bytes.push(
2853 codePoint >> 0x12 | 0xF0,
2854 codePoint >> 0xC & 0x3F | 0x80,
2855 codePoint >> 0x6 & 0x3F | 0x80,
2856 codePoint & 0x3F | 0x80
2857 )
2858 } else {
2859 throw new Error('Invalid code point')
2860 }
2861 }
2862
2863 return bytes
2864}
2865
2866function asciiToBytes (str) {
2867 var byteArray = []
2868 for (var i = 0; i < str.length; ++i) {
2869 // Node's code seems to be doing this and not & 0x7F..
2870 byteArray.push(str.charCodeAt(i) & 0xFF)
2871 }
2872 return byteArray
2873}
2874
2875function utf16leToBytes (str, units) {
2876 var c, hi, lo
2877 var byteArray = []
2878 for (var i = 0; i < str.length; ++i) {
2879 if ((units -= 2) < 0) break
2880
2881 c = str.charCodeAt(i)
2882 hi = c >> 8
2883 lo = c % 256
2884 byteArray.push(lo)
2885 byteArray.push(hi)
2886 }
2887
2888 return byteArray
2889}
2890
2891function base64ToBytes (str) {
2892 return base64.toByteArray(base64clean(str))
2893}
2894
2895function blitBuffer (src, dst, offset, length) {
2896 for (var i = 0; i < length; ++i) {
2897 if ((i + offset >= dst.length) || (i >= src.length)) break
2898 dst[i + offset] = src[i]
2899 }
2900 return i
2901}
2902
2903// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
2904// the `instanceof` check but they should be treated as of that type.
2905// See: https://github.com/feross/buffer/issues/166
2906function isInstance (obj, type) {
2907 return obj instanceof type ||
2908 (obj != null && obj.constructor != null && obj.constructor.name != null &&
2909 obj.constructor.name === type.name)
2910}
2911function numberIsNaN (obj) {
2912 // For IE11 support
2913 return obj !== obj // eslint-disable-line no-self-compare
2914}
2915
2916// Create lookup table for `toString('hex')`
2917// See: https://github.com/feross/buffer/issues/219
2918var hexSliceLookupTable = (function () {
2919 var alphabet = '0123456789abcdef'
2920 var table = new Array(256)
2921 for (var i = 0; i < 16; ++i) {
2922 var i16 = i * 16
2923 for (var j = 0; j < 16; ++j) {
2924 table[i16 + j] = alphabet[i] + alphabet[j]
2925 }
2926 }
2927 return table
2928})()
2929
2930}).call(this)}).call(this,_dereq_("buffer").Buffer)
2931},{"base64-js":7,"buffer":9,"ieee754":52}],10:[function(_dereq_,module,exports){
2932'use strict';
2933
2934var GetIntrinsic = _dereq_('get-intrinsic');
2935
2936var callBind = _dereq_('./');
2937
2938var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));
2939
2940module.exports = function callBoundIntrinsic(name, allowMissing) {
2941 var intrinsic = GetIntrinsic(name, !!allowMissing);
2942 if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
2943 return callBind(intrinsic);
2944 }
2945 return intrinsic;
2946};
2947
2948},{"./":11,"get-intrinsic":42}],11:[function(_dereq_,module,exports){
2949'use strict';
2950
2951var bind = _dereq_('function-bind');
2952var GetIntrinsic = _dereq_('get-intrinsic');
2953var setFunctionLength = _dereq_('set-function-length');
2954
2955var $TypeError = _dereq_('es-errors/type');
2956var $apply = GetIntrinsic('%Function.prototype.apply%');
2957var $call = GetIntrinsic('%Function.prototype.call%');
2958var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
2959
2960var $defineProperty = _dereq_('es-define-property');
2961var $max = GetIntrinsic('%Math.max%');
2962
2963module.exports = function callBind(originalFunction) {
2964 if (typeof originalFunction !== 'function') {
2965 throw new $TypeError('a function is required');
2966 }
2967 var func = $reflectApply(bind, $call, arguments);
2968 return setFunctionLength(
2969 func,
2970 1 + $max(0, originalFunction.length - (arguments.length - 1)),
2971 true
2972 );
2973};
2974
2975var applyBind = function applyBind() {
2976 return $reflectApply(bind, $apply, arguments);
2977};
2978
2979if ($defineProperty) {
2980 $defineProperty(module.exports, 'apply', { value: applyBind });
2981} else {
2982 module.exports.apply = applyBind;
2983}
2984
2985},{"es-define-property":31,"es-errors/type":37,"function-bind":41,"get-intrinsic":42,"set-function-length":104}],12:[function(_dereq_,module,exports){
2986// Copyright Joyent, Inc. and other Node contributors.
2987//
2988// Permission is hereby granted, free of charge, to any person obtaining a
2989// copy of this software and associated documentation files (the
2990// "Software"), to deal in the Software without restriction, including
2991// without limitation the rights to use, copy, modify, merge, publish,
2992// distribute, sublicense, and/or sell copies of the Software, and to permit
2993// persons to whom the Software is furnished to do so, subject to the
2994// following conditions:
2995//
2996// The above copyright notice and this permission notice shall be included
2997// in all copies or substantial portions of the Software.
2998//
2999// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3000// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3001// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3002// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3003// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3004// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3005// USE OR OTHER DEALINGS IN THE SOFTWARE.
3006
3007// NOTE: These type checking functions intentionally don't use `instanceof`
3008// because it is fragile and can be easily faked with `Object.create()`.
3009
3010function isArray(arg) {
3011 if (Array.isArray) {
3012 return Array.isArray(arg);
3013 }
3014 return objectToString(arg) === '[object Array]';
3015}
3016exports.isArray = isArray;
3017
3018function isBoolean(arg) {
3019 return typeof arg === 'boolean';
3020}
3021exports.isBoolean = isBoolean;
3022
3023function isNull(arg) {
3024 return arg === null;
3025}
3026exports.isNull = isNull;
3027
3028function isNullOrUndefined(arg) {
3029 return arg == null;
3030}
3031exports.isNullOrUndefined = isNullOrUndefined;
3032
3033function isNumber(arg) {
3034 return typeof arg === 'number';
3035}
3036exports.isNumber = isNumber;
3037
3038function isString(arg) {
3039 return typeof arg === 'string';
3040}
3041exports.isString = isString;
3042
3043function isSymbol(arg) {
3044 return typeof arg === 'symbol';
3045}
3046exports.isSymbol = isSymbol;
3047
3048function isUndefined(arg) {
3049 return arg === void 0;
3050}
3051exports.isUndefined = isUndefined;
3052
3053function isRegExp(re) {
3054 return objectToString(re) === '[object RegExp]';
3055}
3056exports.isRegExp = isRegExp;
3057
3058function isObject(arg) {
3059 return typeof arg === 'object' && arg !== null;
3060}
3061exports.isObject = isObject;
3062
3063function isDate(d) {
3064 return objectToString(d) === '[object Date]';
3065}
3066exports.isDate = isDate;
3067
3068function isError(e) {
3069 return (objectToString(e) === '[object Error]' || e instanceof Error);
3070}
3071exports.isError = isError;
3072
3073function isFunction(arg) {
3074 return typeof arg === 'function';
3075}
3076exports.isFunction = isFunction;
3077
3078function isPrimitive(arg) {
3079 return arg === null ||
3080 typeof arg === 'boolean' ||
3081 typeof arg === 'number' ||
3082 typeof arg === 'string' ||
3083 typeof arg === 'symbol' || // ES6 symbol
3084 typeof arg === 'undefined';
3085}
3086exports.isPrimitive = isPrimitive;
3087
3088exports.isBuffer = _dereq_('buffer').Buffer.isBuffer;
3089
3090function objectToString(o) {
3091 return Object.prototype.toString.call(o);
3092}
3093
3094},{"buffer":9}],13:[function(_dereq_,module,exports){
3095var Buffer = _dereq_('buffer').Buffer
3096
3097var CHARS = '.PYFGCRLAOEUIDHTNSQJKXBMWVZ_pyfgcrlaoeuidhtnsqjkxbmwvz1234567890'
3098 .split('').sort().join('')
3099
3100module.exports = function (chars, exports) {
3101 chars = chars || CHARS
3102 exports = exports || {}
3103 if(chars.length !== 64) throw new Error('a base 64 encoding requires 64 chars')
3104
3105 var codeToIndex = new Buffer(128)
3106 codeToIndex.fill()
3107
3108 for(var i = 0; i < 64; i++) {
3109 var code = chars.charCodeAt(i)
3110 codeToIndex[code] = i
3111 }
3112
3113 exports.encode = function (data) {
3114 var s = '', l = data.length, hang = 0
3115 for(var i = 0; i < l; i++) {
3116 var v = data[i]
3117
3118 switch (i % 3) {
3119 case 0:
3120 s += chars[v >> 2]
3121 hang = (v & 3) << 4
3122 break;
3123 case 1:
3124 s += chars[hang | v >> 4]
3125 hang = (v & 0xf) << 2
3126 break;
3127 case 2:
3128 s += chars[hang | v >> 6]
3129 s += chars[v & 0x3f]
3130 hang = 0
3131 break;
3132 }
3133
3134 }
3135 if(l%3) s += chars[hang]
3136 return s
3137 }
3138 exports.decode = function (str) {
3139 var l = str.length, j = 0
3140 var b = new Buffer(~~((l/4)*3)), hang = 0
3141
3142 for(var i = 0; i < l; i++) {
3143 var v = codeToIndex[str.charCodeAt(i)]
3144
3145 switch (i % 4) {
3146 case 0:
3147 hang = v << 2;
3148 break;
3149 case 1:
3150 b[j++] = hang | v >> 4
3151 hang = (v << 4) & 0xff
3152 break;
3153 case 2:
3154 b[j++] = hang | v >> 2
3155 hang = (v << 6) & 0xff
3156 break;
3157 case 3:
3158 b[j++] = hang | v
3159 break;
3160 }
3161
3162 }
3163 return b
3164 }
3165 return exports
3166}
3167
3168module.exports(CHARS, module.exports)
3169
3170
3171},{"buffer":9}],14:[function(_dereq_,module,exports){
3172var AbstractIterator = _dereq_('abstract-leveldown').AbstractIterator
3173var inherits = _dereq_('inherits')
3174
3175function DeferredIterator (db, options) {
3176 AbstractIterator.call(this, db)
3177
3178 this._options = options
3179 this._iterator = null
3180 this._operations = []
3181}
3182
3183inherits(DeferredIterator, AbstractIterator)
3184
3185DeferredIterator.prototype.setDb = function (db) {
3186 var it = this._iterator = db.iterator(this._options)
3187 this._operations.forEach(function (op) {
3188 it[op.method].apply(it, op.args)
3189 })
3190}
3191
3192DeferredIterator.prototype._operation = function (method, args) {
3193 if (this._iterator) return this._iterator[method].apply(this._iterator, args)
3194 this._operations.push({ method: method, args: args })
3195}
3196
3197'next end'.split(' ').forEach(function (m) {
3198 DeferredIterator.prototype['_' + m] = function () {
3199 this._operation(m, arguments)
3200 }
3201})
3202
3203// Must defer seek() rather than _seek() because it requires db._serializeKey to be available
3204DeferredIterator.prototype.seek = function () {
3205 this._operation('seek', arguments)
3206}
3207
3208module.exports = DeferredIterator
3209
3210},{"abstract-leveldown":19,"inherits":53}],15:[function(_dereq_,module,exports){
3211var AbstractLevelDOWN = _dereq_('abstract-leveldown').AbstractLevelDOWN
3212var inherits = _dereq_('inherits')
3213var DeferredIterator = _dereq_('./deferred-iterator')
3214var deferrables = 'put get del batch clear'.split(' ')
3215var optionalDeferrables = 'approximateSize compactRange'.split(' ')
3216
3217function DeferredLevelDOWN (db) {
3218 AbstractLevelDOWN.call(this, db.supports || {})
3219
3220 // TODO (future major): remove this fallback; db must have manifest that
3221 // declares approximateSize and compactRange in additionalMethods.
3222 optionalDeferrables.forEach(function (m) {
3223 if (typeof db[m] === 'function' && !this.supports.additionalMethods[m]) {
3224 this.supports.additionalMethods[m] = true
3225 }
3226 }, this)
3227
3228 this._db = db
3229 this._operations = []
3230 closed(this)
3231}
3232
3233inherits(DeferredLevelDOWN, AbstractLevelDOWN)
3234
3235DeferredLevelDOWN.prototype.type = 'deferred-leveldown'
3236
3237DeferredLevelDOWN.prototype._open = function (options, callback) {
3238 var self = this
3239
3240 this._db.open(options, function (err) {
3241 if (err) return callback(err)
3242
3243 self._operations.forEach(function (op) {
3244 if (op.iterator) {
3245 op.iterator.setDb(self._db)
3246 } else {
3247 self._db[op.method].apply(self._db, op.args)
3248 }
3249 })
3250 self._operations = []
3251
3252 open(self)
3253 callback()
3254 })
3255}
3256
3257DeferredLevelDOWN.prototype._close = function (callback) {
3258 var self = this
3259
3260 this._db.close(function (err) {
3261 if (err) return callback(err)
3262 closed(self)
3263 callback()
3264 })
3265}
3266
3267function open (self) {
3268 deferrables.concat('iterator').forEach(function (m) {
3269 self['_' + m] = function () {
3270 return this._db[m].apply(this._db, arguments)
3271 }
3272 })
3273 Object.keys(self.supports.additionalMethods).forEach(function (m) {
3274 self[m] = function () {
3275 return this._db[m].apply(this._db, arguments)
3276 }
3277 })
3278}
3279
3280function closed (self) {
3281 deferrables.forEach(function (m) {
3282 self['_' + m] = function () {
3283 this._operations.push({ method: m, args: arguments })
3284 }
3285 })
3286 Object.keys(self.supports.additionalMethods).forEach(function (m) {
3287 self[m] = function () {
3288 this._operations.push({ method: m, args: arguments })
3289 }
3290 })
3291 self._iterator = function (options) {
3292 var it = new DeferredIterator(self, options)
3293 this._operations.push({ iterator: it })
3294 return it
3295 }
3296}
3297
3298DeferredLevelDOWN.prototype._serializeKey = function (key) {
3299 return key
3300}
3301
3302DeferredLevelDOWN.prototype._serializeValue = function (value) {
3303 return value
3304}
3305
3306module.exports = DeferredLevelDOWN
3307module.exports.DeferredIterator = DeferredIterator
3308
3309},{"./deferred-iterator":14,"abstract-leveldown":19,"inherits":53}],16:[function(_dereq_,module,exports){
3310var nextTick = _dereq_('./next-tick')
3311
3312function AbstractChainedBatch (db) {
3313 if (typeof db !== 'object' || db === null) {
3314 throw new TypeError('First argument must be an abstract-leveldown compliant store')
3315 }
3316
3317 this.db = db
3318 this._operations = []
3319 this._written = false
3320}
3321
3322AbstractChainedBatch.prototype._checkWritten = function () {
3323 if (this._written) {
3324 throw new Error('write() already called on this batch')
3325 }
3326}
3327
3328AbstractChainedBatch.prototype.put = function (key, value) {
3329 this._checkWritten()
3330
3331 var err = this.db._checkKey(key) || this.db._checkValue(value)
3332 if (err) throw err
3333
3334 key = this.db._serializeKey(key)
3335 value = this.db._serializeValue(value)
3336
3337 this._put(key, value)
3338
3339 return this
3340}
3341
3342AbstractChainedBatch.prototype._put = function (key, value) {
3343 this._operations.push({ type: 'put', key: key, value: value })
3344}
3345
3346AbstractChainedBatch.prototype.del = function (key) {
3347 this._checkWritten()
3348
3349 var err = this.db._checkKey(key)
3350 if (err) throw err
3351
3352 key = this.db._serializeKey(key)
3353 this._del(key)
3354
3355 return this
3356}
3357
3358AbstractChainedBatch.prototype._del = function (key) {
3359 this._operations.push({ type: 'del', key: key })
3360}
3361
3362AbstractChainedBatch.prototype.clear = function () {
3363 this._checkWritten()
3364 this._clear()
3365
3366 return this
3367}
3368
3369AbstractChainedBatch.prototype._clear = function () {
3370 this._operations = []
3371}
3372
3373AbstractChainedBatch.prototype.write = function (options, callback) {
3374 this._checkWritten()
3375
3376 if (typeof options === 'function') { callback = options }
3377 if (typeof callback !== 'function') {
3378 throw new Error('write() requires a callback argument')
3379 }
3380 if (typeof options !== 'object' || options === null) {
3381 options = {}
3382 }
3383
3384 this._written = true
3385 this._write(options, callback)
3386}
3387
3388AbstractChainedBatch.prototype._write = function (options, callback) {
3389 this.db._batch(this._operations, options, callback)
3390}
3391
3392// Expose browser-compatible nextTick for dependents
3393AbstractChainedBatch.prototype._nextTick = nextTick
3394
3395module.exports = AbstractChainedBatch
3396
3397},{"./next-tick":20}],17:[function(_dereq_,module,exports){
3398var nextTick = _dereq_('./next-tick')
3399
3400function AbstractIterator (db) {
3401 if (typeof db !== 'object' || db === null) {
3402 throw new TypeError('First argument must be an abstract-leveldown compliant store')
3403 }
3404
3405 this.db = db
3406 this._ended = false
3407 this._nexting = false
3408}
3409
3410AbstractIterator.prototype.next = function (callback) {
3411 var self = this
3412
3413 if (typeof callback !== 'function') {
3414 throw new Error('next() requires a callback argument')
3415 }
3416
3417 if (self._ended) {
3418 nextTick(callback, new Error('cannot call next() after end()'))
3419 return self
3420 }
3421
3422 if (self._nexting) {
3423 nextTick(callback, new Error('cannot call next() before previous next() has completed'))
3424 return self
3425 }
3426
3427 self._nexting = true
3428 self._next(function () {
3429 self._nexting = false
3430 callback.apply(null, arguments)
3431 })
3432
3433 return self
3434}
3435
3436AbstractIterator.prototype._next = function (callback) {
3437 nextTick(callback)
3438}
3439
3440AbstractIterator.prototype.seek = function (target) {
3441 if (this._ended) {
3442 throw new Error('cannot call seek() after end()')
3443 }
3444 if (this._nexting) {
3445 throw new Error('cannot call seek() before next() has completed')
3446 }
3447
3448 target = this.db._serializeKey(target)
3449 this._seek(target)
3450}
3451
3452AbstractIterator.prototype._seek = function (target) {}
3453
3454AbstractIterator.prototype.end = function (callback) {
3455 if (typeof callback !== 'function') {
3456 throw new Error('end() requires a callback argument')
3457 }
3458
3459 if (this._ended) {
3460 return nextTick(callback, new Error('end() already called on iterator'))
3461 }
3462
3463 this._ended = true
3464 this._end(callback)
3465}
3466
3467AbstractIterator.prototype._end = function (callback) {
3468 nextTick(callback)
3469}
3470
3471// Expose browser-compatible nextTick for dependents
3472AbstractIterator.prototype._nextTick = nextTick
3473
3474module.exports = AbstractIterator
3475
3476},{"./next-tick":20}],18:[function(_dereq_,module,exports){
3477var xtend = _dereq_('xtend')
3478var supports = _dereq_('level-supports')
3479var Buffer = _dereq_('buffer').Buffer
3480var AbstractIterator = _dereq_('./abstract-iterator')
3481var AbstractChainedBatch = _dereq_('./abstract-chained-batch')
3482var nextTick = _dereq_('./next-tick')
3483var hasOwnProperty = Object.prototype.hasOwnProperty
3484var rangeOptions = 'start end gt gte lt lte'.split(' ')
3485
3486function AbstractLevelDOWN (manifest) {
3487 this.status = 'new'
3488
3489 // TODO (next major): make this mandatory
3490 this.supports = supports(manifest, {
3491 status: true
3492 })
3493}
3494
3495AbstractLevelDOWN.prototype.open = function (options, callback) {
3496 var self = this
3497 var oldStatus = this.status
3498
3499 if (typeof options === 'function') callback = options
3500
3501 if (typeof callback !== 'function') {
3502 throw new Error('open() requires a callback argument')
3503 }
3504
3505 if (typeof options !== 'object' || options === null) options = {}
3506
3507 options.createIfMissing = options.createIfMissing !== false
3508 options.errorIfExists = !!options.errorIfExists
3509
3510 this.status = 'opening'
3511 this._open(options, function (err) {
3512 if (err) {
3513 self.status = oldStatus
3514 return callback(err)
3515 }
3516 self.status = 'open'
3517 callback()
3518 })
3519}
3520
3521AbstractLevelDOWN.prototype._open = function (options, callback) {
3522 nextTick(callback)
3523}
3524
3525AbstractLevelDOWN.prototype.close = function (callback) {
3526 var self = this
3527 var oldStatus = this.status
3528
3529 if (typeof callback !== 'function') {
3530 throw new Error('close() requires a callback argument')
3531 }
3532
3533 this.status = 'closing'
3534 this._close(function (err) {
3535 if (err) {
3536 self.status = oldStatus
3537 return callback(err)
3538 }
3539 self.status = 'closed'
3540 callback()
3541 })
3542}
3543
3544AbstractLevelDOWN.prototype._close = function (callback) {
3545 nextTick(callback)
3546}
3547
3548AbstractLevelDOWN.prototype.get = function (key, options, callback) {
3549 if (typeof options === 'function') callback = options
3550
3551 if (typeof callback !== 'function') {
3552 throw new Error('get() requires a callback argument')
3553 }
3554
3555 var err = this._checkKey(key)
3556 if (err) return nextTick(callback, err)
3557
3558 key = this._serializeKey(key)
3559
3560 if (typeof options !== 'object' || options === null) options = {}
3561
3562 options.asBuffer = options.asBuffer !== false
3563
3564 this._get(key, options, callback)
3565}
3566
3567AbstractLevelDOWN.prototype._get = function (key, options, callback) {
3568 nextTick(function () { callback(new Error('NotFound')) })
3569}
3570
3571AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
3572 if (typeof options === 'function') callback = options
3573
3574 if (typeof callback !== 'function') {
3575 throw new Error('put() requires a callback argument')
3576 }
3577
3578 var err = this._checkKey(key) || this._checkValue(value)
3579 if (err) return nextTick(callback, err)
3580
3581 key = this._serializeKey(key)
3582 value = this._serializeValue(value)
3583
3584 if (typeof options !== 'object' || options === null) options = {}
3585
3586 this._put(key, value, options, callback)
3587}
3588
3589AbstractLevelDOWN.prototype._put = function (key, value, options, callback) {
3590 nextTick(callback)
3591}
3592
3593AbstractLevelDOWN.prototype.del = function (key, options, callback) {
3594 if (typeof options === 'function') callback = options
3595
3596 if (typeof callback !== 'function') {
3597 throw new Error('del() requires a callback argument')
3598 }
3599
3600 var err = this._checkKey(key)
3601 if (err) return nextTick(callback, err)
3602
3603 key = this._serializeKey(key)
3604
3605 if (typeof options !== 'object' || options === null) options = {}
3606
3607 this._del(key, options, callback)
3608}
3609
3610AbstractLevelDOWN.prototype._del = function (key, options, callback) {
3611 nextTick(callback)
3612}
3613
3614AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
3615 if (!arguments.length) return this._chainedBatch()
3616
3617 if (typeof options === 'function') callback = options
3618
3619 if (typeof array === 'function') callback = array
3620
3621 if (typeof callback !== 'function') {
3622 throw new Error('batch(array) requires a callback argument')
3623 }
3624
3625 if (!Array.isArray(array)) {
3626 return nextTick(callback, new Error('batch(array) requires an array argument'))
3627 }
3628
3629 if (array.length === 0) {
3630 return nextTick(callback)
3631 }
3632
3633 if (typeof options !== 'object' || options === null) options = {}
3634
3635 var serialized = new Array(array.length)
3636
3637 for (var i = 0; i < array.length; i++) {
3638 if (typeof array[i] !== 'object' || array[i] === null) {
3639 return nextTick(callback, new Error('batch(array) element must be an object and not `null`'))
3640 }
3641
3642 var e = xtend(array[i])
3643
3644 if (e.type !== 'put' && e.type !== 'del') {
3645 return nextTick(callback, new Error("`type` must be 'put' or 'del'"))
3646 }
3647
3648 var err = this._checkKey(e.key)
3649 if (err) return nextTick(callback, err)
3650
3651 e.key = this._serializeKey(e.key)
3652
3653 if (e.type === 'put') {
3654 var valueErr = this._checkValue(e.value)
3655 if (valueErr) return nextTick(callback, valueErr)
3656
3657 e.value = this._serializeValue(e.value)
3658 }
3659
3660 serialized[i] = e
3661 }
3662
3663 this._batch(serialized, options, callback)
3664}
3665
3666AbstractLevelDOWN.prototype._batch = function (array, options, callback) {
3667 nextTick(callback)
3668}
3669
3670AbstractLevelDOWN.prototype.clear = function (options, callback) {
3671 if (typeof options === 'function') {
3672 callback = options
3673 } else if (typeof callback !== 'function') {
3674 throw new Error('clear() requires a callback argument')
3675 }
3676
3677 options = cleanRangeOptions(this, options)
3678 options.reverse = !!options.reverse
3679 options.limit = 'limit' in options ? options.limit : -1
3680
3681 this._clear(options, callback)
3682}
3683
3684AbstractLevelDOWN.prototype._clear = function (options, callback) {
3685 // Avoid setupIteratorOptions, would serialize range options a second time.
3686 options.keys = true
3687 options.values = false
3688 options.keyAsBuffer = true
3689 options.valueAsBuffer = true
3690
3691 var iterator = this._iterator(options)
3692 var emptyOptions = {}
3693 var self = this
3694
3695 var next = function (err) {
3696 if (err) {
3697 return iterator.end(function () {
3698 callback(err)
3699 })
3700 }
3701
3702 iterator.next(function (err, key) {
3703 if (err) return next(err)
3704 if (key === undefined) return iterator.end(callback)
3705
3706 // This could be optimized by using a batch, but the default _clear
3707 // is not meant to be fast. Implementations have more room to optimize
3708 // if they override _clear. Note: using _del bypasses key serialization.
3709 self._del(key, emptyOptions, next)
3710 })
3711 }
3712
3713 next()
3714}
3715
3716AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
3717 options = cleanRangeOptions(this, options)
3718
3719 options.reverse = !!options.reverse
3720 options.keys = options.keys !== false
3721 options.values = options.values !== false
3722 options.limit = 'limit' in options ? options.limit : -1
3723 options.keyAsBuffer = options.keyAsBuffer !== false
3724 options.valueAsBuffer = options.valueAsBuffer !== false
3725
3726 return options
3727}
3728
3729function cleanRangeOptions (db, options) {
3730 var result = {}
3731
3732 for (var k in options) {
3733 if (!hasOwnProperty.call(options, k)) continue
3734
3735 var opt = options[k]
3736
3737 if (isRangeOption(k)) {
3738 // Note that we don't reject nullish and empty options here. While
3739 // those types are invalid as keys, they are valid as range options.
3740 opt = db._serializeKey(opt)
3741 }
3742
3743 result[k] = opt
3744 }
3745
3746 return result
3747}
3748
3749function isRangeOption (k) {
3750 return rangeOptions.indexOf(k) !== -1
3751}
3752
3753AbstractLevelDOWN.prototype.iterator = function (options) {
3754 if (typeof options !== 'object' || options === null) options = {}
3755 options = this._setupIteratorOptions(options)
3756 return this._iterator(options)
3757}
3758
3759AbstractLevelDOWN.prototype._iterator = function (options) {
3760 return new AbstractIterator(this)
3761}
3762
3763AbstractLevelDOWN.prototype._chainedBatch = function () {
3764 return new AbstractChainedBatch(this)
3765}
3766
3767AbstractLevelDOWN.prototype._serializeKey = function (key) {
3768 return key
3769}
3770
3771AbstractLevelDOWN.prototype._serializeValue = function (value) {
3772 return value
3773}
3774
3775AbstractLevelDOWN.prototype._checkKey = function (key) {
3776 if (key === null || key === undefined) {
3777 return new Error('key cannot be `null` or `undefined`')
3778 } else if (Buffer.isBuffer(key) && key.length === 0) {
3779 return new Error('key cannot be an empty Buffer')
3780 } else if (key === '') {
3781 return new Error('key cannot be an empty String')
3782 } else if (Array.isArray(key) && key.length === 0) {
3783 return new Error('key cannot be an empty Array')
3784 }
3785}
3786
3787AbstractLevelDOWN.prototype._checkValue = function (value) {
3788 if (value === null || value === undefined) {
3789 return new Error('value cannot be `null` or `undefined`')
3790 }
3791}
3792
3793// Expose browser-compatible nextTick for dependents
3794AbstractLevelDOWN.prototype._nextTick = nextTick
3795
3796module.exports = AbstractLevelDOWN
3797
3798},{"./abstract-chained-batch":16,"./abstract-iterator":17,"./next-tick":20,"buffer":9,"level-supports":75,"xtend":162}],19:[function(_dereq_,module,exports){
3799exports.AbstractLevelDOWN = _dereq_('./abstract-leveldown')
3800exports.AbstractIterator = _dereq_('./abstract-iterator')
3801exports.AbstractChainedBatch = _dereq_('./abstract-chained-batch')
3802
3803},{"./abstract-chained-batch":16,"./abstract-iterator":17,"./abstract-leveldown":18}],20:[function(_dereq_,module,exports){
3804module.exports = _dereq_('immediate')
3805
3806},{"immediate":21}],21:[function(_dereq_,module,exports){
3807'use strict';
3808var types = [
3809 _dereq_('./nextTick'),
3810 _dereq_('./queueMicrotask'),
3811 _dereq_('./mutation.js'),
3812 _dereq_('./messageChannel'),
3813 _dereq_('./stateChange'),
3814 _dereq_('./timeout')
3815];
3816var draining;
3817var currentQueue;
3818var queueIndex = -1;
3819var queue = [];
3820var scheduled = false;
3821function cleanUpNextTick() {
3822 if (!draining || !currentQueue) {
3823 return;
3824 }
3825 draining = false;
3826 if (currentQueue.length) {
3827 queue = currentQueue.concat(queue);
3828 } else {
3829 queueIndex = -1;
3830 }
3831 if (queue.length) {
3832 nextTick();
3833 }
3834}
3835
3836//named nextTick for less confusing stack traces
3837function nextTick() {
3838 if (draining) {
3839 return;
3840 }
3841 scheduled = false;
3842 draining = true;
3843 var len = queue.length;
3844 var timeout = setTimeout(cleanUpNextTick);
3845 while (len) {
3846 currentQueue = queue;
3847 queue = [];
3848 while (currentQueue && ++queueIndex < len) {
3849 currentQueue[queueIndex].run();
3850 }
3851 queueIndex = -1;
3852 len = queue.length;
3853 }
3854 currentQueue = null;
3855 queueIndex = -1;
3856 draining = false;
3857 clearTimeout(timeout);
3858}
3859var scheduleDrain;
3860var i = -1;
3861var len = types.length;
3862while (++i < len) {
3863 if (types[i] && types[i].test && types[i].test()) {
3864 scheduleDrain = types[i].install(nextTick);
3865 break;
3866 }
3867}
3868// v8 likes predictible objects
3869function Item(fun, array) {
3870 this.fun = fun;
3871 this.array = array;
3872}
3873Item.prototype.run = function () {
3874 var fun = this.fun;
3875 var array = this.array;
3876 switch (array.length) {
3877 case 0:
3878 return fun();
3879 case 1:
3880 return fun(array[0]);
3881 case 2:
3882 return fun(array[0], array[1]);
3883 case 3:
3884 return fun(array[0], array[1], array[2]);
3885 default:
3886 return fun.apply(null, array);
3887 }
3888
3889};
3890module.exports = immediate;
3891function immediate(task) {
3892 var args = new Array(arguments.length - 1);
3893 if (arguments.length > 1) {
3894 for (var i = 1; i < arguments.length; i++) {
3895 args[i - 1] = arguments[i];
3896 }
3897 }
3898 queue.push(new Item(task, args));
3899 if (!scheduled && !draining) {
3900 scheduled = true;
3901 scheduleDrain();
3902 }
3903}
3904
3905},{"./messageChannel":22,"./mutation.js":23,"./nextTick":8,"./queueMicrotask":24,"./stateChange":25,"./timeout":26}],22:[function(_dereq_,module,exports){
3906(function (global){(function (){
3907'use strict';
3908
3909exports.test = function () {
3910 if (global.setImmediate) {
3911 // we can only get here in IE10
3912 // which doesn't handel postMessage well
3913 return false;
3914 }
3915 return typeof global.MessageChannel !== 'undefined';
3916};
3917
3918exports.install = function (func) {
3919 var channel = new global.MessageChannel();
3920 channel.port1.onmessage = func;
3921 return function () {
3922 channel.port2.postMessage(0);
3923 };
3924};
3925}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3926},{}],23:[function(_dereq_,module,exports){
3927(function (global){(function (){
3928'use strict';
3929//based off rsvp https://github.com/tildeio/rsvp.js
3930//license https://github.com/tildeio/rsvp.js/blob/master/LICENSE
3931//https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/asap.js
3932
3933var Mutation = global.MutationObserver || global.WebKitMutationObserver;
3934
3935exports.test = function () {
3936 return Mutation;
3937};
3938
3939exports.install = function (handle) {
3940 var called = 0;
3941 var observer = new Mutation(handle);
3942 var element = global.document.createTextNode('');
3943 observer.observe(element, {
3944 characterData: true
3945 });
3946 return function () {
3947 element.data = (called = ++called % 2);
3948 };
3949};
3950}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3951},{}],24:[function(_dereq_,module,exports){
3952(function (global){(function (){
3953'use strict';
3954exports.test = function () {
3955 return typeof global.queueMicrotask === 'function';
3956};
3957
3958exports.install = function (func) {
3959 return function () {
3960 global.queueMicrotask(func);
3961 };
3962};
3963
3964}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3965},{}],25:[function(_dereq_,module,exports){
3966(function (global){(function (){
3967'use strict';
3968
3969exports.test = function () {
3970 return 'document' in global && 'onreadystatechange' in global.document.createElement('script');
3971};
3972
3973exports.install = function (handle) {
3974 return function () {
3975
3976 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
3977 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
3978 var scriptEl = global.document.createElement('script');
3979 scriptEl.onreadystatechange = function () {
3980 handle();
3981
3982 scriptEl.onreadystatechange = null;
3983 scriptEl.parentNode.removeChild(scriptEl);
3984 scriptEl = null;
3985 };
3986 global.document.documentElement.appendChild(scriptEl);
3987
3988 return handle;
3989 };
3990};
3991}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3992},{}],26:[function(_dereq_,module,exports){
3993'use strict';
3994exports.test = function () {
3995 return true;
3996};
3997
3998exports.install = function (t) {
3999 return function () {
4000 setTimeout(t, 0);
4001 };
4002};
4003},{}],27:[function(_dereq_,module,exports){
4004'use strict';
4005
4006var $defineProperty = _dereq_('es-define-property');
4007
4008var $SyntaxError = _dereq_('es-errors/syntax');
4009var $TypeError = _dereq_('es-errors/type');
4010
4011var gopd = _dereq_('gopd');
4012
4013/** @type {import('.')} */
4014module.exports = function defineDataProperty(
4015 obj,
4016 property,
4017 value
4018) {
4019 if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) {
4020 throw new $TypeError('`obj` must be an object or a function`');
4021 }
4022 if (typeof property !== 'string' && typeof property !== 'symbol') {
4023 throw new $TypeError('`property` must be a string or a symbol`');
4024 }
4025 if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) {
4026 throw new $TypeError('`nonEnumerable`, if provided, must be a boolean or null');
4027 }
4028 if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) {
4029 throw new $TypeError('`nonWritable`, if provided, must be a boolean or null');
4030 }
4031 if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) {
4032 throw new $TypeError('`nonConfigurable`, if provided, must be a boolean or null');
4033 }
4034 if (arguments.length > 6 && typeof arguments[6] !== 'boolean') {
4035 throw new $TypeError('`loose`, if provided, must be a boolean');
4036 }
4037
4038 var nonEnumerable = arguments.length > 3 ? arguments[3] : null;
4039 var nonWritable = arguments.length > 4 ? arguments[4] : null;
4040 var nonConfigurable = arguments.length > 5 ? arguments[5] : null;
4041 var loose = arguments.length > 6 ? arguments[6] : false;
4042
4043 /* @type {false | TypedPropertyDescriptor<unknown>} */
4044 var desc = !!gopd && gopd(obj, property);
4045
4046 if ($defineProperty) {
4047 $defineProperty(obj, property, {
4048 configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable,
4049 enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable,
4050 value: value,
4051 writable: nonWritable === null && desc ? desc.writable : !nonWritable
4052 });
4053 } else if (loose || (!nonEnumerable && !nonWritable && !nonConfigurable)) {
4054 // must fall back to [[Set]], and was not explicitly asked to make non-enumerable, non-writable, or non-configurable
4055 obj[property] = value; // eslint-disable-line no-param-reassign
4056 } else {
4057 throw new $SyntaxError('This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.');
4058 }
4059};
4060
4061},{"es-define-property":31,"es-errors/syntax":36,"es-errors/type":37,"gopd":43}],28:[function(_dereq_,module,exports){
4062/**
4063 * Copyright (c) 2013 Petka Antonov
4064 *
4065 * Permission is hereby granted, free of charge, to any person obtaining a copy
4066 * of this software and associated documentation files (the "Software"), to deal
4067 * in the Software without restriction, including without limitation the rights
4068 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
4069 * copies of the Software, and to permit persons to whom the Software is
4070 * furnished to do so, subject to the following conditions:</p>
4071 *
4072 * The above copyright notice and this permission notice shall be included in
4073 * all copies or substantial portions of the Software.
4074 *
4075 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
4076 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
4077 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
4078 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
4079 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
4080 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
4081 * THE SOFTWARE.
4082 */
4083"use strict";
4084function Deque(capacity) {
4085 this._capacity = getCapacity(capacity);
4086 this._length = 0;
4087 this._front = 0;
4088 if (isArray(capacity)) {
4089 var len = capacity.length;
4090 for (var i = 0; i < len; ++i) {
4091 this[i] = capacity[i];
4092 }
4093 this._length = len;
4094 }
4095}
4096
4097Deque.prototype.toArray = function Deque$toArray() {
4098 var len = this._length;
4099 var ret = new Array(len);
4100 var front = this._front;
4101 var capacity = this._capacity;
4102 for (var j = 0; j < len; ++j) {
4103 ret[j] = this[(front + j) & (capacity - 1)];
4104 }
4105 return ret;
4106};
4107
4108Deque.prototype.push = function Deque$push(item) {
4109 var argsLength = arguments.length;
4110 var length = this._length;
4111 if (argsLength > 1) {
4112 var capacity = this._capacity;
4113 if (length + argsLength > capacity) {
4114 for (var i = 0; i < argsLength; ++i) {
4115 this._checkCapacity(length + 1);
4116 var j = (this._front + length) & (this._capacity - 1);
4117 this[j] = arguments[i];
4118 length++;
4119 this._length = length;
4120 }
4121 return length;
4122 }
4123 else {
4124 var j = this._front;
4125 for (var i = 0; i < argsLength; ++i) {
4126 this[(j + length) & (capacity - 1)] = arguments[i];
4127 j++;
4128 }
4129 this._length = length + argsLength;
4130 return length + argsLength;
4131 }
4132
4133 }
4134
4135 if (argsLength === 0) return length;
4136
4137 this._checkCapacity(length + 1);
4138 var i = (this._front + length) & (this._capacity - 1);
4139 this[i] = item;
4140 this._length = length + 1;
4141 return length + 1;
4142};
4143
4144Deque.prototype.pop = function Deque$pop() {
4145 var length = this._length;
4146 if (length === 0) {
4147 return void 0;
4148 }
4149 var i = (this._front + length - 1) & (this._capacity - 1);
4150 var ret = this[i];
4151 this[i] = void 0;
4152 this._length = length - 1;
4153 return ret;
4154};
4155
4156Deque.prototype.shift = function Deque$shift() {
4157 var length = this._length;
4158 if (length === 0) {
4159 return void 0;
4160 }
4161 var front = this._front;
4162 var ret = this[front];
4163 this[front] = void 0;
4164 this._front = (front + 1) & (this._capacity - 1);
4165 this._length = length - 1;
4166 return ret;
4167};
4168
4169Deque.prototype.unshift = function Deque$unshift(item) {
4170 var length = this._length;
4171 var argsLength = arguments.length;
4172
4173
4174 if (argsLength > 1) {
4175 var capacity = this._capacity;
4176 if (length + argsLength > capacity) {
4177 for (var i = argsLength - 1; i >= 0; i--) {
4178 this._checkCapacity(length + 1);
4179 var capacity = this._capacity;
4180 var j = (((( this._front - 1 ) &
4181 ( capacity - 1) ) ^ capacity ) - capacity );
4182 this[j] = arguments[i];
4183 length++;
4184 this._length = length;
4185 this._front = j;
4186 }
4187 return length;
4188 }
4189 else {
4190 var front = this._front;
4191 for (var i = argsLength - 1; i >= 0; i--) {
4192 var j = (((( front - 1 ) &
4193 ( capacity - 1) ) ^ capacity ) - capacity );
4194 this[j] = arguments[i];
4195 front = j;
4196 }
4197 this._front = front;
4198 this._length = length + argsLength;
4199 return length + argsLength;
4200 }
4201 }
4202
4203 if (argsLength === 0) return length;
4204
4205 this._checkCapacity(length + 1);
4206 var capacity = this._capacity;
4207 var i = (((( this._front - 1 ) &
4208 ( capacity - 1) ) ^ capacity ) - capacity );
4209 this[i] = item;
4210 this._length = length + 1;
4211 this._front = i;
4212 return length + 1;
4213};
4214
4215Deque.prototype.peekBack = function Deque$peekBack() {
4216 var length = this._length;
4217 if (length === 0) {
4218 return void 0;
4219 }
4220 var index = (this._front + length - 1) & (this._capacity - 1);
4221 return this[index];
4222};
4223
4224Deque.prototype.peekFront = function Deque$peekFront() {
4225 if (this._length === 0) {
4226 return void 0;
4227 }
4228 return this[this._front];
4229};
4230
4231Deque.prototype.get = function Deque$get(index) {
4232 var i = index;
4233 if ((i !== (i | 0))) {
4234 return void 0;
4235 }
4236 var len = this._length;
4237 if (i < 0) {
4238 i = i + len;
4239 }
4240 if (i < 0 || i >= len) {
4241 return void 0;
4242 }
4243 return this[(this._front + i) & (this._capacity - 1)];
4244};
4245
4246Deque.prototype.isEmpty = function Deque$isEmpty() {
4247 return this._length === 0;
4248};
4249
4250Deque.prototype.clear = function Deque$clear() {
4251 var len = this._length;
4252 var front = this._front;
4253 var capacity = this._capacity;
4254 for (var j = 0; j < len; ++j) {
4255 this[(front + j) & (capacity - 1)] = void 0;
4256 }
4257 this._length = 0;
4258 this._front = 0;
4259};
4260
4261Deque.prototype.toString = function Deque$toString() {
4262 return this.toArray().toString();
4263};
4264
4265Deque.prototype.valueOf = Deque.prototype.toString;
4266Deque.prototype.removeFront = Deque.prototype.shift;
4267Deque.prototype.removeBack = Deque.prototype.pop;
4268Deque.prototype.insertFront = Deque.prototype.unshift;
4269Deque.prototype.insertBack = Deque.prototype.push;
4270Deque.prototype.enqueue = Deque.prototype.push;
4271Deque.prototype.dequeue = Deque.prototype.shift;
4272Deque.prototype.toJSON = Deque.prototype.toArray;
4273
4274Object.defineProperty(Deque.prototype, "length", {
4275 get: function() {
4276 return this._length;
4277 },
4278 set: function() {
4279 throw new RangeError("");
4280 }
4281});
4282
4283Deque.prototype._checkCapacity = function Deque$_checkCapacity(size) {
4284 if (this._capacity < size) {
4285 this._resizeTo(getCapacity(this._capacity * 1.5 + 16));
4286 }
4287};
4288
4289Deque.prototype._resizeTo = function Deque$_resizeTo(capacity) {
4290 var oldCapacity = this._capacity;
4291 this._capacity = capacity;
4292 var front = this._front;
4293 var length = this._length;
4294 if (front + length > oldCapacity) {
4295 var moveItemsCount = (front + length) & (oldCapacity - 1);
4296 arrayMove(this, 0, this, oldCapacity, moveItemsCount);
4297 }
4298};
4299
4300
4301var isArray = Array.isArray;
4302
4303function arrayMove(src, srcIndex, dst, dstIndex, len) {
4304 for (var j = 0; j < len; ++j) {
4305 dst[j + dstIndex] = src[j + srcIndex];
4306 src[j + srcIndex] = void 0;
4307 }
4308}
4309
4310function pow2AtLeast(n) {
4311 n = n >>> 0;
4312 n = n - 1;
4313 n = n | (n >> 1);
4314 n = n | (n >> 2);
4315 n = n | (n >> 4);
4316 n = n | (n >> 8);
4317 n = n | (n >> 16);
4318 return n + 1;
4319}
4320
4321function getCapacity(capacity) {
4322 if (typeof capacity !== "number") {
4323 if (isArray(capacity)) {
4324 capacity = capacity.length;
4325 }
4326 else {
4327 return 16;
4328 }
4329 }
4330 return pow2AtLeast(
4331 Math.min(
4332 Math.max(16, capacity), 1073741824)
4333 );
4334}
4335
4336module.exports = Deque;
4337
4338},{}],29:[function(_dereq_,module,exports){
4339var prr = _dereq_('prr')
4340
4341function init (type, message, cause) {
4342 if (!!message && typeof message != 'string') {
4343 message = message.message || message.name
4344 }
4345 prr(this, {
4346 type : type
4347 , name : type
4348 // can be passed just a 'cause'
4349 , cause : typeof message != 'string' ? message : cause
4350 , message : message
4351 }, 'ewr')
4352}
4353
4354// generic prototype, not intended to be actually used - helpful for `instanceof`
4355function CustomError (message, cause) {
4356 Error.call(this)
4357 if (Error.captureStackTrace)
4358 Error.captureStackTrace(this, this.constructor)
4359 init.call(this, 'CustomError', message, cause)
4360}
4361
4362CustomError.prototype = new Error()
4363
4364function createError (errno, type, proto) {
4365 var err = function (message, cause) {
4366 init.call(this, type, message, cause)
4367 //TODO: the specificity here is stupid, errno should be available everywhere
4368 if (type == 'FilesystemError') {
4369 this.code = this.cause.code
4370 this.path = this.cause.path
4371 this.errno = this.cause.errno
4372 this.message =
4373 (errno.errno[this.cause.errno]
4374 ? errno.errno[this.cause.errno].description
4375 : this.cause.message)
4376 + (this.cause.path ? ' [' + this.cause.path + ']' : '')
4377 }
4378 Error.call(this)
4379 if (Error.captureStackTrace)
4380 Error.captureStackTrace(this, err)
4381 }
4382 err.prototype = !!proto ? new proto() : new CustomError()
4383 return err
4384}
4385
4386module.exports = function (errno) {
4387 var ce = function (type, proto) {
4388 return createError(errno, type, proto)
4389 }
4390 return {
4391 CustomError : CustomError
4392 , FilesystemError : ce('FilesystemError')
4393 , createError : ce
4394 }
4395}
4396
4397},{"prr":95}],30:[function(_dereq_,module,exports){
4398var all = module.exports.all = [
4399 {
4400 errno: -2,
4401 code: 'ENOENT',
4402 description: 'no such file or directory'
4403 },
4404 {
4405 errno: -1,
4406 code: 'UNKNOWN',
4407 description: 'unknown error'
4408 },
4409 {
4410 errno: 0,
4411 code: 'OK',
4412 description: 'success'
4413 },
4414 {
4415 errno: 1,
4416 code: 'EOF',
4417 description: 'end of file'
4418 },
4419 {
4420 errno: 2,
4421 code: 'EADDRINFO',
4422 description: 'getaddrinfo error'
4423 },
4424 {
4425 errno: 3,
4426 code: 'EACCES',
4427 description: 'permission denied'
4428 },
4429 {
4430 errno: 4,
4431 code: 'EAGAIN',
4432 description: 'resource temporarily unavailable'
4433 },
4434 {
4435 errno: 5,
4436 code: 'EADDRINUSE',
4437 description: 'address already in use'
4438 },
4439 {
4440 errno: 6,
4441 code: 'EADDRNOTAVAIL',
4442 description: 'address not available'
4443 },
4444 {
4445 errno: 7,
4446 code: 'EAFNOSUPPORT',
4447 description: 'address family not supported'
4448 },
4449 {
4450 errno: 8,
4451 code: 'EALREADY',
4452 description: 'connection already in progress'
4453 },
4454 {
4455 errno: 9,
4456 code: 'EBADF',
4457 description: 'bad file descriptor'
4458 },
4459 {
4460 errno: 10,
4461 code: 'EBUSY',
4462 description: 'resource busy or locked'
4463 },
4464 {
4465 errno: 11,
4466 code: 'ECONNABORTED',
4467 description: 'software caused connection abort'
4468 },
4469 {
4470 errno: 12,
4471 code: 'ECONNREFUSED',
4472 description: 'connection refused'
4473 },
4474 {
4475 errno: 13,
4476 code: 'ECONNRESET',
4477 description: 'connection reset by peer'
4478 },
4479 {
4480 errno: 14,
4481 code: 'EDESTADDRREQ',
4482 description: 'destination address required'
4483 },
4484 {
4485 errno: 15,
4486 code: 'EFAULT',
4487 description: 'bad address in system call argument'
4488 },
4489 {
4490 errno: 16,
4491 code: 'EHOSTUNREACH',
4492 description: 'host is unreachable'
4493 },
4494 {
4495 errno: 17,
4496 code: 'EINTR',
4497 description: 'interrupted system call'
4498 },
4499 {
4500 errno: 18,
4501 code: 'EINVAL',
4502 description: 'invalid argument'
4503 },
4504 {
4505 errno: 19,
4506 code: 'EISCONN',
4507 description: 'socket is already connected'
4508 },
4509 {
4510 errno: 20,
4511 code: 'EMFILE',
4512 description: 'too many open files'
4513 },
4514 {
4515 errno: 21,
4516 code: 'EMSGSIZE',
4517 description: 'message too long'
4518 },
4519 {
4520 errno: 22,
4521 code: 'ENETDOWN',
4522 description: 'network is down'
4523 },
4524 {
4525 errno: 23,
4526 code: 'ENETUNREACH',
4527 description: 'network is unreachable'
4528 },
4529 {
4530 errno: 24,
4531 code: 'ENFILE',
4532 description: 'file table overflow'
4533 },
4534 {
4535 errno: 25,
4536 code: 'ENOBUFS',
4537 description: 'no buffer space available'
4538 },
4539 {
4540 errno: 26,
4541 code: 'ENOMEM',
4542 description: 'not enough memory'
4543 },
4544 {
4545 errno: 27,
4546 code: 'ENOTDIR',
4547 description: 'not a directory'
4548 },
4549 {
4550 errno: 28,
4551 code: 'EISDIR',
4552 description: 'illegal operation on a directory'
4553 },
4554 {
4555 errno: 29,
4556 code: 'ENONET',
4557 description: 'machine is not on the network'
4558 },
4559 {
4560 errno: 31,
4561 code: 'ENOTCONN',
4562 description: 'socket is not connected'
4563 },
4564 {
4565 errno: 32,
4566 code: 'ENOTSOCK',
4567 description: 'socket operation on non-socket'
4568 },
4569 {
4570 errno: 33,
4571 code: 'ENOTSUP',
4572 description: 'operation not supported on socket'
4573 },
4574 {
4575 errno: 34,
4576 code: 'ENOENT',
4577 description: 'no such file or directory'
4578 },
4579 {
4580 errno: 35,
4581 code: 'ENOSYS',
4582 description: 'function not implemented'
4583 },
4584 {
4585 errno: 36,
4586 code: 'EPIPE',
4587 description: 'broken pipe'
4588 },
4589 {
4590 errno: 37,
4591 code: 'EPROTO',
4592 description: 'protocol error'
4593 },
4594 {
4595 errno: 38,
4596 code: 'EPROTONOSUPPORT',
4597 description: 'protocol not supported'
4598 },
4599 {
4600 errno: 39,
4601 code: 'EPROTOTYPE',
4602 description: 'protocol wrong type for socket'
4603 },
4604 {
4605 errno: 40,
4606 code: 'ETIMEDOUT',
4607 description: 'connection timed out'
4608 },
4609 {
4610 errno: 41,
4611 code: 'ECHARSET',
4612 description: 'invalid Unicode character'
4613 },
4614 {
4615 errno: 42,
4616 code: 'EAIFAMNOSUPPORT',
4617 description: 'address family for hostname not supported'
4618 },
4619 {
4620 errno: 44,
4621 code: 'EAISERVICE',
4622 description: 'servname not supported for ai_socktype'
4623 },
4624 {
4625 errno: 45,
4626 code: 'EAISOCKTYPE',
4627 description: 'ai_socktype not supported'
4628 },
4629 {
4630 errno: 46,
4631 code: 'ESHUTDOWN',
4632 description: 'cannot send after transport endpoint shutdown'
4633 },
4634 {
4635 errno: 47,
4636 code: 'EEXIST',
4637 description: 'file already exists'
4638 },
4639 {
4640 errno: 48,
4641 code: 'ESRCH',
4642 description: 'no such process'
4643 },
4644 {
4645 errno: 49,
4646 code: 'ENAMETOOLONG',
4647 description: 'name too long'
4648 },
4649 {
4650 errno: 50,
4651 code: 'EPERM',
4652 description: 'operation not permitted'
4653 },
4654 {
4655 errno: 51,
4656 code: 'ELOOP',
4657 description: 'too many symbolic links encountered'
4658 },
4659 {
4660 errno: 52,
4661 code: 'EXDEV',
4662 description: 'cross-device link not permitted'
4663 },
4664 {
4665 errno: 53,
4666 code: 'ENOTEMPTY',
4667 description: 'directory not empty'
4668 },
4669 {
4670 errno: 54,
4671 code: 'ENOSPC',
4672 description: 'no space left on device'
4673 },
4674 {
4675 errno: 55,
4676 code: 'EIO',
4677 description: 'i/o error'
4678 },
4679 {
4680 errno: 56,
4681 code: 'EROFS',
4682 description: 'read-only file system'
4683 },
4684 {
4685 errno: 57,
4686 code: 'ENODEV',
4687 description: 'no such device'
4688 },
4689 {
4690 errno: 58,
4691 code: 'ESPIPE',
4692 description: 'invalid seek'
4693 },
4694 {
4695 errno: 59,
4696 code: 'ECANCELED',
4697 description: 'operation canceled'
4698 }
4699]
4700
4701module.exports.errno = {}
4702module.exports.code = {}
4703
4704all.forEach(function (error) {
4705 module.exports.errno[error.errno] = error
4706 module.exports.code[error.code] = error
4707})
4708
4709module.exports.custom = _dereq_('./custom')(module.exports)
4710module.exports.create = module.exports.custom.createError
4711
4712},{"./custom":29}],31:[function(_dereq_,module,exports){
4713'use strict';
4714
4715var GetIntrinsic = _dereq_('get-intrinsic');
4716
4717/** @type {import('.')} */
4718var $defineProperty = GetIntrinsic('%Object.defineProperty%', true) || false;
4719if ($defineProperty) {
4720 try {
4721 $defineProperty({}, 'a', { value: 1 });
4722 } catch (e) {
4723 // IE 8 has a broken defineProperty
4724 $defineProperty = false;
4725 }
4726}
4727
4728module.exports = $defineProperty;
4729
4730},{"get-intrinsic":42}],32:[function(_dereq_,module,exports){
4731'use strict';
4732
4733/** @type {import('./eval')} */
4734module.exports = EvalError;
4735
4736},{}],33:[function(_dereq_,module,exports){
4737'use strict';
4738
4739/** @type {import('.')} */
4740module.exports = Error;
4741
4742},{}],34:[function(_dereq_,module,exports){
4743'use strict';
4744
4745/** @type {import('./range')} */
4746module.exports = RangeError;
4747
4748},{}],35:[function(_dereq_,module,exports){
4749'use strict';
4750
4751/** @type {import('./ref')} */
4752module.exports = ReferenceError;
4753
4754},{}],36:[function(_dereq_,module,exports){
4755'use strict';
4756
4757/** @type {import('./syntax')} */
4758module.exports = SyntaxError;
4759
4760},{}],37:[function(_dereq_,module,exports){
4761'use strict';
4762
4763/** @type {import('./type')} */
4764module.exports = TypeError;
4765
4766},{}],38:[function(_dereq_,module,exports){
4767'use strict';
4768
4769/** @type {import('./uri')} */
4770module.exports = URIError;
4771
4772},{}],39:[function(_dereq_,module,exports){
4773// Copyright Joyent, Inc. and other Node contributors.
4774//
4775// Permission is hereby granted, free of charge, to any person obtaining a
4776// copy of this software and associated documentation files (the
4777// "Software"), to deal in the Software without restriction, including
4778// without limitation the rights to use, copy, modify, merge, publish,
4779// distribute, sublicense, and/or sell copies of the Software, and to permit
4780// persons to whom the Software is furnished to do so, subject to the
4781// following conditions:
4782//
4783// The above copyright notice and this permission notice shall be included
4784// in all copies or substantial portions of the Software.
4785//
4786// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4787// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4788// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4789// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4790// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4791// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4792// USE OR OTHER DEALINGS IN THE SOFTWARE.
4793
4794var objectCreate = Object.create || objectCreatePolyfill
4795var objectKeys = Object.keys || objectKeysPolyfill
4796var bind = Function.prototype.bind || functionBindPolyfill
4797
4798function EventEmitter() {
4799 if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
4800 this._events = objectCreate(null);
4801 this._eventsCount = 0;
4802 }
4803
4804 this._maxListeners = this._maxListeners || undefined;
4805}
4806module.exports = EventEmitter;
4807
4808// Backwards-compat with node 0.10.x
4809EventEmitter.EventEmitter = EventEmitter;
4810
4811EventEmitter.prototype._events = undefined;
4812EventEmitter.prototype._maxListeners = undefined;
4813
4814// By default EventEmitters will print a warning if more than 10 listeners are
4815// added to it. This is a useful default which helps finding memory leaks.
4816var defaultMaxListeners = 10;
4817
4818var hasDefineProperty;
4819try {
4820 var o = {};
4821 if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
4822 hasDefineProperty = o.x === 0;
4823} catch (err) { hasDefineProperty = false }
4824if (hasDefineProperty) {
4825 Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
4826 enumerable: true,
4827 get: function() {
4828 return defaultMaxListeners;
4829 },
4830 set: function(arg) {
4831 // check whether the input is a positive number (whose value is zero or
4832 // greater and not a NaN).
4833 if (typeof arg !== 'number' || arg < 0 || arg !== arg)
4834 throw new TypeError('"defaultMaxListeners" must be a positive number');
4835 defaultMaxListeners = arg;
4836 }
4837 });
4838} else {
4839 EventEmitter.defaultMaxListeners = defaultMaxListeners;
4840}
4841
4842// Obviously not all Emitters should be limited to 10. This function allows
4843// that to be increased. Set to zero for unlimited.
4844EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
4845 if (typeof n !== 'number' || n < 0 || isNaN(n))
4846 throw new TypeError('"n" argument must be a positive number');
4847 this._maxListeners = n;
4848 return this;
4849};
4850
4851function $getMaxListeners(that) {
4852 if (that._maxListeners === undefined)
4853 return EventEmitter.defaultMaxListeners;
4854 return that._maxListeners;
4855}
4856
4857EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
4858 return $getMaxListeners(this);
4859};
4860
4861// These standalone emit* functions are used to optimize calling of event
4862// handlers for fast cases because emit() itself often has a variable number of
4863// arguments and can be deoptimized because of that. These functions always have
4864// the same number of arguments and thus do not get deoptimized, so the code
4865// inside them can execute faster.
4866function emitNone(handler, isFn, self) {
4867 if (isFn)
4868 handler.call(self);
4869 else {
4870 var len = handler.length;
4871 var listeners = arrayClone(handler, len);
4872 for (var i = 0; i < len; ++i)
4873 listeners[i].call(self);
4874 }
4875}
4876function emitOne(handler, isFn, self, arg1) {
4877 if (isFn)
4878 handler.call(self, arg1);
4879 else {
4880 var len = handler.length;
4881 var listeners = arrayClone(handler, len);
4882 for (var i = 0; i < len; ++i)
4883 listeners[i].call(self, arg1);
4884 }
4885}
4886function emitTwo(handler, isFn, self, arg1, arg2) {
4887 if (isFn)
4888 handler.call(self, arg1, arg2);
4889 else {
4890 var len = handler.length;
4891 var listeners = arrayClone(handler, len);
4892 for (var i = 0; i < len; ++i)
4893 listeners[i].call(self, arg1, arg2);
4894 }
4895}
4896function emitThree(handler, isFn, self, arg1, arg2, arg3) {
4897 if (isFn)
4898 handler.call(self, arg1, arg2, arg3);
4899 else {
4900 var len = handler.length;
4901 var listeners = arrayClone(handler, len);
4902 for (var i = 0; i < len; ++i)
4903 listeners[i].call(self, arg1, arg2, arg3);
4904 }
4905}
4906
4907function emitMany(handler, isFn, self, args) {
4908 if (isFn)
4909 handler.apply(self, args);
4910 else {
4911 var len = handler.length;
4912 var listeners = arrayClone(handler, len);
4913 for (var i = 0; i < len; ++i)
4914 listeners[i].apply(self, args);
4915 }
4916}
4917
4918EventEmitter.prototype.emit = function emit(type) {
4919 var er, handler, len, args, i, events;
4920 var doError = (type === 'error');
4921
4922 events = this._events;
4923 if (events)
4924 doError = (doError && events.error == null);
4925 else if (!doError)
4926 return false;
4927
4928 // If there is no 'error' event listener then throw.
4929 if (doError) {
4930 if (arguments.length > 1)
4931 er = arguments[1];
4932 if (er instanceof Error) {
4933 throw er; // Unhandled 'error' event
4934 } else {
4935 // At least give some kind of context to the user
4936 var err = new Error('Unhandled "error" event. (' + er + ')');
4937 err.context = er;
4938 throw err;
4939 }
4940 return false;
4941 }
4942
4943 handler = events[type];
4944
4945 if (!handler)
4946 return false;
4947
4948 var isFn = typeof handler === 'function';
4949 len = arguments.length;
4950 switch (len) {
4951 // fast cases
4952 case 1:
4953 emitNone(handler, isFn, this);
4954 break;
4955 case 2:
4956 emitOne(handler, isFn, this, arguments[1]);
4957 break;
4958 case 3:
4959 emitTwo(handler, isFn, this, arguments[1], arguments[2]);
4960 break;
4961 case 4:
4962 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
4963 break;
4964 // slower
4965 default:
4966 args = new Array(len - 1);
4967 for (i = 1; i < len; i++)
4968 args[i - 1] = arguments[i];
4969 emitMany(handler, isFn, this, args);
4970 }
4971
4972 return true;
4973};
4974
4975function _addListener(target, type, listener, prepend) {
4976 var m;
4977 var events;
4978 var existing;
4979
4980 if (typeof listener !== 'function')
4981 throw new TypeError('"listener" argument must be a function');
4982
4983 events = target._events;
4984 if (!events) {
4985 events = target._events = objectCreate(null);
4986 target._eventsCount = 0;
4987 } else {
4988 // To avoid recursion in the case that type === "newListener"! Before
4989 // adding it to the listeners, first emit "newListener".
4990 if (events.newListener) {
4991 target.emit('newListener', type,
4992 listener.listener ? listener.listener : listener);
4993
4994 // Re-assign `events` because a newListener handler could have caused the
4995 // this._events to be assigned to a new object
4996 events = target._events;
4997 }
4998 existing = events[type];
4999 }
5000
5001 if (!existing) {
5002 // Optimize the case of one listener. Don't need the extra array object.
5003 existing = events[type] = listener;
5004 ++target._eventsCount;
5005 } else {
5006 if (typeof existing === 'function') {
5007 // Adding the second element, need to change to array.
5008 existing = events[type] =
5009 prepend ? [listener, existing] : [existing, listener];
5010 } else {
5011 // If we've already got an array, just append.
5012 if (prepend) {
5013 existing.unshift(listener);
5014 } else {
5015 existing.push(listener);
5016 }
5017 }
5018
5019 // Check for listener leak
5020 if (!existing.warned) {
5021 m = $getMaxListeners(target);
5022 if (m && m > 0 && existing.length > m) {
5023 existing.warned = true;
5024 var w = new Error('Possible EventEmitter memory leak detected. ' +
5025 existing.length + ' "' + String(type) + '" listeners ' +
5026 'added. Use emitter.setMaxListeners() to ' +
5027 'increase limit.');
5028 w.name = 'MaxListenersExceededWarning';
5029 w.emitter = target;
5030 w.type = type;
5031 w.count = existing.length;
5032 if (typeof console === 'object' && console.warn) {
5033 console.warn('%s: %s', w.name, w.message);
5034 }
5035 }
5036 }
5037 }
5038
5039 return target;
5040}
5041
5042EventEmitter.prototype.addListener = function addListener(type, listener) {
5043 return _addListener(this, type, listener, false);
5044};
5045
5046EventEmitter.prototype.on = EventEmitter.prototype.addListener;
5047
5048EventEmitter.prototype.prependListener =
5049 function prependListener(type, listener) {
5050 return _addListener(this, type, listener, true);
5051 };
5052
5053function onceWrapper() {
5054 if (!this.fired) {
5055 this.target.removeListener(this.type, this.wrapFn);
5056 this.fired = true;
5057 switch (arguments.length) {
5058 case 0:
5059 return this.listener.call(this.target);
5060 case 1:
5061 return this.listener.call(this.target, arguments[0]);
5062 case 2:
5063 return this.listener.call(this.target, arguments[0], arguments[1]);
5064 case 3:
5065 return this.listener.call(this.target, arguments[0], arguments[1],
5066 arguments[2]);
5067 default:
5068 var args = new Array(arguments.length);
5069 for (var i = 0; i < args.length; ++i)
5070 args[i] = arguments[i];
5071 this.listener.apply(this.target, args);
5072 }
5073 }
5074}
5075
5076function _onceWrap(target, type, listener) {
5077 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
5078 var wrapped = bind.call(onceWrapper, state);
5079 wrapped.listener = listener;
5080 state.wrapFn = wrapped;
5081 return wrapped;
5082}
5083
5084EventEmitter.prototype.once = function once(type, listener) {
5085 if (typeof listener !== 'function')
5086 throw new TypeError('"listener" argument must be a function');
5087 this.on(type, _onceWrap(this, type, listener));
5088 return this;
5089};
5090
5091EventEmitter.prototype.prependOnceListener =
5092 function prependOnceListener(type, listener) {
5093 if (typeof listener !== 'function')
5094 throw new TypeError('"listener" argument must be a function');
5095 this.prependListener(type, _onceWrap(this, type, listener));
5096 return this;
5097 };
5098
5099// Emits a 'removeListener' event if and only if the listener was removed.
5100EventEmitter.prototype.removeListener =
5101 function removeListener(type, listener) {
5102 var list, events, position, i, originalListener;
5103
5104 if (typeof listener !== 'function')
5105 throw new TypeError('"listener" argument must be a function');
5106
5107 events = this._events;
5108 if (!events)
5109 return this;
5110
5111 list = events[type];
5112 if (!list)
5113 return this;
5114
5115 if (list === listener || list.listener === listener) {
5116 if (--this._eventsCount === 0)
5117 this._events = objectCreate(null);
5118 else {
5119 delete events[type];
5120 if (events.removeListener)
5121 this.emit('removeListener', type, list.listener || listener);
5122 }
5123 } else if (typeof list !== 'function') {
5124 position = -1;
5125
5126 for (i = list.length - 1; i >= 0; i--) {
5127 if (list[i] === listener || list[i].listener === listener) {
5128 originalListener = list[i].listener;
5129 position = i;
5130 break;
5131 }
5132 }
5133
5134 if (position < 0)
5135 return this;
5136
5137 if (position === 0)
5138 list.shift();
5139 else
5140 spliceOne(list, position);
5141
5142 if (list.length === 1)
5143 events[type] = list[0];
5144
5145 if (events.removeListener)
5146 this.emit('removeListener', type, originalListener || listener);
5147 }
5148
5149 return this;
5150 };
5151
5152EventEmitter.prototype.removeAllListeners =
5153 function removeAllListeners(type) {
5154 var listeners, events, i;
5155
5156 events = this._events;
5157 if (!events)
5158 return this;
5159
5160 // not listening for removeListener, no need to emit
5161 if (!events.removeListener) {
5162 if (arguments.length === 0) {
5163 this._events = objectCreate(null);
5164 this._eventsCount = 0;
5165 } else if (events[type]) {
5166 if (--this._eventsCount === 0)
5167 this._events = objectCreate(null);
5168 else
5169 delete events[type];
5170 }
5171 return this;
5172 }
5173
5174 // emit removeListener for all listeners on all events
5175 if (arguments.length === 0) {
5176 var keys = objectKeys(events);
5177 var key;
5178 for (i = 0; i < keys.length; ++i) {
5179 key = keys[i];
5180 if (key === 'removeListener') continue;
5181 this.removeAllListeners(key);
5182 }
5183 this.removeAllListeners('removeListener');
5184 this._events = objectCreate(null);
5185 this._eventsCount = 0;
5186 return this;
5187 }
5188
5189 listeners = events[type];
5190
5191 if (typeof listeners === 'function') {
5192 this.removeListener(type, listeners);
5193 } else if (listeners) {
5194 // LIFO order
5195 for (i = listeners.length - 1; i >= 0; i--) {
5196 this.removeListener(type, listeners[i]);
5197 }
5198 }
5199
5200 return this;
5201 };
5202
5203function _listeners(target, type, unwrap) {
5204 var events = target._events;
5205
5206 if (!events)
5207 return [];
5208
5209 var evlistener = events[type];
5210 if (!evlistener)
5211 return [];
5212
5213 if (typeof evlistener === 'function')
5214 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
5215
5216 return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
5217}
5218
5219EventEmitter.prototype.listeners = function listeners(type) {
5220 return _listeners(this, type, true);
5221};
5222
5223EventEmitter.prototype.rawListeners = function rawListeners(type) {
5224 return _listeners(this, type, false);
5225};
5226
5227EventEmitter.listenerCount = function(emitter, type) {
5228 if (typeof emitter.listenerCount === 'function') {
5229 return emitter.listenerCount(type);
5230 } else {
5231 return listenerCount.call(emitter, type);
5232 }
5233};
5234
5235EventEmitter.prototype.listenerCount = listenerCount;
5236function listenerCount(type) {
5237 var events = this._events;
5238
5239 if (events) {
5240 var evlistener = events[type];
5241
5242 if (typeof evlistener === 'function') {
5243 return 1;
5244 } else if (evlistener) {
5245 return evlistener.length;
5246 }
5247 }
5248
5249 return 0;
5250}
5251
5252EventEmitter.prototype.eventNames = function eventNames() {
5253 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
5254};
5255
5256// About 1.5x faster than the two-arg version of Array#splice().
5257function spliceOne(list, index) {
5258 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
5259 list[i] = list[k];
5260 list.pop();
5261}
5262
5263function arrayClone(arr, n) {
5264 var copy = new Array(n);
5265 for (var i = 0; i < n; ++i)
5266 copy[i] = arr[i];
5267 return copy;
5268}
5269
5270function unwrapListeners(arr) {
5271 var ret = new Array(arr.length);
5272 for (var i = 0; i < ret.length; ++i) {
5273 ret[i] = arr[i].listener || arr[i];
5274 }
5275 return ret;
5276}
5277
5278function objectCreatePolyfill(proto) {
5279 var F = function() {};
5280 F.prototype = proto;
5281 return new F;
5282}
5283function objectKeysPolyfill(obj) {
5284 var keys = [];
5285 for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
5286 keys.push(k);
5287 }
5288 return k;
5289}
5290function functionBindPolyfill(context) {
5291 var fn = this;
5292 return function () {
5293 return fn.apply(context, arguments);
5294 };
5295}
5296
5297},{}],40:[function(_dereq_,module,exports){
5298'use strict';
5299
5300/* eslint no-invalid-this: 1 */
5301
5302var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
5303var toStr = Object.prototype.toString;
5304var max = Math.max;
5305var funcType = '[object Function]';
5306
5307var concatty = function concatty(a, b) {
5308 var arr = [];
5309
5310 for (var i = 0; i < a.length; i += 1) {
5311 arr[i] = a[i];
5312 }
5313 for (var j = 0; j < b.length; j += 1) {
5314 arr[j + a.length] = b[j];
5315 }
5316
5317 return arr;
5318};
5319
5320var slicy = function slicy(arrLike, offset) {
5321 var arr = [];
5322 for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
5323 arr[j] = arrLike[i];
5324 }
5325 return arr;
5326};
5327
5328var joiny = function (arr, joiner) {
5329 var str = '';
5330 for (var i = 0; i < arr.length; i += 1) {
5331 str += arr[i];
5332 if (i + 1 < arr.length) {
5333 str += joiner;
5334 }
5335 }
5336 return str;
5337};
5338
5339module.exports = function bind(that) {
5340 var target = this;
5341 if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
5342 throw new TypeError(ERROR_MESSAGE + target);
5343 }
5344 var args = slicy(arguments, 1);
5345
5346 var bound;
5347 var binder = function () {
5348 if (this instanceof bound) {
5349 var result = target.apply(
5350 this,
5351 concatty(args, arguments)
5352 );
5353 if (Object(result) === result) {
5354 return result;
5355 }
5356 return this;
5357 }
5358 return target.apply(
5359 that,
5360 concatty(args, arguments)
5361 );
5362
5363 };
5364
5365 var boundLength = max(0, target.length - args.length);
5366 var boundArgs = [];
5367 for (var i = 0; i < boundLength; i++) {
5368 boundArgs[i] = '$' + i;
5369 }
5370
5371 bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);
5372
5373 if (target.prototype) {
5374 var Empty = function Empty() {};
5375 Empty.prototype = target.prototype;
5376 bound.prototype = new Empty();
5377 Empty.prototype = null;
5378 }
5379
5380 return bound;
5381};
5382
5383},{}],41:[function(_dereq_,module,exports){
5384'use strict';
5385
5386var implementation = _dereq_('./implementation');
5387
5388module.exports = Function.prototype.bind || implementation;
5389
5390},{"./implementation":40}],42:[function(_dereq_,module,exports){
5391'use strict';
5392
5393var undefined;
5394
5395var $Error = _dereq_('es-errors');
5396var $EvalError = _dereq_('es-errors/eval');
5397var $RangeError = _dereq_('es-errors/range');
5398var $ReferenceError = _dereq_('es-errors/ref');
5399var $SyntaxError = _dereq_('es-errors/syntax');
5400var $TypeError = _dereq_('es-errors/type');
5401var $URIError = _dereq_('es-errors/uri');
5402
5403var $Function = Function;
5404
5405// eslint-disable-next-line consistent-return
5406var getEvalledConstructor = function (expressionSyntax) {
5407 try {
5408 return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
5409 } catch (e) {}
5410};
5411
5412var $gOPD = Object.getOwnPropertyDescriptor;
5413if ($gOPD) {
5414 try {
5415 $gOPD({}, '');
5416 } catch (e) {
5417 $gOPD = null; // this is IE 8, which has a broken gOPD
5418 }
5419}
5420
5421var throwTypeError = function () {
5422 throw new $TypeError();
5423};
5424var ThrowTypeError = $gOPD
5425 ? (function () {
5426 try {
5427 // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
5428 arguments.callee; // IE 8 does not throw here
5429 return throwTypeError;
5430 } catch (calleeThrows) {
5431 try {
5432 // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
5433 return $gOPD(arguments, 'callee').get;
5434 } catch (gOPDthrows) {
5435 return throwTypeError;
5436 }
5437 }
5438 }())
5439 : throwTypeError;
5440
5441var hasSymbols = _dereq_('has-symbols')();
5442var hasProto = _dereq_('has-proto')();
5443
5444var getProto = Object.getPrototypeOf || (
5445 hasProto
5446 ? function (x) { return x.__proto__; } // eslint-disable-line no-proto
5447 : null
5448);
5449
5450var needsEval = {};
5451
5452var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array);
5453
5454var INTRINSICS = {
5455 __proto__: null,
5456 '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
5457 '%Array%': Array,
5458 '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
5459 '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined,
5460 '%AsyncFromSyncIteratorPrototype%': undefined,
5461 '%AsyncFunction%': needsEval,
5462 '%AsyncGenerator%': needsEval,
5463 '%AsyncGeneratorFunction%': needsEval,
5464 '%AsyncIteratorPrototype%': needsEval,
5465 '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
5466 '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
5467 '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array,
5468 '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array,
5469 '%Boolean%': Boolean,
5470 '%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
5471 '%Date%': Date,
5472 '%decodeURI%': decodeURI,
5473 '%decodeURIComponent%': decodeURIComponent,
5474 '%encodeURI%': encodeURI,
5475 '%encodeURIComponent%': encodeURIComponent,
5476 '%Error%': $Error,
5477 '%eval%': eval, // eslint-disable-line no-eval
5478 '%EvalError%': $EvalError,
5479 '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
5480 '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
5481 '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
5482 '%Function%': $Function,
5483 '%GeneratorFunction%': needsEval,
5484 '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
5485 '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
5486 '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
5487 '%isFinite%': isFinite,
5488 '%isNaN%': isNaN,
5489 '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined,
5490 '%JSON%': typeof JSON === 'object' ? JSON : undefined,
5491 '%Map%': typeof Map === 'undefined' ? undefined : Map,
5492 '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()),
5493 '%Math%': Math,
5494 '%Number%': Number,
5495 '%Object%': Object,
5496 '%parseFloat%': parseFloat,
5497 '%parseInt%': parseInt,
5498 '%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
5499 '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
5500 '%RangeError%': $RangeError,
5501 '%ReferenceError%': $ReferenceError,
5502 '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
5503 '%RegExp%': RegExp,
5504 '%Set%': typeof Set === 'undefined' ? undefined : Set,
5505 '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()),
5506 '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
5507 '%String%': String,
5508 '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined,
5509 '%Symbol%': hasSymbols ? Symbol : undefined,
5510 '%SyntaxError%': $SyntaxError,
5511 '%ThrowTypeError%': ThrowTypeError,
5512 '%TypedArray%': TypedArray,
5513 '%TypeError%': $TypeError,
5514 '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
5515 '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
5516 '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
5517 '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
5518 '%URIError%': $URIError,
5519 '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
5520 '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
5521 '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
5522};
5523
5524if (getProto) {
5525 try {
5526 null.error; // eslint-disable-line no-unused-expressions
5527 } catch (e) {
5528 // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
5529 var errorProto = getProto(getProto(e));
5530 INTRINSICS['%Error.prototype%'] = errorProto;
5531 }
5532}
5533
5534var doEval = function doEval(name) {
5535 var value;
5536 if (name === '%AsyncFunction%') {
5537 value = getEvalledConstructor('async function () {}');
5538 } else if (name === '%GeneratorFunction%') {
5539 value = getEvalledConstructor('function* () {}');
5540 } else if (name === '%AsyncGeneratorFunction%') {
5541 value = getEvalledConstructor('async function* () {}');
5542 } else if (name === '%AsyncGenerator%') {
5543 var fn = doEval('%AsyncGeneratorFunction%');
5544 if (fn) {
5545 value = fn.prototype;
5546 }
5547 } else if (name === '%AsyncIteratorPrototype%') {
5548 var gen = doEval('%AsyncGenerator%');
5549 if (gen && getProto) {
5550 value = getProto(gen.prototype);
5551 }
5552 }
5553
5554 INTRINSICS[name] = value;
5555
5556 return value;
5557};
5558
5559var LEGACY_ALIASES = {
5560 __proto__: null,
5561 '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
5562 '%ArrayPrototype%': ['Array', 'prototype'],
5563 '%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
5564 '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
5565 '%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
5566 '%ArrayProto_values%': ['Array', 'prototype', 'values'],
5567 '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
5568 '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
5569 '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
5570 '%BooleanPrototype%': ['Boolean', 'prototype'],
5571 '%DataViewPrototype%': ['DataView', 'prototype'],
5572 '%DatePrototype%': ['Date', 'prototype'],
5573 '%ErrorPrototype%': ['Error', 'prototype'],
5574 '%EvalErrorPrototype%': ['EvalError', 'prototype'],
5575 '%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
5576 '%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
5577 '%FunctionPrototype%': ['Function', 'prototype'],
5578 '%Generator%': ['GeneratorFunction', 'prototype'],
5579 '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
5580 '%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
5581 '%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
5582 '%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
5583 '%JSONParse%': ['JSON', 'parse'],
5584 '%JSONStringify%': ['JSON', 'stringify'],
5585 '%MapPrototype%': ['Map', 'prototype'],
5586 '%NumberPrototype%': ['Number', 'prototype'],
5587 '%ObjectPrototype%': ['Object', 'prototype'],
5588 '%ObjProto_toString%': ['Object', 'prototype', 'toString'],
5589 '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
5590 '%PromisePrototype%': ['Promise', 'prototype'],
5591 '%PromiseProto_then%': ['Promise', 'prototype', 'then'],
5592 '%Promise_all%': ['Promise', 'all'],
5593 '%Promise_reject%': ['Promise', 'reject'],
5594 '%Promise_resolve%': ['Promise', 'resolve'],
5595 '%RangeErrorPrototype%': ['RangeError', 'prototype'],
5596 '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
5597 '%RegExpPrototype%': ['RegExp', 'prototype'],
5598 '%SetPrototype%': ['Set', 'prototype'],
5599 '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
5600 '%StringPrototype%': ['String', 'prototype'],
5601 '%SymbolPrototype%': ['Symbol', 'prototype'],
5602 '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
5603 '%TypedArrayPrototype%': ['TypedArray', 'prototype'],
5604 '%TypeErrorPrototype%': ['TypeError', 'prototype'],
5605 '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
5606 '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
5607 '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
5608 '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
5609 '%URIErrorPrototype%': ['URIError', 'prototype'],
5610 '%WeakMapPrototype%': ['WeakMap', 'prototype'],
5611 '%WeakSetPrototype%': ['WeakSet', 'prototype']
5612};
5613
5614var bind = _dereq_('function-bind');
5615var hasOwn = _dereq_('hasown');
5616var $concat = bind.call(Function.call, Array.prototype.concat);
5617var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
5618var $replace = bind.call(Function.call, String.prototype.replace);
5619var $strSlice = bind.call(Function.call, String.prototype.slice);
5620var $exec = bind.call(Function.call, RegExp.prototype.exec);
5621
5622/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
5623var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
5624var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
5625var stringToPath = function stringToPath(string) {
5626 var first = $strSlice(string, 0, 1);
5627 var last = $strSlice(string, -1);
5628 if (first === '%' && last !== '%') {
5629 throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
5630 } else if (last === '%' && first !== '%') {
5631 throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
5632 }
5633 var result = [];
5634 $replace(string, rePropName, function (match, number, quote, subString) {
5635 result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
5636 });
5637 return result;
5638};
5639/* end adaptation */
5640
5641var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
5642 var intrinsicName = name;
5643 var alias;
5644 if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
5645 alias = LEGACY_ALIASES[intrinsicName];
5646 intrinsicName = '%' + alias[0] + '%';
5647 }
5648
5649 if (hasOwn(INTRINSICS, intrinsicName)) {
5650 var value = INTRINSICS[intrinsicName];
5651 if (value === needsEval) {
5652 value = doEval(intrinsicName);
5653 }
5654 if (typeof value === 'undefined' && !allowMissing) {
5655 throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
5656 }
5657
5658 return {
5659 alias: alias,
5660 name: intrinsicName,
5661 value: value
5662 };
5663 }
5664
5665 throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
5666};
5667
5668module.exports = function GetIntrinsic(name, allowMissing) {
5669 if (typeof name !== 'string' || name.length === 0) {
5670 throw new $TypeError('intrinsic name must be a non-empty string');
5671 }
5672 if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
5673 throw new $TypeError('"allowMissing" argument must be a boolean');
5674 }
5675
5676 if ($exec(/^%?[^%]*%?$/, name) === null) {
5677 throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
5678 }
5679 var parts = stringToPath(name);
5680 var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
5681
5682 var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
5683 var intrinsicRealName = intrinsic.name;
5684 var value = intrinsic.value;
5685 var skipFurtherCaching = false;
5686
5687 var alias = intrinsic.alias;
5688 if (alias) {
5689 intrinsicBaseName = alias[0];
5690 $spliceApply(parts, $concat([0, 1], alias));
5691 }
5692
5693 for (var i = 1, isOwn = true; i < parts.length; i += 1) {
5694 var part = parts[i];
5695 var first = $strSlice(part, 0, 1);
5696 var last = $strSlice(part, -1);
5697 if (
5698 (
5699 (first === '"' || first === "'" || first === '`')
5700 || (last === '"' || last === "'" || last === '`')
5701 )
5702 && first !== last
5703 ) {
5704 throw new $SyntaxError('property names with quotes must have matching quotes');
5705 }
5706 if (part === 'constructor' || !isOwn) {
5707 skipFurtherCaching = true;
5708 }
5709
5710 intrinsicBaseName += '.' + part;
5711 intrinsicRealName = '%' + intrinsicBaseName + '%';
5712
5713 if (hasOwn(INTRINSICS, intrinsicRealName)) {
5714 value = INTRINSICS[intrinsicRealName];
5715 } else if (value != null) {
5716 if (!(part in value)) {
5717 if (!allowMissing) {
5718 throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
5719 }
5720 return void undefined;
5721 }
5722 if ($gOPD && (i + 1) >= parts.length) {
5723 var desc = $gOPD(value, part);
5724 isOwn = !!desc;
5725
5726 // By convention, when a data property is converted to an accessor
5727 // property to emulate a data property that does not suffer from
5728 // the override mistake, that accessor's getter is marked with
5729 // an `originalValue` property. Here, when we detect this, we
5730 // uphold the illusion by pretending to see that original data
5731 // property, i.e., returning the value rather than the getter
5732 // itself.
5733 if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
5734 value = desc.get;
5735 } else {
5736 value = value[part];
5737 }
5738 } else {
5739 isOwn = hasOwn(value, part);
5740 value = value[part];
5741 }
5742
5743 if (isOwn && !skipFurtherCaching) {
5744 INTRINSICS[intrinsicRealName] = value;
5745 }
5746 }
5747 }
5748 return value;
5749};
5750
5751},{"es-errors":33,"es-errors/eval":32,"es-errors/range":34,"es-errors/ref":35,"es-errors/syntax":36,"es-errors/type":37,"es-errors/uri":38,"function-bind":41,"has-proto":46,"has-symbols":47,"hasown":49}],43:[function(_dereq_,module,exports){
5752'use strict';
5753
5754var GetIntrinsic = _dereq_('get-intrinsic');
5755
5756var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);
5757
5758if ($gOPD) {
5759 try {
5760 $gOPD([], 'length');
5761 } catch (e) {
5762 // IE 8 has a broken gOPD
5763 $gOPD = null;
5764 }
5765}
5766
5767module.exports = $gOPD;
5768
5769},{"get-intrinsic":42}],44:[function(_dereq_,module,exports){
5770/**
5771 * # hasLocalStorage()
5772 *
5773 * returns `true` or `false` depending on whether localStorage is supported or not.
5774 * Beware that some browsers like Safari do not support localStorage in private mode.
5775 *
5776 * inspired by this cappuccino commit
5777 * https://github.com/cappuccino/cappuccino/commit/063b05d9643c35b303568a28809e4eb3224f71ec
5778 *
5779 * @returns {Boolean}
5780 */
5781function hasLocalStorage() {
5782 try {
5783
5784 // we've to put this in here. I've seen Firefox throwing `Security error: 1000`
5785 // when cookies have been disabled
5786 if (typeof localStorage === 'undefined') {
5787 return false;
5788 }
5789
5790 // Just because localStorage exists does not mean it works. In particular it might be disabled
5791 // as it is when Safari's private browsing mode is active.
5792 localStorage.setItem('Storage-Test', '1');
5793
5794 // that should not happen ...
5795 if (localStorage.getItem('Storage-Test') !== '1') {
5796 return false;
5797 }
5798
5799 // okay, let's clean up if we got here.
5800 localStorage.removeItem('Storage-Test');
5801 } catch (_error) {
5802
5803 // in case of an error, like Safari's Private Mode, return false
5804 return false;
5805 }
5806
5807 // we're good.
5808 return true;
5809}
5810
5811
5812if (typeof exports === 'object') {
5813 module.exports = hasLocalStorage;
5814}
5815
5816},{}],45:[function(_dereq_,module,exports){
5817'use strict';
5818
5819var $defineProperty = _dereq_('es-define-property');
5820
5821var hasPropertyDescriptors = function hasPropertyDescriptors() {
5822 return !!$defineProperty;
5823};
5824
5825hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() {
5826 // node v0.6 has a bug where array lengths can be Set but not Defined
5827 if (!$defineProperty) {
5828 return null;
5829 }
5830 try {
5831 return $defineProperty([], 'length', { value: 1 }).length !== 1;
5832 } catch (e) {
5833 // In Firefox 4-22, defining length on an array throws an exception.
5834 return true;
5835 }
5836};
5837
5838module.exports = hasPropertyDescriptors;
5839
5840},{"es-define-property":31}],46:[function(_dereq_,module,exports){
5841'use strict';
5842
5843var test = {
5844 __proto__: null,
5845 foo: {}
5846};
5847
5848var $Object = Object;
5849
5850/** @type {import('.')} */
5851module.exports = function hasProto() {
5852 // @ts-expect-error: TS errors on an inherited property for some reason
5853 return { __proto__: test }.foo === test.foo
5854 && !(test instanceof $Object);
5855};
5856
5857},{}],47:[function(_dereq_,module,exports){
5858'use strict';
5859
5860var origSymbol = typeof Symbol !== 'undefined' && Symbol;
5861var hasSymbolSham = _dereq_('./shams');
5862
5863module.exports = function hasNativeSymbols() {
5864 if (typeof origSymbol !== 'function') { return false; }
5865 if (typeof Symbol !== 'function') { return false; }
5866 if (typeof origSymbol('foo') !== 'symbol') { return false; }
5867 if (typeof Symbol('bar') !== 'symbol') { return false; }
5868
5869 return hasSymbolSham();
5870};
5871
5872},{"./shams":48}],48:[function(_dereq_,module,exports){
5873'use strict';
5874
5875/* eslint complexity: [2, 18], max-statements: [2, 33] */
5876module.exports = function hasSymbols() {
5877 if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
5878 if (typeof Symbol.iterator === 'symbol') { return true; }
5879
5880 var obj = {};
5881 var sym = Symbol('test');
5882 var symObj = Object(sym);
5883 if (typeof sym === 'string') { return false; }
5884
5885 if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
5886 if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
5887
5888 // temp disabled per https://github.com/ljharb/object.assign/issues/17
5889 // if (sym instanceof Symbol) { return false; }
5890 // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
5891 // if (!(symObj instanceof Symbol)) { return false; }
5892
5893 // if (typeof Symbol.prototype.toString !== 'function') { return false; }
5894 // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
5895
5896 var symVal = 42;
5897 obj[sym] = symVal;
5898 for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
5899 if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
5900
5901 if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
5902
5903 var syms = Object.getOwnPropertySymbols(obj);
5904 if (syms.length !== 1 || syms[0] !== sym) { return false; }
5905
5906 if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
5907
5908 if (typeof Object.getOwnPropertyDescriptor === 'function') {
5909 var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
5910 if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
5911 }
5912
5913 return true;
5914};
5915
5916},{}],49:[function(_dereq_,module,exports){
5917'use strict';
5918
5919var call = Function.prototype.call;
5920var $hasOwn = Object.prototype.hasOwnProperty;
5921var bind = _dereq_('function-bind');
5922
5923/** @type {import('.')} */
5924module.exports = bind.call(call, $hasOwn);
5925
5926},{"function-bind":41}],50:[function(_dereq_,module,exports){
5927(function (global){(function (){
5928var exports = module.exports = {};
5929var localStorageMemory = _dereq_('localstorage-memory');
5930exports.hasLocalStorage = _dereq_('has-localstorage');
5931
5932/**
5933 * returns localStorage-compatible API, either backed by window.localStorage
5934 * or memory if it's not available or not persistent.
5935 *
5936 * It also adds an object API (`.getObject(key)`,
5937 * `.setObject(key, properties)`) and a `isPresistent` property
5938 *
5939 * @returns {Object}
5940 */
5941exports.create = function () {
5942 var api;
5943
5944 if (!exports.hasLocalStorage()) {
5945 api = localStorageMemory;
5946 api.isPersistent = false;
5947 } else {
5948 api = global.localStorage;
5949 api = {
5950 get length() { return global.localStorage.length; },
5951 getItem: global.localStorage.getItem.bind(global.localStorage),
5952 setItem: global.localStorage.setItem.bind(global.localStorage),
5953 removeItem: global.localStorage.removeItem.bind(global.localStorage),
5954 key: global.localStorage.key.bind(global.localStorage),
5955 clear: global.localStorage.clear.bind(global.localStorage),
5956 };
5957
5958 api.isPersistent = true;
5959 }
5960
5961 api.getObject = exports.getObject.bind(null, api);
5962 api.setObject = exports.setObject.bind(null, api);
5963
5964 return api;
5965};
5966
5967/**
5968 * sets key to passed Object.
5969 *
5970 * @returns undefined
5971 */
5972exports.setObject = function (store, key, object) {
5973 if (typeof object !== 'object') {
5974 return store.setItem(key, object);
5975 }
5976
5977 return store.setItem(key, JSON.stringify(object));
5978};
5979
5980/**
5981 * returns Object for key, or null
5982 *
5983 * @returns {Object|null}
5984 */
5985exports.getObject = function (store, key) {
5986 var item = store.getItem(key);
5987
5988 if (!item) {
5989 return null;
5990 }
5991
5992 try {
5993 return JSON.parse(item);
5994 } catch (e) {
5995 return item;
5996 }
5997};
5998
5999}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
6000},{"has-localstorage":44,"localstorage-memory":86}],51:[function(_dereq_,module,exports){
6001var api = _dereq_('./api');
6002module.exports = api.create();
6003
6004},{"./api":50}],52:[function(_dereq_,module,exports){
6005/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
6006exports.read = function (buffer, offset, isLE, mLen, nBytes) {
6007 var e, m
6008 var eLen = (nBytes * 8) - mLen - 1
6009 var eMax = (1 << eLen) - 1
6010 var eBias = eMax >> 1
6011 var nBits = -7
6012 var i = isLE ? (nBytes - 1) : 0
6013 var d = isLE ? -1 : 1
6014 var s = buffer[offset + i]
6015
6016 i += d
6017
6018 e = s & ((1 << (-nBits)) - 1)
6019 s >>= (-nBits)
6020 nBits += eLen
6021 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
6022
6023 m = e & ((1 << (-nBits)) - 1)
6024 e >>= (-nBits)
6025 nBits += mLen
6026 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
6027
6028 if (e === 0) {
6029 e = 1 - eBias
6030 } else if (e === eMax) {
6031 return m ? NaN : ((s ? -1 : 1) * Infinity)
6032 } else {
6033 m = m + Math.pow(2, mLen)
6034 e = e - eBias
6035 }
6036 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
6037}
6038
6039exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
6040 var e, m, c
6041 var eLen = (nBytes * 8) - mLen - 1
6042 var eMax = (1 << eLen) - 1
6043 var eBias = eMax >> 1
6044 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
6045 var i = isLE ? 0 : (nBytes - 1)
6046 var d = isLE ? 1 : -1
6047 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
6048
6049 value = Math.abs(value)
6050
6051 if (isNaN(value) || value === Infinity) {
6052 m = isNaN(value) ? 1 : 0
6053 e = eMax
6054 } else {
6055 e = Math.floor(Math.log(value) / Math.LN2)
6056 if (value * (c = Math.pow(2, -e)) < 1) {
6057 e--
6058 c *= 2
6059 }
6060 if (e + eBias >= 1) {
6061 value += rt / c
6062 } else {
6063 value += rt * Math.pow(2, 1 - eBias)
6064 }
6065 if (value * c >= 2) {
6066 e++
6067 c /= 2
6068 }
6069
6070 if (e + eBias >= eMax) {
6071 m = 0
6072 e = eMax
6073 } else if (e + eBias >= 1) {
6074 m = ((value * c) - 1) * Math.pow(2, mLen)
6075 e = e + eBias
6076 } else {
6077 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
6078 e = 0
6079 }
6080 }
6081
6082 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
6083
6084 e = (e << mLen) | m
6085 eLen += mLen
6086 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
6087
6088 buffer[offset + i - d] |= s * 128
6089}
6090
6091},{}],53:[function(_dereq_,module,exports){
6092if (typeof Object.create === 'function') {
6093 // implementation from standard node.js 'util' module
6094 module.exports = function inherits(ctor, superCtor) {
6095 if (superCtor) {
6096 ctor.super_ = superCtor
6097 ctor.prototype = Object.create(superCtor.prototype, {
6098 constructor: {
6099 value: ctor,
6100 enumerable: false,
6101 writable: true,
6102 configurable: true
6103 }
6104 })
6105 }
6106 };
6107} else {
6108 // old school shim for old browsers
6109 module.exports = function inherits(ctor, superCtor) {
6110 if (superCtor) {
6111 ctor.super_ = superCtor
6112 var TempCtor = function () {}
6113 TempCtor.prototype = superCtor.prototype
6114 ctor.prototype = new TempCtor()
6115 ctor.prototype.constructor = ctor
6116 }
6117 }
6118}
6119
6120},{}],54:[function(_dereq_,module,exports){
6121/*!
6122 * Determine if an object is a Buffer
6123 *
6124 * @author Feross Aboukhadijeh <https://feross.org>
6125 * @license MIT
6126 */
6127
6128// The _isBuffer check is for Safari 5-7 support, because it's missing
6129// Object.prototype.constructor. Remove this eventually
6130module.exports = function (obj) {
6131 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
6132}
6133
6134function isBuffer (obj) {
6135 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
6136}
6137
6138// For Node v0.10 support. Remove this eventually.
6139function isSlowBuffer (obj) {
6140 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
6141}
6142
6143},{}],55:[function(_dereq_,module,exports){
6144module.exports = Array.isArray || function (arr) {
6145 return Object.prototype.toString.call(arr) == '[object Array]';
6146};
6147
6148},{}],56:[function(_dereq_,module,exports){
6149var encodings = _dereq_('./lib/encodings')
6150
6151module.exports = Codec
6152
6153function Codec (opts) {
6154 if (!(this instanceof Codec)) {
6155 return new Codec(opts)
6156 }
6157 this.opts = opts || {}
6158 this.encodings = encodings
6159}
6160
6161Codec.prototype._encoding = function (encoding) {
6162 if (typeof encoding === 'string') encoding = encodings[encoding]
6163 if (!encoding) encoding = encodings.id
6164 return encoding
6165}
6166
6167Codec.prototype._keyEncoding = function (opts, batchOpts) {
6168 return this._encoding((batchOpts && batchOpts.keyEncoding) ||
6169 (opts && opts.keyEncoding) ||
6170 this.opts.keyEncoding)
6171}
6172
6173Codec.prototype._valueEncoding = function (opts, batchOpts) {
6174 return this._encoding((batchOpts && (batchOpts.valueEncoding || batchOpts.encoding)) ||
6175 (opts && (opts.valueEncoding || opts.encoding)) ||
6176 (this.opts.valueEncoding || this.opts.encoding))
6177}
6178
6179Codec.prototype.encodeKey = function (key, opts, batchOpts) {
6180 return this._keyEncoding(opts, batchOpts).encode(key)
6181}
6182
6183Codec.prototype.encodeValue = function (value, opts, batchOpts) {
6184 return this._valueEncoding(opts, batchOpts).encode(value)
6185}
6186
6187Codec.prototype.decodeKey = function (key, opts) {
6188 return this._keyEncoding(opts).decode(key)
6189}
6190
6191Codec.prototype.decodeValue = function (value, opts) {
6192 return this._valueEncoding(opts).decode(value)
6193}
6194
6195Codec.prototype.encodeBatch = function (ops, opts) {
6196 var self = this
6197
6198 return ops.map(function (_op) {
6199 var op = {
6200 type: _op.type,
6201 key: self.encodeKey(_op.key, opts, _op)
6202 }
6203 if (self.keyAsBuffer(opts, _op)) op.keyEncoding = 'binary'
6204 if (_op.prefix) op.prefix = _op.prefix
6205 if ('value' in _op) {
6206 op.value = self.encodeValue(_op.value, opts, _op)
6207 if (self.valueAsBuffer(opts, _op)) op.valueEncoding = 'binary'
6208 }
6209 return op
6210 })
6211}
6212
6213var ltgtKeys = ['lt', 'gt', 'lte', 'gte', 'start', 'end']
6214
6215Codec.prototype.encodeLtgt = function (ltgt) {
6216 var self = this
6217 var ret = {}
6218 Object.keys(ltgt).forEach(function (key) {
6219 ret[key] = ltgtKeys.indexOf(key) > -1
6220 ? self.encodeKey(ltgt[key], ltgt)
6221 : ltgt[key]
6222 })
6223 return ret
6224}
6225
6226Codec.prototype.createStreamDecoder = function (opts) {
6227 var self = this
6228
6229 if (opts.keys && opts.values) {
6230 return function (key, value) {
6231 return {
6232 key: self.decodeKey(key, opts),
6233 value: self.decodeValue(value, opts)
6234 }
6235 }
6236 } else if (opts.keys) {
6237 return function (key) {
6238 return self.decodeKey(key, opts)
6239 }
6240 } else if (opts.values) {
6241 return function (_, value) {
6242 return self.decodeValue(value, opts)
6243 }
6244 } else {
6245 return function () {}
6246 }
6247}
6248
6249Codec.prototype.keyAsBuffer = function (opts) {
6250 return this._keyEncoding(opts).buffer
6251}
6252
6253Codec.prototype.valueAsBuffer = function (opts) {
6254 return this._valueEncoding(opts).buffer
6255}
6256
6257},{"./lib/encodings":57}],57:[function(_dereq_,module,exports){
6258var Buffer = _dereq_('buffer').Buffer
6259
6260exports.utf8 = exports['utf-8'] = {
6261 encode: function (data) {
6262 return isBinary(data) ? data : String(data)
6263 },
6264 decode: identity,
6265 buffer: false,
6266 type: 'utf8'
6267}
6268
6269exports.json = {
6270 encode: JSON.stringify,
6271 decode: JSON.parse,
6272 buffer: false,
6273 type: 'json'
6274}
6275
6276exports.binary = {
6277 encode: function (data) {
6278 return isBinary(data) ? data : Buffer.from(data)
6279 },
6280 decode: identity,
6281 buffer: true,
6282 type: 'binary'
6283}
6284
6285exports.none = {
6286 encode: identity,
6287 decode: identity,
6288 buffer: false,
6289 type: 'id'
6290}
6291
6292exports.id = exports.none
6293
6294var bufferEncodings = [
6295 'hex',
6296 'ascii',
6297 'base64',
6298 'ucs2',
6299 'ucs-2',
6300 'utf16le',
6301 'utf-16le'
6302]
6303
6304bufferEncodings.forEach(function (type) {
6305 exports[type] = {
6306 encode: function (data) {
6307 return isBinary(data) ? data : Buffer.from(data, type)
6308 },
6309 decode: function (buffer) {
6310 return buffer.toString(type)
6311 },
6312 buffer: true,
6313 type: type
6314 }
6315})
6316
6317function identity (value) {
6318 return value
6319}
6320
6321function isBinary (data) {
6322 return data === undefined || data === null || Buffer.isBuffer(data)
6323}
6324
6325},{"buffer":9}],58:[function(_dereq_,module,exports){
6326var createError = _dereq_('errno').create
6327var LevelUPError = createError('LevelUPError')
6328var NotFoundError = createError('NotFoundError', LevelUPError)
6329
6330NotFoundError.prototype.notFound = true
6331NotFoundError.prototype.status = 404
6332
6333module.exports = {
6334 LevelUPError: LevelUPError,
6335 InitializationError: createError('InitializationError', LevelUPError),
6336 OpenError: createError('OpenError', LevelUPError),
6337 ReadError: createError('ReadError', LevelUPError),
6338 WriteError: createError('WriteError', LevelUPError),
6339 NotFoundError: NotFoundError,
6340 EncodingError: createError('EncodingError', LevelUPError)
6341}
6342
6343},{"errno":30}],59:[function(_dereq_,module,exports){
6344var inherits = _dereq_('inherits')
6345var Readable = _dereq_('readable-stream').Readable
6346var extend = _dereq_('xtend')
6347
6348module.exports = ReadStream
6349inherits(ReadStream, Readable)
6350
6351function ReadStream (iterator, options) {
6352 if (!(this instanceof ReadStream)) return new ReadStream(iterator, options)
6353 options = options || {}
6354 Readable.call(this, extend(options, {
6355 objectMode: true
6356 }))
6357 this._iterator = iterator
6358 this._options = options
6359 this.on('end', this.destroy.bind(this, null, null))
6360}
6361
6362ReadStream.prototype._read = function () {
6363 var self = this
6364 var options = this._options
6365 if (this.destroyed) return
6366
6367 this._iterator.next(function (err, key, value) {
6368 if (self.destroyed) return
6369 if (err) return self.destroy(err)
6370
6371 if (key === undefined && value === undefined) {
6372 self.push(null)
6373 } else if (options.keys !== false && options.values === false) {
6374 self.push(key)
6375 } else if (options.keys === false && options.values !== false) {
6376 self.push(value)
6377 } else {
6378 self.push({ key: key, value: value })
6379 }
6380 })
6381}
6382
6383ReadStream.prototype._destroy = function (err, callback) {
6384 this._iterator.end(function (err2) {
6385 callback(err || err2)
6386 })
6387}
6388
6389},{"inherits":53,"readable-stream":74,"xtend":162}],60:[function(_dereq_,module,exports){
6390'use strict';
6391
6392function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
6393
6394var codes = {};
6395
6396function createErrorType(code, message, Base) {
6397 if (!Base) {
6398 Base = Error;
6399 }
6400
6401 function getMessage(arg1, arg2, arg3) {
6402 if (typeof message === 'string') {
6403 return message;
6404 } else {
6405 return message(arg1, arg2, arg3);
6406 }
6407 }
6408
6409 var NodeError =
6410 /*#__PURE__*/
6411 function (_Base) {
6412 _inheritsLoose(NodeError, _Base);
6413
6414 function NodeError(arg1, arg2, arg3) {
6415 return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
6416 }
6417
6418 return NodeError;
6419 }(Base);
6420
6421 NodeError.prototype.name = Base.name;
6422 NodeError.prototype.code = code;
6423 codes[code] = NodeError;
6424} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
6425
6426
6427function oneOf(expected, thing) {
6428 if (Array.isArray(expected)) {
6429 var len = expected.length;
6430 expected = expected.map(function (i) {
6431 return String(i);
6432 });
6433
6434 if (len > 2) {
6435 return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
6436 } else if (len === 2) {
6437 return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
6438 } else {
6439 return "of ".concat(thing, " ").concat(expected[0]);
6440 }
6441 } else {
6442 return "of ".concat(thing, " ").concat(String(expected));
6443 }
6444} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
6445
6446
6447function startsWith(str, search, pos) {
6448 return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
6449} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
6450
6451
6452function endsWith(str, search, this_len) {
6453 if (this_len === undefined || this_len > str.length) {
6454 this_len = str.length;
6455 }
6456
6457 return str.substring(this_len - search.length, this_len) === search;
6458} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
6459
6460
6461function includes(str, search, start) {
6462 if (typeof start !== 'number') {
6463 start = 0;
6464 }
6465
6466 if (start + search.length > str.length) {
6467 return false;
6468 } else {
6469 return str.indexOf(search, start) !== -1;
6470 }
6471}
6472
6473createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
6474 return 'The value "' + value + '" is invalid for option "' + name + '"';
6475}, TypeError);
6476createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
6477 // determiner: 'must be' or 'must not be'
6478 var determiner;
6479
6480 if (typeof expected === 'string' && startsWith(expected, 'not ')) {
6481 determiner = 'must not be';
6482 expected = expected.replace(/^not /, '');
6483 } else {
6484 determiner = 'must be';
6485 }
6486
6487 var msg;
6488
6489 if (endsWith(name, ' argument')) {
6490 // For cases like 'first argument'
6491 msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
6492 } else {
6493 var type = includes(name, '.') ? 'property' : 'argument';
6494 msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
6495 }
6496
6497 msg += ". Received type ".concat(typeof actual);
6498 return msg;
6499}, TypeError);
6500createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
6501createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
6502 return 'The ' + name + ' method is not implemented';
6503});
6504createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
6505createErrorType('ERR_STREAM_DESTROYED', function (name) {
6506 return 'Cannot call ' + name + ' after a stream was destroyed';
6507});
6508createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
6509createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
6510createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
6511createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
6512createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
6513 return 'Unknown encoding: ' + arg;
6514}, TypeError);
6515createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
6516module.exports.codes = codes;
6517
6518},{}],61:[function(_dereq_,module,exports){
6519(function (process){(function (){
6520// Copyright Joyent, Inc. and other Node contributors.
6521//
6522// Permission is hereby granted, free of charge, to any person obtaining a
6523// copy of this software and associated documentation files (the
6524// "Software"), to deal in the Software without restriction, including
6525// without limitation the rights to use, copy, modify, merge, publish,
6526// distribute, sublicense, and/or sell copies of the Software, and to permit
6527// persons to whom the Software is furnished to do so, subject to the
6528// following conditions:
6529//
6530// The above copyright notice and this permission notice shall be included
6531// in all copies or substantial portions of the Software.
6532//
6533// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6534// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6535// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6536// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6537// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6538// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6539// USE OR OTHER DEALINGS IN THE SOFTWARE.
6540
6541// a duplex stream is just a stream that is both readable and writable.
6542// Since JS doesn't have multiple prototypal inheritance, this class
6543// prototypally inherits from Readable, and then parasitically from
6544// Writable.
6545
6546'use strict';
6547
6548/*<replacement>*/
6549var objectKeys = Object.keys || function (obj) {
6550 var keys = [];
6551 for (var key in obj) keys.push(key);
6552 return keys;
6553};
6554/*</replacement>*/
6555
6556module.exports = Duplex;
6557var Readable = _dereq_('./_stream_readable');
6558var Writable = _dereq_('./_stream_writable');
6559_dereq_('inherits')(Duplex, Readable);
6560{
6561 // Allow the keys array to be GC'ed.
6562 var keys = objectKeys(Writable.prototype);
6563 for (var v = 0; v < keys.length; v++) {
6564 var method = keys[v];
6565 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
6566 }
6567}
6568function Duplex(options) {
6569 if (!(this instanceof Duplex)) return new Duplex(options);
6570 Readable.call(this, options);
6571 Writable.call(this, options);
6572 this.allowHalfOpen = true;
6573 if (options) {
6574 if (options.readable === false) this.readable = false;
6575 if (options.writable === false) this.writable = false;
6576 if (options.allowHalfOpen === false) {
6577 this.allowHalfOpen = false;
6578 this.once('end', onend);
6579 }
6580 }
6581}
6582Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
6583 // making it explicit this property is not enumerable
6584 // because otherwise some prototype manipulation in
6585 // userland will fail
6586 enumerable: false,
6587 get: function get() {
6588 return this._writableState.highWaterMark;
6589 }
6590});
6591Object.defineProperty(Duplex.prototype, 'writableBuffer', {
6592 // making it explicit this property is not enumerable
6593 // because otherwise some prototype manipulation in
6594 // userland will fail
6595 enumerable: false,
6596 get: function get() {
6597 return this._writableState && this._writableState.getBuffer();
6598 }
6599});
6600Object.defineProperty(Duplex.prototype, 'writableLength', {
6601 // making it explicit this property is not enumerable
6602 // because otherwise some prototype manipulation in
6603 // userland will fail
6604 enumerable: false,
6605 get: function get() {
6606 return this._writableState.length;
6607 }
6608});
6609
6610// the no-half-open enforcer
6611function onend() {
6612 // If the writable side ended, then we're ok.
6613 if (this._writableState.ended) return;
6614
6615 // no more data can be written.
6616 // But allow more writes to happen in this tick.
6617 process.nextTick(onEndNT, this);
6618}
6619function onEndNT(self) {
6620 self.end();
6621}
6622Object.defineProperty(Duplex.prototype, 'destroyed', {
6623 // making it explicit this property is not enumerable
6624 // because otherwise some prototype manipulation in
6625 // userland will fail
6626 enumerable: false,
6627 get: function get() {
6628 if (this._readableState === undefined || this._writableState === undefined) {
6629 return false;
6630 }
6631 return this._readableState.destroyed && this._writableState.destroyed;
6632 },
6633 set: function set(value) {
6634 // we ignore the value if the stream
6635 // has not been initialized yet
6636 if (this._readableState === undefined || this._writableState === undefined) {
6637 return;
6638 }
6639
6640 // backward compatibility, the user is explicitly
6641 // managing destroyed
6642 this._readableState.destroyed = value;
6643 this._writableState.destroyed = value;
6644 }
6645});
6646}).call(this)}).call(this,_dereq_('_process'))
6647},{"./_stream_readable":63,"./_stream_writable":65,"_process":94,"inherits":53}],62:[function(_dereq_,module,exports){
6648// Copyright Joyent, Inc. and other Node contributors.
6649//
6650// Permission is hereby granted, free of charge, to any person obtaining a
6651// copy of this software and associated documentation files (the
6652// "Software"), to deal in the Software without restriction, including
6653// without limitation the rights to use, copy, modify, merge, publish,
6654// distribute, sublicense, and/or sell copies of the Software, and to permit
6655// persons to whom the Software is furnished to do so, subject to the
6656// following conditions:
6657//
6658// The above copyright notice and this permission notice shall be included
6659// in all copies or substantial portions of the Software.
6660//
6661// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6662// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6663// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6664// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6665// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6666// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6667// USE OR OTHER DEALINGS IN THE SOFTWARE.
6668
6669// a passthrough stream.
6670// basically just the most minimal sort of Transform stream.
6671// Every written chunk gets output as-is.
6672
6673'use strict';
6674
6675module.exports = PassThrough;
6676var Transform = _dereq_('./_stream_transform');
6677_dereq_('inherits')(PassThrough, Transform);
6678function PassThrough(options) {
6679 if (!(this instanceof PassThrough)) return new PassThrough(options);
6680 Transform.call(this, options);
6681}
6682PassThrough.prototype._transform = function (chunk, encoding, cb) {
6683 cb(null, chunk);
6684};
6685},{"./_stream_transform":64,"inherits":53}],63:[function(_dereq_,module,exports){
6686(function (process,global){(function (){
6687// Copyright Joyent, Inc. and other Node contributors.
6688//
6689// Permission is hereby granted, free of charge, to any person obtaining a
6690// copy of this software and associated documentation files (the
6691// "Software"), to deal in the Software without restriction, including
6692// without limitation the rights to use, copy, modify, merge, publish,
6693// distribute, sublicense, and/or sell copies of the Software, and to permit
6694// persons to whom the Software is furnished to do so, subject to the
6695// following conditions:
6696//
6697// The above copyright notice and this permission notice shall be included
6698// in all copies or substantial portions of the Software.
6699//
6700// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6701// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6702// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6703// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6704// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6705// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6706// USE OR OTHER DEALINGS IN THE SOFTWARE.
6707
6708'use strict';
6709
6710module.exports = Readable;
6711
6712/*<replacement>*/
6713var Duplex;
6714/*</replacement>*/
6715
6716Readable.ReadableState = ReadableState;
6717
6718/*<replacement>*/
6719var EE = _dereq_('events').EventEmitter;
6720var EElistenerCount = function EElistenerCount(emitter, type) {
6721 return emitter.listeners(type).length;
6722};
6723/*</replacement>*/
6724
6725/*<replacement>*/
6726var Stream = _dereq_('./internal/streams/stream');
6727/*</replacement>*/
6728
6729var Buffer = _dereq_('buffer').Buffer;
6730var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
6731function _uint8ArrayToBuffer(chunk) {
6732 return Buffer.from(chunk);
6733}
6734function _isUint8Array(obj) {
6735 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
6736}
6737
6738/*<replacement>*/
6739var debugUtil = _dereq_('util');
6740var debug;
6741if (debugUtil && debugUtil.debuglog) {
6742 debug = debugUtil.debuglog('stream');
6743} else {
6744 debug = function debug() {};
6745}
6746/*</replacement>*/
6747
6748var BufferList = _dereq_('./internal/streams/buffer_list');
6749var destroyImpl = _dereq_('./internal/streams/destroy');
6750var _require = _dereq_('./internal/streams/state'),
6751 getHighWaterMark = _require.getHighWaterMark;
6752var _require$codes = _dereq_('../errors').codes,
6753 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
6754 ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
6755 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
6756 ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;
6757
6758// Lazy loaded to improve the startup performance.
6759var StringDecoder;
6760var createReadableStreamAsyncIterator;
6761var from;
6762_dereq_('inherits')(Readable, Stream);
6763var errorOrDestroy = destroyImpl.errorOrDestroy;
6764var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
6765function prependListener(emitter, event, fn) {
6766 // Sadly this is not cacheable as some libraries bundle their own
6767 // event emitter implementation with them.
6768 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
6769
6770 // This is a hack to make sure that our error handler is attached before any
6771 // userland ones. NEVER DO THIS. This is here only because this code needs
6772 // to continue to work with older versions of Node.js that do not include
6773 // the prependListener() method. The goal is to eventually remove this hack.
6774 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]];
6775}
6776function ReadableState(options, stream, isDuplex) {
6777 Duplex = Duplex || _dereq_('./_stream_duplex');
6778 options = options || {};
6779
6780 // Duplex streams are both readable and writable, but share
6781 // the same options object.
6782 // However, some cases require setting options to different
6783 // values for the readable and the writable sides of the duplex stream.
6784 // These options can be provided separately as readableXXX and writableXXX.
6785 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;
6786
6787 // object stream flag. Used to make read(n) ignore n and to
6788 // make all the buffer merging and length checks go away
6789 this.objectMode = !!options.objectMode;
6790 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
6791
6792 // the point at which it stops calling _read() to fill the buffer
6793 // Note: 0 is a valid value, means "don't call _read preemptively ever"
6794 this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex);
6795
6796 // A linked list is used to store data chunks instead of an array because the
6797 // linked list can remove elements from the beginning faster than
6798 // array.shift()
6799 this.buffer = new BufferList();
6800 this.length = 0;
6801 this.pipes = null;
6802 this.pipesCount = 0;
6803 this.flowing = null;
6804 this.ended = false;
6805 this.endEmitted = false;
6806 this.reading = false;
6807
6808 // a flag to be able to tell if the event 'readable'/'data' is emitted
6809 // immediately, or on a later tick. We set this to true at first, because
6810 // any actions that shouldn't happen until "later" should generally also
6811 // not happen before the first read call.
6812 this.sync = true;
6813
6814 // whenever we return null, then we set a flag to say
6815 // that we're awaiting a 'readable' event emission.
6816 this.needReadable = false;
6817 this.emittedReadable = false;
6818 this.readableListening = false;
6819 this.resumeScheduled = false;
6820 this.paused = true;
6821
6822 // Should close be emitted on destroy. Defaults to true.
6823 this.emitClose = options.emitClose !== false;
6824
6825 // Should .destroy() be called after 'end' (and potentially 'finish')
6826 this.autoDestroy = !!options.autoDestroy;
6827
6828 // has it been destroyed
6829 this.destroyed = false;
6830
6831 // Crypto is kind of old and crusty. Historically, its default string
6832 // encoding is 'binary' so we have to make this configurable.
6833 // Everything else in the universe uses 'utf8', though.
6834 this.defaultEncoding = options.defaultEncoding || 'utf8';
6835
6836 // the number of writers that are awaiting a drain event in .pipe()s
6837 this.awaitDrain = 0;
6838
6839 // if true, a maybeReadMore has been scheduled
6840 this.readingMore = false;
6841 this.decoder = null;
6842 this.encoding = null;
6843 if (options.encoding) {
6844 if (!StringDecoder) StringDecoder = _dereq_('string_decoder/').StringDecoder;
6845 this.decoder = new StringDecoder(options.encoding);
6846 this.encoding = options.encoding;
6847 }
6848}
6849function Readable(options) {
6850 Duplex = Duplex || _dereq_('./_stream_duplex');
6851 if (!(this instanceof Readable)) return new Readable(options);
6852
6853 // Checking for a Stream.Duplex instance is faster here instead of inside
6854 // the ReadableState constructor, at least with V8 6.5
6855 var isDuplex = this instanceof Duplex;
6856 this._readableState = new ReadableState(options, this, isDuplex);
6857
6858 // legacy
6859 this.readable = true;
6860 if (options) {
6861 if (typeof options.read === 'function') this._read = options.read;
6862 if (typeof options.destroy === 'function') this._destroy = options.destroy;
6863 }
6864 Stream.call(this);
6865}
6866Object.defineProperty(Readable.prototype, 'destroyed', {
6867 // making it explicit this property is not enumerable
6868 // because otherwise some prototype manipulation in
6869 // userland will fail
6870 enumerable: false,
6871 get: function get() {
6872 if (this._readableState === undefined) {
6873 return false;
6874 }
6875 return this._readableState.destroyed;
6876 },
6877 set: function set(value) {
6878 // we ignore the value if the stream
6879 // has not been initialized yet
6880 if (!this._readableState) {
6881 return;
6882 }
6883
6884 // backward compatibility, the user is explicitly
6885 // managing destroyed
6886 this._readableState.destroyed = value;
6887 }
6888});
6889Readable.prototype.destroy = destroyImpl.destroy;
6890Readable.prototype._undestroy = destroyImpl.undestroy;
6891Readable.prototype._destroy = function (err, cb) {
6892 cb(err);
6893};
6894
6895// Manually shove something into the read() buffer.
6896// This returns true if the highWaterMark has not been hit yet,
6897// similar to how Writable.write() returns true if you should
6898// write() some more.
6899Readable.prototype.push = function (chunk, encoding) {
6900 var state = this._readableState;
6901 var skipChunkCheck;
6902 if (!state.objectMode) {
6903 if (typeof chunk === 'string') {
6904 encoding = encoding || state.defaultEncoding;
6905 if (encoding !== state.encoding) {
6906 chunk = Buffer.from(chunk, encoding);
6907 encoding = '';
6908 }
6909 skipChunkCheck = true;
6910 }
6911 } else {
6912 skipChunkCheck = true;
6913 }
6914 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
6915};
6916
6917// Unshift should *always* be something directly out of read()
6918Readable.prototype.unshift = function (chunk) {
6919 return readableAddChunk(this, chunk, null, true, false);
6920};
6921function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
6922 debug('readableAddChunk', chunk);
6923 var state = stream._readableState;
6924 if (chunk === null) {
6925 state.reading = false;
6926 onEofChunk(stream, state);
6927 } else {
6928 var er;
6929 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
6930 if (er) {
6931 errorOrDestroy(stream, er);
6932 } else if (state.objectMode || chunk && chunk.length > 0) {
6933 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
6934 chunk = _uint8ArrayToBuffer(chunk);
6935 }
6936 if (addToFront) {
6937 if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
6938 } else if (state.ended) {
6939 errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
6940 } else if (state.destroyed) {
6941 return false;
6942 } else {
6943 state.reading = false;
6944 if (state.decoder && !encoding) {
6945 chunk = state.decoder.write(chunk);
6946 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
6947 } else {
6948 addChunk(stream, state, chunk, false);
6949 }
6950 }
6951 } else if (!addToFront) {
6952 state.reading = false;
6953 maybeReadMore(stream, state);
6954 }
6955 }
6956
6957 // We can push more data if we are below the highWaterMark.
6958 // Also, if we have no data yet, we can stand some more bytes.
6959 // This is to work around cases where hwm=0, such as the repl.
6960 return !state.ended && (state.length < state.highWaterMark || state.length === 0);
6961}
6962function addChunk(stream, state, chunk, addToFront) {
6963 if (state.flowing && state.length === 0 && !state.sync) {
6964 state.awaitDrain = 0;
6965 stream.emit('data', chunk);
6966 } else {
6967 // update the buffer info.
6968 state.length += state.objectMode ? 1 : chunk.length;
6969 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
6970 if (state.needReadable) emitReadable(stream);
6971 }
6972 maybeReadMore(stream, state);
6973}
6974function chunkInvalid(state, chunk) {
6975 var er;
6976 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
6977 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
6978 }
6979 return er;
6980}
6981Readable.prototype.isPaused = function () {
6982 return this._readableState.flowing === false;
6983};
6984
6985// backwards compatibility.
6986Readable.prototype.setEncoding = function (enc) {
6987 if (!StringDecoder) StringDecoder = _dereq_('string_decoder/').StringDecoder;
6988 var decoder = new StringDecoder(enc);
6989 this._readableState.decoder = decoder;
6990 // If setEncoding(null), decoder.encoding equals utf8
6991 this._readableState.encoding = this._readableState.decoder.encoding;
6992
6993 // Iterate over current buffer to convert already stored Buffers:
6994 var p = this._readableState.buffer.head;
6995 var content = '';
6996 while (p !== null) {
6997 content += decoder.write(p.data);
6998 p = p.next;
6999 }
7000 this._readableState.buffer.clear();
7001 if (content !== '') this._readableState.buffer.push(content);
7002 this._readableState.length = content.length;
7003 return this;
7004};
7005
7006// Don't raise the hwm > 1GB
7007var MAX_HWM = 0x40000000;
7008function computeNewHighWaterMark(n) {
7009 if (n >= MAX_HWM) {
7010 // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
7011 n = MAX_HWM;
7012 } else {
7013 // Get the next highest power of 2 to prevent increasing hwm excessively in
7014 // tiny amounts
7015 n--;
7016 n |= n >>> 1;
7017 n |= n >>> 2;
7018 n |= n >>> 4;
7019 n |= n >>> 8;
7020 n |= n >>> 16;
7021 n++;
7022 }
7023 return n;
7024}
7025
7026// This function is designed to be inlinable, so please take care when making
7027// changes to the function body.
7028function howMuchToRead(n, state) {
7029 if (n <= 0 || state.length === 0 && state.ended) return 0;
7030 if (state.objectMode) return 1;
7031 if (n !== n) {
7032 // Only flow one buffer at a time
7033 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
7034 }
7035 // If we're asking for more than the current hwm, then raise the hwm.
7036 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
7037 if (n <= state.length) return n;
7038 // Don't have enough
7039 if (!state.ended) {
7040 state.needReadable = true;
7041 return 0;
7042 }
7043 return state.length;
7044}
7045
7046// you can override either this method, or the async _read(n) below.
7047Readable.prototype.read = function (n) {
7048 debug('read', n);
7049 n = parseInt(n, 10);
7050 var state = this._readableState;
7051 var nOrig = n;
7052 if (n !== 0) state.emittedReadable = false;
7053
7054 // if we're doing read(0) to trigger a readable event, but we
7055 // already have a bunch of data in the buffer, then just trigger
7056 // the 'readable' event and move on.
7057 if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
7058 debug('read: emitReadable', state.length, state.ended);
7059 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
7060 return null;
7061 }
7062 n = howMuchToRead(n, state);
7063
7064 // if we've ended, and we're now clear, then finish it up.
7065 if (n === 0 && state.ended) {
7066 if (state.length === 0) endReadable(this);
7067 return null;
7068 }
7069
7070 // All the actual chunk generation logic needs to be
7071 // *below* the call to _read. The reason is that in certain
7072 // synthetic stream cases, such as passthrough streams, _read
7073 // may be a completely synchronous operation which may change
7074 // the state of the read buffer, providing enough data when
7075 // before there was *not* enough.
7076 //
7077 // So, the steps are:
7078 // 1. Figure out what the state of things will be after we do
7079 // a read from the buffer.
7080 //
7081 // 2. If that resulting state will trigger a _read, then call _read.
7082 // Note that this may be asynchronous, or synchronous. Yes, it is
7083 // deeply ugly to write APIs this way, but that still doesn't mean
7084 // that the Readable class should behave improperly, as streams are
7085 // designed to be sync/async agnostic.
7086 // Take note if the _read call is sync or async (ie, if the read call
7087 // has returned yet), so that we know whether or not it's safe to emit
7088 // 'readable' etc.
7089 //
7090 // 3. Actually pull the requested chunks out of the buffer and return.
7091
7092 // if we need a readable event, then we need to do some reading.
7093 var doRead = state.needReadable;
7094 debug('need readable', doRead);
7095
7096 // if we currently have less than the highWaterMark, then also read some
7097 if (state.length === 0 || state.length - n < state.highWaterMark) {
7098 doRead = true;
7099 debug('length less than watermark', doRead);
7100 }
7101
7102 // however, if we've ended, then there's no point, and if we're already
7103 // reading, then it's unnecessary.
7104 if (state.ended || state.reading) {
7105 doRead = false;
7106 debug('reading or ended', doRead);
7107 } else if (doRead) {
7108 debug('do read');
7109 state.reading = true;
7110 state.sync = true;
7111 // if the length is currently zero, then we *need* a readable event.
7112 if (state.length === 0) state.needReadable = true;
7113 // call internal read method
7114 this._read(state.highWaterMark);
7115 state.sync = false;
7116 // If _read pushed data synchronously, then `reading` will be false,
7117 // and we need to re-evaluate how much data we can return to the user.
7118 if (!state.reading) n = howMuchToRead(nOrig, state);
7119 }
7120 var ret;
7121 if (n > 0) ret = fromList(n, state);else ret = null;
7122 if (ret === null) {
7123 state.needReadable = state.length <= state.highWaterMark;
7124 n = 0;
7125 } else {
7126 state.length -= n;
7127 state.awaitDrain = 0;
7128 }
7129 if (state.length === 0) {
7130 // If we have nothing in the buffer, then we want to know
7131 // as soon as we *do* get something into the buffer.
7132 if (!state.ended) state.needReadable = true;
7133
7134 // If we tried to read() past the EOF, then emit end on the next tick.
7135 if (nOrig !== n && state.ended) endReadable(this);
7136 }
7137 if (ret !== null) this.emit('data', ret);
7138 return ret;
7139};
7140function onEofChunk(stream, state) {
7141 debug('onEofChunk');
7142 if (state.ended) return;
7143 if (state.decoder) {
7144 var chunk = state.decoder.end();
7145 if (chunk && chunk.length) {
7146 state.buffer.push(chunk);
7147 state.length += state.objectMode ? 1 : chunk.length;
7148 }
7149 }
7150 state.ended = true;
7151 if (state.sync) {
7152 // if we are sync, wait until next tick to emit the data.
7153 // Otherwise we risk emitting data in the flow()
7154 // the readable code triggers during a read() call
7155 emitReadable(stream);
7156 } else {
7157 // emit 'readable' now to make sure it gets picked up.
7158 state.needReadable = false;
7159 if (!state.emittedReadable) {
7160 state.emittedReadable = true;
7161 emitReadable_(stream);
7162 }
7163 }
7164}
7165
7166// Don't emit readable right away in sync mode, because this can trigger
7167// another read() call => stack overflow. This way, it might trigger
7168// a nextTick recursion warning, but that's not so bad.
7169function emitReadable(stream) {
7170 var state = stream._readableState;
7171 debug('emitReadable', state.needReadable, state.emittedReadable);
7172 state.needReadable = false;
7173 if (!state.emittedReadable) {
7174 debug('emitReadable', state.flowing);
7175 state.emittedReadable = true;
7176 process.nextTick(emitReadable_, stream);
7177 }
7178}
7179function emitReadable_(stream) {
7180 var state = stream._readableState;
7181 debug('emitReadable_', state.destroyed, state.length, state.ended);
7182 if (!state.destroyed && (state.length || state.ended)) {
7183 stream.emit('readable');
7184 state.emittedReadable = false;
7185 }
7186
7187 // The stream needs another readable event if
7188 // 1. It is not flowing, as the flow mechanism will take
7189 // care of it.
7190 // 2. It is not ended.
7191 // 3. It is below the highWaterMark, so we can schedule
7192 // another readable later.
7193 state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
7194 flow(stream);
7195}
7196
7197// at this point, the user has presumably seen the 'readable' event,
7198// and called read() to consume some data. that may have triggered
7199// in turn another _read(n) call, in which case reading = true if
7200// it's in progress.
7201// However, if we're not ended, or reading, and the length < hwm,
7202// then go ahead and try to read some more preemptively.
7203function maybeReadMore(stream, state) {
7204 if (!state.readingMore) {
7205 state.readingMore = true;
7206 process.nextTick(maybeReadMore_, stream, state);
7207 }
7208}
7209function maybeReadMore_(stream, state) {
7210 // Attempt to read more data if we should.
7211 //
7212 // The conditions for reading more data are (one of):
7213 // - Not enough data buffered (state.length < state.highWaterMark). The loop
7214 // is responsible for filling the buffer with enough data if such data
7215 // is available. If highWaterMark is 0 and we are not in the flowing mode
7216 // we should _not_ attempt to buffer any extra data. We'll get more data
7217 // when the stream consumer calls read() instead.
7218 // - No data in the buffer, and the stream is in flowing mode. In this mode
7219 // the loop below is responsible for ensuring read() is called. Failing to
7220 // call read here would abort the flow and there's no other mechanism for
7221 // continuing the flow if the stream consumer has just subscribed to the
7222 // 'data' event.
7223 //
7224 // In addition to the above conditions to keep reading data, the following
7225 // conditions prevent the data from being read:
7226 // - The stream has ended (state.ended).
7227 // - There is already a pending 'read' operation (state.reading). This is a
7228 // case where the the stream has called the implementation defined _read()
7229 // method, but they are processing the call asynchronously and have _not_
7230 // called push() with new data. In this case we skip performing more
7231 // read()s. The execution ends in this method again after the _read() ends
7232 // up calling push() with more data.
7233 while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
7234 var len = state.length;
7235 debug('maybeReadMore read 0');
7236 stream.read(0);
7237 if (len === state.length)
7238 // didn't get any data, stop spinning.
7239 break;
7240 }
7241 state.readingMore = false;
7242}
7243
7244// abstract method. to be overridden in specific implementation classes.
7245// call cb(er, data) where data is <= n in length.
7246// for virtual (non-string, non-buffer) streams, "length" is somewhat
7247// arbitrary, and perhaps not very meaningful.
7248Readable.prototype._read = function (n) {
7249 errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
7250};
7251Readable.prototype.pipe = function (dest, pipeOpts) {
7252 var src = this;
7253 var state = this._readableState;
7254 switch (state.pipesCount) {
7255 case 0:
7256 state.pipes = dest;
7257 break;
7258 case 1:
7259 state.pipes = [state.pipes, dest];
7260 break;
7261 default:
7262 state.pipes.push(dest);
7263 break;
7264 }
7265 state.pipesCount += 1;
7266 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
7267 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
7268 var endFn = doEnd ? onend : unpipe;
7269 if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
7270 dest.on('unpipe', onunpipe);
7271 function onunpipe(readable, unpipeInfo) {
7272 debug('onunpipe');
7273 if (readable === src) {
7274 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
7275 unpipeInfo.hasUnpiped = true;
7276 cleanup();
7277 }
7278 }
7279 }
7280 function onend() {
7281 debug('onend');
7282 dest.end();
7283 }
7284
7285 // when the dest drains, it reduces the awaitDrain counter
7286 // on the source. This would be more elegant with a .once()
7287 // handler in flow(), but adding and removing repeatedly is
7288 // too slow.
7289 var ondrain = pipeOnDrain(src);
7290 dest.on('drain', ondrain);
7291 var cleanedUp = false;
7292 function cleanup() {
7293 debug('cleanup');
7294 // cleanup event handlers once the pipe is broken
7295 dest.removeListener('close', onclose);
7296 dest.removeListener('finish', onfinish);
7297 dest.removeListener('drain', ondrain);
7298 dest.removeListener('error', onerror);
7299 dest.removeListener('unpipe', onunpipe);
7300 src.removeListener('end', onend);
7301 src.removeListener('end', unpipe);
7302 src.removeListener('data', ondata);
7303 cleanedUp = true;
7304
7305 // if the reader is waiting for a drain event from this
7306 // specific writer, then it would cause it to never start
7307 // flowing again.
7308 // So, if this is awaiting a drain, then we just call it now.
7309 // If we don't know, then assume that we are waiting for one.
7310 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
7311 }
7312 src.on('data', ondata);
7313 function ondata(chunk) {
7314 debug('ondata');
7315 var ret = dest.write(chunk);
7316 debug('dest.write', ret);
7317 if (ret === false) {
7318 // If the user unpiped during `dest.write()`, it is possible
7319 // to get stuck in a permanently paused state if that write
7320 // also returned false.
7321 // => Check whether `dest` is still a piping destination.
7322 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
7323 debug('false write response, pause', state.awaitDrain);
7324 state.awaitDrain++;
7325 }
7326 src.pause();
7327 }
7328 }
7329
7330 // if the dest has an error, then stop piping into it.
7331 // however, don't suppress the throwing behavior for this.
7332 function onerror(er) {
7333 debug('onerror', er);
7334 unpipe();
7335 dest.removeListener('error', onerror);
7336 if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
7337 }
7338
7339 // Make sure our error handler is attached before userland ones.
7340 prependListener(dest, 'error', onerror);
7341
7342 // Both close and finish should trigger unpipe, but only once.
7343 function onclose() {
7344 dest.removeListener('finish', onfinish);
7345 unpipe();
7346 }
7347 dest.once('close', onclose);
7348 function onfinish() {
7349 debug('onfinish');
7350 dest.removeListener('close', onclose);
7351 unpipe();
7352 }
7353 dest.once('finish', onfinish);
7354 function unpipe() {
7355 debug('unpipe');
7356 src.unpipe(dest);
7357 }
7358
7359 // tell the dest that it's being piped to
7360 dest.emit('pipe', src);
7361
7362 // start the flow if it hasn't been started already.
7363 if (!state.flowing) {
7364 debug('pipe resume');
7365 src.resume();
7366 }
7367 return dest;
7368};
7369function pipeOnDrain(src) {
7370 return function pipeOnDrainFunctionResult() {
7371 var state = src._readableState;
7372 debug('pipeOnDrain', state.awaitDrain);
7373 if (state.awaitDrain) state.awaitDrain--;
7374 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
7375 state.flowing = true;
7376 flow(src);
7377 }
7378 };
7379}
7380Readable.prototype.unpipe = function (dest) {
7381 var state = this._readableState;
7382 var unpipeInfo = {
7383 hasUnpiped: false
7384 };
7385
7386 // if we're not piping anywhere, then do nothing.
7387 if (state.pipesCount === 0) return this;
7388
7389 // just one destination. most common case.
7390 if (state.pipesCount === 1) {
7391 // passed in one, but it's not the right one.
7392 if (dest && dest !== state.pipes) return this;
7393 if (!dest) dest = state.pipes;
7394
7395 // got a match.
7396 state.pipes = null;
7397 state.pipesCount = 0;
7398 state.flowing = false;
7399 if (dest) dest.emit('unpipe', this, unpipeInfo);
7400 return this;
7401 }
7402
7403 // slow case. multiple pipe destinations.
7404
7405 if (!dest) {
7406 // remove all.
7407 var dests = state.pipes;
7408 var len = state.pipesCount;
7409 state.pipes = null;
7410 state.pipesCount = 0;
7411 state.flowing = false;
7412 for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, {
7413 hasUnpiped: false
7414 });
7415 return this;
7416 }
7417
7418 // try to find the right one.
7419 var index = indexOf(state.pipes, dest);
7420 if (index === -1) return this;
7421 state.pipes.splice(index, 1);
7422 state.pipesCount -= 1;
7423 if (state.pipesCount === 1) state.pipes = state.pipes[0];
7424 dest.emit('unpipe', this, unpipeInfo);
7425 return this;
7426};
7427
7428// set up data events if they are asked for
7429// Ensure readable listeners eventually get something
7430Readable.prototype.on = function (ev, fn) {
7431 var res = Stream.prototype.on.call(this, ev, fn);
7432 var state = this._readableState;
7433 if (ev === 'data') {
7434 // update readableListening so that resume() may be a no-op
7435 // a few lines down. This is needed to support once('readable').
7436 state.readableListening = this.listenerCount('readable') > 0;
7437
7438 // Try start flowing on next tick if stream isn't explicitly paused
7439 if (state.flowing !== false) this.resume();
7440 } else if (ev === 'readable') {
7441 if (!state.endEmitted && !state.readableListening) {
7442 state.readableListening = state.needReadable = true;
7443 state.flowing = false;
7444 state.emittedReadable = false;
7445 debug('on readable', state.length, state.reading);
7446 if (state.length) {
7447 emitReadable(this);
7448 } else if (!state.reading) {
7449 process.nextTick(nReadingNextTick, this);
7450 }
7451 }
7452 }
7453 return res;
7454};
7455Readable.prototype.addListener = Readable.prototype.on;
7456Readable.prototype.removeListener = function (ev, fn) {
7457 var res = Stream.prototype.removeListener.call(this, ev, fn);
7458 if (ev === 'readable') {
7459 // We need to check if there is someone still listening to
7460 // readable and reset the state. However this needs to happen
7461 // after readable has been emitted but before I/O (nextTick) to
7462 // support once('readable', fn) cycles. This means that calling
7463 // resume within the same tick will have no
7464 // effect.
7465 process.nextTick(updateReadableListening, this);
7466 }
7467 return res;
7468};
7469Readable.prototype.removeAllListeners = function (ev) {
7470 var res = Stream.prototype.removeAllListeners.apply(this, arguments);
7471 if (ev === 'readable' || ev === undefined) {
7472 // We need to check if there is someone still listening to
7473 // readable and reset the state. However this needs to happen
7474 // after readable has been emitted but before I/O (nextTick) to
7475 // support once('readable', fn) cycles. This means that calling
7476 // resume within the same tick will have no
7477 // effect.
7478 process.nextTick(updateReadableListening, this);
7479 }
7480 return res;
7481};
7482function updateReadableListening(self) {
7483 var state = self._readableState;
7484 state.readableListening = self.listenerCount('readable') > 0;
7485 if (state.resumeScheduled && !state.paused) {
7486 // flowing needs to be set to true now, otherwise
7487 // the upcoming resume will not flow.
7488 state.flowing = true;
7489
7490 // crude way to check if we should resume
7491 } else if (self.listenerCount('data') > 0) {
7492 self.resume();
7493 }
7494}
7495function nReadingNextTick(self) {
7496 debug('readable nexttick read 0');
7497 self.read(0);
7498}
7499
7500// pause() and resume() are remnants of the legacy readable stream API
7501// If the user uses them, then switch into old mode.
7502Readable.prototype.resume = function () {
7503 var state = this._readableState;
7504 if (!state.flowing) {
7505 debug('resume');
7506 // we flow only if there is no one listening
7507 // for readable, but we still have to call
7508 // resume()
7509 state.flowing = !state.readableListening;
7510 resume(this, state);
7511 }
7512 state.paused = false;
7513 return this;
7514};
7515function resume(stream, state) {
7516 if (!state.resumeScheduled) {
7517 state.resumeScheduled = true;
7518 process.nextTick(resume_, stream, state);
7519 }
7520}
7521function resume_(stream, state) {
7522 debug('resume', state.reading);
7523 if (!state.reading) {
7524 stream.read(0);
7525 }
7526 state.resumeScheduled = false;
7527 stream.emit('resume');
7528 flow(stream);
7529 if (state.flowing && !state.reading) stream.read(0);
7530}
7531Readable.prototype.pause = function () {
7532 debug('call pause flowing=%j', this._readableState.flowing);
7533 if (this._readableState.flowing !== false) {
7534 debug('pause');
7535 this._readableState.flowing = false;
7536 this.emit('pause');
7537 }
7538 this._readableState.paused = true;
7539 return this;
7540};
7541function flow(stream) {
7542 var state = stream._readableState;
7543 debug('flow', state.flowing);
7544 while (state.flowing && stream.read() !== null);
7545}
7546
7547// wrap an old-style stream as the async data source.
7548// This is *not* part of the readable stream interface.
7549// It is an ugly unfortunate mess of history.
7550Readable.prototype.wrap = function (stream) {
7551 var _this = this;
7552 var state = this._readableState;
7553 var paused = false;
7554 stream.on('end', function () {
7555 debug('wrapped end');
7556 if (state.decoder && !state.ended) {
7557 var chunk = state.decoder.end();
7558 if (chunk && chunk.length) _this.push(chunk);
7559 }
7560 _this.push(null);
7561 });
7562 stream.on('data', function (chunk) {
7563 debug('wrapped data');
7564 if (state.decoder) chunk = state.decoder.write(chunk);
7565
7566 // don't skip over falsy values in objectMode
7567 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
7568 var ret = _this.push(chunk);
7569 if (!ret) {
7570 paused = true;
7571 stream.pause();
7572 }
7573 });
7574
7575 // proxy all the other methods.
7576 // important when wrapping filters and duplexes.
7577 for (var i in stream) {
7578 if (this[i] === undefined && typeof stream[i] === 'function') {
7579 this[i] = function methodWrap(method) {
7580 return function methodWrapReturnFunction() {
7581 return stream[method].apply(stream, arguments);
7582 };
7583 }(i);
7584 }
7585 }
7586
7587 // proxy certain important events.
7588 for (var n = 0; n < kProxyEvents.length; n++) {
7589 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
7590 }
7591
7592 // when we try to consume some more bytes, simply unpause the
7593 // underlying stream.
7594 this._read = function (n) {
7595 debug('wrapped _read', n);
7596 if (paused) {
7597 paused = false;
7598 stream.resume();
7599 }
7600 };
7601 return this;
7602};
7603if (typeof Symbol === 'function') {
7604 Readable.prototype[Symbol.asyncIterator] = function () {
7605 if (createReadableStreamAsyncIterator === undefined) {
7606 createReadableStreamAsyncIterator = _dereq_('./internal/streams/async_iterator');
7607 }
7608 return createReadableStreamAsyncIterator(this);
7609 };
7610}
7611Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
7612 // making it explicit this property is not enumerable
7613 // because otherwise some prototype manipulation in
7614 // userland will fail
7615 enumerable: false,
7616 get: function get() {
7617 return this._readableState.highWaterMark;
7618 }
7619});
7620Object.defineProperty(Readable.prototype, 'readableBuffer', {
7621 // making it explicit this property is not enumerable
7622 // because otherwise some prototype manipulation in
7623 // userland will fail
7624 enumerable: false,
7625 get: function get() {
7626 return this._readableState && this._readableState.buffer;
7627 }
7628});
7629Object.defineProperty(Readable.prototype, 'readableFlowing', {
7630 // making it explicit this property is not enumerable
7631 // because otherwise some prototype manipulation in
7632 // userland will fail
7633 enumerable: false,
7634 get: function get() {
7635 return this._readableState.flowing;
7636 },
7637 set: function set(state) {
7638 if (this._readableState) {
7639 this._readableState.flowing = state;
7640 }
7641 }
7642});
7643
7644// exposed for testing purposes only.
7645Readable._fromList = fromList;
7646Object.defineProperty(Readable.prototype, 'readableLength', {
7647 // making it explicit this property is not enumerable
7648 // because otherwise some prototype manipulation in
7649 // userland will fail
7650 enumerable: false,
7651 get: function get() {
7652 return this._readableState.length;
7653 }
7654});
7655
7656// Pluck off n bytes from an array of buffers.
7657// Length is the combined lengths of all the buffers in the list.
7658// This function is designed to be inlinable, so please take care when making
7659// changes to the function body.
7660function fromList(n, state) {
7661 // nothing buffered
7662 if (state.length === 0) return null;
7663 var ret;
7664 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
7665 // read it all, truncate the list
7666 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
7667 state.buffer.clear();
7668 } else {
7669 // read part of list
7670 ret = state.buffer.consume(n, state.decoder);
7671 }
7672 return ret;
7673}
7674function endReadable(stream) {
7675 var state = stream._readableState;
7676 debug('endReadable', state.endEmitted);
7677 if (!state.endEmitted) {
7678 state.ended = true;
7679 process.nextTick(endReadableNT, state, stream);
7680 }
7681}
7682function endReadableNT(state, stream) {
7683 debug('endReadableNT', state.endEmitted, state.length);
7684
7685 // Check that we didn't get one last unshift.
7686 if (!state.endEmitted && state.length === 0) {
7687 state.endEmitted = true;
7688 stream.readable = false;
7689 stream.emit('end');
7690 if (state.autoDestroy) {
7691 // In case of duplex streams we need a way to detect
7692 // if the writable side is ready for autoDestroy as well
7693 var wState = stream._writableState;
7694 if (!wState || wState.autoDestroy && wState.finished) {
7695 stream.destroy();
7696 }
7697 }
7698 }
7699}
7700if (typeof Symbol === 'function') {
7701 Readable.from = function (iterable, opts) {
7702 if (from === undefined) {
7703 from = _dereq_('./internal/streams/from');
7704 }
7705 return from(Readable, iterable, opts);
7706 };
7707}
7708function indexOf(xs, x) {
7709 for (var i = 0, l = xs.length; i < l; i++) {
7710 if (xs[i] === x) return i;
7711 }
7712 return -1;
7713}
7714}).call(this)}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
7715},{"../errors":60,"./_stream_duplex":61,"./internal/streams/async_iterator":66,"./internal/streams/buffer_list":67,"./internal/streams/destroy":68,"./internal/streams/from":70,"./internal/streams/state":72,"./internal/streams/stream":73,"_process":94,"buffer":9,"events":39,"inherits":53,"string_decoder/":123,"util":8}],64:[function(_dereq_,module,exports){
7716// Copyright Joyent, Inc. and other Node contributors.
7717//
7718// Permission is hereby granted, free of charge, to any person obtaining a
7719// copy of this software and associated documentation files (the
7720// "Software"), to deal in the Software without restriction, including
7721// without limitation the rights to use, copy, modify, merge, publish,
7722// distribute, sublicense, and/or sell copies of the Software, and to permit
7723// persons to whom the Software is furnished to do so, subject to the
7724// following conditions:
7725//
7726// The above copyright notice and this permission notice shall be included
7727// in all copies or substantial portions of the Software.
7728//
7729// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7730// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7731// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7732// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7733// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7734// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7735// USE OR OTHER DEALINGS IN THE SOFTWARE.
7736
7737// a transform stream is a readable/writable stream where you do
7738// something with the data. Sometimes it's called a "filter",
7739// but that's not a great name for it, since that implies a thing where
7740// some bits pass through, and others are simply ignored. (That would
7741// be a valid example of a transform, of course.)
7742//
7743// While the output is causally related to the input, it's not a
7744// necessarily symmetric or synchronous transformation. For example,
7745// a zlib stream might take multiple plain-text writes(), and then
7746// emit a single compressed chunk some time in the future.
7747//
7748// Here's how this works:
7749//
7750// The Transform stream has all the aspects of the readable and writable
7751// stream classes. When you write(chunk), that calls _write(chunk,cb)
7752// internally, and returns false if there's a lot of pending writes
7753// buffered up. When you call read(), that calls _read(n) until
7754// there's enough pending readable data buffered up.
7755//
7756// In a transform stream, the written data is placed in a buffer. When
7757// _read(n) is called, it transforms the queued up data, calling the
7758// buffered _write cb's as it consumes chunks. If consuming a single
7759// written chunk would result in multiple output chunks, then the first
7760// outputted bit calls the readcb, and subsequent chunks just go into
7761// the read buffer, and will cause it to emit 'readable' if necessary.
7762//
7763// This way, back-pressure is actually determined by the reading side,
7764// since _read has to be called to start processing a new chunk. However,
7765// a pathological inflate type of transform can cause excessive buffering
7766// here. For example, imagine a stream where every byte of input is
7767// interpreted as an integer from 0-255, and then results in that many
7768// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
7769// 1kb of data being output. In this case, you could write a very small
7770// amount of input, and end up with a very large amount of output. In
7771// such a pathological inflating mechanism, there'd be no way to tell
7772// the system to stop doing the transform. A single 4MB write could
7773// cause the system to run out of memory.
7774//
7775// However, even in such a pathological case, only a single written chunk
7776// would be consumed, and then the rest would wait (un-transformed) until
7777// the results of the previous transformed chunk were consumed.
7778
7779'use strict';
7780
7781module.exports = Transform;
7782var _require$codes = _dereq_('../errors').codes,
7783 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
7784 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
7785 ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
7786 ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
7787var Duplex = _dereq_('./_stream_duplex');
7788_dereq_('inherits')(Transform, Duplex);
7789function afterTransform(er, data) {
7790 var ts = this._transformState;
7791 ts.transforming = false;
7792 var cb = ts.writecb;
7793 if (cb === null) {
7794 return this.emit('error', new ERR_MULTIPLE_CALLBACK());
7795 }
7796 ts.writechunk = null;
7797 ts.writecb = null;
7798 if (data != null)
7799 // single equals check for both `null` and `undefined`
7800 this.push(data);
7801 cb(er);
7802 var rs = this._readableState;
7803 rs.reading = false;
7804 if (rs.needReadable || rs.length < rs.highWaterMark) {
7805 this._read(rs.highWaterMark);
7806 }
7807}
7808function Transform(options) {
7809 if (!(this instanceof Transform)) return new Transform(options);
7810 Duplex.call(this, options);
7811 this._transformState = {
7812 afterTransform: afterTransform.bind(this),
7813 needTransform: false,
7814 transforming: false,
7815 writecb: null,
7816 writechunk: null,
7817 writeencoding: null
7818 };
7819
7820 // start out asking for a readable event once data is transformed.
7821 this._readableState.needReadable = true;
7822
7823 // we have implemented the _read method, and done the other things
7824 // that Readable wants before the first _read call, so unset the
7825 // sync guard flag.
7826 this._readableState.sync = false;
7827 if (options) {
7828 if (typeof options.transform === 'function') this._transform = options.transform;
7829 if (typeof options.flush === 'function') this._flush = options.flush;
7830 }
7831
7832 // When the writable side finishes, then flush out anything remaining.
7833 this.on('prefinish', prefinish);
7834}
7835function prefinish() {
7836 var _this = this;
7837 if (typeof this._flush === 'function' && !this._readableState.destroyed) {
7838 this._flush(function (er, data) {
7839 done(_this, er, data);
7840 });
7841 } else {
7842 done(this, null, null);
7843 }
7844}
7845Transform.prototype.push = function (chunk, encoding) {
7846 this._transformState.needTransform = false;
7847 return Duplex.prototype.push.call(this, chunk, encoding);
7848};
7849
7850// This is the part where you do stuff!
7851// override this function in implementation classes.
7852// 'chunk' is an input chunk.
7853//
7854// Call `push(newChunk)` to pass along transformed output
7855// to the readable side. You may call 'push' zero or more times.
7856//
7857// Call `cb(err)` when you are done with this chunk. If you pass
7858// an error, then that'll put the hurt on the whole operation. If you
7859// never call cb(), then you'll never get another chunk.
7860Transform.prototype._transform = function (chunk, encoding, cb) {
7861 cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
7862};
7863Transform.prototype._write = function (chunk, encoding, cb) {
7864 var ts = this._transformState;
7865 ts.writecb = cb;
7866 ts.writechunk = chunk;
7867 ts.writeencoding = encoding;
7868 if (!ts.transforming) {
7869 var rs = this._readableState;
7870 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
7871 }
7872};
7873
7874// Doesn't matter what the args are here.
7875// _transform does all the work.
7876// That we got here means that the readable side wants more data.
7877Transform.prototype._read = function (n) {
7878 var ts = this._transformState;
7879 if (ts.writechunk !== null && !ts.transforming) {
7880 ts.transforming = true;
7881 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
7882 } else {
7883 // mark that we need a transform, so that any data that comes in
7884 // will get processed, now that we've asked for it.
7885 ts.needTransform = true;
7886 }
7887};
7888Transform.prototype._destroy = function (err, cb) {
7889 Duplex.prototype._destroy.call(this, err, function (err2) {
7890 cb(err2);
7891 });
7892};
7893function done(stream, er, data) {
7894 if (er) return stream.emit('error', er);
7895 if (data != null)
7896 // single equals check for both `null` and `undefined`
7897 stream.push(data);
7898
7899 // TODO(BridgeAR): Write a test for these two error cases
7900 // if there's nothing in the write buffer, then that means
7901 // that nothing more will ever be provided
7902 if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
7903 if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
7904 return stream.push(null);
7905}
7906},{"../errors":60,"./_stream_duplex":61,"inherits":53}],65:[function(_dereq_,module,exports){
7907(function (process,global){(function (){
7908// Copyright Joyent, Inc. and other Node contributors.
7909//
7910// Permission is hereby granted, free of charge, to any person obtaining a
7911// copy of this software and associated documentation files (the
7912// "Software"), to deal in the Software without restriction, including
7913// without limitation the rights to use, copy, modify, merge, publish,
7914// distribute, sublicense, and/or sell copies of the Software, and to permit
7915// persons to whom the Software is furnished to do so, subject to the
7916// following conditions:
7917//
7918// The above copyright notice and this permission notice shall be included
7919// in all copies or substantial portions of the Software.
7920//
7921// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7922// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7923// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7924// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7925// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7926// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7927// USE OR OTHER DEALINGS IN THE SOFTWARE.
7928
7929// A bit simpler than readable streams.
7930// Implement an async ._write(chunk, encoding, cb), and it'll handle all
7931// the drain event emission and buffering.
7932
7933'use strict';
7934
7935module.exports = Writable;
7936
7937/* <replacement> */
7938function WriteReq(chunk, encoding, cb) {
7939 this.chunk = chunk;
7940 this.encoding = encoding;
7941 this.callback = cb;
7942 this.next = null;
7943}
7944
7945// It seems a linked list but it is not
7946// there will be only 2 of these for each stream
7947function CorkedRequest(state) {
7948 var _this = this;
7949 this.next = null;
7950 this.entry = null;
7951 this.finish = function () {
7952 onCorkedFinish(_this, state);
7953 };
7954}
7955/* </replacement> */
7956
7957/*<replacement>*/
7958var Duplex;
7959/*</replacement>*/
7960
7961Writable.WritableState = WritableState;
7962
7963/*<replacement>*/
7964var internalUtil = {
7965 deprecate: _dereq_('util-deprecate')
7966};
7967/*</replacement>*/
7968
7969/*<replacement>*/
7970var Stream = _dereq_('./internal/streams/stream');
7971/*</replacement>*/
7972
7973var Buffer = _dereq_('buffer').Buffer;
7974var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
7975function _uint8ArrayToBuffer(chunk) {
7976 return Buffer.from(chunk);
7977}
7978function _isUint8Array(obj) {
7979 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
7980}
7981var destroyImpl = _dereq_('./internal/streams/destroy');
7982var _require = _dereq_('./internal/streams/state'),
7983 getHighWaterMark = _require.getHighWaterMark;
7984var _require$codes = _dereq_('../errors').codes,
7985 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
7986 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
7987 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
7988 ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
7989 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
7990 ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
7991 ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
7992 ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
7993var errorOrDestroy = destroyImpl.errorOrDestroy;
7994_dereq_('inherits')(Writable, Stream);
7995function nop() {}
7996function WritableState(options, stream, isDuplex) {
7997 Duplex = Duplex || _dereq_('./_stream_duplex');
7998 options = options || {};
7999
8000 // Duplex streams are both readable and writable, but share
8001 // the same options object.
8002 // However, some cases require setting options to different
8003 // values for the readable and the writable sides of the duplex stream,
8004 // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
8005 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;
8006
8007 // object stream flag to indicate whether or not this stream
8008 // contains buffers or objects.
8009 this.objectMode = !!options.objectMode;
8010 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
8011
8012 // the point at which write() starts returning false
8013 // Note: 0 is a valid value, means that we always return false if
8014 // the entire buffer is not flushed immediately on write()
8015 this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex);
8016
8017 // if _final has been called
8018 this.finalCalled = false;
8019
8020 // drain event flag.
8021 this.needDrain = false;
8022 // at the start of calling end()
8023 this.ending = false;
8024 // when end() has been called, and returned
8025 this.ended = false;
8026 // when 'finish' is emitted
8027 this.finished = false;
8028
8029 // has it been destroyed
8030 this.destroyed = false;
8031
8032 // should we decode strings into buffers before passing to _write?
8033 // this is here so that some node-core streams can optimize string
8034 // handling at a lower level.
8035 var noDecode = options.decodeStrings === false;
8036 this.decodeStrings = !noDecode;
8037
8038 // Crypto is kind of old and crusty. Historically, its default string
8039 // encoding is 'binary' so we have to make this configurable.
8040 // Everything else in the universe uses 'utf8', though.
8041 this.defaultEncoding = options.defaultEncoding || 'utf8';
8042
8043 // not an actual buffer we keep track of, but a measurement
8044 // of how much we're waiting to get pushed to some underlying
8045 // socket or file.
8046 this.length = 0;
8047
8048 // a flag to see when we're in the middle of a write.
8049 this.writing = false;
8050
8051 // when true all writes will be buffered until .uncork() call
8052 this.corked = 0;
8053
8054 // a flag to be able to tell if the onwrite cb is called immediately,
8055 // or on a later tick. We set this to true at first, because any
8056 // actions that shouldn't happen until "later" should generally also
8057 // not happen before the first write call.
8058 this.sync = true;
8059
8060 // a flag to know if we're processing previously buffered items, which
8061 // may call the _write() callback in the same tick, so that we don't
8062 // end up in an overlapped onwrite situation.
8063 this.bufferProcessing = false;
8064
8065 // the callback that's passed to _write(chunk,cb)
8066 this.onwrite = function (er) {
8067 onwrite(stream, er);
8068 };
8069
8070 // the callback that the user supplies to write(chunk,encoding,cb)
8071 this.writecb = null;
8072
8073 // the amount that is being written when _write is called.
8074 this.writelen = 0;
8075 this.bufferedRequest = null;
8076 this.lastBufferedRequest = null;
8077
8078 // number of pending user-supplied write callbacks
8079 // this must be 0 before 'finish' can be emitted
8080 this.pendingcb = 0;
8081
8082 // emit prefinish if the only thing we're waiting for is _write cbs
8083 // This is relevant for synchronous Transform streams
8084 this.prefinished = false;
8085
8086 // True if the error was already emitted and should not be thrown again
8087 this.errorEmitted = false;
8088
8089 // Should close be emitted on destroy. Defaults to true.
8090 this.emitClose = options.emitClose !== false;
8091
8092 // Should .destroy() be called after 'finish' (and potentially 'end')
8093 this.autoDestroy = !!options.autoDestroy;
8094
8095 // count buffered requests
8096 this.bufferedRequestCount = 0;
8097
8098 // allocate the first CorkedRequest, there is always
8099 // one allocated and free to use, and we maintain at most two
8100 this.corkedRequestsFree = new CorkedRequest(this);
8101}
8102WritableState.prototype.getBuffer = function getBuffer() {
8103 var current = this.bufferedRequest;
8104 var out = [];
8105 while (current) {
8106 out.push(current);
8107 current = current.next;
8108 }
8109 return out;
8110};
8111(function () {
8112 try {
8113 Object.defineProperty(WritableState.prototype, 'buffer', {
8114 get: internalUtil.deprecate(function writableStateBufferGetter() {
8115 return this.getBuffer();
8116 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
8117 });
8118 } catch (_) {}
8119})();
8120
8121// Test _writableState for inheritance to account for Duplex streams,
8122// whose prototype chain only points to Readable.
8123var realHasInstance;
8124if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
8125 realHasInstance = Function.prototype[Symbol.hasInstance];
8126 Object.defineProperty(Writable, Symbol.hasInstance, {
8127 value: function value(object) {
8128 if (realHasInstance.call(this, object)) return true;
8129 if (this !== Writable) return false;
8130 return object && object._writableState instanceof WritableState;
8131 }
8132 });
8133} else {
8134 realHasInstance = function realHasInstance(object) {
8135 return object instanceof this;
8136 };
8137}
8138function Writable(options) {
8139 Duplex = Duplex || _dereq_('./_stream_duplex');
8140
8141 // Writable ctor is applied to Duplexes, too.
8142 // `realHasInstance` is necessary because using plain `instanceof`
8143 // would return false, as no `_writableState` property is attached.
8144
8145 // Trying to use the custom `instanceof` for Writable here will also break the
8146 // Node.js LazyTransform implementation, which has a non-trivial getter for
8147 // `_writableState` that would lead to infinite recursion.
8148
8149 // Checking for a Stream.Duplex instance is faster here instead of inside
8150 // the WritableState constructor, at least with V8 6.5
8151 var isDuplex = this instanceof Duplex;
8152 if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
8153 this._writableState = new WritableState(options, this, isDuplex);
8154
8155 // legacy.
8156 this.writable = true;
8157 if (options) {
8158 if (typeof options.write === 'function') this._write = options.write;
8159 if (typeof options.writev === 'function') this._writev = options.writev;
8160 if (typeof options.destroy === 'function') this._destroy = options.destroy;
8161 if (typeof options.final === 'function') this._final = options.final;
8162 }
8163 Stream.call(this);
8164}
8165
8166// Otherwise people can pipe Writable streams, which is just wrong.
8167Writable.prototype.pipe = function () {
8168 errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
8169};
8170function writeAfterEnd(stream, cb) {
8171 var er = new ERR_STREAM_WRITE_AFTER_END();
8172 // TODO: defer error events consistently everywhere, not just the cb
8173 errorOrDestroy(stream, er);
8174 process.nextTick(cb, er);
8175}
8176
8177// Checks that a user-supplied chunk is valid, especially for the particular
8178// mode the stream is in. Currently this means that `null` is never accepted
8179// and undefined/non-string values are only allowed in object mode.
8180function validChunk(stream, state, chunk, cb) {
8181 var er;
8182 if (chunk === null) {
8183 er = new ERR_STREAM_NULL_VALUES();
8184 } else if (typeof chunk !== 'string' && !state.objectMode) {
8185 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
8186 }
8187 if (er) {
8188 errorOrDestroy(stream, er);
8189 process.nextTick(cb, er);
8190 return false;
8191 }
8192 return true;
8193}
8194Writable.prototype.write = function (chunk, encoding, cb) {
8195 var state = this._writableState;
8196 var ret = false;
8197 var isBuf = !state.objectMode && _isUint8Array(chunk);
8198 if (isBuf && !Buffer.isBuffer(chunk)) {
8199 chunk = _uint8ArrayToBuffer(chunk);
8200 }
8201 if (typeof encoding === 'function') {
8202 cb = encoding;
8203 encoding = null;
8204 }
8205 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
8206 if (typeof cb !== 'function') cb = nop;
8207 if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
8208 state.pendingcb++;
8209 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
8210 }
8211 return ret;
8212};
8213Writable.prototype.cork = function () {
8214 this._writableState.corked++;
8215};
8216Writable.prototype.uncork = function () {
8217 var state = this._writableState;
8218 if (state.corked) {
8219 state.corked--;
8220 if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
8221 }
8222};
8223Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
8224 // node::ParseEncoding() requires lower case.
8225 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
8226 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);
8227 this._writableState.defaultEncoding = encoding;
8228 return this;
8229};
8230Object.defineProperty(Writable.prototype, 'writableBuffer', {
8231 // making it explicit this property is not enumerable
8232 // because otherwise some prototype manipulation in
8233 // userland will fail
8234 enumerable: false,
8235 get: function get() {
8236 return this._writableState && this._writableState.getBuffer();
8237 }
8238});
8239function decodeChunk(state, chunk, encoding) {
8240 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
8241 chunk = Buffer.from(chunk, encoding);
8242 }
8243 return chunk;
8244}
8245Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
8246 // making it explicit this property is not enumerable
8247 // because otherwise some prototype manipulation in
8248 // userland will fail
8249 enumerable: false,
8250 get: function get() {
8251 return this._writableState.highWaterMark;
8252 }
8253});
8254
8255// if we're already writing something, then just put this
8256// in the queue, and wait our turn. Otherwise, call _write
8257// If we return false, then we need a drain event, so set that flag.
8258function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
8259 if (!isBuf) {
8260 var newChunk = decodeChunk(state, chunk, encoding);
8261 if (chunk !== newChunk) {
8262 isBuf = true;
8263 encoding = 'buffer';
8264 chunk = newChunk;
8265 }
8266 }
8267 var len = state.objectMode ? 1 : chunk.length;
8268 state.length += len;
8269 var ret = state.length < state.highWaterMark;
8270 // we must ensure that previous needDrain will not be reset to false.
8271 if (!ret) state.needDrain = true;
8272 if (state.writing || state.corked) {
8273 var last = state.lastBufferedRequest;
8274 state.lastBufferedRequest = {
8275 chunk: chunk,
8276 encoding: encoding,
8277 isBuf: isBuf,
8278 callback: cb,
8279 next: null
8280 };
8281 if (last) {
8282 last.next = state.lastBufferedRequest;
8283 } else {
8284 state.bufferedRequest = state.lastBufferedRequest;
8285 }
8286 state.bufferedRequestCount += 1;
8287 } else {
8288 doWrite(stream, state, false, len, chunk, encoding, cb);
8289 }
8290 return ret;
8291}
8292function doWrite(stream, state, writev, len, chunk, encoding, cb) {
8293 state.writelen = len;
8294 state.writecb = cb;
8295 state.writing = true;
8296 state.sync = true;
8297 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);
8298 state.sync = false;
8299}
8300function onwriteError(stream, state, sync, er, cb) {
8301 --state.pendingcb;
8302 if (sync) {
8303 // defer the callback if we are being called synchronously
8304 // to avoid piling up things on the stack
8305 process.nextTick(cb, er);
8306 // this can emit finish, and it will always happen
8307 // after error
8308 process.nextTick(finishMaybe, stream, state);
8309 stream._writableState.errorEmitted = true;
8310 errorOrDestroy(stream, er);
8311 } else {
8312 // the caller expect this to happen before if
8313 // it is async
8314 cb(er);
8315 stream._writableState.errorEmitted = true;
8316 errorOrDestroy(stream, er);
8317 // this can emit finish, but finish must
8318 // always follow error
8319 finishMaybe(stream, state);
8320 }
8321}
8322function onwriteStateUpdate(state) {
8323 state.writing = false;
8324 state.writecb = null;
8325 state.length -= state.writelen;
8326 state.writelen = 0;
8327}
8328function onwrite(stream, er) {
8329 var state = stream._writableState;
8330 var sync = state.sync;
8331 var cb = state.writecb;
8332 if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
8333 onwriteStateUpdate(state);
8334 if (er) onwriteError(stream, state, sync, er, cb);else {
8335 // Check if we're actually ready to finish, but don't emit yet
8336 var finished = needFinish(state) || stream.destroyed;
8337 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
8338 clearBuffer(stream, state);
8339 }
8340 if (sync) {
8341 process.nextTick(afterWrite, stream, state, finished, cb);
8342 } else {
8343 afterWrite(stream, state, finished, cb);
8344 }
8345 }
8346}
8347function afterWrite(stream, state, finished, cb) {
8348 if (!finished) onwriteDrain(stream, state);
8349 state.pendingcb--;
8350 cb();
8351 finishMaybe(stream, state);
8352}
8353
8354// Must force callback to be called on nextTick, so that we don't
8355// emit 'drain' before the write() consumer gets the 'false' return
8356// value, and has a chance to attach a 'drain' listener.
8357function onwriteDrain(stream, state) {
8358 if (state.length === 0 && state.needDrain) {
8359 state.needDrain = false;
8360 stream.emit('drain');
8361 }
8362}
8363
8364// if there's something in the buffer waiting, then process it
8365function clearBuffer(stream, state) {
8366 state.bufferProcessing = true;
8367 var entry = state.bufferedRequest;
8368 if (stream._writev && entry && entry.next) {
8369 // Fast case, write everything using _writev()
8370 var l = state.bufferedRequestCount;
8371 var buffer = new Array(l);
8372 var holder = state.corkedRequestsFree;
8373 holder.entry = entry;
8374 var count = 0;
8375 var allBuffers = true;
8376 while (entry) {
8377 buffer[count] = entry;
8378 if (!entry.isBuf) allBuffers = false;
8379 entry = entry.next;
8380 count += 1;
8381 }
8382 buffer.allBuffers = allBuffers;
8383 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
8384
8385 // doWrite is almost always async, defer these to save a bit of time
8386 // as the hot path ends with doWrite
8387 state.pendingcb++;
8388 state.lastBufferedRequest = null;
8389 if (holder.next) {
8390 state.corkedRequestsFree = holder.next;
8391 holder.next = null;
8392 } else {
8393 state.corkedRequestsFree = new CorkedRequest(state);
8394 }
8395 state.bufferedRequestCount = 0;
8396 } else {
8397 // Slow case, write chunks one-by-one
8398 while (entry) {
8399 var chunk = entry.chunk;
8400 var encoding = entry.encoding;
8401 var cb = entry.callback;
8402 var len = state.objectMode ? 1 : chunk.length;
8403 doWrite(stream, state, false, len, chunk, encoding, cb);
8404 entry = entry.next;
8405 state.bufferedRequestCount--;
8406 // if we didn't call the onwrite immediately, then
8407 // it means that we need to wait until it does.
8408 // also, that means that the chunk and cb are currently
8409 // being processed, so move the buffer counter past them.
8410 if (state.writing) {
8411 break;
8412 }
8413 }
8414 if (entry === null) state.lastBufferedRequest = null;
8415 }
8416 state.bufferedRequest = entry;
8417 state.bufferProcessing = false;
8418}
8419Writable.prototype._write = function (chunk, encoding, cb) {
8420 cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
8421};
8422Writable.prototype._writev = null;
8423Writable.prototype.end = function (chunk, encoding, cb) {
8424 var state = this._writableState;
8425 if (typeof chunk === 'function') {
8426 cb = chunk;
8427 chunk = null;
8428 encoding = null;
8429 } else if (typeof encoding === 'function') {
8430 cb = encoding;
8431 encoding = null;
8432 }
8433 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
8434
8435 // .end() fully uncorks
8436 if (state.corked) {
8437 state.corked = 1;
8438 this.uncork();
8439 }
8440
8441 // ignore unnecessary end() calls.
8442 if (!state.ending) endWritable(this, state, cb);
8443 return this;
8444};
8445Object.defineProperty(Writable.prototype, 'writableLength', {
8446 // making it explicit this property is not enumerable
8447 // because otherwise some prototype manipulation in
8448 // userland will fail
8449 enumerable: false,
8450 get: function get() {
8451 return this._writableState.length;
8452 }
8453});
8454function needFinish(state) {
8455 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
8456}
8457function callFinal(stream, state) {
8458 stream._final(function (err) {
8459 state.pendingcb--;
8460 if (err) {
8461 errorOrDestroy(stream, err);
8462 }
8463 state.prefinished = true;
8464 stream.emit('prefinish');
8465 finishMaybe(stream, state);
8466 });
8467}
8468function prefinish(stream, state) {
8469 if (!state.prefinished && !state.finalCalled) {
8470 if (typeof stream._final === 'function' && !state.destroyed) {
8471 state.pendingcb++;
8472 state.finalCalled = true;
8473 process.nextTick(callFinal, stream, state);
8474 } else {
8475 state.prefinished = true;
8476 stream.emit('prefinish');
8477 }
8478 }
8479}
8480function finishMaybe(stream, state) {
8481 var need = needFinish(state);
8482 if (need) {
8483 prefinish(stream, state);
8484 if (state.pendingcb === 0) {
8485 state.finished = true;
8486 stream.emit('finish');
8487 if (state.autoDestroy) {
8488 // In case of duplex streams we need a way to detect
8489 // if the readable side is ready for autoDestroy as well
8490 var rState = stream._readableState;
8491 if (!rState || rState.autoDestroy && rState.endEmitted) {
8492 stream.destroy();
8493 }
8494 }
8495 }
8496 }
8497 return need;
8498}
8499function endWritable(stream, state, cb) {
8500 state.ending = true;
8501 finishMaybe(stream, state);
8502 if (cb) {
8503 if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
8504 }
8505 state.ended = true;
8506 stream.writable = false;
8507}
8508function onCorkedFinish(corkReq, state, err) {
8509 var entry = corkReq.entry;
8510 corkReq.entry = null;
8511 while (entry) {
8512 var cb = entry.callback;
8513 state.pendingcb--;
8514 cb(err);
8515 entry = entry.next;
8516 }
8517
8518 // reuse the free corkReq.
8519 state.corkedRequestsFree.next = corkReq;
8520}
8521Object.defineProperty(Writable.prototype, 'destroyed', {
8522 // making it explicit this property is not enumerable
8523 // because otherwise some prototype manipulation in
8524 // userland will fail
8525 enumerable: false,
8526 get: function get() {
8527 if (this._writableState === undefined) {
8528 return false;
8529 }
8530 return this._writableState.destroyed;
8531 },
8532 set: function set(value) {
8533 // we ignore the value if the stream
8534 // has not been initialized yet
8535 if (!this._writableState) {
8536 return;
8537 }
8538
8539 // backward compatibility, the user is explicitly
8540 // managing destroyed
8541 this._writableState.destroyed = value;
8542 }
8543});
8544Writable.prototype.destroy = destroyImpl.destroy;
8545Writable.prototype._undestroy = destroyImpl.undestroy;
8546Writable.prototype._destroy = function (err, cb) {
8547 cb(err);
8548};
8549}).call(this)}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
8550},{"../errors":60,"./_stream_duplex":61,"./internal/streams/destroy":68,"./internal/streams/state":72,"./internal/streams/stream":73,"_process":94,"buffer":9,"inherits":53,"util-deprecate":142}],66:[function(_dereq_,module,exports){
8551(function (process){(function (){
8552'use strict';
8553
8554var _Object$setPrototypeO;
8555function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
8556function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
8557function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
8558var finished = _dereq_('./end-of-stream');
8559var kLastResolve = Symbol('lastResolve');
8560var kLastReject = Symbol('lastReject');
8561var kError = Symbol('error');
8562var kEnded = Symbol('ended');
8563var kLastPromise = Symbol('lastPromise');
8564var kHandlePromise = Symbol('handlePromise');
8565var kStream = Symbol('stream');
8566function createIterResult(value, done) {
8567 return {
8568 value: value,
8569 done: done
8570 };
8571}
8572function readAndResolve(iter) {
8573 var resolve = iter[kLastResolve];
8574 if (resolve !== null) {
8575 var data = iter[kStream].read();
8576 // we defer if data is null
8577 // we can be expecting either 'end' or
8578 // 'error'
8579 if (data !== null) {
8580 iter[kLastPromise] = null;
8581 iter[kLastResolve] = null;
8582 iter[kLastReject] = null;
8583 resolve(createIterResult(data, false));
8584 }
8585 }
8586}
8587function onReadable(iter) {
8588 // we wait for the next tick, because it might
8589 // emit an error with process.nextTick
8590 process.nextTick(readAndResolve, iter);
8591}
8592function wrapForNext(lastPromise, iter) {
8593 return function (resolve, reject) {
8594 lastPromise.then(function () {
8595 if (iter[kEnded]) {
8596 resolve(createIterResult(undefined, true));
8597 return;
8598 }
8599 iter[kHandlePromise](resolve, reject);
8600 }, reject);
8601 };
8602}
8603var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
8604var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
8605 get stream() {
8606 return this[kStream];
8607 },
8608 next: function next() {
8609 var _this = this;
8610 // if we have detected an error in the meanwhile
8611 // reject straight away
8612 var error = this[kError];
8613 if (error !== null) {
8614 return Promise.reject(error);
8615 }
8616 if (this[kEnded]) {
8617 return Promise.resolve(createIterResult(undefined, true));
8618 }
8619 if (this[kStream].destroyed) {
8620 // We need to defer via nextTick because if .destroy(err) is
8621 // called, the error will be emitted via nextTick, and
8622 // we cannot guarantee that there is no error lingering around
8623 // waiting to be emitted.
8624 return new Promise(function (resolve, reject) {
8625 process.nextTick(function () {
8626 if (_this[kError]) {
8627 reject(_this[kError]);
8628 } else {
8629 resolve(createIterResult(undefined, true));
8630 }
8631 });
8632 });
8633 }
8634
8635 // if we have multiple next() calls
8636 // we will wait for the previous Promise to finish
8637 // this logic is optimized to support for await loops,
8638 // where next() is only called once at a time
8639 var lastPromise = this[kLastPromise];
8640 var promise;
8641 if (lastPromise) {
8642 promise = new Promise(wrapForNext(lastPromise, this));
8643 } else {
8644 // fast path needed to support multiple this.push()
8645 // without triggering the next() queue
8646 var data = this[kStream].read();
8647 if (data !== null) {
8648 return Promise.resolve(createIterResult(data, false));
8649 }
8650 promise = new Promise(this[kHandlePromise]);
8651 }
8652 this[kLastPromise] = promise;
8653 return promise;
8654 }
8655}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
8656 return this;
8657}), _defineProperty(_Object$setPrototypeO, "return", function _return() {
8658 var _this2 = this;
8659 // destroy(err, cb) is a private API
8660 // we can guarantee we have that here, because we control the
8661 // Readable class this is attached to
8662 return new Promise(function (resolve, reject) {
8663 _this2[kStream].destroy(null, function (err) {
8664 if (err) {
8665 reject(err);
8666 return;
8667 }
8668 resolve(createIterResult(undefined, true));
8669 });
8670 });
8671}), _Object$setPrototypeO), AsyncIteratorPrototype);
8672var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
8673 var _Object$create;
8674 var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
8675 value: stream,
8676 writable: true
8677 }), _defineProperty(_Object$create, kLastResolve, {
8678 value: null,
8679 writable: true
8680 }), _defineProperty(_Object$create, kLastReject, {
8681 value: null,
8682 writable: true
8683 }), _defineProperty(_Object$create, kError, {
8684 value: null,
8685 writable: true
8686 }), _defineProperty(_Object$create, kEnded, {
8687 value: stream._readableState.endEmitted,
8688 writable: true
8689 }), _defineProperty(_Object$create, kHandlePromise, {
8690 value: function value(resolve, reject) {
8691 var data = iterator[kStream].read();
8692 if (data) {
8693 iterator[kLastPromise] = null;
8694 iterator[kLastResolve] = null;
8695 iterator[kLastReject] = null;
8696 resolve(createIterResult(data, false));
8697 } else {
8698 iterator[kLastResolve] = resolve;
8699 iterator[kLastReject] = reject;
8700 }
8701 },
8702 writable: true
8703 }), _Object$create));
8704 iterator[kLastPromise] = null;
8705 finished(stream, function (err) {
8706 if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
8707 var reject = iterator[kLastReject];
8708 // reject if we are waiting for data in the Promise
8709 // returned by next() and store the error
8710 if (reject !== null) {
8711 iterator[kLastPromise] = null;
8712 iterator[kLastResolve] = null;
8713 iterator[kLastReject] = null;
8714 reject(err);
8715 }
8716 iterator[kError] = err;
8717 return;
8718 }
8719 var resolve = iterator[kLastResolve];
8720 if (resolve !== null) {
8721 iterator[kLastPromise] = null;
8722 iterator[kLastResolve] = null;
8723 iterator[kLastReject] = null;
8724 resolve(createIterResult(undefined, true));
8725 }
8726 iterator[kEnded] = true;
8727 });
8728 stream.on('readable', onReadable.bind(null, iterator));
8729 return iterator;
8730};
8731module.exports = createReadableStreamAsyncIterator;
8732}).call(this)}).call(this,_dereq_('_process'))
8733},{"./end-of-stream":69,"_process":94}],67:[function(_dereq_,module,exports){
8734'use strict';
8735
8736function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
8737function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
8738function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
8739function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
8740function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
8741function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
8742function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
8743function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
8744var _require = _dereq_('buffer'),
8745 Buffer = _require.Buffer;
8746var _require2 = _dereq_('util'),
8747 inspect = _require2.inspect;
8748var custom = inspect && inspect.custom || 'inspect';
8749function copyBuffer(src, target, offset) {
8750 Buffer.prototype.copy.call(src, target, offset);
8751}
8752module.exports = /*#__PURE__*/function () {
8753 function BufferList() {
8754 _classCallCheck(this, BufferList);
8755 this.head = null;
8756 this.tail = null;
8757 this.length = 0;
8758 }
8759 _createClass(BufferList, [{
8760 key: "push",
8761 value: function push(v) {
8762 var entry = {
8763 data: v,
8764 next: null
8765 };
8766 if (this.length > 0) this.tail.next = entry;else this.head = entry;
8767 this.tail = entry;
8768 ++this.length;
8769 }
8770 }, {
8771 key: "unshift",
8772 value: function unshift(v) {
8773 var entry = {
8774 data: v,
8775 next: this.head
8776 };
8777 if (this.length === 0) this.tail = entry;
8778 this.head = entry;
8779 ++this.length;
8780 }
8781 }, {
8782 key: "shift",
8783 value: function shift() {
8784 if (this.length === 0) return;
8785 var ret = this.head.data;
8786 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
8787 --this.length;
8788 return ret;
8789 }
8790 }, {
8791 key: "clear",
8792 value: function clear() {
8793 this.head = this.tail = null;
8794 this.length = 0;
8795 }
8796 }, {
8797 key: "join",
8798 value: function join(s) {
8799 if (this.length === 0) return '';
8800 var p = this.head;
8801 var ret = '' + p.data;
8802 while (p = p.next) ret += s + p.data;
8803 return ret;
8804 }
8805 }, {
8806 key: "concat",
8807 value: function concat(n) {
8808 if (this.length === 0) return Buffer.alloc(0);
8809 var ret = Buffer.allocUnsafe(n >>> 0);
8810 var p = this.head;
8811 var i = 0;
8812 while (p) {
8813 copyBuffer(p.data, ret, i);
8814 i += p.data.length;
8815 p = p.next;
8816 }
8817 return ret;
8818 }
8819
8820 // Consumes a specified amount of bytes or characters from the buffered data.
8821 }, {
8822 key: "consume",
8823 value: function consume(n, hasStrings) {
8824 var ret;
8825 if (n < this.head.data.length) {
8826 // `slice` is the same for buffers and strings.
8827 ret = this.head.data.slice(0, n);
8828 this.head.data = this.head.data.slice(n);
8829 } else if (n === this.head.data.length) {
8830 // First chunk is a perfect match.
8831 ret = this.shift();
8832 } else {
8833 // Result spans more than one buffer.
8834 ret = hasStrings ? this._getString(n) : this._getBuffer(n);
8835 }
8836 return ret;
8837 }
8838 }, {
8839 key: "first",
8840 value: function first() {
8841 return this.head.data;
8842 }
8843
8844 // Consumes a specified amount of characters from the buffered data.
8845 }, {
8846 key: "_getString",
8847 value: function _getString(n) {
8848 var p = this.head;
8849 var c = 1;
8850 var ret = p.data;
8851 n -= ret.length;
8852 while (p = p.next) {
8853 var str = p.data;
8854 var nb = n > str.length ? str.length : n;
8855 if (nb === str.length) ret += str;else ret += str.slice(0, n);
8856 n -= nb;
8857 if (n === 0) {
8858 if (nb === str.length) {
8859 ++c;
8860 if (p.next) this.head = p.next;else this.head = this.tail = null;
8861 } else {
8862 this.head = p;
8863 p.data = str.slice(nb);
8864 }
8865 break;
8866 }
8867 ++c;
8868 }
8869 this.length -= c;
8870 return ret;
8871 }
8872
8873 // Consumes a specified amount of bytes from the buffered data.
8874 }, {
8875 key: "_getBuffer",
8876 value: function _getBuffer(n) {
8877 var ret = Buffer.allocUnsafe(n);
8878 var p = this.head;
8879 var c = 1;
8880 p.data.copy(ret);
8881 n -= p.data.length;
8882 while (p = p.next) {
8883 var buf = p.data;
8884 var nb = n > buf.length ? buf.length : n;
8885 buf.copy(ret, ret.length - n, 0, nb);
8886 n -= nb;
8887 if (n === 0) {
8888 if (nb === buf.length) {
8889 ++c;
8890 if (p.next) this.head = p.next;else this.head = this.tail = null;
8891 } else {
8892 this.head = p;
8893 p.data = buf.slice(nb);
8894 }
8895 break;
8896 }
8897 ++c;
8898 }
8899 this.length -= c;
8900 return ret;
8901 }
8902
8903 // Make sure the linked list only shows the minimal necessary information.
8904 }, {
8905 key: custom,
8906 value: function value(_, options) {
8907 return inspect(this, _objectSpread(_objectSpread({}, options), {}, {
8908 // Only inspect one level.
8909 depth: 0,
8910 // It should not recurse.
8911 customInspect: false
8912 }));
8913 }
8914 }]);
8915 return BufferList;
8916}();
8917},{"buffer":9,"util":8}],68:[function(_dereq_,module,exports){
8918(function (process){(function (){
8919'use strict';
8920
8921// undocumented cb() API, needed for core, not for public API
8922function destroy(err, cb) {
8923 var _this = this;
8924 var readableDestroyed = this._readableState && this._readableState.destroyed;
8925 var writableDestroyed = this._writableState && this._writableState.destroyed;
8926 if (readableDestroyed || writableDestroyed) {
8927 if (cb) {
8928 cb(err);
8929 } else if (err) {
8930 if (!this._writableState) {
8931 process.nextTick(emitErrorNT, this, err);
8932 } else if (!this._writableState.errorEmitted) {
8933 this._writableState.errorEmitted = true;
8934 process.nextTick(emitErrorNT, this, err);
8935 }
8936 }
8937 return this;
8938 }
8939
8940 // we set destroyed to true before firing error callbacks in order
8941 // to make it re-entrance safe in case destroy() is called within callbacks
8942
8943 if (this._readableState) {
8944 this._readableState.destroyed = true;
8945 }
8946
8947 // if this is a duplex stream mark the writable part as destroyed as well
8948 if (this._writableState) {
8949 this._writableState.destroyed = true;
8950 }
8951 this._destroy(err || null, function (err) {
8952 if (!cb && err) {
8953 if (!_this._writableState) {
8954 process.nextTick(emitErrorAndCloseNT, _this, err);
8955 } else if (!_this._writableState.errorEmitted) {
8956 _this._writableState.errorEmitted = true;
8957 process.nextTick(emitErrorAndCloseNT, _this, err);
8958 } else {
8959 process.nextTick(emitCloseNT, _this);
8960 }
8961 } else if (cb) {
8962 process.nextTick(emitCloseNT, _this);
8963 cb(err);
8964 } else {
8965 process.nextTick(emitCloseNT, _this);
8966 }
8967 });
8968 return this;
8969}
8970function emitErrorAndCloseNT(self, err) {
8971 emitErrorNT(self, err);
8972 emitCloseNT(self);
8973}
8974function emitCloseNT(self) {
8975 if (self._writableState && !self._writableState.emitClose) return;
8976 if (self._readableState && !self._readableState.emitClose) return;
8977 self.emit('close');
8978}
8979function undestroy() {
8980 if (this._readableState) {
8981 this._readableState.destroyed = false;
8982 this._readableState.reading = false;
8983 this._readableState.ended = false;
8984 this._readableState.endEmitted = false;
8985 }
8986 if (this._writableState) {
8987 this._writableState.destroyed = false;
8988 this._writableState.ended = false;
8989 this._writableState.ending = false;
8990 this._writableState.finalCalled = false;
8991 this._writableState.prefinished = false;
8992 this._writableState.finished = false;
8993 this._writableState.errorEmitted = false;
8994 }
8995}
8996function emitErrorNT(self, err) {
8997 self.emit('error', err);
8998}
8999function errorOrDestroy(stream, err) {
9000 // We have tests that rely on errors being emitted
9001 // in the same tick, so changing this is semver major.
9002 // For now when you opt-in to autoDestroy we allow
9003 // the error to be emitted nextTick. In a future
9004 // semver major update we should change the default to this.
9005
9006 var rState = stream._readableState;
9007 var wState = stream._writableState;
9008 if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
9009}
9010module.exports = {
9011 destroy: destroy,
9012 undestroy: undestroy,
9013 errorOrDestroy: errorOrDestroy
9014};
9015}).call(this)}).call(this,_dereq_('_process'))
9016},{"_process":94}],69:[function(_dereq_,module,exports){
9017// Ported from https://github.com/mafintosh/end-of-stream with
9018// permission from the author, Mathias Buus (@mafintosh).
9019
9020'use strict';
9021
9022var ERR_STREAM_PREMATURE_CLOSE = _dereq_('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;
9023function once(callback) {
9024 var called = false;
9025 return function () {
9026 if (called) return;
9027 called = true;
9028 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
9029 args[_key] = arguments[_key];
9030 }
9031 callback.apply(this, args);
9032 };
9033}
9034function noop() {}
9035function isRequest(stream) {
9036 return stream.setHeader && typeof stream.abort === 'function';
9037}
9038function eos(stream, opts, callback) {
9039 if (typeof opts === 'function') return eos(stream, null, opts);
9040 if (!opts) opts = {};
9041 callback = once(callback || noop);
9042 var readable = opts.readable || opts.readable !== false && stream.readable;
9043 var writable = opts.writable || opts.writable !== false && stream.writable;
9044 var onlegacyfinish = function onlegacyfinish() {
9045 if (!stream.writable) onfinish();
9046 };
9047 var writableEnded = stream._writableState && stream._writableState.finished;
9048 var onfinish = function onfinish() {
9049 writable = false;
9050 writableEnded = true;
9051 if (!readable) callback.call(stream);
9052 };
9053 var readableEnded = stream._readableState && stream._readableState.endEmitted;
9054 var onend = function onend() {
9055 readable = false;
9056 readableEnded = true;
9057 if (!writable) callback.call(stream);
9058 };
9059 var onerror = function onerror(err) {
9060 callback.call(stream, err);
9061 };
9062 var onclose = function onclose() {
9063 var err;
9064 if (readable && !readableEnded) {
9065 if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
9066 return callback.call(stream, err);
9067 }
9068 if (writable && !writableEnded) {
9069 if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
9070 return callback.call(stream, err);
9071 }
9072 };
9073 var onrequest = function onrequest() {
9074 stream.req.on('finish', onfinish);
9075 };
9076 if (isRequest(stream)) {
9077 stream.on('complete', onfinish);
9078 stream.on('abort', onclose);
9079 if (stream.req) onrequest();else stream.on('request', onrequest);
9080 } else if (writable && !stream._writableState) {
9081 // legacy streams
9082 stream.on('end', onlegacyfinish);
9083 stream.on('close', onlegacyfinish);
9084 }
9085 stream.on('end', onend);
9086 stream.on('finish', onfinish);
9087 if (opts.error !== false) stream.on('error', onerror);
9088 stream.on('close', onclose);
9089 return function () {
9090 stream.removeListener('complete', onfinish);
9091 stream.removeListener('abort', onclose);
9092 stream.removeListener('request', onrequest);
9093 if (stream.req) stream.req.removeListener('finish', onfinish);
9094 stream.removeListener('end', onlegacyfinish);
9095 stream.removeListener('close', onlegacyfinish);
9096 stream.removeListener('finish', onfinish);
9097 stream.removeListener('end', onend);
9098 stream.removeListener('error', onerror);
9099 stream.removeListener('close', onclose);
9100 };
9101}
9102module.exports = eos;
9103},{"../../../errors":60}],70:[function(_dereq_,module,exports){
9104module.exports = function () {
9105 throw new Error('Readable.from is not available in the browser')
9106};
9107
9108},{}],71:[function(_dereq_,module,exports){
9109// Ported from https://github.com/mafintosh/pump with
9110// permission from the author, Mathias Buus (@mafintosh).
9111
9112'use strict';
9113
9114var eos;
9115function once(callback) {
9116 var called = false;
9117 return function () {
9118 if (called) return;
9119 called = true;
9120 callback.apply(void 0, arguments);
9121 };
9122}
9123var _require$codes = _dereq_('../../../errors').codes,
9124 ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
9125 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
9126function noop(err) {
9127 // Rethrow the error if it exists to avoid swallowing it
9128 if (err) throw err;
9129}
9130function isRequest(stream) {
9131 return stream.setHeader && typeof stream.abort === 'function';
9132}
9133function destroyer(stream, reading, writing, callback) {
9134 callback = once(callback);
9135 var closed = false;
9136 stream.on('close', function () {
9137 closed = true;
9138 });
9139 if (eos === undefined) eos = _dereq_('./end-of-stream');
9140 eos(stream, {
9141 readable: reading,
9142 writable: writing
9143 }, function (err) {
9144 if (err) return callback(err);
9145 closed = true;
9146 callback();
9147 });
9148 var destroyed = false;
9149 return function (err) {
9150 if (closed) return;
9151 if (destroyed) return;
9152 destroyed = true;
9153
9154 // request.destroy just do .end - .abort is what we want
9155 if (isRequest(stream)) return stream.abort();
9156 if (typeof stream.destroy === 'function') return stream.destroy();
9157 callback(err || new ERR_STREAM_DESTROYED('pipe'));
9158 };
9159}
9160function call(fn) {
9161 fn();
9162}
9163function pipe(from, to) {
9164 return from.pipe(to);
9165}
9166function popCallback(streams) {
9167 if (!streams.length) return noop;
9168 if (typeof streams[streams.length - 1] !== 'function') return noop;
9169 return streams.pop();
9170}
9171function pipeline() {
9172 for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
9173 streams[_key] = arguments[_key];
9174 }
9175 var callback = popCallback(streams);
9176 if (Array.isArray(streams[0])) streams = streams[0];
9177 if (streams.length < 2) {
9178 throw new ERR_MISSING_ARGS('streams');
9179 }
9180 var error;
9181 var destroys = streams.map(function (stream, i) {
9182 var reading = i < streams.length - 1;
9183 var writing = i > 0;
9184 return destroyer(stream, reading, writing, function (err) {
9185 if (!error) error = err;
9186 if (err) destroys.forEach(call);
9187 if (reading) return;
9188 destroys.forEach(call);
9189 callback(error);
9190 });
9191 });
9192 return streams.reduce(pipe);
9193}
9194module.exports = pipeline;
9195},{"../../../errors":60,"./end-of-stream":69}],72:[function(_dereq_,module,exports){
9196'use strict';
9197
9198var ERR_INVALID_OPT_VALUE = _dereq_('../../../errors').codes.ERR_INVALID_OPT_VALUE;
9199function highWaterMarkFrom(options, isDuplex, duplexKey) {
9200 return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
9201}
9202function getHighWaterMark(state, options, duplexKey, isDuplex) {
9203 var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
9204 if (hwm != null) {
9205 if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
9206 var name = isDuplex ? duplexKey : 'highWaterMark';
9207 throw new ERR_INVALID_OPT_VALUE(name, hwm);
9208 }
9209 return Math.floor(hwm);
9210 }
9211
9212 // Default value
9213 return state.objectMode ? 16 : 16 * 1024;
9214}
9215module.exports = {
9216 getHighWaterMark: getHighWaterMark
9217};
9218},{"../../../errors":60}],73:[function(_dereq_,module,exports){
9219module.exports = _dereq_('events').EventEmitter;
9220
9221},{"events":39}],74:[function(_dereq_,module,exports){
9222exports = module.exports = _dereq_('./lib/_stream_readable.js');
9223exports.Stream = exports;
9224exports.Readable = exports;
9225exports.Writable = _dereq_('./lib/_stream_writable.js');
9226exports.Duplex = _dereq_('./lib/_stream_duplex.js');
9227exports.Transform = _dereq_('./lib/_stream_transform.js');
9228exports.PassThrough = _dereq_('./lib/_stream_passthrough.js');
9229exports.finished = _dereq_('./lib/internal/streams/end-of-stream.js');
9230exports.pipeline = _dereq_('./lib/internal/streams/pipeline.js');
9231
9232},{"./lib/_stream_duplex.js":61,"./lib/_stream_passthrough.js":62,"./lib/_stream_readable.js":63,"./lib/_stream_transform.js":64,"./lib/_stream_writable.js":65,"./lib/internal/streams/end-of-stream.js":69,"./lib/internal/streams/pipeline.js":71}],75:[function(_dereq_,module,exports){
9233'use strict'
9234
9235// For (old) browser support
9236var xtend = _dereq_('xtend')
9237var assign = _dereq_('xtend/mutable')
9238
9239module.exports = function supports () {
9240 var manifest = xtend.apply(null, arguments)
9241
9242 return assign(manifest, {
9243 // Features of abstract-leveldown
9244 bufferKeys: manifest.bufferKeys || false,
9245 snapshots: manifest.snapshots || false,
9246 permanence: manifest.permanence || false,
9247 seek: manifest.seek || false,
9248 clear: manifest.clear || false,
9249
9250 // Features of abstract-leveldown that levelup doesn't have
9251 status: manifest.status || false,
9252
9253 // Features of disk-based implementations
9254 createIfMissing: manifest.createIfMissing || false,
9255 errorIfExists: manifest.errorIfExists || false,
9256
9257 // Features of level(up) that abstract-leveldown doesn't have yet
9258 deferredOpen: manifest.deferredOpen || false,
9259 openCallback: manifest.openCallback || false,
9260 promises: manifest.promises || false,
9261 streams: manifest.streams || false,
9262 encodings: manifest.encodings || false,
9263
9264 // Methods that are not part of abstract-leveldown or levelup
9265 additionalMethods: xtend(manifest.additionalMethods)
9266 })
9267}
9268
9269},{"xtend":162,"xtend/mutable":163}],76:[function(_dereq_,module,exports){
9270var WriteError = _dereq_('level-errors').WriteError
9271var promisify = _dereq_('./promisify')
9272var getCallback = _dereq_('./common').getCallback
9273var getOptions = _dereq_('./common').getOptions
9274
9275function Batch (levelup) {
9276 // TODO (next major): remove this._levelup alias
9277 this.db = this._levelup = levelup
9278 this.batch = levelup.db.batch()
9279 this.ops = []
9280 this.length = 0
9281}
9282
9283Batch.prototype.put = function (key, value) {
9284 try {
9285 this.batch.put(key, value)
9286 } catch (e) {
9287 throw new WriteError(e)
9288 }
9289
9290 this.ops.push({ type: 'put', key: key, value: value })
9291 this.length++
9292
9293 return this
9294}
9295
9296Batch.prototype.del = function (key) {
9297 try {
9298 this.batch.del(key)
9299 } catch (err) {
9300 throw new WriteError(err)
9301 }
9302
9303 this.ops.push({ type: 'del', key: key })
9304 this.length++
9305
9306 return this
9307}
9308
9309Batch.prototype.clear = function () {
9310 try {
9311 this.batch.clear()
9312 } catch (err) {
9313 throw new WriteError(err)
9314 }
9315
9316 this.ops = []
9317 this.length = 0
9318
9319 return this
9320}
9321
9322Batch.prototype.write = function (options, callback) {
9323 var levelup = this._levelup
9324 var ops = this.ops
9325 var promise
9326
9327 callback = getCallback(options, callback)
9328
9329 if (!callback) {
9330 callback = promisify()
9331 promise = callback.promise
9332 }
9333
9334 options = getOptions(options)
9335
9336 try {
9337 this.batch.write(options, function (err) {
9338 if (err) { return callback(new WriteError(err)) }
9339 levelup.emit('batch', ops)
9340 callback()
9341 })
9342 } catch (err) {
9343 throw new WriteError(err)
9344 }
9345
9346 return promise
9347}
9348
9349module.exports = Batch
9350
9351},{"./common":77,"./promisify":79,"level-errors":58}],77:[function(_dereq_,module,exports){
9352exports.getCallback = function (options, callback) {
9353 return typeof options === 'function' ? options : callback
9354}
9355
9356exports.getOptions = function (options) {
9357 return typeof options === 'object' && options !== null ? options : {}
9358}
9359
9360},{}],78:[function(_dereq_,module,exports){
9361(function (process){(function (){
9362var EventEmitter = _dereq_('events').EventEmitter
9363var inherits = _dereq_('util').inherits
9364var extend = _dereq_('xtend')
9365var DeferredLevelDOWN = _dereq_('deferred-leveldown')
9366var IteratorStream = _dereq_('level-iterator-stream')
9367var Batch = _dereq_('./batch')
9368var errors = _dereq_('level-errors')
9369var supports = _dereq_('level-supports')
9370var assert = _dereq_('assert')
9371var promisify = _dereq_('./promisify')
9372var getCallback = _dereq_('./common').getCallback
9373var getOptions = _dereq_('./common').getOptions
9374
9375var WriteError = errors.WriteError
9376var ReadError = errors.ReadError
9377var NotFoundError = errors.NotFoundError
9378var OpenError = errors.OpenError
9379var InitializationError = errors.InitializationError
9380
9381// Possible AbstractLevelDOWN#status values:
9382// - 'new' - newly created, not opened or closed
9383// - 'opening' - waiting for the database to be opened, post open()
9384// - 'open' - successfully opened the database, available for use
9385// - 'closing' - waiting for the database to be closed, post close()
9386// - 'closed' - database has been successfully closed, should not be
9387// used except for another open() operation
9388
9389function LevelUP (db, options, callback) {
9390 if (!(this instanceof LevelUP)) {
9391 return new LevelUP(db, options, callback)
9392 }
9393
9394 var error
9395 var self = this
9396
9397 EventEmitter.call(this)
9398 this.setMaxListeners(Infinity)
9399
9400 if (typeof options === 'function') {
9401 callback = options
9402 options = {}
9403 }
9404
9405 options = options || {}
9406
9407 if (!db || typeof db !== 'object') {
9408 error = new InitializationError('First argument must be an abstract-leveldown compliant store')
9409 if (typeof callback === 'function') {
9410 return process.nextTick(callback, error)
9411 }
9412 throw error
9413 }
9414
9415 assert.strictEqual(typeof db.status, 'string', '.status required, old abstract-leveldown')
9416
9417 this.options = getOptions(options)
9418 this._db = db
9419 this.db = new DeferredLevelDOWN(db)
9420 this.open(callback || function (err) {
9421 if (err) self.emit('error', err)
9422 })
9423
9424 // Create manifest based on deferred-leveldown's
9425 this.supports = supports(this.db.supports, {
9426 status: false,
9427 deferredOpen: true,
9428 openCallback: true,
9429 promises: true,
9430 streams: true
9431 })
9432
9433 // Experimental: enrich levelup interface
9434 Object.keys(this.supports.additionalMethods).forEach(function (method) {
9435 if (this[method] != null) return
9436
9437 // Don't do this.db[method].bind() because this.db is dynamic.
9438 this[method] = function () {
9439 return this.db[method].apply(this.db, arguments)
9440 }
9441 }, this)
9442}
9443
9444LevelUP.prototype.emit = EventEmitter.prototype.emit
9445LevelUP.prototype.once = EventEmitter.prototype.once
9446inherits(LevelUP, EventEmitter)
9447
9448LevelUP.prototype.open = function (opts, callback) {
9449 var self = this
9450 var promise
9451
9452 if (typeof opts === 'function') {
9453 callback = opts
9454 opts = null
9455 }
9456
9457 if (!callback) {
9458 callback = promisify()
9459 promise = callback.promise
9460 }
9461
9462 if (!opts) {
9463 opts = this.options
9464 }
9465
9466 if (this.isOpen()) {
9467 process.nextTick(callback, null, self)
9468 return promise
9469 }
9470
9471 if (this._isOpening()) {
9472 this.once('open', function () { callback(null, self) })
9473 return promise
9474 }
9475
9476 this.emit('opening')
9477
9478 this.db.open(opts, function (err) {
9479 if (err) {
9480 return callback(new OpenError(err))
9481 }
9482 self.db = self._db
9483 callback(null, self)
9484 self.emit('open')
9485 self.emit('ready')
9486 })
9487
9488 return promise
9489}
9490
9491LevelUP.prototype.close = function (callback) {
9492 var self = this
9493 var promise
9494
9495 if (!callback) {
9496 callback = promisify()
9497 promise = callback.promise
9498 }
9499
9500 if (this.isOpen()) {
9501 this.db.close(function () {
9502 self.emit('closed')
9503 callback.apply(null, arguments)
9504 })
9505 this.emit('closing')
9506 this.db = new DeferredLevelDOWN(this._db)
9507 } else if (this.isClosed()) {
9508 process.nextTick(callback)
9509 } else if (this.db.status === 'closing') {
9510 this.once('closed', callback)
9511 } else if (this._isOpening()) {
9512 this.once('open', function () {
9513 self.close(callback)
9514 })
9515 }
9516
9517 return promise
9518}
9519
9520LevelUP.prototype.isOpen = function () {
9521 return this.db.status === 'open'
9522}
9523
9524LevelUP.prototype._isOpening = function () {
9525 return this.db.status === 'opening'
9526}
9527
9528LevelUP.prototype.isClosed = function () {
9529 return (/^clos|new/).test(this.db.status)
9530}
9531
9532LevelUP.prototype.get = function (key, options, callback) {
9533 var promise
9534
9535 callback = getCallback(options, callback)
9536
9537 if (!callback) {
9538 callback = promisify()
9539 promise = callback.promise
9540 }
9541
9542 if (maybeError(this, callback)) { return promise }
9543
9544 options = getOptions(options)
9545
9546 this.db.get(key, options, function (err, value) {
9547 if (err) {
9548 if ((/notfound/i).test(err) || err.notFound) {
9549 err = new NotFoundError('Key not found in database [' + key + ']', err)
9550 } else {
9551 err = new ReadError(err)
9552 }
9553 return callback(err)
9554 }
9555 callback(null, value)
9556 })
9557
9558 return promise
9559}
9560
9561LevelUP.prototype.put = function (key, value, options, callback) {
9562 var self = this
9563 var promise
9564
9565 callback = getCallback(options, callback)
9566
9567 if (!callback) {
9568 callback = promisify()
9569 promise = callback.promise
9570 }
9571
9572 if (maybeError(this, callback)) { return promise }
9573
9574 options = getOptions(options)
9575
9576 this.db.put(key, value, options, function (err) {
9577 if (err) {
9578 return callback(new WriteError(err))
9579 }
9580 self.emit('put', key, value)
9581 callback()
9582 })
9583
9584 return promise
9585}
9586
9587LevelUP.prototype.del = function (key, options, callback) {
9588 var self = this
9589 var promise
9590
9591 callback = getCallback(options, callback)
9592
9593 if (!callback) {
9594 callback = promisify()
9595 promise = callback.promise
9596 }
9597
9598 if (maybeError(this, callback)) { return promise }
9599
9600 options = getOptions(options)
9601
9602 this.db.del(key, options, function (err) {
9603 if (err) {
9604 return callback(new WriteError(err))
9605 }
9606 self.emit('del', key)
9607 callback()
9608 })
9609
9610 return promise
9611}
9612
9613LevelUP.prototype.batch = function (arr, options, callback) {
9614 if (!arguments.length) {
9615 return new Batch(this)
9616 }
9617
9618 var self = this
9619 var promise
9620
9621 if (typeof arr === 'function') callback = arr
9622 else callback = getCallback(options, callback)
9623
9624 if (!callback) {
9625 callback = promisify()
9626 promise = callback.promise
9627 }
9628
9629 if (maybeError(this, callback)) { return promise }
9630
9631 options = getOptions(options)
9632
9633 this.db.batch(arr, options, function (err) {
9634 if (err) {
9635 return callback(new WriteError(err))
9636 }
9637 self.emit('batch', arr)
9638 callback()
9639 })
9640
9641 return promise
9642}
9643
9644LevelUP.prototype.iterator = function (options) {
9645 return this.db.iterator(options)
9646}
9647
9648LevelUP.prototype.clear = function (options, callback) {
9649 var self = this
9650 var promise
9651
9652 callback = getCallback(options, callback)
9653 options = getOptions(options)
9654
9655 if (!callback) {
9656 callback = promisify()
9657 promise = callback.promise
9658 }
9659
9660 if (maybeError(this, callback)) {
9661 return promise
9662 }
9663
9664 this.db.clear(options, function (err) {
9665 if (err) {
9666 return callback(new WriteError(err))
9667 }
9668 self.emit('clear', options)
9669 callback()
9670 })
9671
9672 return promise
9673}
9674
9675LevelUP.prototype.readStream =
9676LevelUP.prototype.createReadStream = function (options) {
9677 options = extend({ keys: true, values: true }, options)
9678 if (typeof options.limit !== 'number') { options.limit = -1 }
9679 return new IteratorStream(this.db.iterator(options), options)
9680}
9681
9682LevelUP.prototype.keyStream =
9683LevelUP.prototype.createKeyStream = function (options) {
9684 return this.createReadStream(extend(options, { keys: true, values: false }))
9685}
9686
9687LevelUP.prototype.valueStream =
9688LevelUP.prototype.createValueStream = function (options) {
9689 return this.createReadStream(extend(options, { keys: false, values: true }))
9690}
9691
9692LevelUP.prototype.toString = function () {
9693 return 'LevelUP'
9694}
9695
9696LevelUP.prototype.type = 'levelup'
9697
9698function maybeError (db, callback) {
9699 if (!db._isOpening() && !db.isOpen()) {
9700 process.nextTick(callback, new ReadError('Database is not open'))
9701 return true
9702 }
9703}
9704
9705LevelUP.errors = errors
9706module.exports = LevelUP.default = LevelUP
9707
9708}).call(this)}).call(this,_dereq_('_process'))
9709},{"./batch":76,"./common":77,"./promisify":79,"_process":94,"assert":6,"deferred-leveldown":15,"events":39,"level-errors":58,"level-iterator-stream":59,"level-supports":75,"util":145,"xtend":162}],79:[function(_dereq_,module,exports){
9710function promisify () {
9711 var callback
9712 var promise = new Promise(function (resolve, reject) {
9713 callback = function callback (err, value) {
9714 if (err) reject(err)
9715 else resolve(value)
9716 }
9717 })
9718 callback.promise = promise
9719 return callback
9720}
9721
9722module.exports = promisify
9723
9724},{}],80:[function(_dereq_,module,exports){
9725(function (Buffer,process,global){(function (){
9726'use strict';
9727
9728var inherits = _dereq_('inherits');
9729var bufferFrom = _dereq_('buffer-from');
9730var AbstractLevelDOWN = _dereq_('abstract-leveldown').AbstractLevelDOWN;
9731var AbstractIterator = _dereq_('abstract-leveldown').AbstractIterator;
9732
9733var LocalStorage = _dereq_('./localstorage').LocalStorage;
9734var LocalStorageCore = _dereq_('./localstorage-core');
9735var utils = _dereq_('./utils');
9736
9737// see http://stackoverflow.com/a/15349865/680742
9738var nextTick = global.setImmediate || process.nextTick;
9739
9740function LDIterator(db, options) {
9741
9742 AbstractIterator.call(this, db);
9743
9744 this._reverse = !!options.reverse;
9745 this._endkey = options.end;
9746 this._startkey = options.start;
9747 this._gt = options.gt;
9748 this._gte = options.gte;
9749 this._lt = options.lt;
9750 this._lte = options.lte;
9751 this._exclusiveStart = options.exclusiveStart;
9752 this._keysOnly = options.values === false;
9753 this._limit = options.limit;
9754 this._count = 0;
9755
9756 this.onInitCompleteListeners = [];
9757}
9758
9759inherits(LDIterator, AbstractIterator);
9760
9761LDIterator.prototype._init = function (callback) {
9762 nextTick(function () {
9763 callback();
9764 });
9765};
9766
9767LDIterator.prototype._next = function (callback) {
9768 var self = this;
9769
9770 function onInitComplete() {
9771 if (self._pos === self._keys.length || self._pos < 0) { // done reading
9772 return callback();
9773 }
9774
9775 var key = self._keys[self._pos];
9776
9777 if (!!self._endkey && (self._reverse ? key < self._endkey : key > self._endkey)) {
9778 return callback();
9779 }
9780
9781 if (!!self._limit && self._limit > 0 && self._count++ >= self._limit) {
9782 return callback();
9783 }
9784
9785 if ((self._lt && key >= self._lt) ||
9786 (self._lte && key > self._lte) ||
9787 (self._gt && key <= self._gt) ||
9788 (self._gte && key < self._gte)) {
9789 return callback();
9790 }
9791
9792 self._pos += self._reverse ? -1 : 1;
9793 if (self._keysOnly) {
9794 return callback(null, key);
9795 }
9796
9797 self.db.container.getItem(key, function (err, value) {
9798 if (err) {
9799 if (err.message === 'NotFound') {
9800 return nextTick(function () {
9801 self._next(callback);
9802 });
9803 }
9804 return callback(err);
9805 }
9806 callback(null, key, value);
9807 });
9808 }
9809 if (!self.initStarted) {
9810 process.nextTick(function () {
9811 self.initStarted = true;
9812 self._init(function (err) {
9813 if (err) {
9814 return callback(err);
9815 }
9816 self.db.container.keys(function (err, keys) {
9817 if (err) {
9818 return callback(err);
9819 }
9820 self._keys = keys;
9821 if (self._startkey) {
9822 var index = utils.sortedIndexOf(self._keys, self._startkey);
9823 var startkey = (index >= self._keys.length || index < 0) ?
9824 undefined : self._keys[index];
9825 self._pos = index;
9826 if (self._reverse) {
9827 if (self._exclusiveStart || startkey !== self._startkey) {
9828 self._pos--;
9829 }
9830 } else if (self._exclusiveStart && startkey === self._startkey) {
9831 self._pos++;
9832 }
9833 } else {
9834 self._pos = self._reverse ? self._keys.length - 1 : 0;
9835 }
9836 onInitComplete();
9837
9838 self.initCompleted = true;
9839 var i = -1;
9840 while (++i < self.onInitCompleteListeners.length) {
9841 nextTick(self.onInitCompleteListeners[i]);
9842 }
9843 });
9844 });
9845 });
9846 } else if (!self.initCompleted) {
9847 self.onInitCompleteListeners.push(onInitComplete);
9848 } else {
9849 process.nextTick(onInitComplete);
9850 }
9851};
9852
9853function LD(location) {
9854 if (!(this instanceof LD)) {
9855 return new LD(location);
9856 }
9857 AbstractLevelDOWN.call(this, location);
9858 this.container = new LocalStorage(location);
9859}
9860
9861inherits(LD, AbstractLevelDOWN);
9862
9863LD.prototype._open = function (options, callback) {
9864 this.container.init(callback);
9865};
9866
9867LD.prototype._put = function (key, value, options, callback) {
9868
9869 var err = checkKeyValue(key, 'key');
9870
9871 if (err) {
9872 return nextTick(function () {
9873 callback(err);
9874 });
9875 }
9876
9877 err = checkKeyValue(value, 'value');
9878
9879 if (err) {
9880 return nextTick(function () {
9881 callback(err);
9882 });
9883 }
9884
9885 if (typeof value === 'object' && !Buffer.isBuffer(value) && value.buffer === undefined) {
9886 var obj = {};
9887 obj.storetype = "json";
9888 obj.data = value;
9889 value = JSON.stringify(obj);
9890 }
9891
9892 this.container.setItem(key, value, callback);
9893};
9894
9895LD.prototype._get = function (key, options, callback) {
9896
9897 var err = checkKeyValue(key, 'key');
9898
9899 if (err) {
9900 return nextTick(function () {
9901 callback(err);
9902 });
9903 }
9904
9905 if (!Buffer.isBuffer(key)) {
9906 key = String(key);
9907 }
9908 this.container.getItem(key, function (err, value) {
9909
9910 if (err) {
9911 return callback(err);
9912 }
9913
9914 if (options.asBuffer !== false && !Buffer.isBuffer(value)) {
9915 value = bufferFrom(value);
9916 }
9917
9918
9919 if (options.asBuffer === false) {
9920 if (value.indexOf("{\"storetype\":\"json\",\"data\"") > -1) {
9921 var res = JSON.parse(value);
9922 value = res.data;
9923 }
9924 }
9925 callback(null, value);
9926 });
9927};
9928
9929LD.prototype._del = function (key, options, callback) {
9930
9931 var err = checkKeyValue(key, 'key');
9932
9933 if (err) {
9934 return nextTick(function () {
9935 callback(err);
9936 });
9937 }
9938 if (!Buffer.isBuffer(key)) {
9939 key = String(key);
9940 }
9941
9942 this.container.removeItem(key, callback);
9943};
9944
9945LD.prototype._batch = function (array, options, callback) {
9946 var self = this;
9947 nextTick(function () {
9948 var err;
9949 var key;
9950 var value;
9951
9952 var numDone = 0;
9953 var overallErr;
9954 function checkDone() {
9955 if (++numDone === array.length) {
9956 callback(overallErr);
9957 }
9958 }
9959
9960 if (Array.isArray(array) && array.length) {
9961 for (var i = 0; i < array.length; i++) {
9962 var task = array[i];
9963 if (task) {
9964 key = Buffer.isBuffer(task.key) ? task.key : String(task.key);
9965 err = checkKeyValue(key, 'key');
9966 if (err) {
9967 overallErr = err;
9968 checkDone();
9969 } else if (task.type === 'del') {
9970 self._del(task.key, options, checkDone);
9971 } else if (task.type === 'put') {
9972 value = Buffer.isBuffer(task.value) ? task.value : String(task.value);
9973 err = checkKeyValue(value, 'value');
9974 if (err) {
9975 overallErr = err;
9976 checkDone();
9977 } else {
9978 self._put(key, value, options, checkDone);
9979 }
9980 }
9981 } else {
9982 checkDone();
9983 }
9984 }
9985 } else {
9986 callback();
9987 }
9988 });
9989};
9990
9991LD.prototype._iterator = function (options) {
9992 return new LDIterator(this, options);
9993};
9994
9995LD.destroy = function (name, callback) {
9996 LocalStorageCore.destroy(name, callback);
9997};
9998
9999function checkKeyValue(obj, type) {
10000 if (obj === null || obj === undefined) {
10001 return new Error(type + ' cannot be `null` or `undefined`');
10002 }
10003 if (obj === null || obj === undefined) {
10004 return new Error(type + ' cannot be `null` or `undefined`');
10005 }
10006
10007 if (type === 'key') {
10008
10009 if (obj instanceof Boolean) {
10010 return new Error(type + ' cannot be `null` or `undefined`');
10011 }
10012 if (obj === '') {
10013 return new Error(type + ' cannot be empty');
10014 }
10015 }
10016 if (obj.toString().indexOf("[object ArrayBuffer]") === 0) {
10017 if (obj.byteLength === 0 || obj.byteLength === undefined) {
10018 return new Error(type + ' cannot be an empty Buffer');
10019 }
10020 }
10021
10022 if (Buffer.isBuffer(obj)) {
10023 if (obj.length === 0) {
10024 return new Error(type + ' cannot be an empty Buffer');
10025 }
10026 } else if (String(obj) === '') {
10027 return new Error(type + ' cannot be an empty String');
10028 }
10029}
10030
10031module.exports = LD;
10032
10033}).call(this)}).call(this,{"isBuffer":_dereq_("../../is-buffer/index.js")},_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10034},{"../../is-buffer/index.js":54,"./localstorage":82,"./localstorage-core":81,"./utils":84,"_process":94,"abstract-leveldown":3,"buffer-from":85,"inherits":53}],81:[function(_dereq_,module,exports){
10035(function (process,global){(function (){
10036'use strict';
10037
10038//
10039// Class that should contain everything necessary to interact
10040// with localStorage as a generic key-value store.
10041// The idea is that authors who want to create an AbstractKeyValueDOWN
10042// module (e.g. on lawnchair, S3, whatever) will only have to
10043// reimplement this file.
10044//
10045
10046// see http://stackoverflow.com/a/15349865/680742
10047var nextTick = global.setImmediate || process.nextTick;
10048
10049// We use humble-localstorage as a wrapper for localStorage because
10050// it falls back to an in-memory implementation in environments without
10051// localStorage, like Node or Safari private browsing.
10052var storage = _dereq_('humble-localstorage');
10053
10054function callbackify(callback, fun) {
10055 var val;
10056 var err;
10057 try {
10058 val = fun();
10059 } catch (e) {
10060 err = e;
10061 }
10062 nextTick(function () {
10063 callback(err, val);
10064 });
10065}
10066
10067function createPrefix(dbname) {
10068 return dbname.replace(/!/g, '!!') + '!'; // escape bangs in dbname;
10069}
10070
10071function LocalStorageCore(dbname) {
10072 this._prefix = createPrefix(dbname);
10073}
10074
10075LocalStorageCore.prototype.getKeys = function (callback) {
10076 var self = this;
10077 callbackify(callback, function () {
10078 var keys = [];
10079 var prefixLen = self._prefix.length;
10080 var i = -1;
10081 var len = storage.length;
10082 while (++i < len) {
10083 var fullKey = storage.key(i);
10084 if (fullKey.substring(0, prefixLen) === self._prefix) {
10085 keys.push(fullKey.substring(prefixLen));
10086 }
10087 }
10088 keys.sort();
10089 return keys;
10090 });
10091};
10092
10093LocalStorageCore.prototype.put = function (key, value, callback) {
10094 var self = this;
10095 callbackify(callback, function () {
10096 storage.setItem(self._prefix + key, value);
10097 });
10098};
10099
10100LocalStorageCore.prototype.get = function (key, callback) {
10101 var self = this;
10102 callbackify(callback, function () {
10103 return storage.getItem(self._prefix + key);
10104 });
10105};
10106
10107LocalStorageCore.prototype.remove = function (key, callback) {
10108 var self = this;
10109 callbackify(callback, function () {
10110 storage.removeItem(self._prefix + key);
10111 });
10112};
10113
10114LocalStorageCore.destroy = function (dbname, callback) {
10115 var prefix = createPrefix(dbname);
10116 callbackify(callback, function () {
10117 var keysToDelete = [];
10118 var i = -1;
10119 var len = storage.length;
10120 while (++i < len) {
10121 var key = storage.key(i);
10122 if (key.substring(0, prefix.length) === prefix) {
10123 keysToDelete.push(key);
10124 }
10125 }
10126 keysToDelete.forEach(function (key) {
10127 storage.removeItem(key);
10128 });
10129 });
10130};
10131
10132module.exports = LocalStorageCore;
10133}).call(this)}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10134},{"_process":94,"humble-localstorage":51}],82:[function(_dereq_,module,exports){
10135(function (Buffer){(function (){
10136'use strict';
10137
10138// ArrayBuffer/Uint8Array are old formats that date back to before we
10139// had a proper browserified buffer type. they may be removed later
10140var arrayBuffPrefix = 'ArrayBuffer:';
10141var arrayBuffRegex = new RegExp('^' + arrayBuffPrefix);
10142var uintPrefix = 'Uint8Array:';
10143var uintRegex = new RegExp('^' + uintPrefix);
10144
10145// this is the new encoding format used going forward
10146var bufferPrefix = 'Buff:';
10147var bufferRegex = new RegExp('^' + bufferPrefix);
10148
10149var utils = _dereq_('./utils');
10150var LocalStorageCore = _dereq_('./localstorage-core');
10151var TaskQueue = _dereq_('./taskqueue');
10152var d64 = _dereq_('d64');
10153
10154function LocalStorage(dbname) {
10155 this._store = new LocalStorageCore(dbname);
10156 this._queue = new TaskQueue();
10157}
10158
10159LocalStorage.prototype.sequentialize = function (callback, fun) {
10160 this._queue.add(fun, callback);
10161};
10162
10163LocalStorage.prototype.init = function (callback) {
10164 var self = this;
10165 self.sequentialize(callback, function (callback) {
10166 self._store.getKeys(function (err, keys) {
10167 if (err) {
10168 return callback(err);
10169 }
10170 self._keys = keys;
10171 return callback();
10172 });
10173 });
10174};
10175
10176LocalStorage.prototype.keys = function (callback) {
10177 var self = this;
10178 self.sequentialize(callback, function (callback) {
10179 self._store.getKeys(function (err, keys) {
10180 callback(null, keys.slice());
10181 });
10182 });
10183};
10184
10185//setItem: Saves and item at the key provided.
10186LocalStorage.prototype.setItem = function (key, value, callback) {
10187 var self = this;
10188 self.sequentialize(callback, function (callback) {
10189 if (Buffer.isBuffer(value)) {
10190 value = bufferPrefix + d64.encode(value);
10191 }
10192
10193 var idx = utils.sortedIndexOf(self._keys, key);
10194 if (self._keys[idx] !== key) {
10195 self._keys.splice(idx, 0, key);
10196 }
10197 self._store.put(key, value, callback);
10198 });
10199};
10200
10201//getItem: Returns the item identified by it's key.
10202LocalStorage.prototype.getItem = function (key, callback) {
10203 var self = this;
10204 self.sequentialize(callback, function (callback) {
10205 self._store.get(key, function (err, retval) {
10206 if (err) {
10207 return callback(err);
10208 }
10209 if (typeof retval === 'undefined' || retval === null) {
10210 // 'NotFound' error, consistent with LevelDOWN API
10211 return callback(new Error('NotFound'));
10212 }
10213 if (typeof retval !== 'undefined') {
10214 if (bufferRegex.test(retval)) {
10215 retval = d64.decode(retval.substring(bufferPrefix.length));
10216 } else if (arrayBuffRegex.test(retval)) {
10217 // this type is kept for backwards
10218 // compatibility with older databases, but may be removed
10219 // after a major version bump
10220 retval = retval.substring(arrayBuffPrefix.length);
10221 retval = new ArrayBuffer(atob(retval).split('').map(function (c) {
10222 return c.charCodeAt(0);
10223 }));
10224 } else if (uintRegex.test(retval)) {
10225 // ditto
10226 retval = retval.substring(uintPrefix.length);
10227 retval = new Uint8Array(atob(retval).split('').map(function (c) {
10228 return c.charCodeAt(0);
10229 }));
10230 }
10231 }
10232 callback(null, retval);
10233 });
10234 });
10235};
10236
10237//removeItem: Removes the item identified by it's key.
10238LocalStorage.prototype.removeItem = function (key, callback) {
10239 var self = this;
10240 self.sequentialize(callback, function (callback) {
10241 var idx = utils.sortedIndexOf(self._keys, key);
10242 if (self._keys[idx] === key) {
10243 self._keys.splice(idx, 1);
10244 self._store.remove(key, function (err) {
10245 if (err) {
10246 return callback(err);
10247 }
10248 callback();
10249 });
10250 } else {
10251 callback();
10252 }
10253 });
10254};
10255
10256LocalStorage.prototype.length = function (callback) {
10257 var self = this;
10258 self.sequentialize(callback, function (callback) {
10259 callback(null, self._keys.length);
10260 });
10261};
10262
10263exports.LocalStorage = LocalStorage;
10264
10265}).call(this)}).call(this,{"isBuffer":_dereq_("../../is-buffer/index.js")})
10266},{"../../is-buffer/index.js":54,"./localstorage-core":81,"./taskqueue":83,"./utils":84,"d64":13}],83:[function(_dereq_,module,exports){
10267(function (process,global){(function (){
10268'use strict';
10269
10270var argsarray = _dereq_('argsarray');
10271var Queue = _dereq_('tiny-queue');
10272
10273// see http://stackoverflow.com/a/15349865/680742
10274var nextTick = global.setImmediate || process.nextTick;
10275
10276function TaskQueue() {
10277 this.queue = new Queue();
10278 this.running = false;
10279}
10280
10281TaskQueue.prototype.add = function (fun, callback) {
10282 this.queue.push({fun: fun, callback: callback});
10283 this.processNext();
10284};
10285
10286TaskQueue.prototype.processNext = function () {
10287 var self = this;
10288 if (self.running || !self.queue.length) {
10289 return;
10290 }
10291 self.running = true;
10292
10293 var task = self.queue.shift();
10294 nextTick(function () {
10295 task.fun(argsarray(function (args) {
10296 task.callback.apply(null, args);
10297 self.running = false;
10298 self.processNext();
10299 }));
10300 });
10301};
10302
10303module.exports = TaskQueue;
10304
10305}).call(this)}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10306},{"_process":94,"argsarray":5,"tiny-queue":141}],84:[function(_dereq_,module,exports){
10307'use strict';
10308// taken from rvagg/memdown commit 2078b40
10309exports.sortedIndexOf = function(arr, item) {
10310 var low = 0;
10311 var high = arr.length;
10312 var mid;
10313 while (low < high) {
10314 mid = (low + high) >>> 1;
10315 if (arr[mid] < item) {
10316 low = mid + 1;
10317 } else {
10318 high = mid;
10319 }
10320 }
10321 return low;
10322};
10323
10324},{}],85:[function(_dereq_,module,exports){
10325(function (Buffer){(function (){
10326var toString = Object.prototype.toString
10327
10328var isModern = (
10329 typeof Buffer.alloc === 'function' &&
10330 typeof Buffer.allocUnsafe === 'function' &&
10331 typeof Buffer.from === 'function'
10332)
10333
10334function isArrayBuffer (input) {
10335 return toString.call(input).slice(8, -1) === 'ArrayBuffer'
10336}
10337
10338function fromArrayBuffer (obj, byteOffset, length) {
10339 byteOffset >>>= 0
10340
10341 var maxLength = obj.byteLength - byteOffset
10342
10343 if (maxLength < 0) {
10344 throw new RangeError("'offset' is out of bounds")
10345 }
10346
10347 if (length === undefined) {
10348 length = maxLength
10349 } else {
10350 length >>>= 0
10351
10352 if (length > maxLength) {
10353 throw new RangeError("'length' is out of bounds")
10354 }
10355 }
10356
10357 return isModern
10358 ? Buffer.from(obj.slice(byteOffset, byteOffset + length))
10359 : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
10360}
10361
10362function fromString (string, encoding) {
10363 if (typeof encoding !== 'string' || encoding === '') {
10364 encoding = 'utf8'
10365 }
10366
10367 if (!Buffer.isEncoding(encoding)) {
10368 throw new TypeError('"encoding" must be a valid string encoding')
10369 }
10370
10371 return isModern
10372 ? Buffer.from(string, encoding)
10373 : new Buffer(string, encoding)
10374}
10375
10376function bufferFrom (value, encodingOrOffset, length) {
10377 if (typeof value === 'number') {
10378 throw new TypeError('"value" argument must not be a number')
10379 }
10380
10381 if (isArrayBuffer(value)) {
10382 return fromArrayBuffer(value, encodingOrOffset, length)
10383 }
10384
10385 if (typeof value === 'string') {
10386 return fromString(value, encodingOrOffset)
10387 }
10388
10389 return isModern
10390 ? Buffer.from(value)
10391 : new Buffer(value)
10392}
10393
10394module.exports = bufferFrom
10395
10396}).call(this)}).call(this,_dereq_("buffer").Buffer)
10397},{"buffer":9}],86:[function(_dereq_,module,exports){
10398(function (root) {
10399 var localStorageMemory = {}
10400 var cache = {}
10401
10402 /**
10403 * number of stored items.
10404 */
10405 localStorageMemory.length = 0
10406
10407 /**
10408 * returns item for passed key, or null
10409 *
10410 * @para {String} key
10411 * name of item to be returned
10412 * @returns {String|null}
10413 */
10414 localStorageMemory.getItem = function (key) {
10415 if (key in cache) {
10416 return cache[key]
10417 }
10418
10419 return null
10420 }
10421
10422 /**
10423 * sets item for key to passed value, as String
10424 *
10425 * @para {String} key
10426 * name of item to be set
10427 * @para {String} value
10428 * value, will always be turned into a String
10429 * @returns {undefined}
10430 */
10431 localStorageMemory.setItem = function (key, value) {
10432 if (typeof value === 'undefined') {
10433 localStorageMemory.removeItem(key)
10434 } else {
10435 if (!(cache.hasOwnProperty(key))) {
10436 localStorageMemory.length++
10437 }
10438
10439 cache[key] = '' + value
10440 }
10441 }
10442
10443 /**
10444 * removes item for passed key
10445 *
10446 * @para {String} key
10447 * name of item to be removed
10448 * @returns {undefined}
10449 */
10450 localStorageMemory.removeItem = function (key) {
10451 if (cache.hasOwnProperty(key)) {
10452 delete cache[key]
10453 localStorageMemory.length--
10454 }
10455 }
10456
10457 /**
10458 * returns name of key at passed index
10459 *
10460 * @para {Number} index
10461 * Position for key to be returned (starts at 0)
10462 * @returns {String|null}
10463 */
10464 localStorageMemory.key = function (index) {
10465 return Object.keys(cache)[index] || null
10466 }
10467
10468 /**
10469 * removes all stored items and sets length to 0
10470 *
10471 * @returns {undefined}
10472 */
10473 localStorageMemory.clear = function () {
10474 cache = {}
10475 localStorageMemory.length = 0
10476 }
10477
10478 if (typeof exports === 'object') {
10479 module.exports = localStorageMemory
10480 } else {
10481 root.localStorageMemory = localStorageMemory
10482 }
10483})(this)
10484
10485},{}],87:[function(_dereq_,module,exports){
10486(function (Buffer){(function (){
10487
10488exports.compare = function (a, b) {
10489
10490 if(Buffer.isBuffer(a)) {
10491 var l = Math.min(a.length, b.length)
10492 for(var i = 0; i < l; i++) {
10493 var cmp = a[i] - b[i]
10494 if(cmp) return cmp
10495 }
10496 return a.length - b.length
10497 }
10498
10499 return a < b ? -1 : a > b ? 1 : 0
10500}
10501
10502// to be compatible with the current abstract-leveldown tests
10503// nullish or empty strings.
10504// I could use !!val but I want to permit numbers and booleans,
10505// if possible.
10506
10507function isDef (val) {
10508 return val !== undefined && val !== ''
10509}
10510
10511function has (range, name) {
10512 return Object.hasOwnProperty.call(range, name)
10513}
10514
10515function hasKey(range, name) {
10516 return Object.hasOwnProperty.call(range, name) && name
10517}
10518
10519var lowerBoundKey = exports.lowerBoundKey = function (range) {
10520 return (
10521 hasKey(range, 'gt')
10522 || hasKey(range, 'gte')
10523 || hasKey(range, 'min')
10524 || (range.reverse ? hasKey(range, 'end') : hasKey(range, 'start'))
10525 || undefined
10526 )
10527}
10528
10529var lowerBound = exports.lowerBound = function (range, def) {
10530 var k = lowerBoundKey(range)
10531 return k ? range[k] : def
10532}
10533
10534var lowerBoundInclusive = exports.lowerBoundInclusive = function (range) {
10535 return has(range, 'gt') ? false : true
10536}
10537
10538var upperBoundInclusive = exports.upperBoundInclusive =
10539 function (range) {
10540 return (has(range, 'lt') /*&& !range.maxEx*/) ? false : true
10541 }
10542
10543var lowerBoundExclusive = exports.lowerBoundExclusive =
10544 function (range) {
10545 return !lowerBoundInclusive(range)
10546 }
10547
10548var upperBoundExclusive = exports.upperBoundExclusive =
10549 function (range) {
10550 return !upperBoundInclusive(range)
10551 }
10552
10553var upperBoundKey = exports.upperBoundKey = function (range) {
10554 return (
10555 hasKey(range, 'lt')
10556 || hasKey(range, 'lte')
10557 || hasKey(range, 'max')
10558 || (range.reverse ? hasKey(range, 'start') : hasKey(range, 'end'))
10559 || undefined
10560 )
10561}
10562
10563var upperBound = exports.upperBound = function (range, def) {
10564 var k = upperBoundKey(range)
10565 return k ? range[k] : def
10566}
10567
10568exports.start = function (range, def) {
10569 return range.reverse ? upperBound(range, def) : lowerBound(range, def)
10570}
10571exports.end = function (range, def) {
10572 return range.reverse ? lowerBound(range, def) : upperBound(range, def)
10573}
10574exports.startInclusive = function (range) {
10575 return (
10576 range.reverse
10577 ? upperBoundInclusive(range)
10578 : lowerBoundInclusive(range)
10579 )
10580}
10581exports.endInclusive = function (range) {
10582 return (
10583 range.reverse
10584 ? lowerBoundInclusive(range)
10585 : upperBoundInclusive(range)
10586 )
10587}
10588
10589function id (e) { return e }
10590
10591exports.toLtgt = function (range, _range, map, lower, upper) {
10592 _range = _range || {}
10593 map = map || id
10594 var defaults = arguments.length > 3
10595 var lb = exports.lowerBoundKey(range)
10596 var ub = exports.upperBoundKey(range)
10597 if(lb) {
10598 if(lb === 'gt') _range.gt = map(range.gt, false)
10599 else _range.gte = map(range[lb], false)
10600 }
10601 else if(defaults)
10602 _range.gte = map(lower, false)
10603
10604 if(ub) {
10605 if(ub === 'lt') _range.lt = map(range.lt, true)
10606 else _range.lte = map(range[ub], true)
10607 }
10608 else if(defaults)
10609 _range.lte = map(upper, true)
10610
10611 if(range.reverse != null)
10612 _range.reverse = !!range.reverse
10613
10614 //if range was used mutably
10615 //(in level-sublevel it's part of an options object
10616 //that has more properties on it.)
10617 if(has(_range, 'max')) delete _range.max
10618 if(has(_range, 'min')) delete _range.min
10619 if(has(_range, 'start')) delete _range.start
10620 if(has(_range, 'end')) delete _range.end
10621
10622 return _range
10623}
10624
10625exports.contains = function (range, key, compare) {
10626 compare = compare || exports.compare
10627
10628 var lb = lowerBound(range)
10629 if(isDef(lb)) {
10630 var cmp = compare(key, lb)
10631 if(cmp < 0 || (cmp === 0 && lowerBoundExclusive(range)))
10632 return false
10633 }
10634
10635 var ub = upperBound(range)
10636 if(isDef(ub)) {
10637 var cmp = compare(key, ub)
10638 if(cmp > 0 || (cmp === 0) && upperBoundExclusive(range))
10639 return false
10640 }
10641
10642 return true
10643}
10644
10645exports.filter = function (range, compare) {
10646 return function (key) {
10647 return exports.contains(range, key, compare)
10648 }
10649}
10650
10651
10652
10653}).call(this)}).call(this,{"isBuffer":_dereq_("../is-buffer/index.js")})
10654},{"../is-buffer/index.js":54}],88:[function(_dereq_,module,exports){
10655'use strict';
10656
10657var keysShim;
10658if (!Object.keys) {
10659 // modified from https://github.com/es-shims/es5-shim
10660 var has = Object.prototype.hasOwnProperty;
10661 var toStr = Object.prototype.toString;
10662 var isArgs = _dereq_('./isArguments'); // eslint-disable-line global-require
10663 var isEnumerable = Object.prototype.propertyIsEnumerable;
10664 var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
10665 var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
10666 var dontEnums = [
10667 'toString',
10668 'toLocaleString',
10669 'valueOf',
10670 'hasOwnProperty',
10671 'isPrototypeOf',
10672 'propertyIsEnumerable',
10673 'constructor'
10674 ];
10675 var equalsConstructorPrototype = function (o) {
10676 var ctor = o.constructor;
10677 return ctor && ctor.prototype === o;
10678 };
10679 var excludedKeys = {
10680 $applicationCache: true,
10681 $console: true,
10682 $external: true,
10683 $frame: true,
10684 $frameElement: true,
10685 $frames: true,
10686 $innerHeight: true,
10687 $innerWidth: true,
10688 $onmozfullscreenchange: true,
10689 $onmozfullscreenerror: true,
10690 $outerHeight: true,
10691 $outerWidth: true,
10692 $pageXOffset: true,
10693 $pageYOffset: true,
10694 $parent: true,
10695 $scrollLeft: true,
10696 $scrollTop: true,
10697 $scrollX: true,
10698 $scrollY: true,
10699 $self: true,
10700 $webkitIndexedDB: true,
10701 $webkitStorageInfo: true,
10702 $window: true
10703 };
10704 var hasAutomationEqualityBug = (function () {
10705 /* global window */
10706 if (typeof window === 'undefined') { return false; }
10707 for (var k in window) {
10708 try {
10709 if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
10710 try {
10711 equalsConstructorPrototype(window[k]);
10712 } catch (e) {
10713 return true;
10714 }
10715 }
10716 } catch (e) {
10717 return true;
10718 }
10719 }
10720 return false;
10721 }());
10722 var equalsConstructorPrototypeIfNotBuggy = function (o) {
10723 /* global window */
10724 if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
10725 return equalsConstructorPrototype(o);
10726 }
10727 try {
10728 return equalsConstructorPrototype(o);
10729 } catch (e) {
10730 return false;
10731 }
10732 };
10733
10734 keysShim = function keys(object) {
10735 var isObject = object !== null && typeof object === 'object';
10736 var isFunction = toStr.call(object) === '[object Function]';
10737 var isArguments = isArgs(object);
10738 var isString = isObject && toStr.call(object) === '[object String]';
10739 var theKeys = [];
10740
10741 if (!isObject && !isFunction && !isArguments) {
10742 throw new TypeError('Object.keys called on a non-object');
10743 }
10744
10745 var skipProto = hasProtoEnumBug && isFunction;
10746 if (isString && object.length > 0 && !has.call(object, 0)) {
10747 for (var i = 0; i < object.length; ++i) {
10748 theKeys.push(String(i));
10749 }
10750 }
10751
10752 if (isArguments && object.length > 0) {
10753 for (var j = 0; j < object.length; ++j) {
10754 theKeys.push(String(j));
10755 }
10756 } else {
10757 for (var name in object) {
10758 if (!(skipProto && name === 'prototype') && has.call(object, name)) {
10759 theKeys.push(String(name));
10760 }
10761 }
10762 }
10763
10764 if (hasDontEnumBug) {
10765 var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
10766
10767 for (var k = 0; k < dontEnums.length; ++k) {
10768 if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
10769 theKeys.push(dontEnums[k]);
10770 }
10771 }
10772 }
10773 return theKeys;
10774 };
10775}
10776module.exports = keysShim;
10777
10778},{"./isArguments":90}],89:[function(_dereq_,module,exports){
10779'use strict';
10780
10781var slice = Array.prototype.slice;
10782var isArgs = _dereq_('./isArguments');
10783
10784var origKeys = Object.keys;
10785var keysShim = origKeys ? function keys(o) { return origKeys(o); } : _dereq_('./implementation');
10786
10787var originalKeys = Object.keys;
10788
10789keysShim.shim = function shimObjectKeys() {
10790 if (Object.keys) {
10791 var keysWorksWithArguments = (function () {
10792 // Safari 5.0 bug
10793 var args = Object.keys(arguments);
10794 return args && args.length === arguments.length;
10795 }(1, 2));
10796 if (!keysWorksWithArguments) {
10797 Object.keys = function keys(object) { // eslint-disable-line func-name-matching
10798 if (isArgs(object)) {
10799 return originalKeys(slice.call(object));
10800 }
10801 return originalKeys(object);
10802 };
10803 }
10804 } else {
10805 Object.keys = keysShim;
10806 }
10807 return Object.keys || keysShim;
10808};
10809
10810module.exports = keysShim;
10811
10812},{"./implementation":88,"./isArguments":90}],90:[function(_dereq_,module,exports){
10813'use strict';
10814
10815var toStr = Object.prototype.toString;
10816
10817module.exports = function isArguments(value) {
10818 var str = toStr.call(value);
10819 var isArgs = str === '[object Arguments]';
10820 if (!isArgs) {
10821 isArgs = str !== '[object Array]' &&
10822 value !== null &&
10823 typeof value === 'object' &&
10824 typeof value.length === 'number' &&
10825 value.length >= 0 &&
10826 toStr.call(value.callee) === '[object Function]';
10827 }
10828 return isArgs;
10829};
10830
10831},{}],91:[function(_dereq_,module,exports){
10832'use strict';
10833
10834// modified from https://github.com/es-shims/es6-shim
10835var objectKeys = _dereq_('object-keys');
10836var hasSymbols = _dereq_('has-symbols/shams')();
10837var callBound = _dereq_('call-bind/callBound');
10838var toObject = Object;
10839var $push = callBound('Array.prototype.push');
10840var $propIsEnumerable = callBound('Object.prototype.propertyIsEnumerable');
10841var originalGetSymbols = hasSymbols ? Object.getOwnPropertySymbols : null;
10842
10843// eslint-disable-next-line no-unused-vars
10844module.exports = function assign(target, source1) {
10845 if (target == null) { throw new TypeError('target must be an object'); }
10846 var to = toObject(target); // step 1
10847 if (arguments.length === 1) {
10848 return to; // step 2
10849 }
10850 for (var s = 1; s < arguments.length; ++s) {
10851 var from = toObject(arguments[s]); // step 3.a.i
10852
10853 // step 3.a.ii:
10854 var keys = objectKeys(from);
10855 var getSymbols = hasSymbols && (Object.getOwnPropertySymbols || originalGetSymbols);
10856 if (getSymbols) {
10857 var syms = getSymbols(from);
10858 for (var j = 0; j < syms.length; ++j) {
10859 var key = syms[j];
10860 if ($propIsEnumerable(from, key)) {
10861 $push(keys, key);
10862 }
10863 }
10864 }
10865
10866 // step 3.a.iii:
10867 for (var i = 0; i < keys.length; ++i) {
10868 var nextKey = keys[i];
10869 if ($propIsEnumerable(from, nextKey)) { // step 3.a.iii.2
10870 var propValue = from[nextKey]; // step 3.a.iii.2.a
10871 to[nextKey] = propValue; // step 3.a.iii.2.b
10872 }
10873 }
10874 }
10875
10876 return to; // step 4
10877};
10878
10879},{"call-bind/callBound":10,"has-symbols/shams":48,"object-keys":89}],92:[function(_dereq_,module,exports){
10880'use strict';
10881
10882var implementation = _dereq_('./implementation');
10883
10884var lacksProperEnumerationOrder = function () {
10885 if (!Object.assign) {
10886 return false;
10887 }
10888 /*
10889 * v8, specifically in node 4.x, has a bug with incorrect property enumeration order
10890 * note: this does not detect the bug unless there's 20 characters
10891 */
10892 var str = 'abcdefghijklmnopqrst';
10893 var letters = str.split('');
10894 var map = {};
10895 for (var i = 0; i < letters.length; ++i) {
10896 map[letters[i]] = letters[i];
10897 }
10898 var obj = Object.assign({}, map);
10899 var actual = '';
10900 for (var k in obj) {
10901 actual += k;
10902 }
10903 return str !== actual;
10904};
10905
10906var assignHasPendingExceptions = function () {
10907 if (!Object.assign || !Object.preventExtensions) {
10908 return false;
10909 }
10910 /*
10911 * Firefox 37 still has "pending exception" logic in its Object.assign implementation,
10912 * which is 72% slower than our shim, and Firefox 40's native implementation.
10913 */
10914 var thrower = Object.preventExtensions({ 1: 2 });
10915 try {
10916 Object.assign(thrower, 'xy');
10917 } catch (e) {
10918 return thrower[1] === 'y';
10919 }
10920 return false;
10921};
10922
10923module.exports = function getPolyfill() {
10924 if (!Object.assign) {
10925 return implementation;
10926 }
10927 if (lacksProperEnumerationOrder()) {
10928 return implementation;
10929 }
10930 if (assignHasPendingExceptions()) {
10931 return implementation;
10932 }
10933 return Object.assign;
10934};
10935
10936},{"./implementation":91}],93:[function(_dereq_,module,exports){
10937(function (process){(function (){
10938'use strict';
10939
10940if (typeof process === 'undefined' ||
10941 !process.version ||
10942 process.version.indexOf('v0.') === 0 ||
10943 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
10944 module.exports = { nextTick: nextTick };
10945} else {
10946 module.exports = process
10947}
10948
10949function nextTick(fn, arg1, arg2, arg3) {
10950 if (typeof fn !== 'function') {
10951 throw new TypeError('"callback" argument must be a function');
10952 }
10953 var len = arguments.length;
10954 var args, i;
10955 switch (len) {
10956 case 0:
10957 case 1:
10958 return process.nextTick(fn);
10959 case 2:
10960 return process.nextTick(function afterTickOne() {
10961 fn.call(null, arg1);
10962 });
10963 case 3:
10964 return process.nextTick(function afterTickTwo() {
10965 fn.call(null, arg1, arg2);
10966 });
10967 case 4:
10968 return process.nextTick(function afterTickThree() {
10969 fn.call(null, arg1, arg2, arg3);
10970 });
10971 default:
10972 args = new Array(len - 1);
10973 i = 0;
10974 while (i < args.length) {
10975 args[i++] = arguments[i];
10976 }
10977 return process.nextTick(function afterTick() {
10978 fn.apply(null, args);
10979 });
10980 }
10981}
10982
10983
10984}).call(this)}).call(this,_dereq_('_process'))
10985},{"_process":94}],94:[function(_dereq_,module,exports){
10986// shim for using process in browser
10987var process = module.exports = {};
10988
10989// cached from whatever global is present so that test runners that stub it
10990// don't break things. But we need to wrap it in a try catch in case it is
10991// wrapped in strict mode code which doesn't define any globals. It's inside a
10992// function because try/catches deoptimize in certain engines.
10993
10994var cachedSetTimeout;
10995var cachedClearTimeout;
10996
10997function defaultSetTimout() {
10998 throw new Error('setTimeout has not been defined');
10999}
11000function defaultClearTimeout () {
11001 throw new Error('clearTimeout has not been defined');
11002}
11003(function () {
11004 try {
11005 if (typeof setTimeout === 'function') {
11006 cachedSetTimeout = setTimeout;
11007 } else {
11008 cachedSetTimeout = defaultSetTimout;
11009 }
11010 } catch (e) {
11011 cachedSetTimeout = defaultSetTimout;
11012 }
11013 try {
11014 if (typeof clearTimeout === 'function') {
11015 cachedClearTimeout = clearTimeout;
11016 } else {
11017 cachedClearTimeout = defaultClearTimeout;
11018 }
11019 } catch (e) {
11020 cachedClearTimeout = defaultClearTimeout;
11021 }
11022} ())
11023function runTimeout(fun) {
11024 if (cachedSetTimeout === setTimeout) {
11025 //normal enviroments in sane situations
11026 return setTimeout(fun, 0);
11027 }
11028 // if setTimeout wasn't available but was latter defined
11029 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
11030 cachedSetTimeout = setTimeout;
11031 return setTimeout(fun, 0);
11032 }
11033 try {
11034 // when when somebody has screwed with setTimeout but no I.E. maddness
11035 return cachedSetTimeout(fun, 0);
11036 } catch(e){
11037 try {
11038 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
11039 return cachedSetTimeout.call(null, fun, 0);
11040 } catch(e){
11041 // 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
11042 return cachedSetTimeout.call(this, fun, 0);
11043 }
11044 }
11045
11046
11047}
11048function runClearTimeout(marker) {
11049 if (cachedClearTimeout === clearTimeout) {
11050 //normal enviroments in sane situations
11051 return clearTimeout(marker);
11052 }
11053 // if clearTimeout wasn't available but was latter defined
11054 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
11055 cachedClearTimeout = clearTimeout;
11056 return clearTimeout(marker);
11057 }
11058 try {
11059 // when when somebody has screwed with setTimeout but no I.E. maddness
11060 return cachedClearTimeout(marker);
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 cachedClearTimeout.call(null, marker);
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 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
11068 return cachedClearTimeout.call(this, marker);
11069 }
11070 }
11071
11072
11073
11074}
11075var queue = [];
11076var draining = false;
11077var currentQueue;
11078var queueIndex = -1;
11079
11080function cleanUpNextTick() {
11081 if (!draining || !currentQueue) {
11082 return;
11083 }
11084 draining = false;
11085 if (currentQueue.length) {
11086 queue = currentQueue.concat(queue);
11087 } else {
11088 queueIndex = -1;
11089 }
11090 if (queue.length) {
11091 drainQueue();
11092 }
11093}
11094
11095function drainQueue() {
11096 if (draining) {
11097 return;
11098 }
11099 var timeout = runTimeout(cleanUpNextTick);
11100 draining = true;
11101
11102 var len = queue.length;
11103 while(len) {
11104 currentQueue = queue;
11105 queue = [];
11106 while (++queueIndex < len) {
11107 if (currentQueue) {
11108 currentQueue[queueIndex].run();
11109 }
11110 }
11111 queueIndex = -1;
11112 len = queue.length;
11113 }
11114 currentQueue = null;
11115 draining = false;
11116 runClearTimeout(timeout);
11117}
11118
11119process.nextTick = function (fun) {
11120 var args = new Array(arguments.length - 1);
11121 if (arguments.length > 1) {
11122 for (var i = 1; i < arguments.length; i++) {
11123 args[i - 1] = arguments[i];
11124 }
11125 }
11126 queue.push(new Item(fun, args));
11127 if (queue.length === 1 && !draining) {
11128 runTimeout(drainQueue);
11129 }
11130};
11131
11132// v8 likes predictible objects
11133function Item(fun, array) {
11134 this.fun = fun;
11135 this.array = array;
11136}
11137Item.prototype.run = function () {
11138 this.fun.apply(null, this.array);
11139};
11140process.title = 'browser';
11141process.browser = true;
11142process.env = {};
11143process.argv = [];
11144process.version = ''; // empty string to avoid regexp issues
11145process.versions = {};
11146
11147function noop() {}
11148
11149process.on = noop;
11150process.addListener = noop;
11151process.once = noop;
11152process.off = noop;
11153process.removeListener = noop;
11154process.removeAllListeners = noop;
11155process.emit = noop;
11156process.prependListener = noop;
11157process.prependOnceListener = noop;
11158
11159process.listeners = function (name) { return [] }
11160
11161process.binding = function (name) {
11162 throw new Error('process.binding is not supported');
11163};
11164
11165process.cwd = function () { return '/' };
11166process.chdir = function (dir) {
11167 throw new Error('process.chdir is not supported');
11168};
11169process.umask = function() { return 0; };
11170
11171},{}],95:[function(_dereq_,module,exports){
11172/*!
11173 * prr
11174 * (c) 2013 Rod Vagg <rod@vagg.org>
11175 * https://github.com/rvagg/prr
11176 * License: MIT
11177 */
11178
11179(function (name, context, definition) {
11180 if (typeof module != 'undefined' && module.exports)
11181 module.exports = definition()
11182 else
11183 context[name] = definition()
11184})('prr', this, function() {
11185
11186 var setProperty = typeof Object.defineProperty == 'function'
11187 ? function (obj, key, options) {
11188 Object.defineProperty(obj, key, options)
11189 return obj
11190 }
11191 : function (obj, key, options) { // < es5
11192 obj[key] = options.value
11193 return obj
11194 }
11195
11196 , makeOptions = function (value, options) {
11197 var oo = typeof options == 'object'
11198 , os = !oo && typeof options == 'string'
11199 , op = function (p) {
11200 return oo
11201 ? !!options[p]
11202 : os
11203 ? options.indexOf(p[0]) > -1
11204 : false
11205 }
11206
11207 return {
11208 enumerable : op('enumerable')
11209 , configurable : op('configurable')
11210 , writable : op('writable')
11211 , value : value
11212 }
11213 }
11214
11215 , prr = function (obj, key, value, options) {
11216 var k
11217
11218 options = makeOptions(value, options)
11219
11220 if (typeof key == 'object') {
11221 for (k in key) {
11222 if (Object.hasOwnProperty.call(key, k)) {
11223 options.value = key[k]
11224 setProperty(obj, k, options)
11225 }
11226 }
11227 return obj
11228 }
11229
11230 return setProperty(obj, key, options)
11231 }
11232
11233 return prr
11234})
11235},{}],96:[function(_dereq_,module,exports){
11236(function (process){(function (){
11237// Copyright Joyent, Inc. and other Node contributors.
11238//
11239// Permission is hereby granted, free of charge, to any person obtaining a
11240// copy of this software and associated documentation files (the
11241// "Software"), to deal in the Software without restriction, including
11242// without limitation the rights to use, copy, modify, merge, publish,
11243// distribute, sublicense, and/or sell copies of the Software, and to permit
11244// persons to whom the Software is furnished to do so, subject to the
11245// following conditions:
11246//
11247// The above copyright notice and this permission notice shall be included
11248// in all copies or substantial portions of the Software.
11249//
11250// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11251// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11252// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11253// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11254// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11255// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11256// USE OR OTHER DEALINGS IN THE SOFTWARE.
11257
11258// a duplex stream is just a stream that is both readable and writable.
11259// Since JS doesn't have multiple prototypal inheritance, this class
11260// prototypally inherits from Readable, and then parasitically from
11261// Writable.
11262
11263module.exports = Duplex;
11264
11265/*<replacement>*/
11266var objectKeys = Object.keys || function (obj) {
11267 var keys = [];
11268 for (var key in obj) keys.push(key);
11269 return keys;
11270}
11271/*</replacement>*/
11272
11273
11274/*<replacement>*/
11275var util = _dereq_('core-util-is');
11276util.inherits = _dereq_('inherits');
11277/*</replacement>*/
11278
11279var Readable = _dereq_('./_stream_readable');
11280var Writable = _dereq_('./_stream_writable');
11281
11282util.inherits(Duplex, Readable);
11283
11284forEach(objectKeys(Writable.prototype), function(method) {
11285 if (!Duplex.prototype[method])
11286 Duplex.prototype[method] = Writable.prototype[method];
11287});
11288
11289function Duplex(options) {
11290 if (!(this instanceof Duplex))
11291 return new Duplex(options);
11292
11293 Readable.call(this, options);
11294 Writable.call(this, options);
11295
11296 if (options && options.readable === false)
11297 this.readable = false;
11298
11299 if (options && options.writable === false)
11300 this.writable = false;
11301
11302 this.allowHalfOpen = true;
11303 if (options && options.allowHalfOpen === false)
11304 this.allowHalfOpen = false;
11305
11306 this.once('end', onend);
11307}
11308
11309// the no-half-open enforcer
11310function onend() {
11311 // if we allow half-open state, or if the writable side ended,
11312 // then we're ok.
11313 if (this.allowHalfOpen || this._writableState.ended)
11314 return;
11315
11316 // no more data can be written.
11317 // But allow more writes to happen in this tick.
11318 process.nextTick(this.end.bind(this));
11319}
11320
11321function forEach (xs, f) {
11322 for (var i = 0, l = xs.length; i < l; i++) {
11323 f(xs[i], i);
11324 }
11325}
11326
11327}).call(this)}).call(this,_dereq_('_process'))
11328},{"./_stream_readable":98,"./_stream_writable":100,"_process":94,"core-util-is":12,"inherits":53}],97:[function(_dereq_,module,exports){
11329// Copyright Joyent, Inc. and other Node contributors.
11330//
11331// Permission is hereby granted, free of charge, to any person obtaining a
11332// copy of this software and associated documentation files (the
11333// "Software"), to deal in the Software without restriction, including
11334// without limitation the rights to use, copy, modify, merge, publish,
11335// distribute, sublicense, and/or sell copies of the Software, and to permit
11336// persons to whom the Software is furnished to do so, subject to the
11337// following conditions:
11338//
11339// The above copyright notice and this permission notice shall be included
11340// in all copies or substantial portions of the Software.
11341//
11342// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11343// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11344// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11345// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11346// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11347// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11348// USE OR OTHER DEALINGS IN THE SOFTWARE.
11349
11350// a passthrough stream.
11351// basically just the most minimal sort of Transform stream.
11352// Every written chunk gets output as-is.
11353
11354module.exports = PassThrough;
11355
11356var Transform = _dereq_('./_stream_transform');
11357
11358/*<replacement>*/
11359var util = _dereq_('core-util-is');
11360util.inherits = _dereq_('inherits');
11361/*</replacement>*/
11362
11363util.inherits(PassThrough, Transform);
11364
11365function PassThrough(options) {
11366 if (!(this instanceof PassThrough))
11367 return new PassThrough(options);
11368
11369 Transform.call(this, options);
11370}
11371
11372PassThrough.prototype._transform = function(chunk, encoding, cb) {
11373 cb(null, chunk);
11374};
11375
11376},{"./_stream_transform":99,"core-util-is":12,"inherits":53}],98:[function(_dereq_,module,exports){
11377(function (process){(function (){
11378// Copyright Joyent, Inc. and other Node contributors.
11379//
11380// Permission is hereby granted, free of charge, to any person obtaining a
11381// copy of this software and associated documentation files (the
11382// "Software"), to deal in the Software without restriction, including
11383// without limitation the rights to use, copy, modify, merge, publish,
11384// distribute, sublicense, and/or sell copies of the Software, and to permit
11385// persons to whom the Software is furnished to do so, subject to the
11386// following conditions:
11387//
11388// The above copyright notice and this permission notice shall be included
11389// in all copies or substantial portions of the Software.
11390//
11391// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11392// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11393// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11394// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11395// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11396// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11397// USE OR OTHER DEALINGS IN THE SOFTWARE.
11398
11399module.exports = Readable;
11400
11401/*<replacement>*/
11402var isArray = _dereq_('isarray');
11403/*</replacement>*/
11404
11405
11406/*<replacement>*/
11407var Buffer = _dereq_('buffer').Buffer;
11408/*</replacement>*/
11409
11410Readable.ReadableState = ReadableState;
11411
11412var EE = _dereq_('events').EventEmitter;
11413
11414/*<replacement>*/
11415if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
11416 return emitter.listeners(type).length;
11417};
11418/*</replacement>*/
11419
11420var Stream = _dereq_('stream');
11421
11422/*<replacement>*/
11423var util = _dereq_('core-util-is');
11424util.inherits = _dereq_('inherits');
11425/*</replacement>*/
11426
11427var StringDecoder;
11428
11429
11430/*<replacement>*/
11431var debug = _dereq_('util');
11432if (debug && debug.debuglog) {
11433 debug = debug.debuglog('stream');
11434} else {
11435 debug = function () {};
11436}
11437/*</replacement>*/
11438
11439
11440util.inherits(Readable, Stream);
11441
11442function ReadableState(options, stream) {
11443 var Duplex = _dereq_('./_stream_duplex');
11444
11445 options = options || {};
11446
11447 // the point at which it stops calling _read() to fill the buffer
11448 // Note: 0 is a valid value, means "don't call _read preemptively ever"
11449 var hwm = options.highWaterMark;
11450 var defaultHwm = options.objectMode ? 16 : 16 * 1024;
11451 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
11452
11453 // cast to ints.
11454 this.highWaterMark = ~~this.highWaterMark;
11455
11456 this.buffer = [];
11457 this.length = 0;
11458 this.pipes = null;
11459 this.pipesCount = 0;
11460 this.flowing = null;
11461 this.ended = false;
11462 this.endEmitted = false;
11463 this.reading = false;
11464
11465 // a flag to be able to tell if the onwrite cb is called immediately,
11466 // or on a later tick. We set this to true at first, because any
11467 // actions that shouldn't happen until "later" should generally also
11468 // not happen before the first write call.
11469 this.sync = true;
11470
11471 // whenever we return null, then we set a flag to say
11472 // that we're awaiting a 'readable' event emission.
11473 this.needReadable = false;
11474 this.emittedReadable = false;
11475 this.readableListening = false;
11476
11477
11478 // object stream flag. Used to make read(n) ignore n and to
11479 // make all the buffer merging and length checks go away
11480 this.objectMode = !!options.objectMode;
11481
11482 if (stream instanceof Duplex)
11483 this.objectMode = this.objectMode || !!options.readableObjectMode;
11484
11485 // Crypto is kind of old and crusty. Historically, its default string
11486 // encoding is 'binary' so we have to make this configurable.
11487 // Everything else in the universe uses 'utf8', though.
11488 this.defaultEncoding = options.defaultEncoding || 'utf8';
11489
11490 // when piping, we only care about 'readable' events that happen
11491 // after read()ing all the bytes and not getting any pushback.
11492 this.ranOut = false;
11493
11494 // the number of writers that are awaiting a drain event in .pipe()s
11495 this.awaitDrain = 0;
11496
11497 // if true, a maybeReadMore has been scheduled
11498 this.readingMore = false;
11499
11500 this.decoder = null;
11501 this.encoding = null;
11502 if (options.encoding) {
11503 if (!StringDecoder)
11504 StringDecoder = _dereq_('string_decoder/').StringDecoder;
11505 this.decoder = new StringDecoder(options.encoding);
11506 this.encoding = options.encoding;
11507 }
11508}
11509
11510function Readable(options) {
11511 var Duplex = _dereq_('./_stream_duplex');
11512
11513 if (!(this instanceof Readable))
11514 return new Readable(options);
11515
11516 this._readableState = new ReadableState(options, this);
11517
11518 // legacy
11519 this.readable = true;
11520
11521 Stream.call(this);
11522}
11523
11524// Manually shove something into the read() buffer.
11525// This returns true if the highWaterMark has not been hit yet,
11526// similar to how Writable.write() returns true if you should
11527// write() some more.
11528Readable.prototype.push = function(chunk, encoding) {
11529 var state = this._readableState;
11530
11531 if (util.isString(chunk) && !state.objectMode) {
11532 encoding = encoding || state.defaultEncoding;
11533 if (encoding !== state.encoding) {
11534 chunk = new Buffer(chunk, encoding);
11535 encoding = '';
11536 }
11537 }
11538
11539 return readableAddChunk(this, state, chunk, encoding, false);
11540};
11541
11542// Unshift should *always* be something directly out of read()
11543Readable.prototype.unshift = function(chunk) {
11544 var state = this._readableState;
11545 return readableAddChunk(this, state, chunk, '', true);
11546};
11547
11548function readableAddChunk(stream, state, chunk, encoding, addToFront) {
11549 var er = chunkInvalid(state, chunk);
11550 if (er) {
11551 stream.emit('error', er);
11552 } else if (util.isNullOrUndefined(chunk)) {
11553 state.reading = false;
11554 if (!state.ended)
11555 onEofChunk(stream, state);
11556 } else if (state.objectMode || chunk && chunk.length > 0) {
11557 if (state.ended && !addToFront) {
11558 var e = new Error('stream.push() after EOF');
11559 stream.emit('error', e);
11560 } else if (state.endEmitted && addToFront) {
11561 var e = new Error('stream.unshift() after end event');
11562 stream.emit('error', e);
11563 } else {
11564 if (state.decoder && !addToFront && !encoding)
11565 chunk = state.decoder.write(chunk);
11566
11567 if (!addToFront)
11568 state.reading = false;
11569
11570 // if we want the data now, just emit it.
11571 if (state.flowing && state.length === 0 && !state.sync) {
11572 stream.emit('data', chunk);
11573 stream.read(0);
11574 } else {
11575 // update the buffer info.
11576 state.length += state.objectMode ? 1 : chunk.length;
11577 if (addToFront)
11578 state.buffer.unshift(chunk);
11579 else
11580 state.buffer.push(chunk);
11581
11582 if (state.needReadable)
11583 emitReadable(stream);
11584 }
11585
11586 maybeReadMore(stream, state);
11587 }
11588 } else if (!addToFront) {
11589 state.reading = false;
11590 }
11591
11592 return needMoreData(state);
11593}
11594
11595
11596
11597// if it's past the high water mark, we can push in some more.
11598// Also, if we have no data yet, we can stand some
11599// more bytes. This is to work around cases where hwm=0,
11600// such as the repl. Also, if the push() triggered a
11601// readable event, and the user called read(largeNumber) such that
11602// needReadable was set, then we ought to push more, so that another
11603// 'readable' event will be triggered.
11604function needMoreData(state) {
11605 return !state.ended &&
11606 (state.needReadable ||
11607 state.length < state.highWaterMark ||
11608 state.length === 0);
11609}
11610
11611// backwards compatibility.
11612Readable.prototype.setEncoding = function(enc) {
11613 if (!StringDecoder)
11614 StringDecoder = _dereq_('string_decoder/').StringDecoder;
11615 this._readableState.decoder = new StringDecoder(enc);
11616 this._readableState.encoding = enc;
11617 return this;
11618};
11619
11620// Don't raise the hwm > 128MB
11621var MAX_HWM = 0x800000;
11622function roundUpToNextPowerOf2(n) {
11623 if (n >= MAX_HWM) {
11624 n = MAX_HWM;
11625 } else {
11626 // Get the next highest power of 2
11627 n--;
11628 for (var p = 1; p < 32; p <<= 1) n |= n >> p;
11629 n++;
11630 }
11631 return n;
11632}
11633
11634function howMuchToRead(n, state) {
11635 if (state.length === 0 && state.ended)
11636 return 0;
11637
11638 if (state.objectMode)
11639 return n === 0 ? 0 : 1;
11640
11641 if (isNaN(n) || util.isNull(n)) {
11642 // only flow one buffer at a time
11643 if (state.flowing && state.buffer.length)
11644 return state.buffer[0].length;
11645 else
11646 return state.length;
11647 }
11648
11649 if (n <= 0)
11650 return 0;
11651
11652 // If we're asking for more than the target buffer level,
11653 // then raise the water mark. Bump up to the next highest
11654 // power of 2, to prevent increasing it excessively in tiny
11655 // amounts.
11656 if (n > state.highWaterMark)
11657 state.highWaterMark = roundUpToNextPowerOf2(n);
11658
11659 // don't have that much. return null, unless we've ended.
11660 if (n > state.length) {
11661 if (!state.ended) {
11662 state.needReadable = true;
11663 return 0;
11664 } else
11665 return state.length;
11666 }
11667
11668 return n;
11669}
11670
11671// you can override either this method, or the async _read(n) below.
11672Readable.prototype.read = function(n) {
11673 debug('read', n);
11674 var state = this._readableState;
11675 var nOrig = n;
11676
11677 if (!util.isNumber(n) || n > 0)
11678 state.emittedReadable = false;
11679
11680 // if we're doing read(0) to trigger a readable event, but we
11681 // already have a bunch of data in the buffer, then just trigger
11682 // the 'readable' event and move on.
11683 if (n === 0 &&
11684 state.needReadable &&
11685 (state.length >= state.highWaterMark || state.ended)) {
11686 debug('read: emitReadable', state.length, state.ended);
11687 if (state.length === 0 && state.ended)
11688 endReadable(this);
11689 else
11690 emitReadable(this);
11691 return null;
11692 }
11693
11694 n = howMuchToRead(n, state);
11695
11696 // if we've ended, and we're now clear, then finish it up.
11697 if (n === 0 && state.ended) {
11698 if (state.length === 0)
11699 endReadable(this);
11700 return null;
11701 }
11702
11703 // All the actual chunk generation logic needs to be
11704 // *below* the call to _read. The reason is that in certain
11705 // synthetic stream cases, such as passthrough streams, _read
11706 // may be a completely synchronous operation which may change
11707 // the state of the read buffer, providing enough data when
11708 // before there was *not* enough.
11709 //
11710 // So, the steps are:
11711 // 1. Figure out what the state of things will be after we do
11712 // a read from the buffer.
11713 //
11714 // 2. If that resulting state will trigger a _read, then call _read.
11715 // Note that this may be asynchronous, or synchronous. Yes, it is
11716 // deeply ugly to write APIs this way, but that still doesn't mean
11717 // that the Readable class should behave improperly, as streams are
11718 // designed to be sync/async agnostic.
11719 // Take note if the _read call is sync or async (ie, if the read call
11720 // has returned yet), so that we know whether or not it's safe to emit
11721 // 'readable' etc.
11722 //
11723 // 3. Actually pull the requested chunks out of the buffer and return.
11724
11725 // if we need a readable event, then we need to do some reading.
11726 var doRead = state.needReadable;
11727 debug('need readable', doRead);
11728
11729 // if we currently have less than the highWaterMark, then also read some
11730 if (state.length === 0 || state.length - n < state.highWaterMark) {
11731 doRead = true;
11732 debug('length less than watermark', doRead);
11733 }
11734
11735 // however, if we've ended, then there's no point, and if we're already
11736 // reading, then it's unnecessary.
11737 if (state.ended || state.reading) {
11738 doRead = false;
11739 debug('reading or ended', doRead);
11740 }
11741
11742 if (doRead) {
11743 debug('do read');
11744 state.reading = true;
11745 state.sync = true;
11746 // if the length is currently zero, then we *need* a readable event.
11747 if (state.length === 0)
11748 state.needReadable = true;
11749 // call internal read method
11750 this._read(state.highWaterMark);
11751 state.sync = false;
11752 }
11753
11754 // If _read pushed data synchronously, then `reading` will be false,
11755 // and we need to re-evaluate how much data we can return to the user.
11756 if (doRead && !state.reading)
11757 n = howMuchToRead(nOrig, state);
11758
11759 var ret;
11760 if (n > 0)
11761 ret = fromList(n, state);
11762 else
11763 ret = null;
11764
11765 if (util.isNull(ret)) {
11766 state.needReadable = true;
11767 n = 0;
11768 }
11769
11770 state.length -= n;
11771
11772 // If we have nothing in the buffer, then we want to know
11773 // as soon as we *do* get something into the buffer.
11774 if (state.length === 0 && !state.ended)
11775 state.needReadable = true;
11776
11777 // If we tried to read() past the EOF, then emit end on the next tick.
11778 if (nOrig !== n && state.ended && state.length === 0)
11779 endReadable(this);
11780
11781 if (!util.isNull(ret))
11782 this.emit('data', ret);
11783
11784 return ret;
11785};
11786
11787function chunkInvalid(state, chunk) {
11788 var er = null;
11789 if (!util.isBuffer(chunk) &&
11790 !util.isString(chunk) &&
11791 !util.isNullOrUndefined(chunk) &&
11792 !state.objectMode) {
11793 er = new TypeError('Invalid non-string/buffer chunk');
11794 }
11795 return er;
11796}
11797
11798
11799function onEofChunk(stream, state) {
11800 if (state.decoder && !state.ended) {
11801 var chunk = state.decoder.end();
11802 if (chunk && chunk.length) {
11803 state.buffer.push(chunk);
11804 state.length += state.objectMode ? 1 : chunk.length;
11805 }
11806 }
11807 state.ended = true;
11808
11809 // emit 'readable' now to make sure it gets picked up.
11810 emitReadable(stream);
11811}
11812
11813// Don't emit readable right away in sync mode, because this can trigger
11814// another read() call => stack overflow. This way, it might trigger
11815// a nextTick recursion warning, but that's not so bad.
11816function emitReadable(stream) {
11817 var state = stream._readableState;
11818 state.needReadable = false;
11819 if (!state.emittedReadable) {
11820 debug('emitReadable', state.flowing);
11821 state.emittedReadable = true;
11822 if (state.sync)
11823 process.nextTick(function() {
11824 emitReadable_(stream);
11825 });
11826 else
11827 emitReadable_(stream);
11828 }
11829}
11830
11831function emitReadable_(stream) {
11832 debug('emit readable');
11833 stream.emit('readable');
11834 flow(stream);
11835}
11836
11837
11838// at this point, the user has presumably seen the 'readable' event,
11839// and called read() to consume some data. that may have triggered
11840// in turn another _read(n) call, in which case reading = true if
11841// it's in progress.
11842// However, if we're not ended, or reading, and the length < hwm,
11843// then go ahead and try to read some more preemptively.
11844function maybeReadMore(stream, state) {
11845 if (!state.readingMore) {
11846 state.readingMore = true;
11847 process.nextTick(function() {
11848 maybeReadMore_(stream, state);
11849 });
11850 }
11851}
11852
11853function maybeReadMore_(stream, state) {
11854 var len = state.length;
11855 while (!state.reading && !state.flowing && !state.ended &&
11856 state.length < state.highWaterMark) {
11857 debug('maybeReadMore read 0');
11858 stream.read(0);
11859 if (len === state.length)
11860 // didn't get any data, stop spinning.
11861 break;
11862 else
11863 len = state.length;
11864 }
11865 state.readingMore = false;
11866}
11867
11868// abstract method. to be overridden in specific implementation classes.
11869// call cb(er, data) where data is <= n in length.
11870// for virtual (non-string, non-buffer) streams, "length" is somewhat
11871// arbitrary, and perhaps not very meaningful.
11872Readable.prototype._read = function(n) {
11873 this.emit('error', new Error('not implemented'));
11874};
11875
11876Readable.prototype.pipe = function(dest, pipeOpts) {
11877 var src = this;
11878 var state = this._readableState;
11879
11880 switch (state.pipesCount) {
11881 case 0:
11882 state.pipes = dest;
11883 break;
11884 case 1:
11885 state.pipes = [state.pipes, dest];
11886 break;
11887 default:
11888 state.pipes.push(dest);
11889 break;
11890 }
11891 state.pipesCount += 1;
11892 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
11893
11894 var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
11895 dest !== process.stdout &&
11896 dest !== process.stderr;
11897
11898 var endFn = doEnd ? onend : cleanup;
11899 if (state.endEmitted)
11900 process.nextTick(endFn);
11901 else
11902 src.once('end', endFn);
11903
11904 dest.on('unpipe', onunpipe);
11905 function onunpipe(readable) {
11906 debug('onunpipe');
11907 if (readable === src) {
11908 cleanup();
11909 }
11910 }
11911
11912 function onend() {
11913 debug('onend');
11914 dest.end();
11915 }
11916
11917 // when the dest drains, it reduces the awaitDrain counter
11918 // on the source. This would be more elegant with a .once()
11919 // handler in flow(), but adding and removing repeatedly is
11920 // too slow.
11921 var ondrain = pipeOnDrain(src);
11922 dest.on('drain', ondrain);
11923
11924 function cleanup() {
11925 debug('cleanup');
11926 // cleanup event handlers once the pipe is broken
11927 dest.removeListener('close', onclose);
11928 dest.removeListener('finish', onfinish);
11929 dest.removeListener('drain', ondrain);
11930 dest.removeListener('error', onerror);
11931 dest.removeListener('unpipe', onunpipe);
11932 src.removeListener('end', onend);
11933 src.removeListener('end', cleanup);
11934 src.removeListener('data', ondata);
11935
11936 // if the reader is waiting for a drain event from this
11937 // specific writer, then it would cause it to never start
11938 // flowing again.
11939 // So, if this is awaiting a drain, then we just call it now.
11940 // If we don't know, then assume that we are waiting for one.
11941 if (state.awaitDrain &&
11942 (!dest._writableState || dest._writableState.needDrain))
11943 ondrain();
11944 }
11945
11946 src.on('data', ondata);
11947 function ondata(chunk) {
11948 debug('ondata');
11949 var ret = dest.write(chunk);
11950 if (false === ret) {
11951 debug('false write response, pause',
11952 src._readableState.awaitDrain);
11953 src._readableState.awaitDrain++;
11954 src.pause();
11955 }
11956 }
11957
11958 // if the dest has an error, then stop piping into it.
11959 // however, don't suppress the throwing behavior for this.
11960 function onerror(er) {
11961 debug('onerror', er);
11962 unpipe();
11963 dest.removeListener('error', onerror);
11964 if (EE.listenerCount(dest, 'error') === 0)
11965 dest.emit('error', er);
11966 }
11967 // This is a brutally ugly hack to make sure that our error handler
11968 // is attached before any userland ones. NEVER DO THIS.
11969 if (!dest._events || !dest._events.error)
11970 dest.on('error', onerror);
11971 else if (isArray(dest._events.error))
11972 dest._events.error.unshift(onerror);
11973 else
11974 dest._events.error = [onerror, dest._events.error];
11975
11976
11977
11978 // Both close and finish should trigger unpipe, but only once.
11979 function onclose() {
11980 dest.removeListener('finish', onfinish);
11981 unpipe();
11982 }
11983 dest.once('close', onclose);
11984 function onfinish() {
11985 debug('onfinish');
11986 dest.removeListener('close', onclose);
11987 unpipe();
11988 }
11989 dest.once('finish', onfinish);
11990
11991 function unpipe() {
11992 debug('unpipe');
11993 src.unpipe(dest);
11994 }
11995
11996 // tell the dest that it's being piped to
11997 dest.emit('pipe', src);
11998
11999 // start the flow if it hasn't been started already.
12000 if (!state.flowing) {
12001 debug('pipe resume');
12002 src.resume();
12003 }
12004
12005 return dest;
12006};
12007
12008function pipeOnDrain(src) {
12009 return function() {
12010 var state = src._readableState;
12011 debug('pipeOnDrain', state.awaitDrain);
12012 if (state.awaitDrain)
12013 state.awaitDrain--;
12014 if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
12015 state.flowing = true;
12016 flow(src);
12017 }
12018 };
12019}
12020
12021
12022Readable.prototype.unpipe = function(dest) {
12023 var state = this._readableState;
12024
12025 // if we're not piping anywhere, then do nothing.
12026 if (state.pipesCount === 0)
12027 return this;
12028
12029 // just one destination. most common case.
12030 if (state.pipesCount === 1) {
12031 // passed in one, but it's not the right one.
12032 if (dest && dest !== state.pipes)
12033 return this;
12034
12035 if (!dest)
12036 dest = state.pipes;
12037
12038 // got a match.
12039 state.pipes = null;
12040 state.pipesCount = 0;
12041 state.flowing = false;
12042 if (dest)
12043 dest.emit('unpipe', this);
12044 return this;
12045 }
12046
12047 // slow case. multiple pipe destinations.
12048
12049 if (!dest) {
12050 // remove all.
12051 var dests = state.pipes;
12052 var len = state.pipesCount;
12053 state.pipes = null;
12054 state.pipesCount = 0;
12055 state.flowing = false;
12056
12057 for (var i = 0; i < len; i++)
12058 dests[i].emit('unpipe', this);
12059 return this;
12060 }
12061
12062 // try to find the right one.
12063 var i = indexOf(state.pipes, dest);
12064 if (i === -1)
12065 return this;
12066
12067 state.pipes.splice(i, 1);
12068 state.pipesCount -= 1;
12069 if (state.pipesCount === 1)
12070 state.pipes = state.pipes[0];
12071
12072 dest.emit('unpipe', this);
12073
12074 return this;
12075};
12076
12077// set up data events if they are asked for
12078// Ensure readable listeners eventually get something
12079Readable.prototype.on = function(ev, fn) {
12080 var res = Stream.prototype.on.call(this, ev, fn);
12081
12082 // If listening to data, and it has not explicitly been paused,
12083 // then call resume to start the flow of data on the next tick.
12084 if (ev === 'data' && false !== this._readableState.flowing) {
12085 this.resume();
12086 }
12087
12088 if (ev === 'readable' && this.readable) {
12089 var state = this._readableState;
12090 if (!state.readableListening) {
12091 state.readableListening = true;
12092 state.emittedReadable = false;
12093 state.needReadable = true;
12094 if (!state.reading) {
12095 var self = this;
12096 process.nextTick(function() {
12097 debug('readable nexttick read 0');
12098 self.read(0);
12099 });
12100 } else if (state.length) {
12101 emitReadable(this, state);
12102 }
12103 }
12104 }
12105
12106 return res;
12107};
12108Readable.prototype.addListener = Readable.prototype.on;
12109
12110// pause() and resume() are remnants of the legacy readable stream API
12111// If the user uses them, then switch into old mode.
12112Readable.prototype.resume = function() {
12113 var state = this._readableState;
12114 if (!state.flowing) {
12115 debug('resume');
12116 state.flowing = true;
12117 if (!state.reading) {
12118 debug('resume read 0');
12119 this.read(0);
12120 }
12121 resume(this, state);
12122 }
12123 return this;
12124};
12125
12126function resume(stream, state) {
12127 if (!state.resumeScheduled) {
12128 state.resumeScheduled = true;
12129 process.nextTick(function() {
12130 resume_(stream, state);
12131 });
12132 }
12133}
12134
12135function resume_(stream, state) {
12136 state.resumeScheduled = false;
12137 stream.emit('resume');
12138 flow(stream);
12139 if (state.flowing && !state.reading)
12140 stream.read(0);
12141}
12142
12143Readable.prototype.pause = function() {
12144 debug('call pause flowing=%j', this._readableState.flowing);
12145 if (false !== this._readableState.flowing) {
12146 debug('pause');
12147 this._readableState.flowing = false;
12148 this.emit('pause');
12149 }
12150 return this;
12151};
12152
12153function flow(stream) {
12154 var state = stream._readableState;
12155 debug('flow', state.flowing);
12156 if (state.flowing) {
12157 do {
12158 var chunk = stream.read();
12159 } while (null !== chunk && state.flowing);
12160 }
12161}
12162
12163// wrap an old-style stream as the async data source.
12164// This is *not* part of the readable stream interface.
12165// It is an ugly unfortunate mess of history.
12166Readable.prototype.wrap = function(stream) {
12167 var state = this._readableState;
12168 var paused = false;
12169
12170 var self = this;
12171 stream.on('end', function() {
12172 debug('wrapped end');
12173 if (state.decoder && !state.ended) {
12174 var chunk = state.decoder.end();
12175 if (chunk && chunk.length)
12176 self.push(chunk);
12177 }
12178
12179 self.push(null);
12180 });
12181
12182 stream.on('data', function(chunk) {
12183 debug('wrapped data');
12184 if (state.decoder)
12185 chunk = state.decoder.write(chunk);
12186 if (!chunk || !state.objectMode && !chunk.length)
12187 return;
12188
12189 var ret = self.push(chunk);
12190 if (!ret) {
12191 paused = true;
12192 stream.pause();
12193 }
12194 });
12195
12196 // proxy all the other methods.
12197 // important when wrapping filters and duplexes.
12198 for (var i in stream) {
12199 if (util.isFunction(stream[i]) && util.isUndefined(this[i])) {
12200 this[i] = function(method) { return function() {
12201 return stream[method].apply(stream, arguments);
12202 }}(i);
12203 }
12204 }
12205
12206 // proxy certain important events.
12207 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
12208 forEach(events, function(ev) {
12209 stream.on(ev, self.emit.bind(self, ev));
12210 });
12211
12212 // when we try to consume some more bytes, simply unpause the
12213 // underlying stream.
12214 self._read = function(n) {
12215 debug('wrapped _read', n);
12216 if (paused) {
12217 paused = false;
12218 stream.resume();
12219 }
12220 };
12221
12222 return self;
12223};
12224
12225
12226
12227// exposed for testing purposes only.
12228Readable._fromList = fromList;
12229
12230// Pluck off n bytes from an array of buffers.
12231// Length is the combined lengths of all the buffers in the list.
12232function fromList(n, state) {
12233 var list = state.buffer;
12234 var length = state.length;
12235 var stringMode = !!state.decoder;
12236 var objectMode = !!state.objectMode;
12237 var ret;
12238
12239 // nothing in the list, definitely empty.
12240 if (list.length === 0)
12241 return null;
12242
12243 if (length === 0)
12244 ret = null;
12245 else if (objectMode)
12246 ret = list.shift();
12247 else if (!n || n >= length) {
12248 // read it all, truncate the array.
12249 if (stringMode)
12250 ret = list.join('');
12251 else
12252 ret = Buffer.concat(list, length);
12253 list.length = 0;
12254 } else {
12255 // read just some of it.
12256 if (n < list[0].length) {
12257 // just take a part of the first list item.
12258 // slice is the same for buffers and strings.
12259 var buf = list[0];
12260 ret = buf.slice(0, n);
12261 list[0] = buf.slice(n);
12262 } else if (n === list[0].length) {
12263 // first list is a perfect match
12264 ret = list.shift();
12265 } else {
12266 // complex case.
12267 // we have enough to cover it, but it spans past the first buffer.
12268 if (stringMode)
12269 ret = '';
12270 else
12271 ret = new Buffer(n);
12272
12273 var c = 0;
12274 for (var i = 0, l = list.length; i < l && c < n; i++) {
12275 var buf = list[0];
12276 var cpy = Math.min(n - c, buf.length);
12277
12278 if (stringMode)
12279 ret += buf.slice(0, cpy);
12280 else
12281 buf.copy(ret, c, 0, cpy);
12282
12283 if (cpy < buf.length)
12284 list[0] = buf.slice(cpy);
12285 else
12286 list.shift();
12287
12288 c += cpy;
12289 }
12290 }
12291 }
12292
12293 return ret;
12294}
12295
12296function endReadable(stream) {
12297 var state = stream._readableState;
12298
12299 // If we get here before consuming all the bytes, then that is a
12300 // bug in node. Should never happen.
12301 if (state.length > 0)
12302 throw new Error('endReadable called on non-empty stream');
12303
12304 if (!state.endEmitted) {
12305 state.ended = true;
12306 process.nextTick(function() {
12307 // Check that we didn't get one last unshift.
12308 if (!state.endEmitted && state.length === 0) {
12309 state.endEmitted = true;
12310 stream.readable = false;
12311 stream.emit('end');
12312 }
12313 });
12314 }
12315}
12316
12317function forEach (xs, f) {
12318 for (var i = 0, l = xs.length; i < l; i++) {
12319 f(xs[i], i);
12320 }
12321}
12322
12323function indexOf (xs, x) {
12324 for (var i = 0, l = xs.length; i < l; i++) {
12325 if (xs[i] === x) return i;
12326 }
12327 return -1;
12328}
12329
12330}).call(this)}).call(this,_dereq_('_process'))
12331},{"./_stream_duplex":96,"_process":94,"buffer":9,"core-util-is":12,"events":39,"inherits":53,"isarray":55,"stream":106,"string_decoder/":101,"util":8}],99:[function(_dereq_,module,exports){
12332// Copyright Joyent, Inc. and other Node contributors.
12333//
12334// Permission is hereby granted, free of charge, to any person obtaining a
12335// copy of this software and associated documentation files (the
12336// "Software"), to deal in the Software without restriction, including
12337// without limitation the rights to use, copy, modify, merge, publish,
12338// distribute, sublicense, and/or sell copies of the Software, and to permit
12339// persons to whom the Software is furnished to do so, subject to the
12340// following conditions:
12341//
12342// The above copyright notice and this permission notice shall be included
12343// in all copies or substantial portions of the Software.
12344//
12345// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12346// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12347// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12348// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12349// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12350// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12351// USE OR OTHER DEALINGS IN THE SOFTWARE.
12352
12353
12354// a transform stream is a readable/writable stream where you do
12355// something with the data. Sometimes it's called a "filter",
12356// but that's not a great name for it, since that implies a thing where
12357// some bits pass through, and others are simply ignored. (That would
12358// be a valid example of a transform, of course.)
12359//
12360// While the output is causally related to the input, it's not a
12361// necessarily symmetric or synchronous transformation. For example,
12362// a zlib stream might take multiple plain-text writes(), and then
12363// emit a single compressed chunk some time in the future.
12364//
12365// Here's how this works:
12366//
12367// The Transform stream has all the aspects of the readable and writable
12368// stream classes. When you write(chunk), that calls _write(chunk,cb)
12369// internally, and returns false if there's a lot of pending writes
12370// buffered up. When you call read(), that calls _read(n) until
12371// there's enough pending readable data buffered up.
12372//
12373// In a transform stream, the written data is placed in a buffer. When
12374// _read(n) is called, it transforms the queued up data, calling the
12375// buffered _write cb's as it consumes chunks. If consuming a single
12376// written chunk would result in multiple output chunks, then the first
12377// outputted bit calls the readcb, and subsequent chunks just go into
12378// the read buffer, and will cause it to emit 'readable' if necessary.
12379//
12380// This way, back-pressure is actually determined by the reading side,
12381// since _read has to be called to start processing a new chunk. However,
12382// a pathological inflate type of transform can cause excessive buffering
12383// here. For example, imagine a stream where every byte of input is
12384// interpreted as an integer from 0-255, and then results in that many
12385// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
12386// 1kb of data being output. In this case, you could write a very small
12387// amount of input, and end up with a very large amount of output. In
12388// such a pathological inflating mechanism, there'd be no way to tell
12389// the system to stop doing the transform. A single 4MB write could
12390// cause the system to run out of memory.
12391//
12392// However, even in such a pathological case, only a single written chunk
12393// would be consumed, and then the rest would wait (un-transformed) until
12394// the results of the previous transformed chunk were consumed.
12395
12396module.exports = Transform;
12397
12398var Duplex = _dereq_('./_stream_duplex');
12399
12400/*<replacement>*/
12401var util = _dereq_('core-util-is');
12402util.inherits = _dereq_('inherits');
12403/*</replacement>*/
12404
12405util.inherits(Transform, Duplex);
12406
12407
12408function TransformState(options, stream) {
12409 this.afterTransform = function(er, data) {
12410 return afterTransform(stream, er, data);
12411 };
12412
12413 this.needTransform = false;
12414 this.transforming = false;
12415 this.writecb = null;
12416 this.writechunk = null;
12417}
12418
12419function afterTransform(stream, er, data) {
12420 var ts = stream._transformState;
12421 ts.transforming = false;
12422
12423 var cb = ts.writecb;
12424
12425 if (!cb)
12426 return stream.emit('error', new Error('no writecb in Transform class'));
12427
12428 ts.writechunk = null;
12429 ts.writecb = null;
12430
12431 if (!util.isNullOrUndefined(data))
12432 stream.push(data);
12433
12434 if (cb)
12435 cb(er);
12436
12437 var rs = stream._readableState;
12438 rs.reading = false;
12439 if (rs.needReadable || rs.length < rs.highWaterMark) {
12440 stream._read(rs.highWaterMark);
12441 }
12442}
12443
12444
12445function Transform(options) {
12446 if (!(this instanceof Transform))
12447 return new Transform(options);
12448
12449 Duplex.call(this, options);
12450
12451 this._transformState = new TransformState(options, this);
12452
12453 // when the writable side finishes, then flush out anything remaining.
12454 var stream = this;
12455
12456 // start out asking for a readable event once data is transformed.
12457 this._readableState.needReadable = true;
12458
12459 // we have implemented the _read method, and done the other things
12460 // that Readable wants before the first _read call, so unset the
12461 // sync guard flag.
12462 this._readableState.sync = false;
12463
12464 this.once('prefinish', function() {
12465 if (util.isFunction(this._flush))
12466 this._flush(function(er) {
12467 done(stream, er);
12468 });
12469 else
12470 done(stream);
12471 });
12472}
12473
12474Transform.prototype.push = function(chunk, encoding) {
12475 this._transformState.needTransform = false;
12476 return Duplex.prototype.push.call(this, chunk, encoding);
12477};
12478
12479// This is the part where you do stuff!
12480// override this function in implementation classes.
12481// 'chunk' is an input chunk.
12482//
12483// Call `push(newChunk)` to pass along transformed output
12484// to the readable side. You may call 'push' zero or more times.
12485//
12486// Call `cb(err)` when you are done with this chunk. If you pass
12487// an error, then that'll put the hurt on the whole operation. If you
12488// never call cb(), then you'll never get another chunk.
12489Transform.prototype._transform = function(chunk, encoding, cb) {
12490 throw new Error('not implemented');
12491};
12492
12493Transform.prototype._write = function(chunk, encoding, cb) {
12494 var ts = this._transformState;
12495 ts.writecb = cb;
12496 ts.writechunk = chunk;
12497 ts.writeencoding = encoding;
12498 if (!ts.transforming) {
12499 var rs = this._readableState;
12500 if (ts.needTransform ||
12501 rs.needReadable ||
12502 rs.length < rs.highWaterMark)
12503 this._read(rs.highWaterMark);
12504 }
12505};
12506
12507// Doesn't matter what the args are here.
12508// _transform does all the work.
12509// That we got here means that the readable side wants more data.
12510Transform.prototype._read = function(n) {
12511 var ts = this._transformState;
12512
12513 if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) {
12514 ts.transforming = true;
12515 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
12516 } else {
12517 // mark that we need a transform, so that any data that comes in
12518 // will get processed, now that we've asked for it.
12519 ts.needTransform = true;
12520 }
12521};
12522
12523
12524function done(stream, er) {
12525 if (er)
12526 return stream.emit('error', er);
12527
12528 // if there's nothing in the write buffer, then that means
12529 // that nothing more will ever be provided
12530 var ws = stream._writableState;
12531 var ts = stream._transformState;
12532
12533 if (ws.length)
12534 throw new Error('calling transform done when ws.length != 0');
12535
12536 if (ts.transforming)
12537 throw new Error('calling transform done when still transforming');
12538
12539 return stream.push(null);
12540}
12541
12542},{"./_stream_duplex":96,"core-util-is":12,"inherits":53}],100:[function(_dereq_,module,exports){
12543(function (process){(function (){
12544// Copyright Joyent, Inc. and other Node contributors.
12545//
12546// Permission is hereby granted, free of charge, to any person obtaining a
12547// copy of this software and associated documentation files (the
12548// "Software"), to deal in the Software without restriction, including
12549// without limitation the rights to use, copy, modify, merge, publish,
12550// distribute, sublicense, and/or sell copies of the Software, and to permit
12551// persons to whom the Software is furnished to do so, subject to the
12552// following conditions:
12553//
12554// The above copyright notice and this permission notice shall be included
12555// in all copies or substantial portions of the Software.
12556//
12557// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12558// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12559// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12560// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12561// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12562// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12563// USE OR OTHER DEALINGS IN THE SOFTWARE.
12564
12565// A bit simpler than readable streams.
12566// Implement an async ._write(chunk, cb), and it'll handle all
12567// the drain event emission and buffering.
12568
12569module.exports = Writable;
12570
12571/*<replacement>*/
12572var Buffer = _dereq_('buffer').Buffer;
12573/*</replacement>*/
12574
12575Writable.WritableState = WritableState;
12576
12577
12578/*<replacement>*/
12579var util = _dereq_('core-util-is');
12580util.inherits = _dereq_('inherits');
12581/*</replacement>*/
12582
12583var Stream = _dereq_('stream');
12584
12585util.inherits(Writable, Stream);
12586
12587function WriteReq(chunk, encoding, cb) {
12588 this.chunk = chunk;
12589 this.encoding = encoding;
12590 this.callback = cb;
12591}
12592
12593function WritableState(options, stream) {
12594 var Duplex = _dereq_('./_stream_duplex');
12595
12596 options = options || {};
12597
12598 // the point at which write() starts returning false
12599 // Note: 0 is a valid value, means that we always return false if
12600 // the entire buffer is not flushed immediately on write()
12601 var hwm = options.highWaterMark;
12602 var defaultHwm = options.objectMode ? 16 : 16 * 1024;
12603 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
12604
12605 // object stream flag to indicate whether or not this stream
12606 // contains buffers or objects.
12607 this.objectMode = !!options.objectMode;
12608
12609 if (stream instanceof Duplex)
12610 this.objectMode = this.objectMode || !!options.writableObjectMode;
12611
12612 // cast to ints.
12613 this.highWaterMark = ~~this.highWaterMark;
12614
12615 this.needDrain = false;
12616 // at the start of calling end()
12617 this.ending = false;
12618 // when end() has been called, and returned
12619 this.ended = false;
12620 // when 'finish' is emitted
12621 this.finished = false;
12622
12623 // should we decode strings into buffers before passing to _write?
12624 // this is here so that some node-core streams can optimize string
12625 // handling at a lower level.
12626 var noDecode = options.decodeStrings === false;
12627 this.decodeStrings = !noDecode;
12628
12629 // Crypto is kind of old and crusty. Historically, its default string
12630 // encoding is 'binary' so we have to make this configurable.
12631 // Everything else in the universe uses 'utf8', though.
12632 this.defaultEncoding = options.defaultEncoding || 'utf8';
12633
12634 // not an actual buffer we keep track of, but a measurement
12635 // of how much we're waiting to get pushed to some underlying
12636 // socket or file.
12637 this.length = 0;
12638
12639 // a flag to see when we're in the middle of a write.
12640 this.writing = false;
12641
12642 // when true all writes will be buffered until .uncork() call
12643 this.corked = 0;
12644
12645 // a flag to be able to tell if the onwrite cb is called immediately,
12646 // or on a later tick. We set this to true at first, because any
12647 // actions that shouldn't happen until "later" should generally also
12648 // not happen before the first write call.
12649 this.sync = true;
12650
12651 // a flag to know if we're processing previously buffered items, which
12652 // may call the _write() callback in the same tick, so that we don't
12653 // end up in an overlapped onwrite situation.
12654 this.bufferProcessing = false;
12655
12656 // the callback that's passed to _write(chunk,cb)
12657 this.onwrite = function(er) {
12658 onwrite(stream, er);
12659 };
12660
12661 // the callback that the user supplies to write(chunk,encoding,cb)
12662 this.writecb = null;
12663
12664 // the amount that is being written when _write is called.
12665 this.writelen = 0;
12666
12667 this.buffer = [];
12668
12669 // number of pending user-supplied write callbacks
12670 // this must be 0 before 'finish' can be emitted
12671 this.pendingcb = 0;
12672
12673 // emit prefinish if the only thing we're waiting for is _write cbs
12674 // This is relevant for synchronous Transform streams
12675 this.prefinished = false;
12676
12677 // True if the error was already emitted and should not be thrown again
12678 this.errorEmitted = false;
12679}
12680
12681function Writable(options) {
12682 var Duplex = _dereq_('./_stream_duplex');
12683
12684 // Writable ctor is applied to Duplexes, though they're not
12685 // instanceof Writable, they're instanceof Readable.
12686 if (!(this instanceof Writable) && !(this instanceof Duplex))
12687 return new Writable(options);
12688
12689 this._writableState = new WritableState(options, this);
12690
12691 // legacy.
12692 this.writable = true;
12693
12694 Stream.call(this);
12695}
12696
12697// Otherwise people can pipe Writable streams, which is just wrong.
12698Writable.prototype.pipe = function() {
12699 this.emit('error', new Error('Cannot pipe. Not readable.'));
12700};
12701
12702
12703function writeAfterEnd(stream, state, cb) {
12704 var er = new Error('write after end');
12705 // TODO: defer error events consistently everywhere, not just the cb
12706 stream.emit('error', er);
12707 process.nextTick(function() {
12708 cb(er);
12709 });
12710}
12711
12712// If we get something that is not a buffer, string, null, or undefined,
12713// and we're not in objectMode, then that's an error.
12714// Otherwise stream chunks are all considered to be of length=1, and the
12715// watermarks determine how many objects to keep in the buffer, rather than
12716// how many bytes or characters.
12717function validChunk(stream, state, chunk, cb) {
12718 var valid = true;
12719 if (!util.isBuffer(chunk) &&
12720 !util.isString(chunk) &&
12721 !util.isNullOrUndefined(chunk) &&
12722 !state.objectMode) {
12723 var er = new TypeError('Invalid non-string/buffer chunk');
12724 stream.emit('error', er);
12725 process.nextTick(function() {
12726 cb(er);
12727 });
12728 valid = false;
12729 }
12730 return valid;
12731}
12732
12733Writable.prototype.write = function(chunk, encoding, cb) {
12734 var state = this._writableState;
12735 var ret = false;
12736
12737 if (util.isFunction(encoding)) {
12738 cb = encoding;
12739 encoding = null;
12740 }
12741
12742 if (util.isBuffer(chunk))
12743 encoding = 'buffer';
12744 else if (!encoding)
12745 encoding = state.defaultEncoding;
12746
12747 if (!util.isFunction(cb))
12748 cb = function() {};
12749
12750 if (state.ended)
12751 writeAfterEnd(this, state, cb);
12752 else if (validChunk(this, state, chunk, cb)) {
12753 state.pendingcb++;
12754 ret = writeOrBuffer(this, state, chunk, encoding, cb);
12755 }
12756
12757 return ret;
12758};
12759
12760Writable.prototype.cork = function() {
12761 var state = this._writableState;
12762
12763 state.corked++;
12764};
12765
12766Writable.prototype.uncork = function() {
12767 var state = this._writableState;
12768
12769 if (state.corked) {
12770 state.corked--;
12771
12772 if (!state.writing &&
12773 !state.corked &&
12774 !state.finished &&
12775 !state.bufferProcessing &&
12776 state.buffer.length)
12777 clearBuffer(this, state);
12778 }
12779};
12780
12781function decodeChunk(state, chunk, encoding) {
12782 if (!state.objectMode &&
12783 state.decodeStrings !== false &&
12784 util.isString(chunk)) {
12785 chunk = new Buffer(chunk, encoding);
12786 }
12787 return chunk;
12788}
12789
12790// if we're already writing something, then just put this
12791// in the queue, and wait our turn. Otherwise, call _write
12792// If we return false, then we need a drain event, so set that flag.
12793function writeOrBuffer(stream, state, chunk, encoding, cb) {
12794 chunk = decodeChunk(state, chunk, encoding);
12795 if (util.isBuffer(chunk))
12796 encoding = 'buffer';
12797 var len = state.objectMode ? 1 : chunk.length;
12798
12799 state.length += len;
12800
12801 var ret = state.length < state.highWaterMark;
12802 // we must ensure that previous needDrain will not be reset to false.
12803 if (!ret)
12804 state.needDrain = true;
12805
12806 if (state.writing || state.corked)
12807 state.buffer.push(new WriteReq(chunk, encoding, cb));
12808 else
12809 doWrite(stream, state, false, len, chunk, encoding, cb);
12810
12811 return ret;
12812}
12813
12814function doWrite(stream, state, writev, len, chunk, encoding, cb) {
12815 state.writelen = len;
12816 state.writecb = cb;
12817 state.writing = true;
12818 state.sync = true;
12819 if (writev)
12820 stream._writev(chunk, state.onwrite);
12821 else
12822 stream._write(chunk, encoding, state.onwrite);
12823 state.sync = false;
12824}
12825
12826function onwriteError(stream, state, sync, er, cb) {
12827 if (sync)
12828 process.nextTick(function() {
12829 state.pendingcb--;
12830 cb(er);
12831 });
12832 else {
12833 state.pendingcb--;
12834 cb(er);
12835 }
12836
12837 stream._writableState.errorEmitted = true;
12838 stream.emit('error', er);
12839}
12840
12841function onwriteStateUpdate(state) {
12842 state.writing = false;
12843 state.writecb = null;
12844 state.length -= state.writelen;
12845 state.writelen = 0;
12846}
12847
12848function onwrite(stream, er) {
12849 var state = stream._writableState;
12850 var sync = state.sync;
12851 var cb = state.writecb;
12852
12853 onwriteStateUpdate(state);
12854
12855 if (er)
12856 onwriteError(stream, state, sync, er, cb);
12857 else {
12858 // Check if we're actually ready to finish, but don't emit yet
12859 var finished = needFinish(stream, state);
12860
12861 if (!finished &&
12862 !state.corked &&
12863 !state.bufferProcessing &&
12864 state.buffer.length) {
12865 clearBuffer(stream, state);
12866 }
12867
12868 if (sync) {
12869 process.nextTick(function() {
12870 afterWrite(stream, state, finished, cb);
12871 });
12872 } else {
12873 afterWrite(stream, state, finished, cb);
12874 }
12875 }
12876}
12877
12878function afterWrite(stream, state, finished, cb) {
12879 if (!finished)
12880 onwriteDrain(stream, state);
12881 state.pendingcb--;
12882 cb();
12883 finishMaybe(stream, state);
12884}
12885
12886// Must force callback to be called on nextTick, so that we don't
12887// emit 'drain' before the write() consumer gets the 'false' return
12888// value, and has a chance to attach a 'drain' listener.
12889function onwriteDrain(stream, state) {
12890 if (state.length === 0 && state.needDrain) {
12891 state.needDrain = false;
12892 stream.emit('drain');
12893 }
12894}
12895
12896
12897// if there's something in the buffer waiting, then process it
12898function clearBuffer(stream, state) {
12899 state.bufferProcessing = true;
12900
12901 if (stream._writev && state.buffer.length > 1) {
12902 // Fast case, write everything using _writev()
12903 var cbs = [];
12904 for (var c = 0; c < state.buffer.length; c++)
12905 cbs.push(state.buffer[c].callback);
12906
12907 // count the one we are adding, as well.
12908 // TODO(isaacs) clean this up
12909 state.pendingcb++;
12910 doWrite(stream, state, true, state.length, state.buffer, '', function(err) {
12911 for (var i = 0; i < cbs.length; i++) {
12912 state.pendingcb--;
12913 cbs[i](err);
12914 }
12915 });
12916
12917 // Clear buffer
12918 state.buffer = [];
12919 } else {
12920 // Slow case, write chunks one-by-one
12921 for (var c = 0; c < state.buffer.length; c++) {
12922 var entry = state.buffer[c];
12923 var chunk = entry.chunk;
12924 var encoding = entry.encoding;
12925 var cb = entry.callback;
12926 var len = state.objectMode ? 1 : chunk.length;
12927
12928 doWrite(stream, state, false, len, chunk, encoding, cb);
12929
12930 // if we didn't call the onwrite immediately, then
12931 // it means that we need to wait until it does.
12932 // also, that means that the chunk and cb are currently
12933 // being processed, so move the buffer counter past them.
12934 if (state.writing) {
12935 c++;
12936 break;
12937 }
12938 }
12939
12940 if (c < state.buffer.length)
12941 state.buffer = state.buffer.slice(c);
12942 else
12943 state.buffer.length = 0;
12944 }
12945
12946 state.bufferProcessing = false;
12947}
12948
12949Writable.prototype._write = function(chunk, encoding, cb) {
12950 cb(new Error('not implemented'));
12951
12952};
12953
12954Writable.prototype._writev = null;
12955
12956Writable.prototype.end = function(chunk, encoding, cb) {
12957 var state = this._writableState;
12958
12959 if (util.isFunction(chunk)) {
12960 cb = chunk;
12961 chunk = null;
12962 encoding = null;
12963 } else if (util.isFunction(encoding)) {
12964 cb = encoding;
12965 encoding = null;
12966 }
12967
12968 if (!util.isNullOrUndefined(chunk))
12969 this.write(chunk, encoding);
12970
12971 // .end() fully uncorks
12972 if (state.corked) {
12973 state.corked = 1;
12974 this.uncork();
12975 }
12976
12977 // ignore unnecessary end() calls.
12978 if (!state.ending && !state.finished)
12979 endWritable(this, state, cb);
12980};
12981
12982
12983function needFinish(stream, state) {
12984 return (state.ending &&
12985 state.length === 0 &&
12986 !state.finished &&
12987 !state.writing);
12988}
12989
12990function prefinish(stream, state) {
12991 if (!state.prefinished) {
12992 state.prefinished = true;
12993 stream.emit('prefinish');
12994 }
12995}
12996
12997function finishMaybe(stream, state) {
12998 var need = needFinish(stream, state);
12999 if (need) {
13000 if (state.pendingcb === 0) {
13001 prefinish(stream, state);
13002 state.finished = true;
13003 stream.emit('finish');
13004 } else
13005 prefinish(stream, state);
13006 }
13007 return need;
13008}
13009
13010function endWritable(stream, state, cb) {
13011 state.ending = true;
13012 finishMaybe(stream, state);
13013 if (cb) {
13014 if (state.finished)
13015 process.nextTick(cb);
13016 else
13017 stream.once('finish', cb);
13018 }
13019 state.ended = true;
13020}
13021
13022}).call(this)}).call(this,_dereq_('_process'))
13023},{"./_stream_duplex":96,"_process":94,"buffer":9,"core-util-is":12,"inherits":53,"stream":106}],101:[function(_dereq_,module,exports){
13024// Copyright Joyent, Inc. and other Node contributors.
13025//
13026// Permission is hereby granted, free of charge, to any person obtaining a
13027// copy of this software and associated documentation files (the
13028// "Software"), to deal in the Software without restriction, including
13029// without limitation the rights to use, copy, modify, merge, publish,
13030// distribute, sublicense, and/or sell copies of the Software, and to permit
13031// persons to whom the Software is furnished to do so, subject to the
13032// following conditions:
13033//
13034// The above copyright notice and this permission notice shall be included
13035// in all copies or substantial portions of the Software.
13036//
13037// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13038// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13039// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13040// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13041// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13042// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13043// USE OR OTHER DEALINGS IN THE SOFTWARE.
13044
13045var Buffer = _dereq_('buffer').Buffer;
13046
13047var isBufferEncoding = Buffer.isEncoding
13048 || function(encoding) {
13049 switch (encoding && encoding.toLowerCase()) {
13050 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;
13051 default: return false;
13052 }
13053 }
13054
13055
13056function assertEncoding(encoding) {
13057 if (encoding && !isBufferEncoding(encoding)) {
13058 throw new Error('Unknown encoding: ' + encoding);
13059 }
13060}
13061
13062// StringDecoder provides an interface for efficiently splitting a series of
13063// buffers into a series of JS strings without breaking apart multi-byte
13064// characters. CESU-8 is handled as part of the UTF-8 encoding.
13065//
13066// @TODO Handling all encodings inside a single object makes it very difficult
13067// to reason about this code, so it should be split up in the future.
13068// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
13069// points as used by CESU-8.
13070var StringDecoder = exports.StringDecoder = function(encoding) {
13071 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
13072 assertEncoding(encoding);
13073 switch (this.encoding) {
13074 case 'utf8':
13075 // CESU-8 represents each of Surrogate Pair by 3-bytes
13076 this.surrogateSize = 3;
13077 break;
13078 case 'ucs2':
13079 case 'utf16le':
13080 // UTF-16 represents each of Surrogate Pair by 2-bytes
13081 this.surrogateSize = 2;
13082 this.detectIncompleteChar = utf16DetectIncompleteChar;
13083 break;
13084 case 'base64':
13085 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
13086 this.surrogateSize = 3;
13087 this.detectIncompleteChar = base64DetectIncompleteChar;
13088 break;
13089 default:
13090 this.write = passThroughWrite;
13091 return;
13092 }
13093
13094 // Enough space to store all bytes of a single character. UTF-8 needs 4
13095 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
13096 this.charBuffer = new Buffer(6);
13097 // Number of bytes received for the current incomplete multi-byte character.
13098 this.charReceived = 0;
13099 // Number of bytes expected for the current incomplete multi-byte character.
13100 this.charLength = 0;
13101};
13102
13103
13104// write decodes the given buffer and returns it as JS string that is
13105// guaranteed to not contain any partial multi-byte characters. Any partial
13106// character found at the end of the buffer is buffered up, and will be
13107// returned when calling write again with the remaining bytes.
13108//
13109// Note: Converting a Buffer containing an orphan surrogate to a String
13110// currently works, but converting a String to a Buffer (via `new Buffer`, or
13111// Buffer#write) will replace incomplete surrogates with the unicode
13112// replacement character. See https://codereview.chromium.org/121173009/ .
13113StringDecoder.prototype.write = function(buffer) {
13114 var charStr = '';
13115 // if our last write ended with an incomplete multibyte character
13116 while (this.charLength) {
13117 // determine how many remaining bytes this buffer has to offer for this char
13118 var available = (buffer.length >= this.charLength - this.charReceived) ?
13119 this.charLength - this.charReceived :
13120 buffer.length;
13121
13122 // add the new bytes to the char buffer
13123 buffer.copy(this.charBuffer, this.charReceived, 0, available);
13124 this.charReceived += available;
13125
13126 if (this.charReceived < this.charLength) {
13127 // still not enough chars in this buffer? wait for more ...
13128 return '';
13129 }
13130
13131 // remove bytes belonging to the current character from the buffer
13132 buffer = buffer.slice(available, buffer.length);
13133
13134 // get the character that was split
13135 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
13136
13137 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
13138 var charCode = charStr.charCodeAt(charStr.length - 1);
13139 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
13140 this.charLength += this.surrogateSize;
13141 charStr = '';
13142 continue;
13143 }
13144 this.charReceived = this.charLength = 0;
13145
13146 // if there are no more bytes in this buffer, just emit our char
13147 if (buffer.length === 0) {
13148 return charStr;
13149 }
13150 break;
13151 }
13152
13153 // determine and set charLength / charReceived
13154 this.detectIncompleteChar(buffer);
13155
13156 var end = buffer.length;
13157 if (this.charLength) {
13158 // buffer the incomplete character bytes we got
13159 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
13160 end -= this.charReceived;
13161 }
13162
13163 charStr += buffer.toString(this.encoding, 0, end);
13164
13165 var end = charStr.length - 1;
13166 var charCode = charStr.charCodeAt(end);
13167 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
13168 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
13169 var size = this.surrogateSize;
13170 this.charLength += size;
13171 this.charReceived += size;
13172 this.charBuffer.copy(this.charBuffer, size, 0, size);
13173 buffer.copy(this.charBuffer, 0, 0, size);
13174 return charStr.substring(0, end);
13175 }
13176
13177 // or just emit the charStr
13178 return charStr;
13179};
13180
13181// detectIncompleteChar determines if there is an incomplete UTF-8 character at
13182// the end of the given buffer. If so, it sets this.charLength to the byte
13183// length that character, and sets this.charReceived to the number of bytes
13184// that are available for this character.
13185StringDecoder.prototype.detectIncompleteChar = function(buffer) {
13186 // determine how many bytes we have to check at the end of this buffer
13187 var i = (buffer.length >= 3) ? 3 : buffer.length;
13188
13189 // Figure out if one of the last i bytes of our buffer announces an
13190 // incomplete char.
13191 for (; i > 0; i--) {
13192 var c = buffer[buffer.length - i];
13193
13194 // See http://en.wikipedia.org/wiki/UTF-8#Description
13195
13196 // 110XXXXX
13197 if (i == 1 && c >> 5 == 0x06) {
13198 this.charLength = 2;
13199 break;
13200 }
13201
13202 // 1110XXXX
13203 if (i <= 2 && c >> 4 == 0x0E) {
13204 this.charLength = 3;
13205 break;
13206 }
13207
13208 // 11110XXX
13209 if (i <= 3 && c >> 3 == 0x1E) {
13210 this.charLength = 4;
13211 break;
13212 }
13213 }
13214 this.charReceived = i;
13215};
13216
13217StringDecoder.prototype.end = function(buffer) {
13218 var res = '';
13219 if (buffer && buffer.length)
13220 res = this.write(buffer);
13221
13222 if (this.charReceived) {
13223 var cr = this.charReceived;
13224 var buf = this.charBuffer;
13225 var enc = this.encoding;
13226 res += buf.slice(0, cr).toString(enc);
13227 }
13228
13229 return res;
13230};
13231
13232function passThroughWrite(buffer) {
13233 return buffer.toString(this.encoding);
13234}
13235
13236function utf16DetectIncompleteChar(buffer) {
13237 this.charReceived = buffer.length % 2;
13238 this.charLength = this.charReceived ? 2 : 0;
13239}
13240
13241function base64DetectIncompleteChar(buffer) {
13242 this.charReceived = buffer.length % 3;
13243 this.charLength = this.charReceived ? 3 : 0;
13244}
13245
13246},{"buffer":9}],102:[function(_dereq_,module,exports){
13247(function (process){(function (){
13248exports = module.exports = _dereq_('./lib/_stream_readable.js');
13249exports.Stream = _dereq_('stream');
13250exports.Readable = exports;
13251exports.Writable = _dereq_('./lib/_stream_writable.js');
13252exports.Duplex = _dereq_('./lib/_stream_duplex.js');
13253exports.Transform = _dereq_('./lib/_stream_transform.js');
13254exports.PassThrough = _dereq_('./lib/_stream_passthrough.js');
13255if (!process.browser && process.env.READABLE_STREAM === 'disable') {
13256 module.exports = _dereq_('stream');
13257}
13258
13259}).call(this)}).call(this,_dereq_('_process'))
13260},{"./lib/_stream_duplex.js":96,"./lib/_stream_passthrough.js":97,"./lib/_stream_readable.js":98,"./lib/_stream_transform.js":99,"./lib/_stream_writable.js":100,"_process":94,"stream":106}],103:[function(_dereq_,module,exports){
13261/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
13262/* eslint-disable node/no-deprecated-api */
13263var buffer = _dereq_('buffer')
13264var Buffer = buffer.Buffer
13265
13266// alternative to using Object.keys for old browsers
13267function copyProps (src, dst) {
13268 for (var key in src) {
13269 dst[key] = src[key]
13270 }
13271}
13272if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
13273 module.exports = buffer
13274} else {
13275 // Copy properties from require('buffer')
13276 copyProps(buffer, exports)
13277 exports.Buffer = SafeBuffer
13278}
13279
13280function SafeBuffer (arg, encodingOrOffset, length) {
13281 return Buffer(arg, encodingOrOffset, length)
13282}
13283
13284SafeBuffer.prototype = Object.create(Buffer.prototype)
13285
13286// Copy static methods from Buffer
13287copyProps(Buffer, SafeBuffer)
13288
13289SafeBuffer.from = function (arg, encodingOrOffset, length) {
13290 if (typeof arg === 'number') {
13291 throw new TypeError('Argument must not be a number')
13292 }
13293 return Buffer(arg, encodingOrOffset, length)
13294}
13295
13296SafeBuffer.alloc = function (size, fill, encoding) {
13297 if (typeof size !== 'number') {
13298 throw new TypeError('Argument must be a number')
13299 }
13300 var buf = Buffer(size)
13301 if (fill !== undefined) {
13302 if (typeof encoding === 'string') {
13303 buf.fill(fill, encoding)
13304 } else {
13305 buf.fill(fill)
13306 }
13307 } else {
13308 buf.fill(0)
13309 }
13310 return buf
13311}
13312
13313SafeBuffer.allocUnsafe = function (size) {
13314 if (typeof size !== 'number') {
13315 throw new TypeError('Argument must be a number')
13316 }
13317 return Buffer(size)
13318}
13319
13320SafeBuffer.allocUnsafeSlow = function (size) {
13321 if (typeof size !== 'number') {
13322 throw new TypeError('Argument must be a number')
13323 }
13324 return buffer.SlowBuffer(size)
13325}
13326
13327},{"buffer":9}],104:[function(_dereq_,module,exports){
13328'use strict';
13329
13330var GetIntrinsic = _dereq_('get-intrinsic');
13331var define = _dereq_('define-data-property');
13332var hasDescriptors = _dereq_('has-property-descriptors')();
13333var gOPD = _dereq_('gopd');
13334
13335var $TypeError = _dereq_('es-errors/type');
13336var $floor = GetIntrinsic('%Math.floor%');
13337
13338/** @type {import('.')} */
13339module.exports = function setFunctionLength(fn, length) {
13340 if (typeof fn !== 'function') {
13341 throw new $TypeError('`fn` is not a function');
13342 }
13343 if (typeof length !== 'number' || length < 0 || length > 0xFFFFFFFF || $floor(length) !== length) {
13344 throw new $TypeError('`length` must be a positive 32-bit integer');
13345 }
13346
13347 var loose = arguments.length > 2 && !!arguments[2];
13348
13349 var functionLengthIsConfigurable = true;
13350 var functionLengthIsWritable = true;
13351 if ('length' in fn && gOPD) {
13352 var desc = gOPD(fn, 'length');
13353 if (desc && !desc.configurable) {
13354 functionLengthIsConfigurable = false;
13355 }
13356 if (desc && !desc.writable) {
13357 functionLengthIsWritable = false;
13358 }
13359 }
13360
13361 if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) {
13362 if (hasDescriptors) {
13363 define(/** @type {Parameters<define>[0]} */ (fn), 'length', length, true, true);
13364 } else {
13365 define(/** @type {Parameters<define>[0]} */ (fn), 'length', length);
13366 }
13367 }
13368 return fn;
13369};
13370
13371},{"define-data-property":27,"es-errors/type":37,"get-intrinsic":42,"gopd":43,"has-property-descriptors":45}],105:[function(_dereq_,module,exports){
13372(function (factory) {
13373 if (typeof exports === 'object') {
13374 // Node/CommonJS
13375 module.exports = factory();
13376 } else if (typeof define === 'function' && define.amd) {
13377 // AMD
13378 define(factory);
13379 } else {
13380 // Browser globals (with support for web workers)
13381 var glob;
13382
13383 try {
13384 glob = window;
13385 } catch (e) {
13386 glob = self;
13387 }
13388
13389 glob.SparkMD5 = factory();
13390 }
13391}(function (undefined) {
13392
13393 'use strict';
13394
13395 /*
13396 * Fastest md5 implementation around (JKM md5).
13397 * Credits: Joseph Myers
13398 *
13399 * @see http://www.myersdaily.org/joseph/javascript/md5-text.html
13400 * @see http://jsperf.com/md5-shootout/7
13401 */
13402
13403 /* this function is much faster,
13404 so if possible we use it. Some IEs
13405 are the only ones I know of that
13406 need the idiotic second function,
13407 generated by an if clause. */
13408 var add32 = function (a, b) {
13409 return (a + b) & 0xFFFFFFFF;
13410 },
13411 hex_chr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
13412
13413
13414 function cmn(q, a, b, x, s, t) {
13415 a = add32(add32(a, q), add32(x, t));
13416 return add32((a << s) | (a >>> (32 - s)), b);
13417 }
13418
13419 function md5cycle(x, k) {
13420 var a = x[0],
13421 b = x[1],
13422 c = x[2],
13423 d = x[3];
13424
13425 a += (b & c | ~b & d) + k[0] - 680876936 | 0;
13426 a = (a << 7 | a >>> 25) + b | 0;
13427 d += (a & b | ~a & c) + k[1] - 389564586 | 0;
13428 d = (d << 12 | d >>> 20) + a | 0;
13429 c += (d & a | ~d & b) + k[2] + 606105819 | 0;
13430 c = (c << 17 | c >>> 15) + d | 0;
13431 b += (c & d | ~c & a) + k[3] - 1044525330 | 0;
13432 b = (b << 22 | b >>> 10) + c | 0;
13433 a += (b & c | ~b & d) + k[4] - 176418897 | 0;
13434 a = (a << 7 | a >>> 25) + b | 0;
13435 d += (a & b | ~a & c) + k[5] + 1200080426 | 0;
13436 d = (d << 12 | d >>> 20) + a | 0;
13437 c += (d & a | ~d & b) + k[6] - 1473231341 | 0;
13438 c = (c << 17 | c >>> 15) + d | 0;
13439 b += (c & d | ~c & a) + k[7] - 45705983 | 0;
13440 b = (b << 22 | b >>> 10) + c | 0;
13441 a += (b & c | ~b & d) + k[8] + 1770035416 | 0;
13442 a = (a << 7 | a >>> 25) + b | 0;
13443 d += (a & b | ~a & c) + k[9] - 1958414417 | 0;
13444 d = (d << 12 | d >>> 20) + a | 0;
13445 c += (d & a | ~d & b) + k[10] - 42063 | 0;
13446 c = (c << 17 | c >>> 15) + d | 0;
13447 b += (c & d | ~c & a) + k[11] - 1990404162 | 0;
13448 b = (b << 22 | b >>> 10) + c | 0;
13449 a += (b & c | ~b & d) + k[12] + 1804603682 | 0;
13450 a = (a << 7 | a >>> 25) + b | 0;
13451 d += (a & b | ~a & c) + k[13] - 40341101 | 0;
13452 d = (d << 12 | d >>> 20) + a | 0;
13453 c += (d & a | ~d & b) + k[14] - 1502002290 | 0;
13454 c = (c << 17 | c >>> 15) + d | 0;
13455 b += (c & d | ~c & a) + k[15] + 1236535329 | 0;
13456 b = (b << 22 | b >>> 10) + c | 0;
13457
13458 a += (b & d | c & ~d) + k[1] - 165796510 | 0;
13459 a = (a << 5 | a >>> 27) + b | 0;
13460 d += (a & c | b & ~c) + k[6] - 1069501632 | 0;
13461 d = (d << 9 | d >>> 23) + a | 0;
13462 c += (d & b | a & ~b) + k[11] + 643717713 | 0;
13463 c = (c << 14 | c >>> 18) + d | 0;
13464 b += (c & a | d & ~a) + k[0] - 373897302 | 0;
13465 b = (b << 20 | b >>> 12) + c | 0;
13466 a += (b & d | c & ~d) + k[5] - 701558691 | 0;
13467 a = (a << 5 | a >>> 27) + b | 0;
13468 d += (a & c | b & ~c) + k[10] + 38016083 | 0;
13469 d = (d << 9 | d >>> 23) + a | 0;
13470 c += (d & b | a & ~b) + k[15] - 660478335 | 0;
13471 c = (c << 14 | c >>> 18) + d | 0;
13472 b += (c & a | d & ~a) + k[4] - 405537848 | 0;
13473 b = (b << 20 | b >>> 12) + c | 0;
13474 a += (b & d | c & ~d) + k[9] + 568446438 | 0;
13475 a = (a << 5 | a >>> 27) + b | 0;
13476 d += (a & c | b & ~c) + k[14] - 1019803690 | 0;
13477 d = (d << 9 | d >>> 23) + a | 0;
13478 c += (d & b | a & ~b) + k[3] - 187363961 | 0;
13479 c = (c << 14 | c >>> 18) + d | 0;
13480 b += (c & a | d & ~a) + k[8] + 1163531501 | 0;
13481 b = (b << 20 | b >>> 12) + c | 0;
13482 a += (b & d | c & ~d) + k[13] - 1444681467 | 0;
13483 a = (a << 5 | a >>> 27) + b | 0;
13484 d += (a & c | b & ~c) + k[2] - 51403784 | 0;
13485 d = (d << 9 | d >>> 23) + a | 0;
13486 c += (d & b | a & ~b) + k[7] + 1735328473 | 0;
13487 c = (c << 14 | c >>> 18) + d | 0;
13488 b += (c & a | d & ~a) + k[12] - 1926607734 | 0;
13489 b = (b << 20 | b >>> 12) + c | 0;
13490
13491 a += (b ^ c ^ d) + k[5] - 378558 | 0;
13492 a = (a << 4 | a >>> 28) + b | 0;
13493 d += (a ^ b ^ c) + k[8] - 2022574463 | 0;
13494 d = (d << 11 | d >>> 21) + a | 0;
13495 c += (d ^ a ^ b) + k[11] + 1839030562 | 0;
13496 c = (c << 16 | c >>> 16) + d | 0;
13497 b += (c ^ d ^ a) + k[14] - 35309556 | 0;
13498 b = (b << 23 | b >>> 9) + c | 0;
13499 a += (b ^ c ^ d) + k[1] - 1530992060 | 0;
13500 a = (a << 4 | a >>> 28) + b | 0;
13501 d += (a ^ b ^ c) + k[4] + 1272893353 | 0;
13502 d = (d << 11 | d >>> 21) + a | 0;
13503 c += (d ^ a ^ b) + k[7] - 155497632 | 0;
13504 c = (c << 16 | c >>> 16) + d | 0;
13505 b += (c ^ d ^ a) + k[10] - 1094730640 | 0;
13506 b = (b << 23 | b >>> 9) + c | 0;
13507 a += (b ^ c ^ d) + k[13] + 681279174 | 0;
13508 a = (a << 4 | a >>> 28) + b | 0;
13509 d += (a ^ b ^ c) + k[0] - 358537222 | 0;
13510 d = (d << 11 | d >>> 21) + a | 0;
13511 c += (d ^ a ^ b) + k[3] - 722521979 | 0;
13512 c = (c << 16 | c >>> 16) + d | 0;
13513 b += (c ^ d ^ a) + k[6] + 76029189 | 0;
13514 b = (b << 23 | b >>> 9) + c | 0;
13515 a += (b ^ c ^ d) + k[9] - 640364487 | 0;
13516 a = (a << 4 | a >>> 28) + b | 0;
13517 d += (a ^ b ^ c) + k[12] - 421815835 | 0;
13518 d = (d << 11 | d >>> 21) + a | 0;
13519 c += (d ^ a ^ b) + k[15] + 530742520 | 0;
13520 c = (c << 16 | c >>> 16) + d | 0;
13521 b += (c ^ d ^ a) + k[2] - 995338651 | 0;
13522 b = (b << 23 | b >>> 9) + c | 0;
13523
13524 a += (c ^ (b | ~d)) + k[0] - 198630844 | 0;
13525 a = (a << 6 | a >>> 26) + b | 0;
13526 d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0;
13527 d = (d << 10 | d >>> 22) + a | 0;
13528 c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0;
13529 c = (c << 15 | c >>> 17) + d | 0;
13530 b += (d ^ (c | ~a)) + k[5] - 57434055 | 0;
13531 b = (b << 21 |b >>> 11) + c | 0;
13532 a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0;
13533 a = (a << 6 | a >>> 26) + b | 0;
13534 d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0;
13535 d = (d << 10 | d >>> 22) + a | 0;
13536 c += (a ^ (d | ~b)) + k[10] - 1051523 | 0;
13537 c = (c << 15 | c >>> 17) + d | 0;
13538 b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0;
13539 b = (b << 21 |b >>> 11) + c | 0;
13540 a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0;
13541 a = (a << 6 | a >>> 26) + b | 0;
13542 d += (b ^ (a | ~c)) + k[15] - 30611744 | 0;
13543 d = (d << 10 | d >>> 22) + a | 0;
13544 c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0;
13545 c = (c << 15 | c >>> 17) + d | 0;
13546 b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0;
13547 b = (b << 21 |b >>> 11) + c | 0;
13548 a += (c ^ (b | ~d)) + k[4] - 145523070 | 0;
13549 a = (a << 6 | a >>> 26) + b | 0;
13550 d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0;
13551 d = (d << 10 | d >>> 22) + a | 0;
13552 c += (a ^ (d | ~b)) + k[2] + 718787259 | 0;
13553 c = (c << 15 | c >>> 17) + d | 0;
13554 b += (d ^ (c | ~a)) + k[9] - 343485551 | 0;
13555 b = (b << 21 | b >>> 11) + c | 0;
13556
13557 x[0] = a + x[0] | 0;
13558 x[1] = b + x[1] | 0;
13559 x[2] = c + x[2] | 0;
13560 x[3] = d + x[3] | 0;
13561 }
13562
13563 function md5blk(s) {
13564 var md5blks = [],
13565 i; /* Andy King said do it this way. */
13566
13567 for (i = 0; i < 64; i += 4) {
13568 md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
13569 }
13570 return md5blks;
13571 }
13572
13573 function md5blk_array(a) {
13574 var md5blks = [],
13575 i; /* Andy King said do it this way. */
13576
13577 for (i = 0; i < 64; i += 4) {
13578 md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);
13579 }
13580 return md5blks;
13581 }
13582
13583 function md51(s) {
13584 var n = s.length,
13585 state = [1732584193, -271733879, -1732584194, 271733878],
13586 i,
13587 length,
13588 tail,
13589 tmp,
13590 lo,
13591 hi;
13592
13593 for (i = 64; i <= n; i += 64) {
13594 md5cycle(state, md5blk(s.substring(i - 64, i)));
13595 }
13596 s = s.substring(i - 64);
13597 length = s.length;
13598 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
13599 for (i = 0; i < length; i += 1) {
13600 tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
13601 }
13602 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13603 if (i > 55) {
13604 md5cycle(state, tail);
13605 for (i = 0; i < 16; i += 1) {
13606 tail[i] = 0;
13607 }
13608 }
13609
13610 // Beware that the final length might not fit in 32 bits so we take care of that
13611 tmp = n * 8;
13612 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
13613 lo = parseInt(tmp[2], 16);
13614 hi = parseInt(tmp[1], 16) || 0;
13615
13616 tail[14] = lo;
13617 tail[15] = hi;
13618
13619 md5cycle(state, tail);
13620 return state;
13621 }
13622
13623 function md51_array(a) {
13624 var n = a.length,
13625 state = [1732584193, -271733879, -1732584194, 271733878],
13626 i,
13627 length,
13628 tail,
13629 tmp,
13630 lo,
13631 hi;
13632
13633 for (i = 64; i <= n; i += 64) {
13634 md5cycle(state, md5blk_array(a.subarray(i - 64, i)));
13635 }
13636
13637 // Not sure if it is a bug, however IE10 will always produce a sub array of length 1
13638 // containing the last element of the parent array if the sub array specified starts
13639 // beyond the length of the parent array - weird.
13640 // https://connect.microsoft.com/IE/feedback/details/771452/typed-array-subarray-issue
13641 a = (i - 64) < n ? a.subarray(i - 64) : new Uint8Array(0);
13642
13643 length = a.length;
13644 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
13645 for (i = 0; i < length; i += 1) {
13646 tail[i >> 2] |= a[i] << ((i % 4) << 3);
13647 }
13648
13649 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13650 if (i > 55) {
13651 md5cycle(state, tail);
13652 for (i = 0; i < 16; i += 1) {
13653 tail[i] = 0;
13654 }
13655 }
13656
13657 // Beware that the final length might not fit in 32 bits so we take care of that
13658 tmp = n * 8;
13659 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
13660 lo = parseInt(tmp[2], 16);
13661 hi = parseInt(tmp[1], 16) || 0;
13662
13663 tail[14] = lo;
13664 tail[15] = hi;
13665
13666 md5cycle(state, tail);
13667
13668 return state;
13669 }
13670
13671 function rhex(n) {
13672 var s = '',
13673 j;
13674 for (j = 0; j < 4; j += 1) {
13675 s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
13676 }
13677 return s;
13678 }
13679
13680 function hex(x) {
13681 var i;
13682 for (i = 0; i < x.length; i += 1) {
13683 x[i] = rhex(x[i]);
13684 }
13685 return x.join('');
13686 }
13687
13688 // In some cases the fast add32 function cannot be used..
13689 if (hex(md51('hello')) !== '5d41402abc4b2a76b9719d911017c592') {
13690 add32 = function (x, y) {
13691 var lsw = (x & 0xFFFF) + (y & 0xFFFF),
13692 msw = (x >> 16) + (y >> 16) + (lsw >> 16);
13693 return (msw << 16) | (lsw & 0xFFFF);
13694 };
13695 }
13696
13697 // ---------------------------------------------------
13698
13699 /**
13700 * ArrayBuffer slice polyfill.
13701 *
13702 * @see https://github.com/ttaubert/node-arraybuffer-slice
13703 */
13704
13705 if (typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.prototype.slice) {
13706 (function () {
13707 function clamp(val, length) {
13708 val = (val | 0) || 0;
13709
13710 if (val < 0) {
13711 return Math.max(val + length, 0);
13712 }
13713
13714 return Math.min(val, length);
13715 }
13716
13717 ArrayBuffer.prototype.slice = function (from, to) {
13718 var length = this.byteLength,
13719 begin = clamp(from, length),
13720 end = length,
13721 num,
13722 target,
13723 targetArray,
13724 sourceArray;
13725
13726 if (to !== undefined) {
13727 end = clamp(to, length);
13728 }
13729
13730 if (begin > end) {
13731 return new ArrayBuffer(0);
13732 }
13733
13734 num = end - begin;
13735 target = new ArrayBuffer(num);
13736 targetArray = new Uint8Array(target);
13737
13738 sourceArray = new Uint8Array(this, begin, num);
13739 targetArray.set(sourceArray);
13740
13741 return target;
13742 };
13743 })();
13744 }
13745
13746 // ---------------------------------------------------
13747
13748 /**
13749 * Helpers.
13750 */
13751
13752 function toUtf8(str) {
13753 if (/[\u0080-\uFFFF]/.test(str)) {
13754 str = unescape(encodeURIComponent(str));
13755 }
13756
13757 return str;
13758 }
13759
13760 function utf8Str2ArrayBuffer(str, returnUInt8Array) {
13761 var length = str.length,
13762 buff = new ArrayBuffer(length),
13763 arr = new Uint8Array(buff),
13764 i;
13765
13766 for (i = 0; i < length; i += 1) {
13767 arr[i] = str.charCodeAt(i);
13768 }
13769
13770 return returnUInt8Array ? arr : buff;
13771 }
13772
13773 function arrayBuffer2Utf8Str(buff) {
13774 return String.fromCharCode.apply(null, new Uint8Array(buff));
13775 }
13776
13777 function concatenateArrayBuffers(first, second, returnUInt8Array) {
13778 var result = new Uint8Array(first.byteLength + second.byteLength);
13779
13780 result.set(new Uint8Array(first));
13781 result.set(new Uint8Array(second), first.byteLength);
13782
13783 return returnUInt8Array ? result : result.buffer;
13784 }
13785
13786 function hexToBinaryString(hex) {
13787 var bytes = [],
13788 length = hex.length,
13789 x;
13790
13791 for (x = 0; x < length - 1; x += 2) {
13792 bytes.push(parseInt(hex.substr(x, 2), 16));
13793 }
13794
13795 return String.fromCharCode.apply(String, bytes);
13796 }
13797
13798 // ---------------------------------------------------
13799
13800 /**
13801 * SparkMD5 OOP implementation.
13802 *
13803 * Use this class to perform an incremental md5, otherwise use the
13804 * static methods instead.
13805 */
13806
13807 function SparkMD5() {
13808 // call reset to init the instance
13809 this.reset();
13810 }
13811
13812 /**
13813 * Appends a string.
13814 * A conversion will be applied if an utf8 string is detected.
13815 *
13816 * @param {String} str The string to be appended
13817 *
13818 * @return {SparkMD5} The instance itself
13819 */
13820 SparkMD5.prototype.append = function (str) {
13821 // Converts the string to utf8 bytes if necessary
13822 // Then append as binary
13823 this.appendBinary(toUtf8(str));
13824
13825 return this;
13826 };
13827
13828 /**
13829 * Appends a binary string.
13830 *
13831 * @param {String} contents The binary string to be appended
13832 *
13833 * @return {SparkMD5} The instance itself
13834 */
13835 SparkMD5.prototype.appendBinary = function (contents) {
13836 this._buff += contents;
13837 this._length += contents.length;
13838
13839 var length = this._buff.length,
13840 i;
13841
13842 for (i = 64; i <= length; i += 64) {
13843 md5cycle(this._hash, md5blk(this._buff.substring(i - 64, i)));
13844 }
13845
13846 this._buff = this._buff.substring(i - 64);
13847
13848 return this;
13849 };
13850
13851 /**
13852 * Finishes the incremental computation, reseting the internal state and
13853 * returning the result.
13854 *
13855 * @param {Boolean} raw True to get the raw string, false to get the hex string
13856 *
13857 * @return {String} The result
13858 */
13859 SparkMD5.prototype.end = function (raw) {
13860 var buff = this._buff,
13861 length = buff.length,
13862 i,
13863 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
13864 ret;
13865
13866 for (i = 0; i < length; i += 1) {
13867 tail[i >> 2] |= buff.charCodeAt(i) << ((i % 4) << 3);
13868 }
13869
13870 this._finish(tail, length);
13871 ret = hex(this._hash);
13872
13873 if (raw) {
13874 ret = hexToBinaryString(ret);
13875 }
13876
13877 this.reset();
13878
13879 return ret;
13880 };
13881
13882 /**
13883 * Resets the internal state of the computation.
13884 *
13885 * @return {SparkMD5} The instance itself
13886 */
13887 SparkMD5.prototype.reset = function () {
13888 this._buff = '';
13889 this._length = 0;
13890 this._hash = [1732584193, -271733879, -1732584194, 271733878];
13891
13892 return this;
13893 };
13894
13895 /**
13896 * Gets the internal state of the computation.
13897 *
13898 * @return {Object} The state
13899 */
13900 SparkMD5.prototype.getState = function () {
13901 return {
13902 buff: this._buff,
13903 length: this._length,
13904 hash: this._hash.slice()
13905 };
13906 };
13907
13908 /**
13909 * Gets the internal state of the computation.
13910 *
13911 * @param {Object} state The state
13912 *
13913 * @return {SparkMD5} The instance itself
13914 */
13915 SparkMD5.prototype.setState = function (state) {
13916 this._buff = state.buff;
13917 this._length = state.length;
13918 this._hash = state.hash;
13919
13920 return this;
13921 };
13922
13923 /**
13924 * Releases memory used by the incremental buffer and other additional
13925 * resources. If you plan to use the instance again, use reset instead.
13926 */
13927 SparkMD5.prototype.destroy = function () {
13928 delete this._hash;
13929 delete this._buff;
13930 delete this._length;
13931 };
13932
13933 /**
13934 * Finish the final calculation based on the tail.
13935 *
13936 * @param {Array} tail The tail (will be modified)
13937 * @param {Number} length The length of the remaining buffer
13938 */
13939 SparkMD5.prototype._finish = function (tail, length) {
13940 var i = length,
13941 tmp,
13942 lo,
13943 hi;
13944
13945 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13946 if (i > 55) {
13947 md5cycle(this._hash, tail);
13948 for (i = 0; i < 16; i += 1) {
13949 tail[i] = 0;
13950 }
13951 }
13952
13953 // Do the final computation based on the tail and length
13954 // Beware that the final length may not fit in 32 bits so we take care of that
13955 tmp = this._length * 8;
13956 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
13957 lo = parseInt(tmp[2], 16);
13958 hi = parseInt(tmp[1], 16) || 0;
13959
13960 tail[14] = lo;
13961 tail[15] = hi;
13962 md5cycle(this._hash, tail);
13963 };
13964
13965 /**
13966 * Performs the md5 hash on a string.
13967 * A conversion will be applied if utf8 string is detected.
13968 *
13969 * @param {String} str The 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.hash = function (str, raw) {
13975 // Converts the string to utf8 bytes if necessary
13976 // Then compute it using the binary function
13977 return SparkMD5.hashBinary(toUtf8(str), raw);
13978 };
13979
13980 /**
13981 * Performs the md5 hash on a binary string.
13982 *
13983 * @param {String} content The binary string
13984 * @param {Boolean} [raw] True to get the raw string, false to get the hex string
13985 *
13986 * @return {String} The result
13987 */
13988 SparkMD5.hashBinary = function (content, raw) {
13989 var hash = md51(content),
13990 ret = hex(hash);
13991
13992 return raw ? hexToBinaryString(ret) : ret;
13993 };
13994
13995 // ---------------------------------------------------
13996
13997 /**
13998 * SparkMD5 OOP implementation for array buffers.
13999 *
14000 * Use this class to perform an incremental md5 ONLY for array buffers.
14001 */
14002 SparkMD5.ArrayBuffer = function () {
14003 // call reset to init the instance
14004 this.reset();
14005 };
14006
14007 /**
14008 * Appends an array buffer.
14009 *
14010 * @param {ArrayBuffer} arr The array to be appended
14011 *
14012 * @return {SparkMD5.ArrayBuffer} The instance itself
14013 */
14014 SparkMD5.ArrayBuffer.prototype.append = function (arr) {
14015 var buff = concatenateArrayBuffers(this._buff.buffer, arr, true),
14016 length = buff.length,
14017 i;
14018
14019 this._length += arr.byteLength;
14020
14021 for (i = 64; i <= length; i += 64) {
14022 md5cycle(this._hash, md5blk_array(buff.subarray(i - 64, i)));
14023 }
14024
14025 this._buff = (i - 64) < length ? new Uint8Array(buff.buffer.slice(i - 64)) : new Uint8Array(0);
14026
14027 return this;
14028 };
14029
14030 /**
14031 * Finishes the incremental computation, reseting the internal state and
14032 * returning the result.
14033 *
14034 * @param {Boolean} raw True to get the raw string, false to get the hex string
14035 *
14036 * @return {String} The result
14037 */
14038 SparkMD5.ArrayBuffer.prototype.end = function (raw) {
14039 var buff = this._buff,
14040 length = buff.length,
14041 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
14042 i,
14043 ret;
14044
14045 for (i = 0; i < length; i += 1) {
14046 tail[i >> 2] |= buff[i] << ((i % 4) << 3);
14047 }
14048
14049 this._finish(tail, length);
14050 ret = hex(this._hash);
14051
14052 if (raw) {
14053 ret = hexToBinaryString(ret);
14054 }
14055
14056 this.reset();
14057
14058 return ret;
14059 };
14060
14061 /**
14062 * Resets the internal state of the computation.
14063 *
14064 * @return {SparkMD5.ArrayBuffer} The instance itself
14065 */
14066 SparkMD5.ArrayBuffer.prototype.reset = function () {
14067 this._buff = new Uint8Array(0);
14068 this._length = 0;
14069 this._hash = [1732584193, -271733879, -1732584194, 271733878];
14070
14071 return this;
14072 };
14073
14074 /**
14075 * Gets the internal state of the computation.
14076 *
14077 * @return {Object} The state
14078 */
14079 SparkMD5.ArrayBuffer.prototype.getState = function () {
14080 var state = SparkMD5.prototype.getState.call(this);
14081
14082 // Convert buffer to a string
14083 state.buff = arrayBuffer2Utf8Str(state.buff);
14084
14085 return state;
14086 };
14087
14088 /**
14089 * Gets the internal state of the computation.
14090 *
14091 * @param {Object} state The state
14092 *
14093 * @return {SparkMD5.ArrayBuffer} The instance itself
14094 */
14095 SparkMD5.ArrayBuffer.prototype.setState = function (state) {
14096 // Convert string to buffer
14097 state.buff = utf8Str2ArrayBuffer(state.buff, true);
14098
14099 return SparkMD5.prototype.setState.call(this, state);
14100 };
14101
14102 SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
14103
14104 SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
14105
14106 /**
14107 * Performs the md5 hash on an array buffer.
14108 *
14109 * @param {ArrayBuffer} arr The array buffer
14110 * @param {Boolean} [raw] True to get the raw string, false to get the hex one
14111 *
14112 * @return {String} The result
14113 */
14114 SparkMD5.ArrayBuffer.hash = function (arr, raw) {
14115 var hash = md51_array(new Uint8Array(arr)),
14116 ret = hex(hash);
14117
14118 return raw ? hexToBinaryString(ret) : ret;
14119 };
14120
14121 return SparkMD5;
14122}));
14123
14124},{}],106:[function(_dereq_,module,exports){
14125// Copyright Joyent, Inc. and other Node contributors.
14126//
14127// Permission is hereby granted, free of charge, to any person obtaining a
14128// copy of this software and associated documentation files (the
14129// "Software"), to deal in the Software without restriction, including
14130// without limitation the rights to use, copy, modify, merge, publish,
14131// distribute, sublicense, and/or sell copies of the Software, and to permit
14132// persons to whom the Software is furnished to do so, subject to the
14133// following conditions:
14134//
14135// The above copyright notice and this permission notice shall be included
14136// in all copies or substantial portions of the Software.
14137//
14138// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14139// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14140// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14141// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14142// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14143// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14144// USE OR OTHER DEALINGS IN THE SOFTWARE.
14145
14146module.exports = Stream;
14147
14148var EE = _dereq_('events').EventEmitter;
14149var inherits = _dereq_('inherits');
14150
14151inherits(Stream, EE);
14152Stream.Readable = _dereq_('readable-stream/readable.js');
14153Stream.Writable = _dereq_('readable-stream/writable.js');
14154Stream.Duplex = _dereq_('readable-stream/duplex.js');
14155Stream.Transform = _dereq_('readable-stream/transform.js');
14156Stream.PassThrough = _dereq_('readable-stream/passthrough.js');
14157
14158// Backwards-compat with node 0.4.x
14159Stream.Stream = Stream;
14160
14161
14162
14163// old-style streams. Note that the pipe method (the only relevant
14164// part of this class) is overridden in the Readable class.
14165
14166function Stream() {
14167 EE.call(this);
14168}
14169
14170Stream.prototype.pipe = function(dest, options) {
14171 var source = this;
14172
14173 function ondata(chunk) {
14174 if (dest.writable) {
14175 if (false === dest.write(chunk) && source.pause) {
14176 source.pause();
14177 }
14178 }
14179 }
14180
14181 source.on('data', ondata);
14182
14183 function ondrain() {
14184 if (source.readable && source.resume) {
14185 source.resume();
14186 }
14187 }
14188
14189 dest.on('drain', ondrain);
14190
14191 // If the 'end' option is not supplied, dest.end() will be called when
14192 // source gets the 'end' or 'close' events. Only dest.end() once.
14193 if (!dest._isStdio && (!options || options.end !== false)) {
14194 source.on('end', onend);
14195 source.on('close', onclose);
14196 }
14197
14198 var didOnEnd = false;
14199 function onend() {
14200 if (didOnEnd) return;
14201 didOnEnd = true;
14202
14203 dest.end();
14204 }
14205
14206
14207 function onclose() {
14208 if (didOnEnd) return;
14209 didOnEnd = true;
14210
14211 if (typeof dest.destroy === 'function') dest.destroy();
14212 }
14213
14214 // don't leave dangling pipes when there are errors.
14215 function onerror(er) {
14216 cleanup();
14217 if (EE.listenerCount(this, 'error') === 0) {
14218 throw er; // Unhandled stream error in pipe.
14219 }
14220 }
14221
14222 source.on('error', onerror);
14223 dest.on('error', onerror);
14224
14225 // remove all the event listeners that were added.
14226 function cleanup() {
14227 source.removeListener('data', ondata);
14228 dest.removeListener('drain', ondrain);
14229
14230 source.removeListener('end', onend);
14231 source.removeListener('close', onclose);
14232
14233 source.removeListener('error', onerror);
14234 dest.removeListener('error', onerror);
14235
14236 source.removeListener('end', cleanup);
14237 source.removeListener('close', cleanup);
14238
14239 dest.removeListener('close', cleanup);
14240 }
14241
14242 source.on('end', cleanup);
14243 source.on('close', cleanup);
14244
14245 dest.on('close', cleanup);
14246
14247 dest.emit('pipe', source);
14248
14249 // Allow for unix-like usage: A.pipe(B).pipe(C)
14250 return dest;
14251};
14252
14253},{"events":39,"inherits":53,"readable-stream/duplex.js":108,"readable-stream/passthrough.js":117,"readable-stream/readable.js":118,"readable-stream/transform.js":119,"readable-stream/writable.js":120}],107:[function(_dereq_,module,exports){
14254var toString = {}.toString;
14255
14256module.exports = Array.isArray || function (arr) {
14257 return toString.call(arr) == '[object Array]';
14258};
14259
14260},{}],108:[function(_dereq_,module,exports){
14261module.exports = _dereq_('./lib/_stream_duplex.js');
14262
14263},{"./lib/_stream_duplex.js":109}],109:[function(_dereq_,module,exports){
14264// Copyright Joyent, Inc. and other Node contributors.
14265//
14266// Permission is hereby granted, free of charge, to any person obtaining a
14267// copy of this software and associated documentation files (the
14268// "Software"), to deal in the Software without restriction, including
14269// without limitation the rights to use, copy, modify, merge, publish,
14270// distribute, sublicense, and/or sell copies of the Software, and to permit
14271// persons to whom the Software is furnished to do so, subject to the
14272// following conditions:
14273//
14274// The above copyright notice and this permission notice shall be included
14275// in all copies or substantial portions of the Software.
14276//
14277// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14278// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14279// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14280// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14281// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14282// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14283// USE OR OTHER DEALINGS IN THE SOFTWARE.
14284
14285// a duplex stream is just a stream that is both readable and writable.
14286// Since JS doesn't have multiple prototypal inheritance, this class
14287// prototypally inherits from Readable, and then parasitically from
14288// Writable.
14289
14290'use strict';
14291
14292/*<replacement>*/
14293
14294var pna = _dereq_('process-nextick-args');
14295/*</replacement>*/
14296
14297/*<replacement>*/
14298var objectKeys = Object.keys || function (obj) {
14299 var keys = [];
14300 for (var key in obj) {
14301 keys.push(key);
14302 }return keys;
14303};
14304/*</replacement>*/
14305
14306module.exports = Duplex;
14307
14308/*<replacement>*/
14309var util = Object.create(_dereq_('core-util-is'));
14310util.inherits = _dereq_('inherits');
14311/*</replacement>*/
14312
14313var Readable = _dereq_('./_stream_readable');
14314var Writable = _dereq_('./_stream_writable');
14315
14316util.inherits(Duplex, Readable);
14317
14318{
14319 // avoid scope creep, the keys array can then be collected
14320 var keys = objectKeys(Writable.prototype);
14321 for (var v = 0; v < keys.length; v++) {
14322 var method = keys[v];
14323 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
14324 }
14325}
14326
14327function Duplex(options) {
14328 if (!(this instanceof Duplex)) return new Duplex(options);
14329
14330 Readable.call(this, options);
14331 Writable.call(this, options);
14332
14333 if (options && options.readable === false) this.readable = false;
14334
14335 if (options && options.writable === false) this.writable = false;
14336
14337 this.allowHalfOpen = true;
14338 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
14339
14340 this.once('end', onend);
14341}
14342
14343Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
14344 // making it explicit this property is not enumerable
14345 // because otherwise some prototype manipulation in
14346 // userland will fail
14347 enumerable: false,
14348 get: function () {
14349 return this._writableState.highWaterMark;
14350 }
14351});
14352
14353// the no-half-open enforcer
14354function onend() {
14355 // if we allow half-open state, or if the writable side ended,
14356 // then we're ok.
14357 if (this.allowHalfOpen || this._writableState.ended) return;
14358
14359 // no more data can be written.
14360 // But allow more writes to happen in this tick.
14361 pna.nextTick(onEndNT, this);
14362}
14363
14364function onEndNT(self) {
14365 self.end();
14366}
14367
14368Object.defineProperty(Duplex.prototype, 'destroyed', {
14369 get: function () {
14370 if (this._readableState === undefined || this._writableState === undefined) {
14371 return false;
14372 }
14373 return this._readableState.destroyed && this._writableState.destroyed;
14374 },
14375 set: function (value) {
14376 // we ignore the value if the stream
14377 // has not been initialized yet
14378 if (this._readableState === undefined || this._writableState === undefined) {
14379 return;
14380 }
14381
14382 // backward compatibility, the user is explicitly
14383 // managing destroyed
14384 this._readableState.destroyed = value;
14385 this._writableState.destroyed = value;
14386 }
14387});
14388
14389Duplex.prototype._destroy = function (err, cb) {
14390 this.push(null);
14391 this.end();
14392
14393 pna.nextTick(cb, err);
14394};
14395},{"./_stream_readable":111,"./_stream_writable":113,"core-util-is":12,"inherits":53,"process-nextick-args":93}],110:[function(_dereq_,module,exports){
14396// Copyright Joyent, Inc. and other Node contributors.
14397//
14398// Permission is hereby granted, free of charge, to any person obtaining a
14399// copy of this software and associated documentation files (the
14400// "Software"), to deal in the Software without restriction, including
14401// without limitation the rights to use, copy, modify, merge, publish,
14402// distribute, sublicense, and/or sell copies of the Software, and to permit
14403// persons to whom the Software is furnished to do so, subject to the
14404// following conditions:
14405//
14406// The above copyright notice and this permission notice shall be included
14407// in all copies or substantial portions of the Software.
14408//
14409// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14410// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14411// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14412// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14413// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14414// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14415// USE OR OTHER DEALINGS IN THE SOFTWARE.
14416
14417// a passthrough stream.
14418// basically just the most minimal sort of Transform stream.
14419// Every written chunk gets output as-is.
14420
14421'use strict';
14422
14423module.exports = PassThrough;
14424
14425var Transform = _dereq_('./_stream_transform');
14426
14427/*<replacement>*/
14428var util = Object.create(_dereq_('core-util-is'));
14429util.inherits = _dereq_('inherits');
14430/*</replacement>*/
14431
14432util.inherits(PassThrough, Transform);
14433
14434function PassThrough(options) {
14435 if (!(this instanceof PassThrough)) return new PassThrough(options);
14436
14437 Transform.call(this, options);
14438}
14439
14440PassThrough.prototype._transform = function (chunk, encoding, cb) {
14441 cb(null, chunk);
14442};
14443},{"./_stream_transform":112,"core-util-is":12,"inherits":53}],111:[function(_dereq_,module,exports){
14444(function (process,global){(function (){
14445// Copyright Joyent, Inc. and other Node contributors.
14446//
14447// Permission is hereby granted, free of charge, to any person obtaining a
14448// copy of this software and associated documentation files (the
14449// "Software"), to deal in the Software without restriction, including
14450// without limitation the rights to use, copy, modify, merge, publish,
14451// distribute, sublicense, and/or sell copies of the Software, and to permit
14452// persons to whom the Software is furnished to do so, subject to the
14453// following conditions:
14454//
14455// The above copyright notice and this permission notice shall be included
14456// in all copies or substantial portions of the Software.
14457//
14458// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14459// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14460// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14461// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14462// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14463// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14464// USE OR OTHER DEALINGS IN THE SOFTWARE.
14465
14466'use strict';
14467
14468/*<replacement>*/
14469
14470var pna = _dereq_('process-nextick-args');
14471/*</replacement>*/
14472
14473module.exports = Readable;
14474
14475/*<replacement>*/
14476var isArray = _dereq_('isarray');
14477/*</replacement>*/
14478
14479/*<replacement>*/
14480var Duplex;
14481/*</replacement>*/
14482
14483Readable.ReadableState = ReadableState;
14484
14485/*<replacement>*/
14486var EE = _dereq_('events').EventEmitter;
14487
14488var EElistenerCount = function (emitter, type) {
14489 return emitter.listeners(type).length;
14490};
14491/*</replacement>*/
14492
14493/*<replacement>*/
14494var Stream = _dereq_('./internal/streams/stream');
14495/*</replacement>*/
14496
14497/*<replacement>*/
14498
14499var Buffer = _dereq_('safe-buffer').Buffer;
14500var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
14501function _uint8ArrayToBuffer(chunk) {
14502 return Buffer.from(chunk);
14503}
14504function _isUint8Array(obj) {
14505 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
14506}
14507
14508/*</replacement>*/
14509
14510/*<replacement>*/
14511var util = Object.create(_dereq_('core-util-is'));
14512util.inherits = _dereq_('inherits');
14513/*</replacement>*/
14514
14515/*<replacement>*/
14516var debugUtil = _dereq_('util');
14517var debug = void 0;
14518if (debugUtil && debugUtil.debuglog) {
14519 debug = debugUtil.debuglog('stream');
14520} else {
14521 debug = function () {};
14522}
14523/*</replacement>*/
14524
14525var BufferList = _dereq_('./internal/streams/BufferList');
14526var destroyImpl = _dereq_('./internal/streams/destroy');
14527var StringDecoder;
14528
14529util.inherits(Readable, Stream);
14530
14531var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
14532
14533function prependListener(emitter, event, fn) {
14534 // Sadly this is not cacheable as some libraries bundle their own
14535 // event emitter implementation with them.
14536 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
14537
14538 // This is a hack to make sure that our error handler is attached before any
14539 // userland ones. NEVER DO THIS. This is here only because this code needs
14540 // to continue to work with older versions of Node.js that do not include
14541 // the prependListener() method. The goal is to eventually remove this hack.
14542 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]];
14543}
14544
14545function ReadableState(options, stream) {
14546 Duplex = Duplex || _dereq_('./_stream_duplex');
14547
14548 options = options || {};
14549
14550 // Duplex streams are both readable and writable, but share
14551 // the same options object.
14552 // However, some cases require setting options to different
14553 // values for the readable and the writable sides of the duplex stream.
14554 // These options can be provided separately as readableXXX and writableXXX.
14555 var isDuplex = stream instanceof Duplex;
14556
14557 // object stream flag. Used to make read(n) ignore n and to
14558 // make all the buffer merging and length checks go away
14559 this.objectMode = !!options.objectMode;
14560
14561 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
14562
14563 // the point at which it stops calling _read() to fill the buffer
14564 // Note: 0 is a valid value, means "don't call _read preemptively ever"
14565 var hwm = options.highWaterMark;
14566 var readableHwm = options.readableHighWaterMark;
14567 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
14568
14569 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
14570
14571 // cast to ints.
14572 this.highWaterMark = Math.floor(this.highWaterMark);
14573
14574 // A linked list is used to store data chunks instead of an array because the
14575 // linked list can remove elements from the beginning faster than
14576 // array.shift()
14577 this.buffer = new BufferList();
14578 this.length = 0;
14579 this.pipes = null;
14580 this.pipesCount = 0;
14581 this.flowing = null;
14582 this.ended = false;
14583 this.endEmitted = false;
14584 this.reading = false;
14585
14586 // a flag to be able to tell if the event 'readable'/'data' is emitted
14587 // immediately, or on a later tick. We set this to true at first, because
14588 // any actions that shouldn't happen until "later" should generally also
14589 // not happen before the first read call.
14590 this.sync = true;
14591
14592 // whenever we return null, then we set a flag to say
14593 // that we're awaiting a 'readable' event emission.
14594 this.needReadable = false;
14595 this.emittedReadable = false;
14596 this.readableListening = false;
14597 this.resumeScheduled = false;
14598
14599 // has it been destroyed
14600 this.destroyed = false;
14601
14602 // Crypto is kind of old and crusty. Historically, its default string
14603 // encoding is 'binary' so we have to make this configurable.
14604 // Everything else in the universe uses 'utf8', though.
14605 this.defaultEncoding = options.defaultEncoding || 'utf8';
14606
14607 // the number of writers that are awaiting a drain event in .pipe()s
14608 this.awaitDrain = 0;
14609
14610 // if true, a maybeReadMore has been scheduled
14611 this.readingMore = false;
14612
14613 this.decoder = null;
14614 this.encoding = null;
14615 if (options.encoding) {
14616 if (!StringDecoder) StringDecoder = _dereq_('string_decoder/').StringDecoder;
14617 this.decoder = new StringDecoder(options.encoding);
14618 this.encoding = options.encoding;
14619 }
14620}
14621
14622function Readable(options) {
14623 Duplex = Duplex || _dereq_('./_stream_duplex');
14624
14625 if (!(this instanceof Readable)) return new Readable(options);
14626
14627 this._readableState = new ReadableState(options, this);
14628
14629 // legacy
14630 this.readable = true;
14631
14632 if (options) {
14633 if (typeof options.read === 'function') this._read = options.read;
14634
14635 if (typeof options.destroy === 'function') this._destroy = options.destroy;
14636 }
14637
14638 Stream.call(this);
14639}
14640
14641Object.defineProperty(Readable.prototype, 'destroyed', {
14642 get: function () {
14643 if (this._readableState === undefined) {
14644 return false;
14645 }
14646 return this._readableState.destroyed;
14647 },
14648 set: function (value) {
14649 // we ignore the value if the stream
14650 // has not been initialized yet
14651 if (!this._readableState) {
14652 return;
14653 }
14654
14655 // backward compatibility, the user is explicitly
14656 // managing destroyed
14657 this._readableState.destroyed = value;
14658 }
14659});
14660
14661Readable.prototype.destroy = destroyImpl.destroy;
14662Readable.prototype._undestroy = destroyImpl.undestroy;
14663Readable.prototype._destroy = function (err, cb) {
14664 this.push(null);
14665 cb(err);
14666};
14667
14668// Manually shove something into the read() buffer.
14669// This returns true if the highWaterMark has not been hit yet,
14670// similar to how Writable.write() returns true if you should
14671// write() some more.
14672Readable.prototype.push = function (chunk, encoding) {
14673 var state = this._readableState;
14674 var skipChunkCheck;
14675
14676 if (!state.objectMode) {
14677 if (typeof chunk === 'string') {
14678 encoding = encoding || state.defaultEncoding;
14679 if (encoding !== state.encoding) {
14680 chunk = Buffer.from(chunk, encoding);
14681 encoding = '';
14682 }
14683 skipChunkCheck = true;
14684 }
14685 } else {
14686 skipChunkCheck = true;
14687 }
14688
14689 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
14690};
14691
14692// Unshift should *always* be something directly out of read()
14693Readable.prototype.unshift = function (chunk) {
14694 return readableAddChunk(this, chunk, null, true, false);
14695};
14696
14697function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
14698 var state = stream._readableState;
14699 if (chunk === null) {
14700 state.reading = false;
14701 onEofChunk(stream, state);
14702 } else {
14703 var er;
14704 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
14705 if (er) {
14706 stream.emit('error', er);
14707 } else if (state.objectMode || chunk && chunk.length > 0) {
14708 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
14709 chunk = _uint8ArrayToBuffer(chunk);
14710 }
14711
14712 if (addToFront) {
14713 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
14714 } else if (state.ended) {
14715 stream.emit('error', new Error('stream.push() after EOF'));
14716 } else {
14717 state.reading = false;
14718 if (state.decoder && !encoding) {
14719 chunk = state.decoder.write(chunk);
14720 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
14721 } else {
14722 addChunk(stream, state, chunk, false);
14723 }
14724 }
14725 } else if (!addToFront) {
14726 state.reading = false;
14727 }
14728 }
14729
14730 return needMoreData(state);
14731}
14732
14733function addChunk(stream, state, chunk, addToFront) {
14734 if (state.flowing && state.length === 0 && !state.sync) {
14735 stream.emit('data', chunk);
14736 stream.read(0);
14737 } else {
14738 // update the buffer info.
14739 state.length += state.objectMode ? 1 : chunk.length;
14740 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
14741
14742 if (state.needReadable) emitReadable(stream);
14743 }
14744 maybeReadMore(stream, state);
14745}
14746
14747function chunkInvalid(state, chunk) {
14748 var er;
14749 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
14750 er = new TypeError('Invalid non-string/buffer chunk');
14751 }
14752 return er;
14753}
14754
14755// if it's past the high water mark, we can push in some more.
14756// Also, if we have no data yet, we can stand some
14757// more bytes. This is to work around cases where hwm=0,
14758// such as the repl. Also, if the push() triggered a
14759// readable event, and the user called read(largeNumber) such that
14760// needReadable was set, then we ought to push more, so that another
14761// 'readable' event will be triggered.
14762function needMoreData(state) {
14763 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
14764}
14765
14766Readable.prototype.isPaused = function () {
14767 return this._readableState.flowing === false;
14768};
14769
14770// backwards compatibility.
14771Readable.prototype.setEncoding = function (enc) {
14772 if (!StringDecoder) StringDecoder = _dereq_('string_decoder/').StringDecoder;
14773 this._readableState.decoder = new StringDecoder(enc);
14774 this._readableState.encoding = enc;
14775 return this;
14776};
14777
14778// Don't raise the hwm > 8MB
14779var MAX_HWM = 0x800000;
14780function computeNewHighWaterMark(n) {
14781 if (n >= MAX_HWM) {
14782 n = MAX_HWM;
14783 } else {
14784 // Get the next highest power of 2 to prevent increasing hwm excessively in
14785 // tiny amounts
14786 n--;
14787 n |= n >>> 1;
14788 n |= n >>> 2;
14789 n |= n >>> 4;
14790 n |= n >>> 8;
14791 n |= n >>> 16;
14792 n++;
14793 }
14794 return n;
14795}
14796
14797// This function is designed to be inlinable, so please take care when making
14798// changes to the function body.
14799function howMuchToRead(n, state) {
14800 if (n <= 0 || state.length === 0 && state.ended) return 0;
14801 if (state.objectMode) return 1;
14802 if (n !== n) {
14803 // Only flow one buffer at a time
14804 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
14805 }
14806 // If we're asking for more than the current hwm, then raise the hwm.
14807 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
14808 if (n <= state.length) return n;
14809 // Don't have enough
14810 if (!state.ended) {
14811 state.needReadable = true;
14812 return 0;
14813 }
14814 return state.length;
14815}
14816
14817// you can override either this method, or the async _read(n) below.
14818Readable.prototype.read = function (n) {
14819 debug('read', n);
14820 n = parseInt(n, 10);
14821 var state = this._readableState;
14822 var nOrig = n;
14823
14824 if (n !== 0) state.emittedReadable = false;
14825
14826 // if we're doing read(0) to trigger a readable event, but we
14827 // already have a bunch of data in the buffer, then just trigger
14828 // the 'readable' event and move on.
14829 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
14830 debug('read: emitReadable', state.length, state.ended);
14831 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
14832 return null;
14833 }
14834
14835 n = howMuchToRead(n, state);
14836
14837 // if we've ended, and we're now clear, then finish it up.
14838 if (n === 0 && state.ended) {
14839 if (state.length === 0) endReadable(this);
14840 return null;
14841 }
14842
14843 // All the actual chunk generation logic needs to be
14844 // *below* the call to _read. The reason is that in certain
14845 // synthetic stream cases, such as passthrough streams, _read
14846 // may be a completely synchronous operation which may change
14847 // the state of the read buffer, providing enough data when
14848 // before there was *not* enough.
14849 //
14850 // So, the steps are:
14851 // 1. Figure out what the state of things will be after we do
14852 // a read from the buffer.
14853 //
14854 // 2. If that resulting state will trigger a _read, then call _read.
14855 // Note that this may be asynchronous, or synchronous. Yes, it is
14856 // deeply ugly to write APIs this way, but that still doesn't mean
14857 // that the Readable class should behave improperly, as streams are
14858 // designed to be sync/async agnostic.
14859 // Take note if the _read call is sync or async (ie, if the read call
14860 // has returned yet), so that we know whether or not it's safe to emit
14861 // 'readable' etc.
14862 //
14863 // 3. Actually pull the requested chunks out of the buffer and return.
14864
14865 // if we need a readable event, then we need to do some reading.
14866 var doRead = state.needReadable;
14867 debug('need readable', doRead);
14868
14869 // if we currently have less than the highWaterMark, then also read some
14870 if (state.length === 0 || state.length - n < state.highWaterMark) {
14871 doRead = true;
14872 debug('length less than watermark', doRead);
14873 }
14874
14875 // however, if we've ended, then there's no point, and if we're already
14876 // reading, then it's unnecessary.
14877 if (state.ended || state.reading) {
14878 doRead = false;
14879 debug('reading or ended', doRead);
14880 } else if (doRead) {
14881 debug('do read');
14882 state.reading = true;
14883 state.sync = true;
14884 // if the length is currently zero, then we *need* a readable event.
14885 if (state.length === 0) state.needReadable = true;
14886 // call internal read method
14887 this._read(state.highWaterMark);
14888 state.sync = false;
14889 // If _read pushed data synchronously, then `reading` will be false,
14890 // and we need to re-evaluate how much data we can return to the user.
14891 if (!state.reading) n = howMuchToRead(nOrig, state);
14892 }
14893
14894 var ret;
14895 if (n > 0) ret = fromList(n, state);else ret = null;
14896
14897 if (ret === null) {
14898 state.needReadable = true;
14899 n = 0;
14900 } else {
14901 state.length -= n;
14902 }
14903
14904 if (state.length === 0) {
14905 // If we have nothing in the buffer, then we want to know
14906 // as soon as we *do* get something into the buffer.
14907 if (!state.ended) state.needReadable = true;
14908
14909 // If we tried to read() past the EOF, then emit end on the next tick.
14910 if (nOrig !== n && state.ended) endReadable(this);
14911 }
14912
14913 if (ret !== null) this.emit('data', ret);
14914
14915 return ret;
14916};
14917
14918function onEofChunk(stream, state) {
14919 if (state.ended) return;
14920 if (state.decoder) {
14921 var chunk = state.decoder.end();
14922 if (chunk && chunk.length) {
14923 state.buffer.push(chunk);
14924 state.length += state.objectMode ? 1 : chunk.length;
14925 }
14926 }
14927 state.ended = true;
14928
14929 // emit 'readable' now to make sure it gets picked up.
14930 emitReadable(stream);
14931}
14932
14933// Don't emit readable right away in sync mode, because this can trigger
14934// another read() call => stack overflow. This way, it might trigger
14935// a nextTick recursion warning, but that's not so bad.
14936function emitReadable(stream) {
14937 var state = stream._readableState;
14938 state.needReadable = false;
14939 if (!state.emittedReadable) {
14940 debug('emitReadable', state.flowing);
14941 state.emittedReadable = true;
14942 if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
14943 }
14944}
14945
14946function emitReadable_(stream) {
14947 debug('emit readable');
14948 stream.emit('readable');
14949 flow(stream);
14950}
14951
14952// at this point, the user has presumably seen the 'readable' event,
14953// and called read() to consume some data. that may have triggered
14954// in turn another _read(n) call, in which case reading = true if
14955// it's in progress.
14956// However, if we're not ended, or reading, and the length < hwm,
14957// then go ahead and try to read some more preemptively.
14958function maybeReadMore(stream, state) {
14959 if (!state.readingMore) {
14960 state.readingMore = true;
14961 pna.nextTick(maybeReadMore_, stream, state);
14962 }
14963}
14964
14965function maybeReadMore_(stream, state) {
14966 var len = state.length;
14967 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
14968 debug('maybeReadMore read 0');
14969 stream.read(0);
14970 if (len === state.length)
14971 // didn't get any data, stop spinning.
14972 break;else len = state.length;
14973 }
14974 state.readingMore = false;
14975}
14976
14977// abstract method. to be overridden in specific implementation classes.
14978// call cb(er, data) where data is <= n in length.
14979// for virtual (non-string, non-buffer) streams, "length" is somewhat
14980// arbitrary, and perhaps not very meaningful.
14981Readable.prototype._read = function (n) {
14982 this.emit('error', new Error('_read() is not implemented'));
14983};
14984
14985Readable.prototype.pipe = function (dest, pipeOpts) {
14986 var src = this;
14987 var state = this._readableState;
14988
14989 switch (state.pipesCount) {
14990 case 0:
14991 state.pipes = dest;
14992 break;
14993 case 1:
14994 state.pipes = [state.pipes, dest];
14995 break;
14996 default:
14997 state.pipes.push(dest);
14998 break;
14999 }
15000 state.pipesCount += 1;
15001 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
15002
15003 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
15004
15005 var endFn = doEnd ? onend : unpipe;
15006 if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
15007
15008 dest.on('unpipe', onunpipe);
15009 function onunpipe(readable, unpipeInfo) {
15010 debug('onunpipe');
15011 if (readable === src) {
15012 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
15013 unpipeInfo.hasUnpiped = true;
15014 cleanup();
15015 }
15016 }
15017 }
15018
15019 function onend() {
15020 debug('onend');
15021 dest.end();
15022 }
15023
15024 // when the dest drains, it reduces the awaitDrain counter
15025 // on the source. This would be more elegant with a .once()
15026 // handler in flow(), but adding and removing repeatedly is
15027 // too slow.
15028 var ondrain = pipeOnDrain(src);
15029 dest.on('drain', ondrain);
15030
15031 var cleanedUp = false;
15032 function cleanup() {
15033 debug('cleanup');
15034 // cleanup event handlers once the pipe is broken
15035 dest.removeListener('close', onclose);
15036 dest.removeListener('finish', onfinish);
15037 dest.removeListener('drain', ondrain);
15038 dest.removeListener('error', onerror);
15039 dest.removeListener('unpipe', onunpipe);
15040 src.removeListener('end', onend);
15041 src.removeListener('end', unpipe);
15042 src.removeListener('data', ondata);
15043
15044 cleanedUp = true;
15045
15046 // if the reader is waiting for a drain event from this
15047 // specific writer, then it would cause it to never start
15048 // flowing again.
15049 // So, if this is awaiting a drain, then we just call it now.
15050 // If we don't know, then assume that we are waiting for one.
15051 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
15052 }
15053
15054 // If the user pushes more data while we're writing to dest then we'll end up
15055 // in ondata again. However, we only want to increase awaitDrain once because
15056 // dest will only emit one 'drain' event for the multiple writes.
15057 // => Introduce a guard on increasing awaitDrain.
15058 var increasedAwaitDrain = false;
15059 src.on('data', ondata);
15060 function ondata(chunk) {
15061 debug('ondata');
15062 increasedAwaitDrain = false;
15063 var ret = dest.write(chunk);
15064 if (false === ret && !increasedAwaitDrain) {
15065 // If the user unpiped during `dest.write()`, it is possible
15066 // to get stuck in a permanently paused state if that write
15067 // also returned false.
15068 // => Check whether `dest` is still a piping destination.
15069 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
15070 debug('false write response, pause', state.awaitDrain);
15071 state.awaitDrain++;
15072 increasedAwaitDrain = true;
15073 }
15074 src.pause();
15075 }
15076 }
15077
15078 // if the dest has an error, then stop piping into it.
15079 // however, don't suppress the throwing behavior for this.
15080 function onerror(er) {
15081 debug('onerror', er);
15082 unpipe();
15083 dest.removeListener('error', onerror);
15084 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
15085 }
15086
15087 // Make sure our error handler is attached before userland ones.
15088 prependListener(dest, 'error', onerror);
15089
15090 // Both close and finish should trigger unpipe, but only once.
15091 function onclose() {
15092 dest.removeListener('finish', onfinish);
15093 unpipe();
15094 }
15095 dest.once('close', onclose);
15096 function onfinish() {
15097 debug('onfinish');
15098 dest.removeListener('close', onclose);
15099 unpipe();
15100 }
15101 dest.once('finish', onfinish);
15102
15103 function unpipe() {
15104 debug('unpipe');
15105 src.unpipe(dest);
15106 }
15107
15108 // tell the dest that it's being piped to
15109 dest.emit('pipe', src);
15110
15111 // start the flow if it hasn't been started already.
15112 if (!state.flowing) {
15113 debug('pipe resume');
15114 src.resume();
15115 }
15116
15117 return dest;
15118};
15119
15120function pipeOnDrain(src) {
15121 return function () {
15122 var state = src._readableState;
15123 debug('pipeOnDrain', state.awaitDrain);
15124 if (state.awaitDrain) state.awaitDrain--;
15125 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
15126 state.flowing = true;
15127 flow(src);
15128 }
15129 };
15130}
15131
15132Readable.prototype.unpipe = function (dest) {
15133 var state = this._readableState;
15134 var unpipeInfo = { hasUnpiped: false };
15135
15136 // if we're not piping anywhere, then do nothing.
15137 if (state.pipesCount === 0) return this;
15138
15139 // just one destination. most common case.
15140 if (state.pipesCount === 1) {
15141 // passed in one, but it's not the right one.
15142 if (dest && dest !== state.pipes) return this;
15143
15144 if (!dest) dest = state.pipes;
15145
15146 // got a match.
15147 state.pipes = null;
15148 state.pipesCount = 0;
15149 state.flowing = false;
15150 if (dest) dest.emit('unpipe', this, unpipeInfo);
15151 return this;
15152 }
15153
15154 // slow case. multiple pipe destinations.
15155
15156 if (!dest) {
15157 // remove all.
15158 var dests = state.pipes;
15159 var len = state.pipesCount;
15160 state.pipes = null;
15161 state.pipesCount = 0;
15162 state.flowing = false;
15163
15164 for (var i = 0; i < len; i++) {
15165 dests[i].emit('unpipe', this, { hasUnpiped: false });
15166 }return this;
15167 }
15168
15169 // try to find the right one.
15170 var index = indexOf(state.pipes, dest);
15171 if (index === -1) return this;
15172
15173 state.pipes.splice(index, 1);
15174 state.pipesCount -= 1;
15175 if (state.pipesCount === 1) state.pipes = state.pipes[0];
15176
15177 dest.emit('unpipe', this, unpipeInfo);
15178
15179 return this;
15180};
15181
15182// set up data events if they are asked for
15183// Ensure readable listeners eventually get something
15184Readable.prototype.on = function (ev, fn) {
15185 var res = Stream.prototype.on.call(this, ev, fn);
15186
15187 if (ev === 'data') {
15188 // Start flowing on next tick if stream isn't explicitly paused
15189 if (this._readableState.flowing !== false) this.resume();
15190 } else if (ev === 'readable') {
15191 var state = this._readableState;
15192 if (!state.endEmitted && !state.readableListening) {
15193 state.readableListening = state.needReadable = true;
15194 state.emittedReadable = false;
15195 if (!state.reading) {
15196 pna.nextTick(nReadingNextTick, this);
15197 } else if (state.length) {
15198 emitReadable(this);
15199 }
15200 }
15201 }
15202
15203 return res;
15204};
15205Readable.prototype.addListener = Readable.prototype.on;
15206
15207function nReadingNextTick(self) {
15208 debug('readable nexttick read 0');
15209 self.read(0);
15210}
15211
15212// pause() and resume() are remnants of the legacy readable stream API
15213// If the user uses them, then switch into old mode.
15214Readable.prototype.resume = function () {
15215 var state = this._readableState;
15216 if (!state.flowing) {
15217 debug('resume');
15218 state.flowing = true;
15219 resume(this, state);
15220 }
15221 return this;
15222};
15223
15224function resume(stream, state) {
15225 if (!state.resumeScheduled) {
15226 state.resumeScheduled = true;
15227 pna.nextTick(resume_, stream, state);
15228 }
15229}
15230
15231function resume_(stream, state) {
15232 if (!state.reading) {
15233 debug('resume read 0');
15234 stream.read(0);
15235 }
15236
15237 state.resumeScheduled = false;
15238 state.awaitDrain = 0;
15239 stream.emit('resume');
15240 flow(stream);
15241 if (state.flowing && !state.reading) stream.read(0);
15242}
15243
15244Readable.prototype.pause = function () {
15245 debug('call pause flowing=%j', this._readableState.flowing);
15246 if (false !== this._readableState.flowing) {
15247 debug('pause');
15248 this._readableState.flowing = false;
15249 this.emit('pause');
15250 }
15251 return this;
15252};
15253
15254function flow(stream) {
15255 var state = stream._readableState;
15256 debug('flow', state.flowing);
15257 while (state.flowing && stream.read() !== null) {}
15258}
15259
15260// wrap an old-style stream as the async data source.
15261// This is *not* part of the readable stream interface.
15262// It is an ugly unfortunate mess of history.
15263Readable.prototype.wrap = function (stream) {
15264 var _this = this;
15265
15266 var state = this._readableState;
15267 var paused = false;
15268
15269 stream.on('end', function () {
15270 debug('wrapped end');
15271 if (state.decoder && !state.ended) {
15272 var chunk = state.decoder.end();
15273 if (chunk && chunk.length) _this.push(chunk);
15274 }
15275
15276 _this.push(null);
15277 });
15278
15279 stream.on('data', function (chunk) {
15280 debug('wrapped data');
15281 if (state.decoder) chunk = state.decoder.write(chunk);
15282
15283 // don't skip over falsy values in objectMode
15284 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
15285
15286 var ret = _this.push(chunk);
15287 if (!ret) {
15288 paused = true;
15289 stream.pause();
15290 }
15291 });
15292
15293 // proxy all the other methods.
15294 // important when wrapping filters and duplexes.
15295 for (var i in stream) {
15296 if (this[i] === undefined && typeof stream[i] === 'function') {
15297 this[i] = function (method) {
15298 return function () {
15299 return stream[method].apply(stream, arguments);
15300 };
15301 }(i);
15302 }
15303 }
15304
15305 // proxy certain important events.
15306 for (var n = 0; n < kProxyEvents.length; n++) {
15307 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
15308 }
15309
15310 // when we try to consume some more bytes, simply unpause the
15311 // underlying stream.
15312 this._read = function (n) {
15313 debug('wrapped _read', n);
15314 if (paused) {
15315 paused = false;
15316 stream.resume();
15317 }
15318 };
15319
15320 return this;
15321};
15322
15323Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
15324 // making it explicit this property is not enumerable
15325 // because otherwise some prototype manipulation in
15326 // userland will fail
15327 enumerable: false,
15328 get: function () {
15329 return this._readableState.highWaterMark;
15330 }
15331});
15332
15333// exposed for testing purposes only.
15334Readable._fromList = fromList;
15335
15336// Pluck off n bytes from an array of buffers.
15337// Length is the combined lengths of all the buffers in the list.
15338// This function is designed to be inlinable, so please take care when making
15339// changes to the function body.
15340function fromList(n, state) {
15341 // nothing buffered
15342 if (state.length === 0) return null;
15343
15344 var ret;
15345 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
15346 // read it all, truncate the list
15347 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);
15348 state.buffer.clear();
15349 } else {
15350 // read part of list
15351 ret = fromListPartial(n, state.buffer, state.decoder);
15352 }
15353
15354 return ret;
15355}
15356
15357// Extracts only enough buffered data to satisfy the amount requested.
15358// This function is designed to be inlinable, so please take care when making
15359// changes to the function body.
15360function fromListPartial(n, list, hasStrings) {
15361 var ret;
15362 if (n < list.head.data.length) {
15363 // slice is the same for buffers and strings
15364 ret = list.head.data.slice(0, n);
15365 list.head.data = list.head.data.slice(n);
15366 } else if (n === list.head.data.length) {
15367 // first chunk is a perfect match
15368 ret = list.shift();
15369 } else {
15370 // result spans more than one buffer
15371 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
15372 }
15373 return ret;
15374}
15375
15376// Copies a specified amount of characters from the list of buffered data
15377// chunks.
15378// This function is designed to be inlinable, so please take care when making
15379// changes to the function body.
15380function copyFromBufferString(n, list) {
15381 var p = list.head;
15382 var c = 1;
15383 var ret = p.data;
15384 n -= ret.length;
15385 while (p = p.next) {
15386 var str = p.data;
15387 var nb = n > str.length ? str.length : n;
15388 if (nb === str.length) ret += str;else ret += str.slice(0, n);
15389 n -= nb;
15390 if (n === 0) {
15391 if (nb === str.length) {
15392 ++c;
15393 if (p.next) list.head = p.next;else list.head = list.tail = null;
15394 } else {
15395 list.head = p;
15396 p.data = str.slice(nb);
15397 }
15398 break;
15399 }
15400 ++c;
15401 }
15402 list.length -= c;
15403 return ret;
15404}
15405
15406// Copies a specified amount of bytes from the list of buffered data chunks.
15407// This function is designed to be inlinable, so please take care when making
15408// changes to the function body.
15409function copyFromBuffer(n, list) {
15410 var ret = Buffer.allocUnsafe(n);
15411 var p = list.head;
15412 var c = 1;
15413 p.data.copy(ret);
15414 n -= p.data.length;
15415 while (p = p.next) {
15416 var buf = p.data;
15417 var nb = n > buf.length ? buf.length : n;
15418 buf.copy(ret, ret.length - n, 0, nb);
15419 n -= nb;
15420 if (n === 0) {
15421 if (nb === buf.length) {
15422 ++c;
15423 if (p.next) list.head = p.next;else list.head = list.tail = null;
15424 } else {
15425 list.head = p;
15426 p.data = buf.slice(nb);
15427 }
15428 break;
15429 }
15430 ++c;
15431 }
15432 list.length -= c;
15433 return ret;
15434}
15435
15436function endReadable(stream) {
15437 var state = stream._readableState;
15438
15439 // If we get here before consuming all the bytes, then that is a
15440 // bug in node. Should never happen.
15441 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
15442
15443 if (!state.endEmitted) {
15444 state.ended = true;
15445 pna.nextTick(endReadableNT, state, stream);
15446 }
15447}
15448
15449function endReadableNT(state, stream) {
15450 // Check that we didn't get one last unshift.
15451 if (!state.endEmitted && state.length === 0) {
15452 state.endEmitted = true;
15453 stream.readable = false;
15454 stream.emit('end');
15455 }
15456}
15457
15458function indexOf(xs, x) {
15459 for (var i = 0, l = xs.length; i < l; i++) {
15460 if (xs[i] === x) return i;
15461 }
15462 return -1;
15463}
15464}).call(this)}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
15465},{"./_stream_duplex":109,"./internal/streams/BufferList":114,"./internal/streams/destroy":115,"./internal/streams/stream":116,"_process":94,"core-util-is":12,"events":39,"inherits":53,"isarray":107,"process-nextick-args":93,"safe-buffer":121,"string_decoder/":122,"util":8}],112:[function(_dereq_,module,exports){
15466// Copyright Joyent, Inc. and other Node contributors.
15467//
15468// Permission is hereby granted, free of charge, to any person obtaining a
15469// copy of this software and associated documentation files (the
15470// "Software"), to deal in the Software without restriction, including
15471// without limitation the rights to use, copy, modify, merge, publish,
15472// distribute, sublicense, and/or sell copies of the Software, and to permit
15473// persons to whom the Software is furnished to do so, subject to the
15474// following conditions:
15475//
15476// The above copyright notice and this permission notice shall be included
15477// in all copies or substantial portions of the Software.
15478//
15479// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15480// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15481// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15482// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15483// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15484// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15485// USE OR OTHER DEALINGS IN THE SOFTWARE.
15486
15487// a transform stream is a readable/writable stream where you do
15488// something with the data. Sometimes it's called a "filter",
15489// but that's not a great name for it, since that implies a thing where
15490// some bits pass through, and others are simply ignored. (That would
15491// be a valid example of a transform, of course.)
15492//
15493// While the output is causally related to the input, it's not a
15494// necessarily symmetric or synchronous transformation. For example,
15495// a zlib stream might take multiple plain-text writes(), and then
15496// emit a single compressed chunk some time in the future.
15497//
15498// Here's how this works:
15499//
15500// The Transform stream has all the aspects of the readable and writable
15501// stream classes. When you write(chunk), that calls _write(chunk,cb)
15502// internally, and returns false if there's a lot of pending writes
15503// buffered up. When you call read(), that calls _read(n) until
15504// there's enough pending readable data buffered up.
15505//
15506// In a transform stream, the written data is placed in a buffer. When
15507// _read(n) is called, it transforms the queued up data, calling the
15508// buffered _write cb's as it consumes chunks. If consuming a single
15509// written chunk would result in multiple output chunks, then the first
15510// outputted bit calls the readcb, and subsequent chunks just go into
15511// the read buffer, and will cause it to emit 'readable' if necessary.
15512//
15513// This way, back-pressure is actually determined by the reading side,
15514// since _read has to be called to start processing a new chunk. However,
15515// a pathological inflate type of transform can cause excessive buffering
15516// here. For example, imagine a stream where every byte of input is
15517// interpreted as an integer from 0-255, and then results in that many
15518// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
15519// 1kb of data being output. In this case, you could write a very small
15520// amount of input, and end up with a very large amount of output. In
15521// such a pathological inflating mechanism, there'd be no way to tell
15522// the system to stop doing the transform. A single 4MB write could
15523// cause the system to run out of memory.
15524//
15525// However, even in such a pathological case, only a single written chunk
15526// would be consumed, and then the rest would wait (un-transformed) until
15527// the results of the previous transformed chunk were consumed.
15528
15529'use strict';
15530
15531module.exports = Transform;
15532
15533var Duplex = _dereq_('./_stream_duplex');
15534
15535/*<replacement>*/
15536var util = Object.create(_dereq_('core-util-is'));
15537util.inherits = _dereq_('inherits');
15538/*</replacement>*/
15539
15540util.inherits(Transform, Duplex);
15541
15542function afterTransform(er, data) {
15543 var ts = this._transformState;
15544 ts.transforming = false;
15545
15546 var cb = ts.writecb;
15547
15548 if (!cb) {
15549 return this.emit('error', new Error('write callback called multiple times'));
15550 }
15551
15552 ts.writechunk = null;
15553 ts.writecb = null;
15554
15555 if (data != null) // single equals check for both `null` and `undefined`
15556 this.push(data);
15557
15558 cb(er);
15559
15560 var rs = this._readableState;
15561 rs.reading = false;
15562 if (rs.needReadable || rs.length < rs.highWaterMark) {
15563 this._read(rs.highWaterMark);
15564 }
15565}
15566
15567function Transform(options) {
15568 if (!(this instanceof Transform)) return new Transform(options);
15569
15570 Duplex.call(this, options);
15571
15572 this._transformState = {
15573 afterTransform: afterTransform.bind(this),
15574 needTransform: false,
15575 transforming: false,
15576 writecb: null,
15577 writechunk: null,
15578 writeencoding: null
15579 };
15580
15581 // start out asking for a readable event once data is transformed.
15582 this._readableState.needReadable = true;
15583
15584 // we have implemented the _read method, and done the other things
15585 // that Readable wants before the first _read call, so unset the
15586 // sync guard flag.
15587 this._readableState.sync = false;
15588
15589 if (options) {
15590 if (typeof options.transform === 'function') this._transform = options.transform;
15591
15592 if (typeof options.flush === 'function') this._flush = options.flush;
15593 }
15594
15595 // When the writable side finishes, then flush out anything remaining.
15596 this.on('prefinish', prefinish);
15597}
15598
15599function prefinish() {
15600 var _this = this;
15601
15602 if (typeof this._flush === 'function') {
15603 this._flush(function (er, data) {
15604 done(_this, er, data);
15605 });
15606 } else {
15607 done(this, null, null);
15608 }
15609}
15610
15611Transform.prototype.push = function (chunk, encoding) {
15612 this._transformState.needTransform = false;
15613 return Duplex.prototype.push.call(this, chunk, encoding);
15614};
15615
15616// This is the part where you do stuff!
15617// override this function in implementation classes.
15618// 'chunk' is an input chunk.
15619//
15620// Call `push(newChunk)` to pass along transformed output
15621// to the readable side. You may call 'push' zero or more times.
15622//
15623// Call `cb(err)` when you are done with this chunk. If you pass
15624// an error, then that'll put the hurt on the whole operation. If you
15625// never call cb(), then you'll never get another chunk.
15626Transform.prototype._transform = function (chunk, encoding, cb) {
15627 throw new Error('_transform() is not implemented');
15628};
15629
15630Transform.prototype._write = function (chunk, encoding, cb) {
15631 var ts = this._transformState;
15632 ts.writecb = cb;
15633 ts.writechunk = chunk;
15634 ts.writeencoding = encoding;
15635 if (!ts.transforming) {
15636 var rs = this._readableState;
15637 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
15638 }
15639};
15640
15641// Doesn't matter what the args are here.
15642// _transform does all the work.
15643// That we got here means that the readable side wants more data.
15644Transform.prototype._read = function (n) {
15645 var ts = this._transformState;
15646
15647 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
15648 ts.transforming = true;
15649 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
15650 } else {
15651 // mark that we need a transform, so that any data that comes in
15652 // will get processed, now that we've asked for it.
15653 ts.needTransform = true;
15654 }
15655};
15656
15657Transform.prototype._destroy = function (err, cb) {
15658 var _this2 = this;
15659
15660 Duplex.prototype._destroy.call(this, err, function (err2) {
15661 cb(err2);
15662 _this2.emit('close');
15663 });
15664};
15665
15666function done(stream, er, data) {
15667 if (er) return stream.emit('error', er);
15668
15669 if (data != null) // single equals check for both `null` and `undefined`
15670 stream.push(data);
15671
15672 // if there's nothing in the write buffer, then that means
15673 // that nothing more will ever be provided
15674 if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
15675
15676 if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
15677
15678 return stream.push(null);
15679}
15680},{"./_stream_duplex":109,"core-util-is":12,"inherits":53}],113:[function(_dereq_,module,exports){
15681(function (process,global,setImmediate){(function (){
15682// Copyright Joyent, Inc. and other Node contributors.
15683//
15684// Permission is hereby granted, free of charge, to any person obtaining a
15685// copy of this software and associated documentation files (the
15686// "Software"), to deal in the Software without restriction, including
15687// without limitation the rights to use, copy, modify, merge, publish,
15688// distribute, sublicense, and/or sell copies of the Software, and to permit
15689// persons to whom the Software is furnished to do so, subject to the
15690// following conditions:
15691//
15692// The above copyright notice and this permission notice shall be included
15693// in all copies or substantial portions of the Software.
15694//
15695// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15696// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15697// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15698// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15699// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15700// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15701// USE OR OTHER DEALINGS IN THE SOFTWARE.
15702
15703// A bit simpler than readable streams.
15704// Implement an async ._write(chunk, encoding, cb), and it'll handle all
15705// the drain event emission and buffering.
15706
15707'use strict';
15708
15709/*<replacement>*/
15710
15711var pna = _dereq_('process-nextick-args');
15712/*</replacement>*/
15713
15714module.exports = Writable;
15715
15716/* <replacement> */
15717function WriteReq(chunk, encoding, cb) {
15718 this.chunk = chunk;
15719 this.encoding = encoding;
15720 this.callback = cb;
15721 this.next = null;
15722}
15723
15724// It seems a linked list but it is not
15725// there will be only 2 of these for each stream
15726function CorkedRequest(state) {
15727 var _this = this;
15728
15729 this.next = null;
15730 this.entry = null;
15731 this.finish = function () {
15732 onCorkedFinish(_this, state);
15733 };
15734}
15735/* </replacement> */
15736
15737/*<replacement>*/
15738var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
15739/*</replacement>*/
15740
15741/*<replacement>*/
15742var Duplex;
15743/*</replacement>*/
15744
15745Writable.WritableState = WritableState;
15746
15747/*<replacement>*/
15748var util = Object.create(_dereq_('core-util-is'));
15749util.inherits = _dereq_('inherits');
15750/*</replacement>*/
15751
15752/*<replacement>*/
15753var internalUtil = {
15754 deprecate: _dereq_('util-deprecate')
15755};
15756/*</replacement>*/
15757
15758/*<replacement>*/
15759var Stream = _dereq_('./internal/streams/stream');
15760/*</replacement>*/
15761
15762/*<replacement>*/
15763
15764var Buffer = _dereq_('safe-buffer').Buffer;
15765var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
15766function _uint8ArrayToBuffer(chunk) {
15767 return Buffer.from(chunk);
15768}
15769function _isUint8Array(obj) {
15770 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
15771}
15772
15773/*</replacement>*/
15774
15775var destroyImpl = _dereq_('./internal/streams/destroy');
15776
15777util.inherits(Writable, Stream);
15778
15779function nop() {}
15780
15781function WritableState(options, stream) {
15782 Duplex = Duplex || _dereq_('./_stream_duplex');
15783
15784 options = options || {};
15785
15786 // Duplex streams are both readable and writable, but share
15787 // the same options object.
15788 // However, some cases require setting options to different
15789 // values for the readable and the writable sides of the duplex stream.
15790 // These options can be provided separately as readableXXX and writableXXX.
15791 var isDuplex = stream instanceof Duplex;
15792
15793 // object stream flag to indicate whether or not this stream
15794 // contains buffers or objects.
15795 this.objectMode = !!options.objectMode;
15796
15797 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
15798
15799 // the point at which write() starts returning false
15800 // Note: 0 is a valid value, means that we always return false if
15801 // the entire buffer is not flushed immediately on write()
15802 var hwm = options.highWaterMark;
15803 var writableHwm = options.writableHighWaterMark;
15804 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
15805
15806 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
15807
15808 // cast to ints.
15809 this.highWaterMark = Math.floor(this.highWaterMark);
15810
15811 // if _final has been called
15812 this.finalCalled = false;
15813
15814 // drain event flag.
15815 this.needDrain = false;
15816 // at the start of calling end()
15817 this.ending = false;
15818 // when end() has been called, and returned
15819 this.ended = false;
15820 // when 'finish' is emitted
15821 this.finished = false;
15822
15823 // has it been destroyed
15824 this.destroyed = false;
15825
15826 // should we decode strings into buffers before passing to _write?
15827 // this is here so that some node-core streams can optimize string
15828 // handling at a lower level.
15829 var noDecode = options.decodeStrings === false;
15830 this.decodeStrings = !noDecode;
15831
15832 // Crypto is kind of old and crusty. Historically, its default string
15833 // encoding is 'binary' so we have to make this configurable.
15834 // Everything else in the universe uses 'utf8', though.
15835 this.defaultEncoding = options.defaultEncoding || 'utf8';
15836
15837 // not an actual buffer we keep track of, but a measurement
15838 // of how much we're waiting to get pushed to some underlying
15839 // socket or file.
15840 this.length = 0;
15841
15842 // a flag to see when we're in the middle of a write.
15843 this.writing = false;
15844
15845 // when true all writes will be buffered until .uncork() call
15846 this.corked = 0;
15847
15848 // a flag to be able to tell if the onwrite cb is called immediately,
15849 // or on a later tick. We set this to true at first, because any
15850 // actions that shouldn't happen until "later" should generally also
15851 // not happen before the first write call.
15852 this.sync = true;
15853
15854 // a flag to know if we're processing previously buffered items, which
15855 // may call the _write() callback in the same tick, so that we don't
15856 // end up in an overlapped onwrite situation.
15857 this.bufferProcessing = false;
15858
15859 // the callback that's passed to _write(chunk,cb)
15860 this.onwrite = function (er) {
15861 onwrite(stream, er);
15862 };
15863
15864 // the callback that the user supplies to write(chunk,encoding,cb)
15865 this.writecb = null;
15866
15867 // the amount that is being written when _write is called.
15868 this.writelen = 0;
15869
15870 this.bufferedRequest = null;
15871 this.lastBufferedRequest = null;
15872
15873 // number of pending user-supplied write callbacks
15874 // this must be 0 before 'finish' can be emitted
15875 this.pendingcb = 0;
15876
15877 // emit prefinish if the only thing we're waiting for is _write cbs
15878 // This is relevant for synchronous Transform streams
15879 this.prefinished = false;
15880
15881 // True if the error was already emitted and should not be thrown again
15882 this.errorEmitted = false;
15883
15884 // count buffered requests
15885 this.bufferedRequestCount = 0;
15886
15887 // allocate the first CorkedRequest, there is always
15888 // one allocated and free to use, and we maintain at most two
15889 this.corkedRequestsFree = new CorkedRequest(this);
15890}
15891
15892WritableState.prototype.getBuffer = function getBuffer() {
15893 var current = this.bufferedRequest;
15894 var out = [];
15895 while (current) {
15896 out.push(current);
15897 current = current.next;
15898 }
15899 return out;
15900};
15901
15902(function () {
15903 try {
15904 Object.defineProperty(WritableState.prototype, 'buffer', {
15905 get: internalUtil.deprecate(function () {
15906 return this.getBuffer();
15907 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
15908 });
15909 } catch (_) {}
15910})();
15911
15912// Test _writableState for inheritance to account for Duplex streams,
15913// whose prototype chain only points to Readable.
15914var realHasInstance;
15915if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
15916 realHasInstance = Function.prototype[Symbol.hasInstance];
15917 Object.defineProperty(Writable, Symbol.hasInstance, {
15918 value: function (object) {
15919 if (realHasInstance.call(this, object)) return true;
15920 if (this !== Writable) return false;
15921
15922 return object && object._writableState instanceof WritableState;
15923 }
15924 });
15925} else {
15926 realHasInstance = function (object) {
15927 return object instanceof this;
15928 };
15929}
15930
15931function Writable(options) {
15932 Duplex = Duplex || _dereq_('./_stream_duplex');
15933
15934 // Writable ctor is applied to Duplexes, too.
15935 // `realHasInstance` is necessary because using plain `instanceof`
15936 // would return false, as no `_writableState` property is attached.
15937
15938 // Trying to use the custom `instanceof` for Writable here will also break the
15939 // Node.js LazyTransform implementation, which has a non-trivial getter for
15940 // `_writableState` that would lead to infinite recursion.
15941 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
15942 return new Writable(options);
15943 }
15944
15945 this._writableState = new WritableState(options, this);
15946
15947 // legacy.
15948 this.writable = true;
15949
15950 if (options) {
15951 if (typeof options.write === 'function') this._write = options.write;
15952
15953 if (typeof options.writev === 'function') this._writev = options.writev;
15954
15955 if (typeof options.destroy === 'function') this._destroy = options.destroy;
15956
15957 if (typeof options.final === 'function') this._final = options.final;
15958 }
15959
15960 Stream.call(this);
15961}
15962
15963// Otherwise people can pipe Writable streams, which is just wrong.
15964Writable.prototype.pipe = function () {
15965 this.emit('error', new Error('Cannot pipe, not readable'));
15966};
15967
15968function writeAfterEnd(stream, cb) {
15969 var er = new Error('write after end');
15970 // TODO: defer error events consistently everywhere, not just the cb
15971 stream.emit('error', er);
15972 pna.nextTick(cb, er);
15973}
15974
15975// Checks that a user-supplied chunk is valid, especially for the particular
15976// mode the stream is in. Currently this means that `null` is never accepted
15977// and undefined/non-string values are only allowed in object mode.
15978function validChunk(stream, state, chunk, cb) {
15979 var valid = true;
15980 var er = false;
15981
15982 if (chunk === null) {
15983 er = new TypeError('May not write null values to stream');
15984 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
15985 er = new TypeError('Invalid non-string/buffer chunk');
15986 }
15987 if (er) {
15988 stream.emit('error', er);
15989 pna.nextTick(cb, er);
15990 valid = false;
15991 }
15992 return valid;
15993}
15994
15995Writable.prototype.write = function (chunk, encoding, cb) {
15996 var state = this._writableState;
15997 var ret = false;
15998 var isBuf = !state.objectMode && _isUint8Array(chunk);
15999
16000 if (isBuf && !Buffer.isBuffer(chunk)) {
16001 chunk = _uint8ArrayToBuffer(chunk);
16002 }
16003
16004 if (typeof encoding === 'function') {
16005 cb = encoding;
16006 encoding = null;
16007 }
16008
16009 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
16010
16011 if (typeof cb !== 'function') cb = nop;
16012
16013 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
16014 state.pendingcb++;
16015 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
16016 }
16017
16018 return ret;
16019};
16020
16021Writable.prototype.cork = function () {
16022 var state = this._writableState;
16023
16024 state.corked++;
16025};
16026
16027Writable.prototype.uncork = function () {
16028 var state = this._writableState;
16029
16030 if (state.corked) {
16031 state.corked--;
16032
16033 if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
16034 }
16035};
16036
16037Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
16038 // node::ParseEncoding() requires lower case.
16039 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
16040 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);
16041 this._writableState.defaultEncoding = encoding;
16042 return this;
16043};
16044
16045function decodeChunk(state, chunk, encoding) {
16046 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
16047 chunk = Buffer.from(chunk, encoding);
16048 }
16049 return chunk;
16050}
16051
16052Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
16053 // making it explicit this property is not enumerable
16054 // because otherwise some prototype manipulation in
16055 // userland will fail
16056 enumerable: false,
16057 get: function () {
16058 return this._writableState.highWaterMark;
16059 }
16060});
16061
16062// if we're already writing something, then just put this
16063// in the queue, and wait our turn. Otherwise, call _write
16064// If we return false, then we need a drain event, so set that flag.
16065function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
16066 if (!isBuf) {
16067 var newChunk = decodeChunk(state, chunk, encoding);
16068 if (chunk !== newChunk) {
16069 isBuf = true;
16070 encoding = 'buffer';
16071 chunk = newChunk;
16072 }
16073 }
16074 var len = state.objectMode ? 1 : chunk.length;
16075
16076 state.length += len;
16077
16078 var ret = state.length < state.highWaterMark;
16079 // we must ensure that previous needDrain will not be reset to false.
16080 if (!ret) state.needDrain = true;
16081
16082 if (state.writing || state.corked) {
16083 var last = state.lastBufferedRequest;
16084 state.lastBufferedRequest = {
16085 chunk: chunk,
16086 encoding: encoding,
16087 isBuf: isBuf,
16088 callback: cb,
16089 next: null
16090 };
16091 if (last) {
16092 last.next = state.lastBufferedRequest;
16093 } else {
16094 state.bufferedRequest = state.lastBufferedRequest;
16095 }
16096 state.bufferedRequestCount += 1;
16097 } else {
16098 doWrite(stream, state, false, len, chunk, encoding, cb);
16099 }
16100
16101 return ret;
16102}
16103
16104function doWrite(stream, state, writev, len, chunk, encoding, cb) {
16105 state.writelen = len;
16106 state.writecb = cb;
16107 state.writing = true;
16108 state.sync = true;
16109 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
16110 state.sync = false;
16111}
16112
16113function onwriteError(stream, state, sync, er, cb) {
16114 --state.pendingcb;
16115
16116 if (sync) {
16117 // defer the callback if we are being called synchronously
16118 // to avoid piling up things on the stack
16119 pna.nextTick(cb, er);
16120 // this can emit finish, and it will always happen
16121 // after error
16122 pna.nextTick(finishMaybe, stream, state);
16123 stream._writableState.errorEmitted = true;
16124 stream.emit('error', er);
16125 } else {
16126 // the caller expect this to happen before if
16127 // it is async
16128 cb(er);
16129 stream._writableState.errorEmitted = true;
16130 stream.emit('error', er);
16131 // this can emit finish, but finish must
16132 // always follow error
16133 finishMaybe(stream, state);
16134 }
16135}
16136
16137function onwriteStateUpdate(state) {
16138 state.writing = false;
16139 state.writecb = null;
16140 state.length -= state.writelen;
16141 state.writelen = 0;
16142}
16143
16144function onwrite(stream, er) {
16145 var state = stream._writableState;
16146 var sync = state.sync;
16147 var cb = state.writecb;
16148
16149 onwriteStateUpdate(state);
16150
16151 if (er) onwriteError(stream, state, sync, er, cb);else {
16152 // Check if we're actually ready to finish, but don't emit yet
16153 var finished = needFinish(state);
16154
16155 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
16156 clearBuffer(stream, state);
16157 }
16158
16159 if (sync) {
16160 /*<replacement>*/
16161 asyncWrite(afterWrite, stream, state, finished, cb);
16162 /*</replacement>*/
16163 } else {
16164 afterWrite(stream, state, finished, cb);
16165 }
16166 }
16167}
16168
16169function afterWrite(stream, state, finished, cb) {
16170 if (!finished) onwriteDrain(stream, state);
16171 state.pendingcb--;
16172 cb();
16173 finishMaybe(stream, state);
16174}
16175
16176// Must force callback to be called on nextTick, so that we don't
16177// emit 'drain' before the write() consumer gets the 'false' return
16178// value, and has a chance to attach a 'drain' listener.
16179function onwriteDrain(stream, state) {
16180 if (state.length === 0 && state.needDrain) {
16181 state.needDrain = false;
16182 stream.emit('drain');
16183 }
16184}
16185
16186// if there's something in the buffer waiting, then process it
16187function clearBuffer(stream, state) {
16188 state.bufferProcessing = true;
16189 var entry = state.bufferedRequest;
16190
16191 if (stream._writev && entry && entry.next) {
16192 // Fast case, write everything using _writev()
16193 var l = state.bufferedRequestCount;
16194 var buffer = new Array(l);
16195 var holder = state.corkedRequestsFree;
16196 holder.entry = entry;
16197
16198 var count = 0;
16199 var allBuffers = true;
16200 while (entry) {
16201 buffer[count] = entry;
16202 if (!entry.isBuf) allBuffers = false;
16203 entry = entry.next;
16204 count += 1;
16205 }
16206 buffer.allBuffers = allBuffers;
16207
16208 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
16209
16210 // doWrite is almost always async, defer these to save a bit of time
16211 // as the hot path ends with doWrite
16212 state.pendingcb++;
16213 state.lastBufferedRequest = null;
16214 if (holder.next) {
16215 state.corkedRequestsFree = holder.next;
16216 holder.next = null;
16217 } else {
16218 state.corkedRequestsFree = new CorkedRequest(state);
16219 }
16220 state.bufferedRequestCount = 0;
16221 } else {
16222 // Slow case, write chunks one-by-one
16223 while (entry) {
16224 var chunk = entry.chunk;
16225 var encoding = entry.encoding;
16226 var cb = entry.callback;
16227 var len = state.objectMode ? 1 : chunk.length;
16228
16229 doWrite(stream, state, false, len, chunk, encoding, cb);
16230 entry = entry.next;
16231 state.bufferedRequestCount--;
16232 // if we didn't call the onwrite immediately, then
16233 // it means that we need to wait until it does.
16234 // also, that means that the chunk and cb are currently
16235 // being processed, so move the buffer counter past them.
16236 if (state.writing) {
16237 break;
16238 }
16239 }
16240
16241 if (entry === null) state.lastBufferedRequest = null;
16242 }
16243
16244 state.bufferedRequest = entry;
16245 state.bufferProcessing = false;
16246}
16247
16248Writable.prototype._write = function (chunk, encoding, cb) {
16249 cb(new Error('_write() is not implemented'));
16250};
16251
16252Writable.prototype._writev = null;
16253
16254Writable.prototype.end = function (chunk, encoding, cb) {
16255 var state = this._writableState;
16256
16257 if (typeof chunk === 'function') {
16258 cb = chunk;
16259 chunk = null;
16260 encoding = null;
16261 } else if (typeof encoding === 'function') {
16262 cb = encoding;
16263 encoding = null;
16264 }
16265
16266 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
16267
16268 // .end() fully uncorks
16269 if (state.corked) {
16270 state.corked = 1;
16271 this.uncork();
16272 }
16273
16274 // ignore unnecessary end() calls.
16275 if (!state.ending) endWritable(this, state, cb);
16276};
16277
16278function needFinish(state) {
16279 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
16280}
16281function callFinal(stream, state) {
16282 stream._final(function (err) {
16283 state.pendingcb--;
16284 if (err) {
16285 stream.emit('error', err);
16286 }
16287 state.prefinished = true;
16288 stream.emit('prefinish');
16289 finishMaybe(stream, state);
16290 });
16291}
16292function prefinish(stream, state) {
16293 if (!state.prefinished && !state.finalCalled) {
16294 if (typeof stream._final === 'function') {
16295 state.pendingcb++;
16296 state.finalCalled = true;
16297 pna.nextTick(callFinal, stream, state);
16298 } else {
16299 state.prefinished = true;
16300 stream.emit('prefinish');
16301 }
16302 }
16303}
16304
16305function finishMaybe(stream, state) {
16306 var need = needFinish(state);
16307 if (need) {
16308 prefinish(stream, state);
16309 if (state.pendingcb === 0) {
16310 state.finished = true;
16311 stream.emit('finish');
16312 }
16313 }
16314 return need;
16315}
16316
16317function endWritable(stream, state, cb) {
16318 state.ending = true;
16319 finishMaybe(stream, state);
16320 if (cb) {
16321 if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
16322 }
16323 state.ended = true;
16324 stream.writable = false;
16325}
16326
16327function onCorkedFinish(corkReq, state, err) {
16328 var entry = corkReq.entry;
16329 corkReq.entry = null;
16330 while (entry) {
16331 var cb = entry.callback;
16332 state.pendingcb--;
16333 cb(err);
16334 entry = entry.next;
16335 }
16336
16337 // reuse the free corkReq.
16338 state.corkedRequestsFree.next = corkReq;
16339}
16340
16341Object.defineProperty(Writable.prototype, 'destroyed', {
16342 get: function () {
16343 if (this._writableState === undefined) {
16344 return false;
16345 }
16346 return this._writableState.destroyed;
16347 },
16348 set: function (value) {
16349 // we ignore the value if the stream
16350 // has not been initialized yet
16351 if (!this._writableState) {
16352 return;
16353 }
16354
16355 // backward compatibility, the user is explicitly
16356 // managing destroyed
16357 this._writableState.destroyed = value;
16358 }
16359});
16360
16361Writable.prototype.destroy = destroyImpl.destroy;
16362Writable.prototype._undestroy = destroyImpl.undestroy;
16363Writable.prototype._destroy = function (err, cb) {
16364 this.end();
16365 cb(err);
16366};
16367}).call(this)}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_("timers").setImmediate)
16368},{"./_stream_duplex":109,"./internal/streams/destroy":115,"./internal/streams/stream":116,"_process":94,"core-util-is":12,"inherits":53,"process-nextick-args":93,"safe-buffer":121,"timers":140,"util-deprecate":142}],114:[function(_dereq_,module,exports){
16369'use strict';
16370
16371function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
16372
16373var Buffer = _dereq_('safe-buffer').Buffer;
16374var util = _dereq_('util');
16375
16376function copyBuffer(src, target, offset) {
16377 src.copy(target, offset);
16378}
16379
16380module.exports = function () {
16381 function BufferList() {
16382 _classCallCheck(this, BufferList);
16383
16384 this.head = null;
16385 this.tail = null;
16386 this.length = 0;
16387 }
16388
16389 BufferList.prototype.push = function push(v) {
16390 var entry = { data: v, next: null };
16391 if (this.length > 0) this.tail.next = entry;else this.head = entry;
16392 this.tail = entry;
16393 ++this.length;
16394 };
16395
16396 BufferList.prototype.unshift = function unshift(v) {
16397 var entry = { data: v, next: this.head };
16398 if (this.length === 0) this.tail = entry;
16399 this.head = entry;
16400 ++this.length;
16401 };
16402
16403 BufferList.prototype.shift = function shift() {
16404 if (this.length === 0) return;
16405 var ret = this.head.data;
16406 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
16407 --this.length;
16408 return ret;
16409 };
16410
16411 BufferList.prototype.clear = function clear() {
16412 this.head = this.tail = null;
16413 this.length = 0;
16414 };
16415
16416 BufferList.prototype.join = function join(s) {
16417 if (this.length === 0) return '';
16418 var p = this.head;
16419 var ret = '' + p.data;
16420 while (p = p.next) {
16421 ret += s + p.data;
16422 }return ret;
16423 };
16424
16425 BufferList.prototype.concat = function concat(n) {
16426 if (this.length === 0) return Buffer.alloc(0);
16427 var ret = Buffer.allocUnsafe(n >>> 0);
16428 var p = this.head;
16429 var i = 0;
16430 while (p) {
16431 copyBuffer(p.data, ret, i);
16432 i += p.data.length;
16433 p = p.next;
16434 }
16435 return ret;
16436 };
16437
16438 return BufferList;
16439}();
16440
16441if (util && util.inspect && util.inspect.custom) {
16442 module.exports.prototype[util.inspect.custom] = function () {
16443 var obj = util.inspect({ length: this.length });
16444 return this.constructor.name + ' ' + obj;
16445 };
16446}
16447},{"safe-buffer":121,"util":8}],115:[function(_dereq_,module,exports){
16448'use strict';
16449
16450/*<replacement>*/
16451
16452var pna = _dereq_('process-nextick-args');
16453/*</replacement>*/
16454
16455// undocumented cb() API, needed for core, not for public API
16456function destroy(err, cb) {
16457 var _this = this;
16458
16459 var readableDestroyed = this._readableState && this._readableState.destroyed;
16460 var writableDestroyed = this._writableState && this._writableState.destroyed;
16461
16462 if (readableDestroyed || writableDestroyed) {
16463 if (cb) {
16464 cb(err);
16465 } else if (err) {
16466 if (!this._writableState) {
16467 pna.nextTick(emitErrorNT, this, err);
16468 } else if (!this._writableState.errorEmitted) {
16469 this._writableState.errorEmitted = true;
16470 pna.nextTick(emitErrorNT, this, err);
16471 }
16472 }
16473
16474 return this;
16475 }
16476
16477 // we set destroyed to true before firing error callbacks in order
16478 // to make it re-entrance safe in case destroy() is called within callbacks
16479
16480 if (this._readableState) {
16481 this._readableState.destroyed = true;
16482 }
16483
16484 // if this is a duplex stream mark the writable part as destroyed as well
16485 if (this._writableState) {
16486 this._writableState.destroyed = true;
16487 }
16488
16489 this._destroy(err || null, function (err) {
16490 if (!cb && err) {
16491 if (!_this._writableState) {
16492 pna.nextTick(emitErrorNT, _this, err);
16493 } else if (!_this._writableState.errorEmitted) {
16494 _this._writableState.errorEmitted = true;
16495 pna.nextTick(emitErrorNT, _this, err);
16496 }
16497 } else if (cb) {
16498 cb(err);
16499 }
16500 });
16501
16502 return this;
16503}
16504
16505function undestroy() {
16506 if (this._readableState) {
16507 this._readableState.destroyed = false;
16508 this._readableState.reading = false;
16509 this._readableState.ended = false;
16510 this._readableState.endEmitted = false;
16511 }
16512
16513 if (this._writableState) {
16514 this._writableState.destroyed = false;
16515 this._writableState.ended = false;
16516 this._writableState.ending = false;
16517 this._writableState.finalCalled = false;
16518 this._writableState.prefinished = false;
16519 this._writableState.finished = false;
16520 this._writableState.errorEmitted = false;
16521 }
16522}
16523
16524function emitErrorNT(self, err) {
16525 self.emit('error', err);
16526}
16527
16528module.exports = {
16529 destroy: destroy,
16530 undestroy: undestroy
16531};
16532},{"process-nextick-args":93}],116:[function(_dereq_,module,exports){
16533arguments[4][73][0].apply(exports,arguments)
16534},{"dup":73,"events":39}],117:[function(_dereq_,module,exports){
16535module.exports = _dereq_('./readable').PassThrough
16536
16537},{"./readable":118}],118:[function(_dereq_,module,exports){
16538exports = module.exports = _dereq_('./lib/_stream_readable.js');
16539exports.Stream = exports;
16540exports.Readable = exports;
16541exports.Writable = _dereq_('./lib/_stream_writable.js');
16542exports.Duplex = _dereq_('./lib/_stream_duplex.js');
16543exports.Transform = _dereq_('./lib/_stream_transform.js');
16544exports.PassThrough = _dereq_('./lib/_stream_passthrough.js');
16545
16546},{"./lib/_stream_duplex.js":109,"./lib/_stream_passthrough.js":110,"./lib/_stream_readable.js":111,"./lib/_stream_transform.js":112,"./lib/_stream_writable.js":113}],119:[function(_dereq_,module,exports){
16547module.exports = _dereq_('./readable').Transform
16548
16549},{"./readable":118}],120:[function(_dereq_,module,exports){
16550module.exports = _dereq_('./lib/_stream_writable.js');
16551
16552},{"./lib/_stream_writable.js":113}],121:[function(_dereq_,module,exports){
16553/* eslint-disable node/no-deprecated-api */
16554var buffer = _dereq_('buffer')
16555var Buffer = buffer.Buffer
16556
16557// alternative to using Object.keys for old browsers
16558function copyProps (src, dst) {
16559 for (var key in src) {
16560 dst[key] = src[key]
16561 }
16562}
16563if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
16564 module.exports = buffer
16565} else {
16566 // Copy properties from require('buffer')
16567 copyProps(buffer, exports)
16568 exports.Buffer = SafeBuffer
16569}
16570
16571function SafeBuffer (arg, encodingOrOffset, length) {
16572 return Buffer(arg, encodingOrOffset, length)
16573}
16574
16575// Copy static methods from Buffer
16576copyProps(Buffer, SafeBuffer)
16577
16578SafeBuffer.from = function (arg, encodingOrOffset, length) {
16579 if (typeof arg === 'number') {
16580 throw new TypeError('Argument must not be a number')
16581 }
16582 return Buffer(arg, encodingOrOffset, length)
16583}
16584
16585SafeBuffer.alloc = function (size, fill, encoding) {
16586 if (typeof size !== 'number') {
16587 throw new TypeError('Argument must be a number')
16588 }
16589 var buf = Buffer(size)
16590 if (fill !== undefined) {
16591 if (typeof encoding === 'string') {
16592 buf.fill(fill, encoding)
16593 } else {
16594 buf.fill(fill)
16595 }
16596 } else {
16597 buf.fill(0)
16598 }
16599 return buf
16600}
16601
16602SafeBuffer.allocUnsafe = function (size) {
16603 if (typeof size !== 'number') {
16604 throw new TypeError('Argument must be a number')
16605 }
16606 return Buffer(size)
16607}
16608
16609SafeBuffer.allocUnsafeSlow = function (size) {
16610 if (typeof size !== 'number') {
16611 throw new TypeError('Argument must be a number')
16612 }
16613 return buffer.SlowBuffer(size)
16614}
16615
16616},{"buffer":9}],122:[function(_dereq_,module,exports){
16617// Copyright Joyent, Inc. and other Node contributors.
16618//
16619// Permission is hereby granted, free of charge, to any person obtaining a
16620// copy of this software and associated documentation files (the
16621// "Software"), to deal in the Software without restriction, including
16622// without limitation the rights to use, copy, modify, merge, publish,
16623// distribute, sublicense, and/or sell copies of the Software, and to permit
16624// persons to whom the Software is furnished to do so, subject to the
16625// following conditions:
16626//
16627// The above copyright notice and this permission notice shall be included
16628// in all copies or substantial portions of the Software.
16629//
16630// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16631// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16632// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
16633// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
16634// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16635// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
16636// USE OR OTHER DEALINGS IN THE SOFTWARE.
16637
16638'use strict';
16639
16640/*<replacement>*/
16641
16642var Buffer = _dereq_('safe-buffer').Buffer;
16643/*</replacement>*/
16644
16645var isEncoding = Buffer.isEncoding || function (encoding) {
16646 encoding = '' + encoding;
16647 switch (encoding && encoding.toLowerCase()) {
16648 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':
16649 return true;
16650 default:
16651 return false;
16652 }
16653};
16654
16655function _normalizeEncoding(enc) {
16656 if (!enc) return 'utf8';
16657 var retried;
16658 while (true) {
16659 switch (enc) {
16660 case 'utf8':
16661 case 'utf-8':
16662 return 'utf8';
16663 case 'ucs2':
16664 case 'ucs-2':
16665 case 'utf16le':
16666 case 'utf-16le':
16667 return 'utf16le';
16668 case 'latin1':
16669 case 'binary':
16670 return 'latin1';
16671 case 'base64':
16672 case 'ascii':
16673 case 'hex':
16674 return enc;
16675 default:
16676 if (retried) return; // undefined
16677 enc = ('' + enc).toLowerCase();
16678 retried = true;
16679 }
16680 }
16681};
16682
16683// Do not cache `Buffer.isEncoding` when checking encoding names as some
16684// modules monkey-patch it to support additional encodings
16685function normalizeEncoding(enc) {
16686 var nenc = _normalizeEncoding(enc);
16687 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
16688 return nenc || enc;
16689}
16690
16691// StringDecoder provides an interface for efficiently splitting a series of
16692// buffers into a series of JS strings without breaking apart multi-byte
16693// characters.
16694exports.StringDecoder = StringDecoder;
16695function StringDecoder(encoding) {
16696 this.encoding = normalizeEncoding(encoding);
16697 var nb;
16698 switch (this.encoding) {
16699 case 'utf16le':
16700 this.text = utf16Text;
16701 this.end = utf16End;
16702 nb = 4;
16703 break;
16704 case 'utf8':
16705 this.fillLast = utf8FillLast;
16706 nb = 4;
16707 break;
16708 case 'base64':
16709 this.text = base64Text;
16710 this.end = base64End;
16711 nb = 3;
16712 break;
16713 default:
16714 this.write = simpleWrite;
16715 this.end = simpleEnd;
16716 return;
16717 }
16718 this.lastNeed = 0;
16719 this.lastTotal = 0;
16720 this.lastChar = Buffer.allocUnsafe(nb);
16721}
16722
16723StringDecoder.prototype.write = function (buf) {
16724 if (buf.length === 0) return '';
16725 var r;
16726 var i;
16727 if (this.lastNeed) {
16728 r = this.fillLast(buf);
16729 if (r === undefined) return '';
16730 i = this.lastNeed;
16731 this.lastNeed = 0;
16732 } else {
16733 i = 0;
16734 }
16735 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
16736 return r || '';
16737};
16738
16739StringDecoder.prototype.end = utf8End;
16740
16741// Returns only complete characters in a Buffer
16742StringDecoder.prototype.text = utf8Text;
16743
16744// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
16745StringDecoder.prototype.fillLast = function (buf) {
16746 if (this.lastNeed <= buf.length) {
16747 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
16748 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
16749 }
16750 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
16751 this.lastNeed -= buf.length;
16752};
16753
16754// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
16755// continuation byte. If an invalid byte is detected, -2 is returned.
16756function utf8CheckByte(byte) {
16757 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;
16758 return byte >> 6 === 0x02 ? -1 : -2;
16759}
16760
16761// Checks at most 3 bytes at the end of a Buffer in order to detect an
16762// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
16763// needed to complete the UTF-8 character (if applicable) are returned.
16764function utf8CheckIncomplete(self, buf, i) {
16765 var j = buf.length - 1;
16766 if (j < i) return 0;
16767 var nb = utf8CheckByte(buf[j]);
16768 if (nb >= 0) {
16769 if (nb > 0) self.lastNeed = nb - 1;
16770 return nb;
16771 }
16772 if (--j < i || nb === -2) return 0;
16773 nb = utf8CheckByte(buf[j]);
16774 if (nb >= 0) {
16775 if (nb > 0) self.lastNeed = nb - 2;
16776 return nb;
16777 }
16778 if (--j < i || nb === -2) return 0;
16779 nb = utf8CheckByte(buf[j]);
16780 if (nb >= 0) {
16781 if (nb > 0) {
16782 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
16783 }
16784 return nb;
16785 }
16786 return 0;
16787}
16788
16789// Validates as many continuation bytes for a multi-byte UTF-8 character as
16790// needed or are available. If we see a non-continuation byte where we expect
16791// one, we "replace" the validated continuation bytes we've seen so far with
16792// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
16793// behavior. The continuation byte check is included three times in the case
16794// where all of the continuation bytes for a character exist in the same buffer.
16795// It is also done this way as a slight performance increase instead of using a
16796// loop.
16797function utf8CheckExtraBytes(self, buf, p) {
16798 if ((buf[0] & 0xC0) !== 0x80) {
16799 self.lastNeed = 0;
16800 return '\ufffd';
16801 }
16802 if (self.lastNeed > 1 && buf.length > 1) {
16803 if ((buf[1] & 0xC0) !== 0x80) {
16804 self.lastNeed = 1;
16805 return '\ufffd';
16806 }
16807 if (self.lastNeed > 2 && buf.length > 2) {
16808 if ((buf[2] & 0xC0) !== 0x80) {
16809 self.lastNeed = 2;
16810 return '\ufffd';
16811 }
16812 }
16813 }
16814}
16815
16816// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
16817function utf8FillLast(buf) {
16818 var p = this.lastTotal - this.lastNeed;
16819 var r = utf8CheckExtraBytes(this, buf, p);
16820 if (r !== undefined) return r;
16821 if (this.lastNeed <= buf.length) {
16822 buf.copy(this.lastChar, p, 0, this.lastNeed);
16823 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
16824 }
16825 buf.copy(this.lastChar, p, 0, buf.length);
16826 this.lastNeed -= buf.length;
16827}
16828
16829// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
16830// partial character, the character's bytes are buffered until the required
16831// number of bytes are available.
16832function utf8Text(buf, i) {
16833 var total = utf8CheckIncomplete(this, buf, i);
16834 if (!this.lastNeed) return buf.toString('utf8', i);
16835 this.lastTotal = total;
16836 var end = buf.length - (total - this.lastNeed);
16837 buf.copy(this.lastChar, 0, end);
16838 return buf.toString('utf8', i, end);
16839}
16840
16841// For UTF-8, a replacement character is added when ending on a partial
16842// character.
16843function utf8End(buf) {
16844 var r = buf && buf.length ? this.write(buf) : '';
16845 if (this.lastNeed) return r + '\ufffd';
16846 return r;
16847}
16848
16849// UTF-16LE typically needs two bytes per character, but even if we have an even
16850// number of bytes available, we need to check if we end on a leading/high
16851// surrogate. In that case, we need to wait for the next two bytes in order to
16852// decode the last character properly.
16853function utf16Text(buf, i) {
16854 if ((buf.length - i) % 2 === 0) {
16855 var r = buf.toString('utf16le', i);
16856 if (r) {
16857 var c = r.charCodeAt(r.length - 1);
16858 if (c >= 0xD800 && c <= 0xDBFF) {
16859 this.lastNeed = 2;
16860 this.lastTotal = 4;
16861 this.lastChar[0] = buf[buf.length - 2];
16862 this.lastChar[1] = buf[buf.length - 1];
16863 return r.slice(0, -1);
16864 }
16865 }
16866 return r;
16867 }
16868 this.lastNeed = 1;
16869 this.lastTotal = 2;
16870 this.lastChar[0] = buf[buf.length - 1];
16871 return buf.toString('utf16le', i, buf.length - 1);
16872}
16873
16874// For UTF-16LE we do not explicitly append special replacement characters if we
16875// end on a partial character, we simply let v8 handle that.
16876function utf16End(buf) {
16877 var r = buf && buf.length ? this.write(buf) : '';
16878 if (this.lastNeed) {
16879 var end = this.lastTotal - this.lastNeed;
16880 return r + this.lastChar.toString('utf16le', 0, end);
16881 }
16882 return r;
16883}
16884
16885function base64Text(buf, i) {
16886 var n = (buf.length - i) % 3;
16887 if (n === 0) return buf.toString('base64', i);
16888 this.lastNeed = 3 - n;
16889 this.lastTotal = 3;
16890 if (n === 1) {
16891 this.lastChar[0] = buf[buf.length - 1];
16892 } else {
16893 this.lastChar[0] = buf[buf.length - 2];
16894 this.lastChar[1] = buf[buf.length - 1];
16895 }
16896 return buf.toString('base64', i, buf.length - n);
16897}
16898
16899function base64End(buf) {
16900 var r = buf && buf.length ? this.write(buf) : '';
16901 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
16902 return r;
16903}
16904
16905// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
16906function simpleWrite(buf) {
16907 return buf.toString(this.encoding);
16908}
16909
16910function simpleEnd(buf) {
16911 return buf && buf.length ? this.write(buf) : '';
16912}
16913},{"safe-buffer":121}],123:[function(_dereq_,module,exports){
16914arguments[4][122][0].apply(exports,arguments)
16915},{"dup":122,"safe-buffer":103}],124:[function(_dereq_,module,exports){
16916arguments[4][60][0].apply(exports,arguments)
16917},{"dup":60}],125:[function(_dereq_,module,exports){
16918arguments[4][61][0].apply(exports,arguments)
16919},{"./_stream_readable":127,"./_stream_writable":129,"_process":94,"dup":61,"inherits":53}],126:[function(_dereq_,module,exports){
16920arguments[4][62][0].apply(exports,arguments)
16921},{"./_stream_transform":128,"dup":62,"inherits":53}],127:[function(_dereq_,module,exports){
16922arguments[4][63][0].apply(exports,arguments)
16923},{"../errors":124,"./_stream_duplex":125,"./internal/streams/async_iterator":130,"./internal/streams/buffer_list":131,"./internal/streams/destroy":132,"./internal/streams/from":134,"./internal/streams/state":136,"./internal/streams/stream":137,"_process":94,"buffer":9,"dup":63,"events":39,"inherits":53,"string_decoder/":123,"util":8}],128:[function(_dereq_,module,exports){
16924arguments[4][64][0].apply(exports,arguments)
16925},{"../errors":124,"./_stream_duplex":125,"dup":64,"inherits":53}],129:[function(_dereq_,module,exports){
16926arguments[4][65][0].apply(exports,arguments)
16927},{"../errors":124,"./_stream_duplex":125,"./internal/streams/destroy":132,"./internal/streams/state":136,"./internal/streams/stream":137,"_process":94,"buffer":9,"dup":65,"inherits":53,"util-deprecate":142}],130:[function(_dereq_,module,exports){
16928arguments[4][66][0].apply(exports,arguments)
16929},{"./end-of-stream":133,"_process":94,"dup":66}],131:[function(_dereq_,module,exports){
16930arguments[4][67][0].apply(exports,arguments)
16931},{"buffer":9,"dup":67,"util":8}],132:[function(_dereq_,module,exports){
16932arguments[4][68][0].apply(exports,arguments)
16933},{"_process":94,"dup":68}],133:[function(_dereq_,module,exports){
16934arguments[4][69][0].apply(exports,arguments)
16935},{"../../../errors":124,"dup":69}],134:[function(_dereq_,module,exports){
16936arguments[4][70][0].apply(exports,arguments)
16937},{"dup":70}],135:[function(_dereq_,module,exports){
16938arguments[4][71][0].apply(exports,arguments)
16939},{"../../../errors":124,"./end-of-stream":133,"dup":71}],136:[function(_dereq_,module,exports){
16940arguments[4][72][0].apply(exports,arguments)
16941},{"../../../errors":124,"dup":72}],137:[function(_dereq_,module,exports){
16942arguments[4][73][0].apply(exports,arguments)
16943},{"dup":73,"events":39}],138:[function(_dereq_,module,exports){
16944arguments[4][74][0].apply(exports,arguments)
16945},{"./lib/_stream_duplex.js":125,"./lib/_stream_passthrough.js":126,"./lib/_stream_readable.js":127,"./lib/_stream_transform.js":128,"./lib/_stream_writable.js":129,"./lib/internal/streams/end-of-stream.js":133,"./lib/internal/streams/pipeline.js":135,"dup":74}],139:[function(_dereq_,module,exports){
16946(function (process){(function (){
16947var Transform = _dereq_('readable-stream').Transform
16948 , inherits = _dereq_('inherits')
16949
16950function DestroyableTransform(opts) {
16951 Transform.call(this, opts)
16952 this._destroyed = false
16953}
16954
16955inherits(DestroyableTransform, Transform)
16956
16957DestroyableTransform.prototype.destroy = function(err) {
16958 if (this._destroyed) return
16959 this._destroyed = true
16960
16961 var self = this
16962 process.nextTick(function() {
16963 if (err)
16964 self.emit('error', err)
16965 self.emit('close')
16966 })
16967}
16968
16969// a noop _transform function
16970function noop (chunk, enc, callback) {
16971 callback(null, chunk)
16972}
16973
16974
16975// create a new export function, used by both the main export and
16976// the .ctor export, contains common logic for dealing with arguments
16977function through2 (construct) {
16978 return function (options, transform, flush) {
16979 if (typeof options == 'function') {
16980 flush = transform
16981 transform = options
16982 options = {}
16983 }
16984
16985 if (typeof transform != 'function')
16986 transform = noop
16987
16988 if (typeof flush != 'function')
16989 flush = null
16990
16991 return construct(options, transform, flush)
16992 }
16993}
16994
16995
16996// main export, just make me a transform stream!
16997module.exports = through2(function (options, transform, flush) {
16998 var t2 = new DestroyableTransform(options)
16999
17000 t2._transform = transform
17001
17002 if (flush)
17003 t2._flush = flush
17004
17005 return t2
17006})
17007
17008
17009// make me a reusable prototype that I can `new`, or implicitly `new`
17010// with a constructor call
17011module.exports.ctor = through2(function (options, transform, flush) {
17012 function Through2 (override) {
17013 if (!(this instanceof Through2))
17014 return new Through2(override)
17015
17016 this.options = Object.assign({}, options, override)
17017
17018 DestroyableTransform.call(this, this.options)
17019 }
17020
17021 inherits(Through2, DestroyableTransform)
17022
17023 Through2.prototype._transform = transform
17024
17025 if (flush)
17026 Through2.prototype._flush = flush
17027
17028 return Through2
17029})
17030
17031
17032module.exports.obj = through2(function (options, transform, flush) {
17033 var t2 = new DestroyableTransform(Object.assign({ objectMode: true, highWaterMark: 16 }, options))
17034
17035 t2._transform = transform
17036
17037 if (flush)
17038 t2._flush = flush
17039
17040 return t2
17041})
17042
17043}).call(this)}).call(this,_dereq_('_process'))
17044},{"_process":94,"inherits":53,"readable-stream":138}],140:[function(_dereq_,module,exports){
17045(function (setImmediate,clearImmediate){(function (){
17046var nextTick = _dereq_('process/browser.js').nextTick;
17047var apply = Function.prototype.apply;
17048var slice = Array.prototype.slice;
17049var immediateIds = {};
17050var nextImmediateId = 0;
17051
17052// DOM APIs, for completeness
17053
17054exports.setTimeout = function() {
17055 return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
17056};
17057exports.setInterval = function() {
17058 return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
17059};
17060exports.clearTimeout =
17061exports.clearInterval = function(timeout) { timeout.close(); };
17062
17063function Timeout(id, clearFn) {
17064 this._id = id;
17065 this._clearFn = clearFn;
17066}
17067Timeout.prototype.unref = Timeout.prototype.ref = function() {};
17068Timeout.prototype.close = function() {
17069 this._clearFn.call(window, this._id);
17070};
17071
17072// Does not start the time, just sets up the members needed.
17073exports.enroll = function(item, msecs) {
17074 clearTimeout(item._idleTimeoutId);
17075 item._idleTimeout = msecs;
17076};
17077
17078exports.unenroll = function(item) {
17079 clearTimeout(item._idleTimeoutId);
17080 item._idleTimeout = -1;
17081};
17082
17083exports._unrefActive = exports.active = function(item) {
17084 clearTimeout(item._idleTimeoutId);
17085
17086 var msecs = item._idleTimeout;
17087 if (msecs >= 0) {
17088 item._idleTimeoutId = setTimeout(function onTimeout() {
17089 if (item._onTimeout)
17090 item._onTimeout();
17091 }, msecs);
17092 }
17093};
17094
17095// That's not how node.js implements it but the exposed api is the same.
17096exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
17097 var id = nextImmediateId++;
17098 var args = arguments.length < 2 ? false : slice.call(arguments, 1);
17099
17100 immediateIds[id] = true;
17101
17102 nextTick(function onNextTick() {
17103 if (immediateIds[id]) {
17104 // fn.call() is faster so we optimize for the common use-case
17105 // @see http://jsperf.com/call-apply-segu
17106 if (args) {
17107 fn.apply(null, args);
17108 } else {
17109 fn.call(null);
17110 }
17111 // Prevent ids from leaking
17112 exports.clearImmediate(id);
17113 }
17114 });
17115
17116 return id;
17117};
17118
17119exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
17120 delete immediateIds[id];
17121};
17122}).call(this)}).call(this,_dereq_("timers").setImmediate,_dereq_("timers").clearImmediate)
17123},{"process/browser.js":94,"timers":140}],141:[function(_dereq_,module,exports){
17124'use strict';
17125
17126// Simple FIFO queue implementation to avoid having to do shift()
17127// on an array, which is slow.
17128
17129function Queue() {
17130 this.length = 0;
17131}
17132
17133Queue.prototype.push = function (item) {
17134 var node = {item: item};
17135 if (this.last) {
17136 this.last = this.last.next = node;
17137 } else {
17138 this.last = this.first = node;
17139 }
17140 this.length++;
17141};
17142
17143Queue.prototype.shift = function () {
17144 var node = this.first;
17145 if (node) {
17146 this.first = node.next;
17147 if (!(--this.length)) {
17148 this.last = undefined;
17149 }
17150 return node.item;
17151 }
17152};
17153
17154Queue.prototype.slice = function (start, end) {
17155 start = typeof start === 'undefined' ? 0 : start;
17156 end = typeof end === 'undefined' ? Infinity : end;
17157
17158 var output = [];
17159
17160 var i = 0;
17161 for (var node = this.first; node; node = node.next) {
17162 if (--end < 0) {
17163 break;
17164 } else if (++i > start) {
17165 output.push(node.item);
17166 }
17167 }
17168 return output;
17169}
17170
17171module.exports = Queue;
17172
17173},{}],142:[function(_dereq_,module,exports){
17174(function (global){(function (){
17175
17176/**
17177 * Module exports.
17178 */
17179
17180module.exports = deprecate;
17181
17182/**
17183 * Mark that a method should not be used.
17184 * Returns a modified function which warns once by default.
17185 *
17186 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
17187 *
17188 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
17189 * will throw an Error when invoked.
17190 *
17191 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
17192 * will invoke `console.trace()` instead of `console.error()`.
17193 *
17194 * @param {Function} fn - the function to deprecate
17195 * @param {String} msg - the string to print to the console when `fn` is invoked
17196 * @returns {Function} a new "deprecated" version of `fn`
17197 * @api public
17198 */
17199
17200function deprecate (fn, msg) {
17201 if (config('noDeprecation')) {
17202 return fn;
17203 }
17204
17205 var warned = false;
17206 function deprecated() {
17207 if (!warned) {
17208 if (config('throwDeprecation')) {
17209 throw new Error(msg);
17210 } else if (config('traceDeprecation')) {
17211 console.trace(msg);
17212 } else {
17213 console.warn(msg);
17214 }
17215 warned = true;
17216 }
17217 return fn.apply(this, arguments);
17218 }
17219
17220 return deprecated;
17221}
17222
17223/**
17224 * Checks `localStorage` for boolean values for the given `name`.
17225 *
17226 * @param {String} name
17227 * @returns {Boolean}
17228 * @api private
17229 */
17230
17231function config (name) {
17232 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
17233 try {
17234 if (!global.localStorage) return false;
17235 } catch (_) {
17236 return false;
17237 }
17238 var val = global.localStorage[name];
17239 if (null == val) return false;
17240 return String(val).toLowerCase() === 'true';
17241}
17242
17243}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
17244},{}],143:[function(_dereq_,module,exports){
17245if (typeof Object.create === 'function') {
17246 // implementation from standard node.js 'util' module
17247 module.exports = function inherits(ctor, superCtor) {
17248 ctor.super_ = superCtor
17249 ctor.prototype = Object.create(superCtor.prototype, {
17250 constructor: {
17251 value: ctor,
17252 enumerable: false,
17253 writable: true,
17254 configurable: true
17255 }
17256 });
17257 };
17258} else {
17259 // old school shim for old browsers
17260 module.exports = function inherits(ctor, superCtor) {
17261 ctor.super_ = superCtor
17262 var TempCtor = function () {}
17263 TempCtor.prototype = superCtor.prototype
17264 ctor.prototype = new TempCtor()
17265 ctor.prototype.constructor = ctor
17266 }
17267}
17268
17269},{}],144:[function(_dereq_,module,exports){
17270module.exports = function isBuffer(arg) {
17271 return arg && typeof arg === 'object'
17272 && typeof arg.copy === 'function'
17273 && typeof arg.fill === 'function'
17274 && typeof arg.readUInt8 === 'function';
17275}
17276},{}],145:[function(_dereq_,module,exports){
17277(function (process,global){(function (){
17278// Copyright Joyent, Inc. and other Node contributors.
17279//
17280// Permission is hereby granted, free of charge, to any person obtaining a
17281// copy of this software and associated documentation files (the
17282// "Software"), to deal in the Software without restriction, including
17283// without limitation the rights to use, copy, modify, merge, publish,
17284// distribute, sublicense, and/or sell copies of the Software, and to permit
17285// persons to whom the Software is furnished to do so, subject to the
17286// following conditions:
17287//
17288// The above copyright notice and this permission notice shall be included
17289// in all copies or substantial portions of the Software.
17290//
17291// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17292// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17293// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17294// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
17295// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
17296// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
17297// USE OR OTHER DEALINGS IN THE SOFTWARE.
17298
17299var formatRegExp = /%[sdj%]/g;
17300exports.format = function(f) {
17301 if (!isString(f)) {
17302 var objects = [];
17303 for (var i = 0; i < arguments.length; i++) {
17304 objects.push(inspect(arguments[i]));
17305 }
17306 return objects.join(' ');
17307 }
17308
17309 var i = 1;
17310 var args = arguments;
17311 var len = args.length;
17312 var str = String(f).replace(formatRegExp, function(x) {
17313 if (x === '%%') return '%';
17314 if (i >= len) return x;
17315 switch (x) {
17316 case '%s': return String(args[i++]);
17317 case '%d': return Number(args[i++]);
17318 case '%j':
17319 try {
17320 return JSON.stringify(args[i++]);
17321 } catch (_) {
17322 return '[Circular]';
17323 }
17324 default:
17325 return x;
17326 }
17327 });
17328 for (var x = args[i]; i < len; x = args[++i]) {
17329 if (isNull(x) || !isObject(x)) {
17330 str += ' ' + x;
17331 } else {
17332 str += ' ' + inspect(x);
17333 }
17334 }
17335 return str;
17336};
17337
17338
17339// Mark that a method should not be used.
17340// Returns a modified function which warns once by default.
17341// If --no-deprecation is set, then it is a no-op.
17342exports.deprecate = function(fn, msg) {
17343 // Allow for deprecating things in the process of starting up.
17344 if (isUndefined(global.process)) {
17345 return function() {
17346 return exports.deprecate(fn, msg).apply(this, arguments);
17347 };
17348 }
17349
17350 if (process.noDeprecation === true) {
17351 return fn;
17352 }
17353
17354 var warned = false;
17355 function deprecated() {
17356 if (!warned) {
17357 if (process.throwDeprecation) {
17358 throw new Error(msg);
17359 } else if (process.traceDeprecation) {
17360 console.trace(msg);
17361 } else {
17362 console.error(msg);
17363 }
17364 warned = true;
17365 }
17366 return fn.apply(this, arguments);
17367 }
17368
17369 return deprecated;
17370};
17371
17372
17373var debugs = {};
17374var debugEnviron;
17375exports.debuglog = function(set) {
17376 if (isUndefined(debugEnviron))
17377 debugEnviron = process.env.NODE_DEBUG || '';
17378 set = set.toUpperCase();
17379 if (!debugs[set]) {
17380 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
17381 var pid = process.pid;
17382 debugs[set] = function() {
17383 var msg = exports.format.apply(exports, arguments);
17384 console.error('%s %d: %s', set, pid, msg);
17385 };
17386 } else {
17387 debugs[set] = function() {};
17388 }
17389 }
17390 return debugs[set];
17391};
17392
17393
17394/**
17395 * Echos the value of a value. Trys to print the value out
17396 * in the best way possible given the different types.
17397 *
17398 * @param {Object} obj The object to print out.
17399 * @param {Object} opts Optional options object that alters the output.
17400 */
17401/* legacy: obj, showHidden, depth, colors*/
17402function inspect(obj, opts) {
17403 // default options
17404 var ctx = {
17405 seen: [],
17406 stylize: stylizeNoColor
17407 };
17408 // legacy...
17409 if (arguments.length >= 3) ctx.depth = arguments[2];
17410 if (arguments.length >= 4) ctx.colors = arguments[3];
17411 if (isBoolean(opts)) {
17412 // legacy...
17413 ctx.showHidden = opts;
17414 } else if (opts) {
17415 // got an "options" object
17416 exports._extend(ctx, opts);
17417 }
17418 // set default options
17419 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
17420 if (isUndefined(ctx.depth)) ctx.depth = 2;
17421 if (isUndefined(ctx.colors)) ctx.colors = false;
17422 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
17423 if (ctx.colors) ctx.stylize = stylizeWithColor;
17424 return formatValue(ctx, obj, ctx.depth);
17425}
17426exports.inspect = inspect;
17427
17428
17429// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
17430inspect.colors = {
17431 'bold' : [1, 22],
17432 'italic' : [3, 23],
17433 'underline' : [4, 24],
17434 'inverse' : [7, 27],
17435 'white' : [37, 39],
17436 'grey' : [90, 39],
17437 'black' : [30, 39],
17438 'blue' : [34, 39],
17439 'cyan' : [36, 39],
17440 'green' : [32, 39],
17441 'magenta' : [35, 39],
17442 'red' : [31, 39],
17443 'yellow' : [33, 39]
17444};
17445
17446// Don't use 'blue' not visible on cmd.exe
17447inspect.styles = {
17448 'special': 'cyan',
17449 'number': 'yellow',
17450 'boolean': 'yellow',
17451 'undefined': 'grey',
17452 'null': 'bold',
17453 'string': 'green',
17454 'date': 'magenta',
17455 // "name": intentionally not styling
17456 'regexp': 'red'
17457};
17458
17459
17460function stylizeWithColor(str, styleType) {
17461 var style = inspect.styles[styleType];
17462
17463 if (style) {
17464 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
17465 '\u001b[' + inspect.colors[style][1] + 'm';
17466 } else {
17467 return str;
17468 }
17469}
17470
17471
17472function stylizeNoColor(str, styleType) {
17473 return str;
17474}
17475
17476
17477function arrayToHash(array) {
17478 var hash = {};
17479
17480 array.forEach(function(val, idx) {
17481 hash[val] = true;
17482 });
17483
17484 return hash;
17485}
17486
17487
17488function formatValue(ctx, value, recurseTimes) {
17489 // Provide a hook for user-specified inspect functions.
17490 // Check that value is an object with an inspect function on it
17491 if (ctx.customInspect &&
17492 value &&
17493 isFunction(value.inspect) &&
17494 // Filter out the util module, it's inspect function is special
17495 value.inspect !== exports.inspect &&
17496 // Also filter out any prototype objects using the circular check.
17497 !(value.constructor && value.constructor.prototype === value)) {
17498 var ret = value.inspect(recurseTimes, ctx);
17499 if (!isString(ret)) {
17500 ret = formatValue(ctx, ret, recurseTimes);
17501 }
17502 return ret;
17503 }
17504
17505 // Primitive types cannot have properties
17506 var primitive = formatPrimitive(ctx, value);
17507 if (primitive) {
17508 return primitive;
17509 }
17510
17511 // Look up the keys of the object.
17512 var keys = Object.keys(value);
17513 var visibleKeys = arrayToHash(keys);
17514
17515 if (ctx.showHidden) {
17516 keys = Object.getOwnPropertyNames(value);
17517 }
17518
17519 // IE doesn't make error fields non-enumerable
17520 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
17521 if (isError(value)
17522 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
17523 return formatError(value);
17524 }
17525
17526 // Some type of object without properties can be shortcutted.
17527 if (keys.length === 0) {
17528 if (isFunction(value)) {
17529 var name = value.name ? ': ' + value.name : '';
17530 return ctx.stylize('[Function' + name + ']', 'special');
17531 }
17532 if (isRegExp(value)) {
17533 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
17534 }
17535 if (isDate(value)) {
17536 return ctx.stylize(Date.prototype.toString.call(value), 'date');
17537 }
17538 if (isError(value)) {
17539 return formatError(value);
17540 }
17541 }
17542
17543 var base = '', array = false, braces = ['{', '}'];
17544
17545 // Make Array say that they are Array
17546 if (isArray(value)) {
17547 array = true;
17548 braces = ['[', ']'];
17549 }
17550
17551 // Make functions say that they are functions
17552 if (isFunction(value)) {
17553 var n = value.name ? ': ' + value.name : '';
17554 base = ' [Function' + n + ']';
17555 }
17556
17557 // Make RegExps say that they are RegExps
17558 if (isRegExp(value)) {
17559 base = ' ' + RegExp.prototype.toString.call(value);
17560 }
17561
17562 // Make dates with properties first say the date
17563 if (isDate(value)) {
17564 base = ' ' + Date.prototype.toUTCString.call(value);
17565 }
17566
17567 // Make error with message first say the error
17568 if (isError(value)) {
17569 base = ' ' + formatError(value);
17570 }
17571
17572 if (keys.length === 0 && (!array || value.length == 0)) {
17573 return braces[0] + base + braces[1];
17574 }
17575
17576 if (recurseTimes < 0) {
17577 if (isRegExp(value)) {
17578 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
17579 } else {
17580 return ctx.stylize('[Object]', 'special');
17581 }
17582 }
17583
17584 ctx.seen.push(value);
17585
17586 var output;
17587 if (array) {
17588 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
17589 } else {
17590 output = keys.map(function(key) {
17591 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
17592 });
17593 }
17594
17595 ctx.seen.pop();
17596
17597 return reduceToSingleString(output, base, braces);
17598}
17599
17600
17601function formatPrimitive(ctx, value) {
17602 if (isUndefined(value))
17603 return ctx.stylize('undefined', 'undefined');
17604 if (isString(value)) {
17605 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
17606 .replace(/'/g, "\\'")
17607 .replace(/\\"/g, '"') + '\'';
17608 return ctx.stylize(simple, 'string');
17609 }
17610 if (isNumber(value))
17611 return ctx.stylize('' + value, 'number');
17612 if (isBoolean(value))
17613 return ctx.stylize('' + value, 'boolean');
17614 // For some reason typeof null is "object", so special case here.
17615 if (isNull(value))
17616 return ctx.stylize('null', 'null');
17617}
17618
17619
17620function formatError(value) {
17621 return '[' + Error.prototype.toString.call(value) + ']';
17622}
17623
17624
17625function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
17626 var output = [];
17627 for (var i = 0, l = value.length; i < l; ++i) {
17628 if (hasOwnProperty(value, String(i))) {
17629 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
17630 String(i), true));
17631 } else {
17632 output.push('');
17633 }
17634 }
17635 keys.forEach(function(key) {
17636 if (!key.match(/^\d+$/)) {
17637 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
17638 key, true));
17639 }
17640 });
17641 return output;
17642}
17643
17644
17645function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
17646 var name, str, desc;
17647 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
17648 if (desc.get) {
17649 if (desc.set) {
17650 str = ctx.stylize('[Getter/Setter]', 'special');
17651 } else {
17652 str = ctx.stylize('[Getter]', 'special');
17653 }
17654 } else {
17655 if (desc.set) {
17656 str = ctx.stylize('[Setter]', 'special');
17657 }
17658 }
17659 if (!hasOwnProperty(visibleKeys, key)) {
17660 name = '[' + key + ']';
17661 }
17662 if (!str) {
17663 if (ctx.seen.indexOf(desc.value) < 0) {
17664 if (isNull(recurseTimes)) {
17665 str = formatValue(ctx, desc.value, null);
17666 } else {
17667 str = formatValue(ctx, desc.value, recurseTimes - 1);
17668 }
17669 if (str.indexOf('\n') > -1) {
17670 if (array) {
17671 str = str.split('\n').map(function(line) {
17672 return ' ' + line;
17673 }).join('\n').substr(2);
17674 } else {
17675 str = '\n' + str.split('\n').map(function(line) {
17676 return ' ' + line;
17677 }).join('\n');
17678 }
17679 }
17680 } else {
17681 str = ctx.stylize('[Circular]', 'special');
17682 }
17683 }
17684 if (isUndefined(name)) {
17685 if (array && key.match(/^\d+$/)) {
17686 return str;
17687 }
17688 name = JSON.stringify('' + key);
17689 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
17690 name = name.substr(1, name.length - 2);
17691 name = ctx.stylize(name, 'name');
17692 } else {
17693 name = name.replace(/'/g, "\\'")
17694 .replace(/\\"/g, '"')
17695 .replace(/(^"|"$)/g, "'");
17696 name = ctx.stylize(name, 'string');
17697 }
17698 }
17699
17700 return name + ': ' + str;
17701}
17702
17703
17704function reduceToSingleString(output, base, braces) {
17705 var numLinesEst = 0;
17706 var length = output.reduce(function(prev, cur) {
17707 numLinesEst++;
17708 if (cur.indexOf('\n') >= 0) numLinesEst++;
17709 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
17710 }, 0);
17711
17712 if (length > 60) {
17713 return braces[0] +
17714 (base === '' ? '' : base + '\n ') +
17715 ' ' +
17716 output.join(',\n ') +
17717 ' ' +
17718 braces[1];
17719 }
17720
17721 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
17722}
17723
17724
17725// NOTE: These type checking functions intentionally don't use `instanceof`
17726// because it is fragile and can be easily faked with `Object.create()`.
17727function isArray(ar) {
17728 return Array.isArray(ar);
17729}
17730exports.isArray = isArray;
17731
17732function isBoolean(arg) {
17733 return typeof arg === 'boolean';
17734}
17735exports.isBoolean = isBoolean;
17736
17737function isNull(arg) {
17738 return arg === null;
17739}
17740exports.isNull = isNull;
17741
17742function isNullOrUndefined(arg) {
17743 return arg == null;
17744}
17745exports.isNullOrUndefined = isNullOrUndefined;
17746
17747function isNumber(arg) {
17748 return typeof arg === 'number';
17749}
17750exports.isNumber = isNumber;
17751
17752function isString(arg) {
17753 return typeof arg === 'string';
17754}
17755exports.isString = isString;
17756
17757function isSymbol(arg) {
17758 return typeof arg === 'symbol';
17759}
17760exports.isSymbol = isSymbol;
17761
17762function isUndefined(arg) {
17763 return arg === void 0;
17764}
17765exports.isUndefined = isUndefined;
17766
17767function isRegExp(re) {
17768 return isObject(re) && objectToString(re) === '[object RegExp]';
17769}
17770exports.isRegExp = isRegExp;
17771
17772function isObject(arg) {
17773 return typeof arg === 'object' && arg !== null;
17774}
17775exports.isObject = isObject;
17776
17777function isDate(d) {
17778 return isObject(d) && objectToString(d) === '[object Date]';
17779}
17780exports.isDate = isDate;
17781
17782function isError(e) {
17783 return isObject(e) &&
17784 (objectToString(e) === '[object Error]' || e instanceof Error);
17785}
17786exports.isError = isError;
17787
17788function isFunction(arg) {
17789 return typeof arg === 'function';
17790}
17791exports.isFunction = isFunction;
17792
17793function isPrimitive(arg) {
17794 return arg === null ||
17795 typeof arg === 'boolean' ||
17796 typeof arg === 'number' ||
17797 typeof arg === 'string' ||
17798 typeof arg === 'symbol' || // ES6 symbol
17799 typeof arg === 'undefined';
17800}
17801exports.isPrimitive = isPrimitive;
17802
17803exports.isBuffer = _dereq_('./support/isBuffer');
17804
17805function objectToString(o) {
17806 return Object.prototype.toString.call(o);
17807}
17808
17809
17810function pad(n) {
17811 return n < 10 ? '0' + n.toString(10) : n.toString(10);
17812}
17813
17814
17815var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
17816 'Oct', 'Nov', 'Dec'];
17817
17818// 26 Feb 16:19:34
17819function timestamp() {
17820 var d = new Date();
17821 var time = [pad(d.getHours()),
17822 pad(d.getMinutes()),
17823 pad(d.getSeconds())].join(':');
17824 return [d.getDate(), months[d.getMonth()], time].join(' ');
17825}
17826
17827
17828// log is just a thin wrapper to console.log that prepends a timestamp
17829exports.log = function() {
17830 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
17831};
17832
17833
17834/**
17835 * Inherit the prototype methods from one constructor into another.
17836 *
17837 * The Function.prototype.inherits from lang.js rewritten as a standalone
17838 * function (not on Function.prototype). NOTE: If this file is to be loaded
17839 * during bootstrapping this function needs to be rewritten using some native
17840 * functions as prototype setup using normal JavaScript does not work as
17841 * expected during bootstrapping (see mirror.js in r114903).
17842 *
17843 * @param {function} ctor Constructor function which needs to inherit the
17844 * prototype.
17845 * @param {function} superCtor Constructor function to inherit prototype from.
17846 */
17847exports.inherits = _dereq_('inherits');
17848
17849exports._extend = function(origin, add) {
17850 // Don't do anything if add isn't an object
17851 if (!add || !isObject(add)) return origin;
17852
17853 var keys = Object.keys(add);
17854 var i = keys.length;
17855 while (i--) {
17856 origin[keys[i]] = add[keys[i]];
17857 }
17858 return origin;
17859};
17860
17861function hasOwnProperty(obj, prop) {
17862 return Object.prototype.hasOwnProperty.call(obj, prop);
17863}
17864
17865}).call(this)}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
17866},{"./support/isBuffer":144,"_process":94,"inherits":143}],146:[function(_dereq_,module,exports){
17867"use strict";
17868
17869Object.defineProperty(exports, "__esModule", {
17870 value: true
17871});
17872Object.defineProperty(exports, "v1", {
17873 enumerable: true,
17874 get: function () {
17875 return _v.default;
17876 }
17877});
17878Object.defineProperty(exports, "v3", {
17879 enumerable: true,
17880 get: function () {
17881 return _v2.default;
17882 }
17883});
17884Object.defineProperty(exports, "v4", {
17885 enumerable: true,
17886 get: function () {
17887 return _v3.default;
17888 }
17889});
17890Object.defineProperty(exports, "v5", {
17891 enumerable: true,
17892 get: function () {
17893 return _v4.default;
17894 }
17895});
17896Object.defineProperty(exports, "NIL", {
17897 enumerable: true,
17898 get: function () {
17899 return _nil.default;
17900 }
17901});
17902Object.defineProperty(exports, "version", {
17903 enumerable: true,
17904 get: function () {
17905 return _version.default;
17906 }
17907});
17908Object.defineProperty(exports, "validate", {
17909 enumerable: true,
17910 get: function () {
17911 return _validate.default;
17912 }
17913});
17914Object.defineProperty(exports, "stringify", {
17915 enumerable: true,
17916 get: function () {
17917 return _stringify.default;
17918 }
17919});
17920Object.defineProperty(exports, "parse", {
17921 enumerable: true,
17922 get: function () {
17923 return _parse.default;
17924 }
17925});
17926
17927var _v = _interopRequireDefault(_dereq_("./v1.js"));
17928
17929var _v2 = _interopRequireDefault(_dereq_("./v3.js"));
17930
17931var _v3 = _interopRequireDefault(_dereq_("./v4.js"));
17932
17933var _v4 = _interopRequireDefault(_dereq_("./v5.js"));
17934
17935var _nil = _interopRequireDefault(_dereq_("./nil.js"));
17936
17937var _version = _interopRequireDefault(_dereq_("./version.js"));
17938
17939var _validate = _interopRequireDefault(_dereq_("./validate.js"));
17940
17941var _stringify = _interopRequireDefault(_dereq_("./stringify.js"));
17942
17943var _parse = _interopRequireDefault(_dereq_("./parse.js"));
17944
17945function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17946},{"./nil.js":148,"./parse.js":149,"./stringify.js":153,"./v1.js":154,"./v3.js":155,"./v4.js":157,"./v5.js":158,"./validate.js":159,"./version.js":160}],147:[function(_dereq_,module,exports){
17947"use strict";
17948
17949Object.defineProperty(exports, "__esModule", {
17950 value: true
17951});
17952exports.default = void 0;
17953
17954/*
17955 * Browser-compatible JavaScript MD5
17956 *
17957 * Modification of JavaScript MD5
17958 * https://github.com/blueimp/JavaScript-MD5
17959 *
17960 * Copyright 2011, Sebastian Tschan
17961 * https://blueimp.net
17962 *
17963 * Licensed under the MIT license:
17964 * https://opensource.org/licenses/MIT
17965 *
17966 * Based on
17967 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
17968 * Digest Algorithm, as defined in RFC 1321.
17969 * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
17970 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
17971 * Distributed under the BSD License
17972 * See http://pajhome.org.uk/crypt/md5 for more info.
17973 */
17974function md5(bytes) {
17975 if (typeof bytes === 'string') {
17976 const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
17977
17978 bytes = new Uint8Array(msg.length);
17979
17980 for (let i = 0; i < msg.length; ++i) {
17981 bytes[i] = msg.charCodeAt(i);
17982 }
17983 }
17984
17985 return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));
17986}
17987/*
17988 * Convert an array of little-endian words to an array of bytes
17989 */
17990
17991
17992function md5ToHexEncodedArray(input) {
17993 const output = [];
17994 const length32 = input.length * 32;
17995 const hexTab = '0123456789abcdef';
17996
17997 for (let i = 0; i < length32; i += 8) {
17998 const x = input[i >> 5] >>> i % 32 & 0xff;
17999 const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);
18000 output.push(hex);
18001 }
18002
18003 return output;
18004}
18005/**
18006 * Calculate output length with padding and bit length
18007 */
18008
18009
18010function getOutputLength(inputLength8) {
18011 return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
18012}
18013/*
18014 * Calculate the MD5 of an array of little-endian words, and a bit length.
18015 */
18016
18017
18018function wordsToMd5(x, len) {
18019 /* append padding */
18020 x[len >> 5] |= 0x80 << len % 32;
18021 x[getOutputLength(len) - 1] = len;
18022 let a = 1732584193;
18023 let b = -271733879;
18024 let c = -1732584194;
18025 let d = 271733878;
18026
18027 for (let i = 0; i < x.length; i += 16) {
18028 const olda = a;
18029 const oldb = b;
18030 const oldc = c;
18031 const oldd = d;
18032 a = md5ff(a, b, c, d, x[i], 7, -680876936);
18033 d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
18034 c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
18035 b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
18036 a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
18037 d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
18038 c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
18039 b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
18040 a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
18041 d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
18042 c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
18043 b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
18044 a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
18045 d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
18046 c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
18047 b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
18048 a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
18049 d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
18050 c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
18051 b = md5gg(b, c, d, a, x[i], 20, -373897302);
18052 a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
18053 d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
18054 c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
18055 b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
18056 a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
18057 d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
18058 c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
18059 b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
18060 a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
18061 d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
18062 c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
18063 b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
18064 a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
18065 d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
18066 c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
18067 b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
18068 a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
18069 d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
18070 c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
18071 b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
18072 a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
18073 d = md5hh(d, a, b, c, x[i], 11, -358537222);
18074 c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
18075 b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
18076 a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
18077 d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
18078 c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
18079 b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
18080 a = md5ii(a, b, c, d, x[i], 6, -198630844);
18081 d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
18082 c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
18083 b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
18084 a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
18085 d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
18086 c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
18087 b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
18088 a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
18089 d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
18090 c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
18091 b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
18092 a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
18093 d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
18094 c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
18095 b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
18096 a = safeAdd(a, olda);
18097 b = safeAdd(b, oldb);
18098 c = safeAdd(c, oldc);
18099 d = safeAdd(d, oldd);
18100 }
18101
18102 return [a, b, c, d];
18103}
18104/*
18105 * Convert an array bytes to an array of little-endian words
18106 * Characters >255 have their high-byte silently ignored.
18107 */
18108
18109
18110function bytesToWords(input) {
18111 if (input.length === 0) {
18112 return [];
18113 }
18114
18115 const length8 = input.length * 8;
18116 const output = new Uint32Array(getOutputLength(length8));
18117
18118 for (let i = 0; i < length8; i += 8) {
18119 output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;
18120 }
18121
18122 return output;
18123}
18124/*
18125 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
18126 * to work around bugs in some JS interpreters.
18127 */
18128
18129
18130function safeAdd(x, y) {
18131 const lsw = (x & 0xffff) + (y & 0xffff);
18132 const msw = (x >> 16) + (y >> 16) + (lsw >> 16);
18133 return msw << 16 | lsw & 0xffff;
18134}
18135/*
18136 * Bitwise rotate a 32-bit number to the left.
18137 */
18138
18139
18140function bitRotateLeft(num, cnt) {
18141 return num << cnt | num >>> 32 - cnt;
18142}
18143/*
18144 * These functions implement the four basic operations the algorithm uses.
18145 */
18146
18147
18148function md5cmn(q, a, b, x, s, t) {
18149 return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
18150}
18151
18152function md5ff(a, b, c, d, x, s, t) {
18153 return md5cmn(b & c | ~b & d, a, b, x, s, t);
18154}
18155
18156function md5gg(a, b, c, d, x, s, t) {
18157 return md5cmn(b & d | c & ~d, a, b, x, s, t);
18158}
18159
18160function md5hh(a, b, c, d, x, s, t) {
18161 return md5cmn(b ^ c ^ d, a, b, x, s, t);
18162}
18163
18164function md5ii(a, b, c, d, x, s, t) {
18165 return md5cmn(c ^ (b | ~d), a, b, x, s, t);
18166}
18167
18168var _default = md5;
18169exports.default = _default;
18170},{}],148:[function(_dereq_,module,exports){
18171"use strict";
18172
18173Object.defineProperty(exports, "__esModule", {
18174 value: true
18175});
18176exports.default = void 0;
18177var _default = '00000000-0000-0000-0000-000000000000';
18178exports.default = _default;
18179},{}],149:[function(_dereq_,module,exports){
18180"use strict";
18181
18182Object.defineProperty(exports, "__esModule", {
18183 value: true
18184});
18185exports.default = void 0;
18186
18187var _validate = _interopRequireDefault(_dereq_("./validate.js"));
18188
18189function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18190
18191function parse(uuid) {
18192 if (!(0, _validate.default)(uuid)) {
18193 throw TypeError('Invalid UUID');
18194 }
18195
18196 let v;
18197 const arr = new Uint8Array(16); // Parse ########-....-....-....-............
18198
18199 arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
18200 arr[1] = v >>> 16 & 0xff;
18201 arr[2] = v >>> 8 & 0xff;
18202 arr[3] = v & 0xff; // Parse ........-####-....-....-............
18203
18204 arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
18205 arr[5] = v & 0xff; // Parse ........-....-####-....-............
18206
18207 arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
18208 arr[7] = v & 0xff; // Parse ........-....-....-####-............
18209
18210 arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
18211 arr[9] = v & 0xff; // Parse ........-....-....-....-############
18212 // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
18213
18214 arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
18215 arr[11] = v / 0x100000000 & 0xff;
18216 arr[12] = v >>> 24 & 0xff;
18217 arr[13] = v >>> 16 & 0xff;
18218 arr[14] = v >>> 8 & 0xff;
18219 arr[15] = v & 0xff;
18220 return arr;
18221}
18222
18223var _default = parse;
18224exports.default = _default;
18225},{"./validate.js":159}],150:[function(_dereq_,module,exports){
18226"use strict";
18227
18228Object.defineProperty(exports, "__esModule", {
18229 value: true
18230});
18231exports.default = void 0;
18232var _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;
18233exports.default = _default;
18234},{}],151:[function(_dereq_,module,exports){
18235"use strict";
18236
18237Object.defineProperty(exports, "__esModule", {
18238 value: true
18239});
18240exports.default = rng;
18241// Unique ID creation requires a high quality random # generator. In the browser we therefore
18242// require the crypto API and do not support built-in fallback to lower quality random number
18243// generators (like Math.random()).
18244let getRandomValues;
18245const rnds8 = new Uint8Array(16);
18246
18247function rng() {
18248 // lazy load so that environments that need to polyfill have a chance to do so
18249 if (!getRandomValues) {
18250 // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
18251 // find the complete implementation of crypto (msCrypto) on IE11.
18252 getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
18253
18254 if (!getRandomValues) {
18255 throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
18256 }
18257 }
18258
18259 return getRandomValues(rnds8);
18260}
18261},{}],152:[function(_dereq_,module,exports){
18262"use strict";
18263
18264Object.defineProperty(exports, "__esModule", {
18265 value: true
18266});
18267exports.default = void 0;
18268
18269// Adapted from Chris Veness' SHA1 code at
18270// http://www.movable-type.co.uk/scripts/sha1.html
18271function f(s, x, y, z) {
18272 switch (s) {
18273 case 0:
18274 return x & y ^ ~x & z;
18275
18276 case 1:
18277 return x ^ y ^ z;
18278
18279 case 2:
18280 return x & y ^ x & z ^ y & z;
18281
18282 case 3:
18283 return x ^ y ^ z;
18284 }
18285}
18286
18287function ROTL(x, n) {
18288 return x << n | x >>> 32 - n;
18289}
18290
18291function sha1(bytes) {
18292 const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
18293 const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
18294
18295 if (typeof bytes === 'string') {
18296 const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
18297
18298 bytes = [];
18299
18300 for (let i = 0; i < msg.length; ++i) {
18301 bytes.push(msg.charCodeAt(i));
18302 }
18303 } else if (!Array.isArray(bytes)) {
18304 // Convert Array-like to Array
18305 bytes = Array.prototype.slice.call(bytes);
18306 }
18307
18308 bytes.push(0x80);
18309 const l = bytes.length / 4 + 2;
18310 const N = Math.ceil(l / 16);
18311 const M = new Array(N);
18312
18313 for (let i = 0; i < N; ++i) {
18314 const arr = new Uint32Array(16);
18315
18316 for (let j = 0; j < 16; ++j) {
18317 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];
18318 }
18319
18320 M[i] = arr;
18321 }
18322
18323 M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
18324 M[N - 1][14] = Math.floor(M[N - 1][14]);
18325 M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;
18326
18327 for (let i = 0; i < N; ++i) {
18328 const W = new Uint32Array(80);
18329
18330 for (let t = 0; t < 16; ++t) {
18331 W[t] = M[i][t];
18332 }
18333
18334 for (let t = 16; t < 80; ++t) {
18335 W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);
18336 }
18337
18338 let a = H[0];
18339 let b = H[1];
18340 let c = H[2];
18341 let d = H[3];
18342 let e = H[4];
18343
18344 for (let t = 0; t < 80; ++t) {
18345 const s = Math.floor(t / 20);
18346 const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0;
18347 e = d;
18348 d = c;
18349 c = ROTL(b, 30) >>> 0;
18350 b = a;
18351 a = T;
18352 }
18353
18354 H[0] = H[0] + a >>> 0;
18355 H[1] = H[1] + b >>> 0;
18356 H[2] = H[2] + c >>> 0;
18357 H[3] = H[3] + d >>> 0;
18358 H[4] = H[4] + e >>> 0;
18359 }
18360
18361 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];
18362}
18363
18364var _default = sha1;
18365exports.default = _default;
18366},{}],153:[function(_dereq_,module,exports){
18367"use strict";
18368
18369Object.defineProperty(exports, "__esModule", {
18370 value: true
18371});
18372exports.default = void 0;
18373
18374var _validate = _interopRequireDefault(_dereq_("./validate.js"));
18375
18376function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18377
18378/**
18379 * Convert array of 16 byte values to UUID string format of the form:
18380 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
18381 */
18382const byteToHex = [];
18383
18384for (let i = 0; i < 256; ++i) {
18385 byteToHex.push((i + 0x100).toString(16).substr(1));
18386}
18387
18388function stringify(arr, offset = 0) {
18389 // Note: Be careful editing this code! It's been tuned for performance
18390 // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
18391 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
18392 // of the following:
18393 // - One or more input array values don't map to a hex octet (leading to
18394 // "undefined" in the uuid)
18395 // - Invalid input values for the RFC `version` or `variant` fields
18396
18397 if (!(0, _validate.default)(uuid)) {
18398 throw TypeError('Stringified UUID is invalid');
18399 }
18400
18401 return uuid;
18402}
18403
18404var _default = stringify;
18405exports.default = _default;
18406},{"./validate.js":159}],154:[function(_dereq_,module,exports){
18407"use strict";
18408
18409Object.defineProperty(exports, "__esModule", {
18410 value: true
18411});
18412exports.default = void 0;
18413
18414var _rng = _interopRequireDefault(_dereq_("./rng.js"));
18415
18416var _stringify = _interopRequireDefault(_dereq_("./stringify.js"));
18417
18418function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18419
18420// **`v1()` - Generate time-based UUID**
18421//
18422// Inspired by https://github.com/LiosK/UUID.js
18423// and http://docs.python.org/library/uuid.html
18424let _nodeId;
18425
18426let _clockseq; // Previous uuid creation time
18427
18428
18429let _lastMSecs = 0;
18430let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details
18431
18432function v1(options, buf, offset) {
18433 let i = buf && offset || 0;
18434 const b = buf || new Array(16);
18435 options = options || {};
18436 let node = options.node || _nodeId;
18437 let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not
18438 // specified. We do this lazily to minimize issues related to insufficient
18439 // system entropy. See #189
18440
18441 if (node == null || clockseq == null) {
18442 const seedBytes = options.random || (options.rng || _rng.default)();
18443
18444 if (node == null) {
18445 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
18446 node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
18447 }
18448
18449 if (clockseq == null) {
18450 // Per 4.2.2, randomize (14 bit) clockseq
18451 clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
18452 }
18453 } // UUID timestamps are 100 nano-second units since the Gregorian epoch,
18454 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
18455 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
18456 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
18457
18458
18459 let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock
18460 // cycle to simulate higher resolution clock
18461
18462 let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)
18463
18464 const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression
18465
18466 if (dt < 0 && options.clockseq === undefined) {
18467 clockseq = clockseq + 1 & 0x3fff;
18468 } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
18469 // time interval
18470
18471
18472 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
18473 nsecs = 0;
18474 } // Per 4.2.1.2 Throw error if too many uuids are requested
18475
18476
18477 if (nsecs >= 10000) {
18478 throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
18479 }
18480
18481 _lastMSecs = msecs;
18482 _lastNSecs = nsecs;
18483 _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
18484
18485 msecs += 12219292800000; // `time_low`
18486
18487 const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
18488 b[i++] = tl >>> 24 & 0xff;
18489 b[i++] = tl >>> 16 & 0xff;
18490 b[i++] = tl >>> 8 & 0xff;
18491 b[i++] = tl & 0xff; // `time_mid`
18492
18493 const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
18494 b[i++] = tmh >>> 8 & 0xff;
18495 b[i++] = tmh & 0xff; // `time_high_and_version`
18496
18497 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
18498
18499 b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
18500
18501 b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`
18502
18503 b[i++] = clockseq & 0xff; // `node`
18504
18505 for (let n = 0; n < 6; ++n) {
18506 b[i + n] = node[n];
18507 }
18508
18509 return buf || (0, _stringify.default)(b);
18510}
18511
18512var _default = v1;
18513exports.default = _default;
18514},{"./rng.js":151,"./stringify.js":153}],155:[function(_dereq_,module,exports){
18515"use strict";
18516
18517Object.defineProperty(exports, "__esModule", {
18518 value: true
18519});
18520exports.default = void 0;
18521
18522var _v = _interopRequireDefault(_dereq_("./v35.js"));
18523
18524var _md = _interopRequireDefault(_dereq_("./md5.js"));
18525
18526function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18527
18528const v3 = (0, _v.default)('v3', 0x30, _md.default);
18529var _default = v3;
18530exports.default = _default;
18531},{"./md5.js":147,"./v35.js":156}],156:[function(_dereq_,module,exports){
18532"use strict";
18533
18534Object.defineProperty(exports, "__esModule", {
18535 value: true
18536});
18537exports.default = _default;
18538exports.URL = exports.DNS = void 0;
18539
18540var _stringify = _interopRequireDefault(_dereq_("./stringify.js"));
18541
18542var _parse = _interopRequireDefault(_dereq_("./parse.js"));
18543
18544function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18545
18546function stringToBytes(str) {
18547 str = unescape(encodeURIComponent(str)); // UTF8 escape
18548
18549 const bytes = [];
18550
18551 for (let i = 0; i < str.length; ++i) {
18552 bytes.push(str.charCodeAt(i));
18553 }
18554
18555 return bytes;
18556}
18557
18558const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
18559exports.DNS = DNS;
18560const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
18561exports.URL = URL;
18562
18563function _default(name, version, hashfunc) {
18564 function generateUUID(value, namespace, buf, offset) {
18565 if (typeof value === 'string') {
18566 value = stringToBytes(value);
18567 }
18568
18569 if (typeof namespace === 'string') {
18570 namespace = (0, _parse.default)(namespace);
18571 }
18572
18573 if (namespace.length !== 16) {
18574 throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
18575 } // Compute hash of namespace and value, Per 4.3
18576 // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
18577 // hashfunc([...namespace, ... value])`
18578
18579
18580 let bytes = new Uint8Array(16 + value.length);
18581 bytes.set(namespace);
18582 bytes.set(value, namespace.length);
18583 bytes = hashfunc(bytes);
18584 bytes[6] = bytes[6] & 0x0f | version;
18585 bytes[8] = bytes[8] & 0x3f | 0x80;
18586
18587 if (buf) {
18588 offset = offset || 0;
18589
18590 for (let i = 0; i < 16; ++i) {
18591 buf[offset + i] = bytes[i];
18592 }
18593
18594 return buf;
18595 }
18596
18597 return (0, _stringify.default)(bytes);
18598 } // Function#name is not settable on some platforms (#270)
18599
18600
18601 try {
18602 generateUUID.name = name; // eslint-disable-next-line no-empty
18603 } catch (err) {} // For CommonJS default export support
18604
18605
18606 generateUUID.DNS = DNS;
18607 generateUUID.URL = URL;
18608 return generateUUID;
18609}
18610},{"./parse.js":149,"./stringify.js":153}],157:[function(_dereq_,module,exports){
18611"use strict";
18612
18613Object.defineProperty(exports, "__esModule", {
18614 value: true
18615});
18616exports.default = void 0;
18617
18618var _rng = _interopRequireDefault(_dereq_("./rng.js"));
18619
18620var _stringify = _interopRequireDefault(_dereq_("./stringify.js"));
18621
18622function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18623
18624function v4(options, buf, offset) {
18625 options = options || {};
18626
18627 const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
18628
18629
18630 rnds[6] = rnds[6] & 0x0f | 0x40;
18631 rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
18632
18633 if (buf) {
18634 offset = offset || 0;
18635
18636 for (let i = 0; i < 16; ++i) {
18637 buf[offset + i] = rnds[i];
18638 }
18639
18640 return buf;
18641 }
18642
18643 return (0, _stringify.default)(rnds);
18644}
18645
18646var _default = v4;
18647exports.default = _default;
18648},{"./rng.js":151,"./stringify.js":153}],158:[function(_dereq_,module,exports){
18649"use strict";
18650
18651Object.defineProperty(exports, "__esModule", {
18652 value: true
18653});
18654exports.default = void 0;
18655
18656var _v = _interopRequireDefault(_dereq_("./v35.js"));
18657
18658var _sha = _interopRequireDefault(_dereq_("./sha1.js"));
18659
18660function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18661
18662const v5 = (0, _v.default)('v5', 0x50, _sha.default);
18663var _default = v5;
18664exports.default = _default;
18665},{"./sha1.js":152,"./v35.js":156}],159:[function(_dereq_,module,exports){
18666"use strict";
18667
18668Object.defineProperty(exports, "__esModule", {
18669 value: true
18670});
18671exports.default = void 0;
18672
18673var _regex = _interopRequireDefault(_dereq_("./regex.js"));
18674
18675function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18676
18677function validate(uuid) {
18678 return typeof uuid === 'string' && _regex.default.test(uuid);
18679}
18680
18681var _default = validate;
18682exports.default = _default;
18683},{"./regex.js":150}],160:[function(_dereq_,module,exports){
18684"use strict";
18685
18686Object.defineProperty(exports, "__esModule", {
18687 value: true
18688});
18689exports.default = void 0;
18690
18691var _validate = _interopRequireDefault(_dereq_("./validate.js"));
18692
18693function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18694
18695function version(uuid) {
18696 if (!(0, _validate.default)(uuid)) {
18697 throw TypeError('Invalid UUID');
18698 }
18699
18700 return parseInt(uuid.substr(14, 1), 16);
18701}
18702
18703var _default = version;
18704exports.default = _default;
18705},{"./validate.js":159}],161:[function(_dereq_,module,exports){
18706'use strict';
18707
18708/**
18709 * Stringify/parse functions that don't operate
18710 * recursively, so they avoid call stack exceeded
18711 * errors.
18712 */
18713exports.stringify = function stringify(input) {
18714 var queue = [];
18715 queue.push({obj: input});
18716
18717 var res = '';
18718 var next, obj, prefix, val, i, arrayPrefix, keys, k, key, value, objPrefix;
18719 while ((next = queue.pop())) {
18720 obj = next.obj;
18721 prefix = next.prefix || '';
18722 val = next.val || '';
18723 res += prefix;
18724 if (val) {
18725 res += val;
18726 } else if (typeof obj !== 'object') {
18727 res += typeof obj === 'undefined' ? null : JSON.stringify(obj);
18728 } else if (obj === null) {
18729 res += 'null';
18730 } else if (Array.isArray(obj)) {
18731 queue.push({val: ']'});
18732 for (i = obj.length - 1; i >= 0; i--) {
18733 arrayPrefix = i === 0 ? '' : ',';
18734 queue.push({obj: obj[i], prefix: arrayPrefix});
18735 }
18736 queue.push({val: '['});
18737 } else { // object
18738 keys = [];
18739 for (k in obj) {
18740 if (obj.hasOwnProperty(k)) {
18741 keys.push(k);
18742 }
18743 }
18744 queue.push({val: '}'});
18745 for (i = keys.length - 1; i >= 0; i--) {
18746 key = keys[i];
18747 value = obj[key];
18748 objPrefix = (i > 0 ? ',' : '');
18749 objPrefix += JSON.stringify(key) + ':';
18750 queue.push({obj: value, prefix: objPrefix});
18751 }
18752 queue.push({val: '{'});
18753 }
18754 }
18755 return res;
18756};
18757
18758// Convenience function for the parse function.
18759// This pop function is basically copied from
18760// pouchCollate.parseIndexableString
18761function pop(obj, stack, metaStack) {
18762 var lastMetaElement = metaStack[metaStack.length - 1];
18763 if (obj === lastMetaElement.element) {
18764 // popping a meta-element, e.g. an object whose value is another object
18765 metaStack.pop();
18766 lastMetaElement = metaStack[metaStack.length - 1];
18767 }
18768 var element = lastMetaElement.element;
18769 var lastElementIndex = lastMetaElement.index;
18770 if (Array.isArray(element)) {
18771 element.push(obj);
18772 } else if (lastElementIndex === stack.length - 2) { // obj with key+value
18773 var key = stack.pop();
18774 element[key] = obj;
18775 } else {
18776 stack.push(obj); // obj with key only
18777 }
18778}
18779
18780exports.parse = function (str) {
18781 var stack = [];
18782 var metaStack = []; // stack for arrays and objects
18783 var i = 0;
18784 var collationIndex,parsedNum,numChar;
18785 var parsedString,lastCh,numConsecutiveSlashes,ch;
18786 var arrayElement, objElement;
18787 while (true) {
18788 collationIndex = str[i++];
18789 if (collationIndex === '}' ||
18790 collationIndex === ']' ||
18791 typeof collationIndex === 'undefined') {
18792 if (stack.length === 1) {
18793 return stack.pop();
18794 } else {
18795 pop(stack.pop(), stack, metaStack);
18796 continue;
18797 }
18798 }
18799 switch (collationIndex) {
18800 case ' ':
18801 case '\t':
18802 case '\n':
18803 case ':':
18804 case ',':
18805 break;
18806 case 'n':
18807 i += 3; // 'ull'
18808 pop(null, stack, metaStack);
18809 break;
18810 case 't':
18811 i += 3; // 'rue'
18812 pop(true, stack, metaStack);
18813 break;
18814 case 'f':
18815 i += 4; // 'alse'
18816 pop(false, stack, metaStack);
18817 break;
18818 case '0':
18819 case '1':
18820 case '2':
18821 case '3':
18822 case '4':
18823 case '5':
18824 case '6':
18825 case '7':
18826 case '8':
18827 case '9':
18828 case '-':
18829 parsedNum = '';
18830 i--;
18831 while (true) {
18832 numChar = str[i++];
18833 if (/[\d\.\-e\+]/.test(numChar)) {
18834 parsedNum += numChar;
18835 } else {
18836 i--;
18837 break;
18838 }
18839 }
18840 pop(parseFloat(parsedNum), stack, metaStack);
18841 break;
18842 case '"':
18843 parsedString = '';
18844 lastCh = void 0;
18845 numConsecutiveSlashes = 0;
18846 while (true) {
18847 ch = str[i++];
18848 if (ch !== '"' || (lastCh === '\\' &&
18849 numConsecutiveSlashes % 2 === 1)) {
18850 parsedString += ch;
18851 lastCh = ch;
18852 if (lastCh === '\\') {
18853 numConsecutiveSlashes++;
18854 } else {
18855 numConsecutiveSlashes = 0;
18856 }
18857 } else {
18858 break;
18859 }
18860 }
18861 pop(JSON.parse('"' + parsedString + '"'), stack, metaStack);
18862 break;
18863 case '[':
18864 arrayElement = { element: [], index: stack.length };
18865 stack.push(arrayElement.element);
18866 metaStack.push(arrayElement);
18867 break;
18868 case '{':
18869 objElement = { element: {}, index: stack.length };
18870 stack.push(objElement.element);
18871 metaStack.push(objElement);
18872 break;
18873 default:
18874 throw new Error(
18875 'unexpectedly reached end of input: ' + collationIndex);
18876 }
18877 }
18878};
18879
18880},{}],162:[function(_dereq_,module,exports){
18881module.exports = extend
18882
18883var hasOwnProperty = Object.prototype.hasOwnProperty;
18884
18885function extend() {
18886 var target = {}
18887
18888 for (var i = 0; i < arguments.length; i++) {
18889 var source = arguments[i]
18890
18891 for (var key in source) {
18892 if (hasOwnProperty.call(source, key)) {
18893 target[key] = source[key]
18894 }
18895 }
18896 }
18897
18898 return target
18899}
18900
18901},{}],163:[function(_dereq_,module,exports){
18902module.exports = extend
18903
18904var hasOwnProperty = Object.prototype.hasOwnProperty;
18905
18906function extend(target) {
18907 for (var i = 1; i < arguments.length; i++) {
18908 var source = arguments[i]
18909
18910 for (var key in source) {
18911 if (hasOwnProperty.call(source, key)) {
18912 target[key] = source[key]
18913 }
18914 }
18915 }
18916
18917 return target
18918}
18919
18920},{}],164:[function(_dereq_,module,exports){
18921(function (Buffer){(function (){
18922'use strict';
18923
18924function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
18925
18926var levelup = _interopDefault(_dereq_('levelup'));
18927var ltgt = _interopDefault(_dereq_('ltgt'));
18928var Codec = _interopDefault(_dereq_('level-codec'));
18929var ReadableStreamCore = _interopDefault(_dereq_('readable-stream'));
18930var through2 = _dereq_('through2');
18931var Deque = _interopDefault(_dereq_('double-ended-queue'));
18932var Md5 = _interopDefault(_dereq_('spark-md5'));
18933var EE = _interopDefault(_dereq_('events'));
18934var uuid = _dereq_('uuid');
18935var vuvuzela = _interopDefault(_dereq_('vuvuzela'));
18936var localstoragedown = _interopDefault(_dereq_('localstorage-down'));
18937
18938function isFunction(f) {
18939 return 'function' === typeof f;
18940}
18941
18942function getPrefix(db) {
18943 if (isFunction(db.prefix)) {
18944 return db.prefix();
18945 }
18946 return db;
18947}
18948
18949function clone(_obj) {
18950 var obj = {};
18951 for (var k in _obj) {
18952 obj[k] = _obj[k];
18953 }
18954 return obj;
18955}
18956
18957function nut(db, precodec, codec) {
18958 function encodePrefix(prefix, key, opts1, opts2) {
18959 return precodec.encode([ prefix, codec.encodeKey(key, opts1, opts2 ) ]);
18960 }
18961
18962 function addEncodings(op, prefix) {
18963 if (prefix && prefix.options) {
18964 op.keyEncoding =
18965 op.keyEncoding || prefix.options.keyEncoding;
18966 op.valueEncoding =
18967 op.valueEncoding || prefix.options.valueEncoding;
18968 }
18969 return op;
18970 }
18971
18972 db.open(function () { /* no-op */});
18973
18974 return {
18975 apply: function (ops, opts, cb) {
18976 opts = opts || {};
18977
18978 var batch = [];
18979 var i = -1;
18980 var len = ops.length;
18981
18982 while (++i < len) {
18983 var op = ops[i];
18984 addEncodings(op, op.prefix);
18985 op.prefix = getPrefix(op.prefix);
18986 batch.push({
18987 key: encodePrefix(op.prefix, op.key, opts, op),
18988 value: op.type !== 'del' && codec.encodeValue(op.value, opts, op),
18989 type: op.type
18990 });
18991 }
18992 db.db.batch(batch, opts, cb);
18993 },
18994 get: function (key, prefix, opts, cb) {
18995 opts.asBuffer = codec.valueAsBuffer(opts);
18996 return db.db.get(
18997 encodePrefix(prefix, key, opts),
18998 opts,
18999 function (err, value) {
19000 if (err) {
19001 cb(err);
19002 } else {
19003 cb(null, codec.decodeValue(value, opts));
19004 }
19005 }
19006 );
19007 },
19008 createDecoder: function (opts) {
19009 return function (key, value) {
19010 return {
19011 key: codec.decodeKey(precodec.decode(key)[1], opts),
19012 value: codec.decodeValue(value, opts)
19013 };
19014 };
19015 },
19016 isClosed: function isClosed() {
19017 return db.isClosed();
19018 },
19019 close: function close(cb) {
19020 return db.close(cb);
19021 },
19022 iterator: function (_opts) {
19023 var opts = clone(_opts || {});
19024 var prefix = _opts.prefix || [];
19025
19026 function encodeKey(key) {
19027 return encodePrefix(prefix, key, opts, {});
19028 }
19029
19030 ltgt.toLtgt(_opts, opts, encodeKey, precodec.lowerBound, precodec.upperBound);
19031
19032 // if these legacy values are in the options, remove them
19033
19034 opts.prefix = null;
19035
19036 //************************************************
19037 //hard coded defaults, for now...
19038 //TODO: pull defaults and encoding out of levelup.
19039 opts.keyAsBuffer = opts.valueAsBuffer = false;
19040 //************************************************
19041
19042
19043 //this is vital, otherwise limit: undefined will
19044 //create an empty stream.
19045 /* istanbul ignore next */
19046 if ('number' !== typeof opts.limit) {
19047 opts.limit = -1;
19048 }
19049
19050 opts.keyAsBuffer = precodec.buffer;
19051 opts.valueAsBuffer = codec.valueAsBuffer(opts);
19052
19053 function wrapIterator(iterator) {
19054 return {
19055 next: function (cb) {
19056 return iterator.next(cb);
19057 },
19058 end: function (cb) {
19059 iterator.end(cb);
19060 }
19061 };
19062 }
19063
19064 return wrapIterator(db.db.iterator(opts));
19065 }
19066 };
19067}
19068
19069class NotFoundError extends Error {
19070 constructor() {
19071 super();
19072 this.name = 'NotFoundError';
19073 }
19074}
19075
19076var EventEmitter = EE.EventEmitter;
19077var version = "6.5.4";
19078
19079var NOT_FOUND_ERROR = new NotFoundError();
19080
19081var sublevel = function (nut, prefix, createStream, options) {
19082 var emitter = new EventEmitter();
19083 emitter.sublevels = {};
19084 emitter.options = options;
19085
19086 emitter.version = version;
19087
19088 emitter.methods = {};
19089 prefix = prefix || [];
19090
19091 function mergeOpts(opts) {
19092 var o = {};
19093 var k;
19094 if (options) {
19095 for (k in options) {
19096 if (typeof options[k] !== 'undefined') {
19097 o[k] = options[k];
19098 }
19099 }
19100 }
19101 if (opts) {
19102 for (k in opts) {
19103 if (typeof opts[k] !== 'undefined') {
19104 o[k] = opts[k];
19105 }
19106 }
19107 }
19108 return o;
19109 }
19110
19111 emitter.put = function (key, value, opts, cb) {
19112 if ('function' === typeof opts) {
19113 cb = opts;
19114 opts = {};
19115 }
19116
19117 nut.apply([{
19118 key, value,
19119 prefix: prefix.slice(), type: 'put'
19120 }], mergeOpts(opts), function (err) {
19121 /* istanbul ignore next */
19122 if (err) {
19123 return cb(err);
19124 }
19125 emitter.emit('put', key, value);
19126 cb(null);
19127 });
19128 };
19129
19130 emitter.prefix = function () {
19131 return prefix.slice();
19132 };
19133
19134 emitter.batch = function (ops, opts, cb) {
19135 if ('function' === typeof opts) {
19136 cb = opts;
19137 opts = {};
19138 }
19139
19140 ops = ops.map(function (op) {
19141 return {
19142 key: op.key,
19143 value: op.value,
19144 prefix: op.prefix || prefix,
19145 keyEncoding: op.keyEncoding, // *
19146 valueEncoding: op.valueEncoding, // * (TODO: encodings on sublevel)
19147 type: op.type
19148 };
19149 });
19150
19151 nut.apply(ops, mergeOpts(opts), function (err) {
19152 /* istanbul ignore next */
19153 if (err) {
19154 return cb(err);
19155 }
19156 emitter.emit('batch', ops);
19157 cb(null);
19158 });
19159 };
19160
19161 emitter.get = function (key, opts, cb) {
19162 /* istanbul ignore else */
19163 if ('function' === typeof opts) {
19164 cb = opts;
19165 opts = {};
19166 }
19167 nut.get(key, prefix, mergeOpts(opts), function (err, value) {
19168 if (err) {
19169 cb(NOT_FOUND_ERROR);
19170 } else {
19171 cb(null, value);
19172 }
19173 });
19174 };
19175
19176 emitter.sublevel = function (name, opts) {
19177 return emitter.sublevels[name] =
19178 emitter.sublevels[name] || sublevel(nut, prefix.concat(name), createStream, mergeOpts(opts));
19179 };
19180
19181 emitter.readStream = emitter.createReadStream = function (opts) {
19182 opts = mergeOpts(opts);
19183 opts.prefix = prefix;
19184 var stream;
19185 var it = nut.iterator(opts);
19186
19187 stream = createStream(opts, nut.createDecoder(opts));
19188 stream.setIterator(it);
19189
19190 return stream;
19191 };
19192
19193 emitter.close = function (cb) {
19194 nut.close(cb);
19195 };
19196
19197 emitter.isOpen = nut.isOpen;
19198 emitter.isClosed = nut.isClosed;
19199
19200 return emitter;
19201};
19202
19203/* Copyright (c) 2012-2014 LevelUP contributors
19204 * See list at <https://github.com/rvagg/node-levelup#contributing>
19205 * MIT License <https://github.com/rvagg/node-levelup/blob/master/LICENSE.md>
19206 */
19207
19208var Readable = ReadableStreamCore.Readable;
19209
19210function createClass(parent, init) {
19211 let klass = function (...args) {
19212 if (!(this instanceof klass)) {
19213 return new klass(...args);
19214 }
19215 init.apply(this, args);
19216 };
19217 klass.prototype = Object.create(parent.prototype, {
19218 constructor: { value: klass }
19219 });
19220 return klass;
19221}
19222
19223class ReadStreamInternal extends Readable {
19224 constructor(options, makeData) {
19225 super({ objectMode: true, highWaterMark: options.highWaterMark });
19226 this._setup(options, makeData);
19227 }
19228
19229 _setup(options, makeData) {
19230 super.constructor({ objectMode: true, highWaterMark: options.highWaterMark });
19231
19232 // purely to keep `db` around until we're done so it's not GCed if the user doesn't keep a ref
19233 this._waiting = false;
19234 this._options = options;
19235 this._makeData = makeData;
19236 }
19237
19238 setIterator(it) {
19239 this._iterator = it;
19240 /* istanbul ignore if */
19241 if (this._destroyed) {
19242 return it.end(function () {});
19243 }
19244 /* istanbul ignore if */
19245 if (this._waiting) {
19246 this._waiting = false;
19247 return this._read();
19248 }
19249 return this;
19250 }
19251
19252 _cleanup(err) {
19253 if (this._destroyed) {
19254 return;
19255 }
19256
19257 this._destroyed = true;
19258
19259 var self = this;
19260 /* istanbul ignore if */
19261 if (err && err.message !== 'iterator has ended') {
19262 self.emit('error', err);
19263 }
19264
19265 /* istanbul ignore else */
19266 if (self._iterator) {
19267 self._iterator.end(function () {
19268 self._iterator = null;
19269 self.emit('close');
19270 });
19271 } else {
19272 self.emit('close');
19273 }
19274 }
19275
19276 destroy() {
19277 this._cleanup();
19278 }
19279
19280 _read() {
19281 var self = this;
19282 /* istanbul ignore if */
19283 if (self._destroyed) {
19284 return;
19285 }
19286 /* istanbul ignore if */
19287 if (!self._iterator) {
19288 return this._waiting = true;
19289 }
19290
19291 self._iterator.next(function (err, key, value) {
19292 if (err || (key === undefined && value === undefined)) {
19293 if (!err && !self._destroyed) {
19294 self.push(null);
19295 }
19296 return self._cleanup(err);
19297 }
19298
19299
19300 value = self._makeData(key, value);
19301 if (!self._destroyed) {
19302 self.push(value);
19303 }
19304 });
19305 }
19306}
19307
19308const ReadStream = createClass(ReadStreamInternal, function (options, makeData) {
19309 ReadStreamInternal.prototype._setup.call(this, options, makeData);
19310});
19311
19312var precodec = {
19313 encode: function (decodedKey) {
19314 return '\xff' + decodedKey[0] + '\xff' + decodedKey[1];
19315 },
19316 decode: function (encodedKeyAsBuffer) {
19317 var str = encodedKeyAsBuffer.toString();
19318 var idx = str.indexOf('\xff', 1);
19319 return [str.substring(1, idx), str.substring(idx + 1)];
19320 },
19321 lowerBound: '\x00',
19322 upperBound: '\xff'
19323};
19324
19325var codec = new Codec();
19326
19327function sublevelPouch(db) {
19328 return sublevel(nut(db, precodec, codec), [], ReadStream, db.options);
19329}
19330
19331function isBinaryObject(object) {
19332 return (typeof ArrayBuffer !== 'undefined' && object instanceof ArrayBuffer) ||
19333 (typeof Blob !== 'undefined' && object instanceof Blob);
19334}
19335
19336/**
19337 * @template {ArrayBuffer | Blob} T
19338 * @param {T} object
19339 * @returns {T}
19340 */
19341function cloneBinaryObject(object) {
19342 return object instanceof ArrayBuffer
19343 ? object.slice(0)
19344 : object.slice(0, object.size, object.type);
19345}
19346
19347// most of this is borrowed from lodash.isPlainObject:
19348// https://github.com/fis-components/lodash.isplainobject/
19349// blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js
19350
19351var funcToString = Function.prototype.toString;
19352var objectCtorString = funcToString.call(Object);
19353
19354function isPlainObject(value) {
19355 var proto = Object.getPrototypeOf(value);
19356 /* istanbul ignore if */
19357 if (proto === null) { // not sure when this happens, but I guess it can
19358 return true;
19359 }
19360 var Ctor = proto.constructor;
19361 return (typeof Ctor == 'function' &&
19362 Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
19363}
19364
19365function clone$1(object) {
19366 var newObject;
19367 var i;
19368 var len;
19369
19370 if (!object || typeof object !== 'object') {
19371 return object;
19372 }
19373
19374 if (Array.isArray(object)) {
19375 newObject = [];
19376 for (i = 0, len = object.length; i < len; i++) {
19377 newObject[i] = clone$1(object[i]);
19378 }
19379 return newObject;
19380 }
19381
19382 // special case: to avoid inconsistencies between IndexedDB
19383 // and other backends, we automatically stringify Dates
19384 if (object instanceof Date && isFinite(object)) {
19385 return object.toISOString();
19386 }
19387
19388 if (isBinaryObject(object)) {
19389 return cloneBinaryObject(object);
19390 }
19391
19392 if (!isPlainObject(object)) {
19393 return object; // don't clone objects like Workers
19394 }
19395
19396 newObject = {};
19397 for (i in object) {
19398 /* istanbul ignore else */
19399 if (Object.prototype.hasOwnProperty.call(object, i)) {
19400 var value = clone$1(object[i]);
19401 if (typeof value !== 'undefined') {
19402 newObject[i] = value;
19403 }
19404 }
19405 }
19406 return newObject;
19407}
19408
19409function once(fun) {
19410 var called = false;
19411 return function (...args) {
19412 /* istanbul ignore if */
19413 if (called) {
19414 // this is a smoke test and should never actually happen
19415 throw new Error('once called more than once');
19416 } else {
19417 called = true;
19418 fun.apply(this, args);
19419 }
19420 };
19421}
19422
19423function toPromise(func) {
19424 //create the function we will be returning
19425 return function (...args) {
19426 // Clone arguments
19427 args = clone$1(args);
19428 var self = this;
19429 // if the last argument is a function, assume its a callback
19430 var usedCB = (typeof args[args.length - 1] === 'function') ? args.pop() : false;
19431 var promise = new Promise(function (fulfill, reject) {
19432 var resp;
19433 try {
19434 var callback = once(function (err, mesg) {
19435 if (err) {
19436 reject(err);
19437 } else {
19438 fulfill(mesg);
19439 }
19440 });
19441 // create a callback for this invocation
19442 // apply the function in the orig context
19443 args.push(callback);
19444 resp = func.apply(self, args);
19445 if (resp && typeof resp.then === 'function') {
19446 fulfill(resp);
19447 }
19448 } catch (e) {
19449 reject(e);
19450 }
19451 });
19452 // if there is a callback, call it back
19453 if (usedCB) {
19454 promise.then(function (result) {
19455 usedCB(null, result);
19456 }, usedCB);
19457 }
19458 return promise;
19459 };
19460}
19461
19462function logApiCall(self, name, args) {
19463 /* istanbul ignore if */
19464 if (self.constructor.listeners('debug').length) {
19465 var logArgs = ['api', self.name, name];
19466 for (var i = 0; i < args.length - 1; i++) {
19467 logArgs.push(args[i]);
19468 }
19469 self.constructor.emit('debug', logArgs);
19470
19471 // override the callback itself to log the response
19472 var origCallback = args[args.length - 1];
19473 args[args.length - 1] = function (err, res) {
19474 var responseArgs = ['api', self.name, name];
19475 responseArgs = responseArgs.concat(
19476 err ? ['error', err] : ['success', res]
19477 );
19478 self.constructor.emit('debug', responseArgs);
19479 origCallback(err, res);
19480 };
19481 }
19482}
19483
19484function adapterFun(name, callback) {
19485 return toPromise(function (...args) {
19486 if (this._closed) {
19487 return Promise.reject(new Error('database is closed'));
19488 }
19489 if (this._destroyed) {
19490 return Promise.reject(new Error('database is destroyed'));
19491 }
19492 var self = this;
19493 logApiCall(self, name, args);
19494 if (!this.taskqueue.isReady) {
19495 return new Promise(function (fulfill, reject) {
19496 self.taskqueue.addTask(function (failed) {
19497 if (failed) {
19498 reject(failed);
19499 } else {
19500 fulfill(self[name].apply(self, args));
19501 }
19502 });
19503 });
19504 }
19505 return callback.apply(this, args);
19506 });
19507}
19508
19509// like underscore/lodash _.pick()
19510function pick(obj, arr) {
19511 var res = {};
19512 for (var i = 0, len = arr.length; i < len; i++) {
19513 var prop = arr[i];
19514 if (prop in obj) {
19515 res[prop] = obj[prop];
19516 }
19517 }
19518 return res;
19519}
19520
19521// Most browsers throttle concurrent requests at 6, so it's silly
19522// to shim _bulk_get by trying to launch potentially hundreds of requests
19523// and then letting the majority time out. We can handle this ourselves.
19524var MAX_NUM_CONCURRENT_REQUESTS = 6;
19525
19526function identityFunction(x) {
19527 return x;
19528}
19529
19530function formatResultForOpenRevsGet(result) {
19531 return [{
19532 ok: result
19533 }];
19534}
19535
19536// shim for P/CouchDB adapters that don't directly implement _bulk_get
19537function bulkGet(db, opts, callback) {
19538 var requests = opts.docs;
19539
19540 // consolidate into one request per doc if possible
19541 var requestsById = new Map();
19542 requests.forEach(function (request) {
19543 if (requestsById.has(request.id)) {
19544 requestsById.get(request.id).push(request);
19545 } else {
19546 requestsById.set(request.id, [request]);
19547 }
19548 });
19549
19550 var numDocs = requestsById.size;
19551 var numDone = 0;
19552 var perDocResults = new Array(numDocs);
19553
19554 function collapseResultsAndFinish() {
19555 var results = [];
19556 perDocResults.forEach(function (res) {
19557 res.docs.forEach(function (info) {
19558 results.push({
19559 id: res.id,
19560 docs: [info]
19561 });
19562 });
19563 });
19564 callback(null, {results});
19565 }
19566
19567 function checkDone() {
19568 if (++numDone === numDocs) {
19569 collapseResultsAndFinish();
19570 }
19571 }
19572
19573 function gotResult(docIndex, id, docs) {
19574 perDocResults[docIndex] = {id, docs};
19575 checkDone();
19576 }
19577
19578 var allRequests = [];
19579 requestsById.forEach(function (value, key) {
19580 allRequests.push(key);
19581 });
19582
19583 var i = 0;
19584
19585 function nextBatch() {
19586
19587 if (i >= allRequests.length) {
19588 return;
19589 }
19590
19591 var upTo = Math.min(i + MAX_NUM_CONCURRENT_REQUESTS, allRequests.length);
19592 var batch = allRequests.slice(i, upTo);
19593 processBatch(batch, i);
19594 i += batch.length;
19595 }
19596
19597 function processBatch(batch, offset) {
19598 batch.forEach(function (docId, j) {
19599 var docIdx = offset + j;
19600 var docRequests = requestsById.get(docId);
19601
19602 // just use the first request as the "template"
19603 // TODO: The _bulk_get API allows for more subtle use cases than this,
19604 // but for now it is unlikely that there will be a mix of different
19605 // "atts_since" or "attachments" in the same request, since it's just
19606 // replicate.js that is using this for the moment.
19607 // Also, atts_since is aspirational, since we don't support it yet.
19608 var docOpts = pick(docRequests[0], ['atts_since', 'attachments']);
19609 docOpts.open_revs = docRequests.map(function (request) {
19610 // rev is optional, open_revs disallowed
19611 return request.rev;
19612 });
19613
19614 // remove falsey / undefined revisions
19615 docOpts.open_revs = docOpts.open_revs.filter(identityFunction);
19616
19617 var formatResult = identityFunction;
19618
19619 if (docOpts.open_revs.length === 0) {
19620 delete docOpts.open_revs;
19621
19622 // when fetching only the "winning" leaf,
19623 // transform the result so it looks like an open_revs
19624 // request
19625 formatResult = formatResultForOpenRevsGet;
19626 }
19627
19628 // globally-supplied options
19629 ['revs', 'attachments', 'binary', 'ajax', 'latest'].forEach(function (param) {
19630 if (param in opts) {
19631 docOpts[param] = opts[param];
19632 }
19633 });
19634 db.get(docId, docOpts, function (err, res) {
19635 var result;
19636 /* istanbul ignore if */
19637 if (err) {
19638 result = [{error: err}];
19639 } else {
19640 result = formatResult(res);
19641 }
19642 gotResult(docIdx, docId, result);
19643 nextBatch();
19644 });
19645 });
19646 }
19647
19648 nextBatch();
19649
19650}
19651
19652var hasLocal;
19653
19654try {
19655 localStorage.setItem('_pouch_check_localstorage', 1);
19656 hasLocal = !!localStorage.getItem('_pouch_check_localstorage');
19657} catch (e) {
19658 hasLocal = false;
19659}
19660
19661function hasLocalStorage() {
19662 return hasLocal;
19663}
19664
19665const nextTick = typeof queueMicrotask === "function"
19666 ? queueMicrotask
19667 : function nextTick(fn) {
19668 Promise.resolve().then(fn);
19669 };
19670
19671class Changes extends EE {
19672 constructor() {
19673 super();
19674
19675 this._listeners = {};
19676
19677 if (hasLocalStorage()) {
19678 addEventListener("storage", (e) => {
19679 this.emit(e.key);
19680 });
19681 }
19682 }
19683
19684 addListener(dbName, id, db, opts) {
19685 if (this._listeners[id]) {
19686 return;
19687 }
19688 var inprogress = false;
19689 var self = this;
19690 function eventFunction() {
19691 if (!self._listeners[id]) {
19692 return;
19693 }
19694 if (inprogress) {
19695 inprogress = 'waiting';
19696 return;
19697 }
19698 inprogress = true;
19699 var changesOpts = pick(opts, [
19700 'style', 'include_docs', 'attachments', 'conflicts', 'filter',
19701 'doc_ids', 'view', 'since', 'query_params', 'binary', 'return_docs'
19702 ]);
19703
19704 function onError() {
19705 inprogress = false;
19706 }
19707
19708 db.changes(changesOpts).on('change', function (c) {
19709 if (c.seq > opts.since && !opts.cancelled) {
19710 opts.since = c.seq;
19711 opts.onChange(c);
19712 }
19713 }).on('complete', function () {
19714 if (inprogress === 'waiting') {
19715 nextTick(eventFunction);
19716 }
19717 inprogress = false;
19718 }).on('error', onError);
19719 }
19720 this._listeners[id] = eventFunction;
19721 this.on(dbName, eventFunction);
19722 }
19723
19724 removeListener(dbName, id) {
19725 if (!(id in this._listeners)) {
19726 return;
19727 }
19728 super.removeListener(dbName, this._listeners[id]);
19729 delete this._listeners[id];
19730 }
19731
19732 notifyLocalWindows(dbName) {
19733 //do a useless change on a storage thing
19734 //in order to get other windows's listeners to activate
19735 if (hasLocalStorage()) {
19736 localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a";
19737 }
19738 }
19739
19740 notify(dbName) {
19741 this.emit(dbName);
19742 this.notifyLocalWindows(dbName);
19743 }
19744}
19745
19746function guardedConsole(method) {
19747 /* istanbul ignore else */
19748 if (typeof console !== 'undefined' && typeof console[method] === 'function') {
19749 var args = Array.prototype.slice.call(arguments, 1);
19750 console[method].apply(console, args);
19751 }
19752}
19753
19754class PouchError extends Error {
19755 constructor(status, error, reason) {
19756 super();
19757 this.status = status;
19758 this.name = error;
19759 this.message = reason;
19760 this.error = true;
19761 }
19762
19763 toString() {
19764 return JSON.stringify({
19765 status: this.status,
19766 name: this.name,
19767 message: this.message,
19768 reason: this.reason
19769 });
19770 }
19771}
19772
19773var UNAUTHORIZED = new PouchError(401, 'unauthorized', "Name or password is incorrect.");
19774var MISSING_BULK_DOCS = new PouchError(400, 'bad_request', "Missing JSON list of 'docs'");
19775var MISSING_DOC = new PouchError(404, 'not_found', 'missing');
19776var REV_CONFLICT = new PouchError(409, 'conflict', 'Document update conflict');
19777var INVALID_ID = new PouchError(400, 'bad_request', '_id field must contain a string');
19778var MISSING_ID = new PouchError(412, 'missing_id', '_id is required for puts');
19779var RESERVED_ID = new PouchError(400, 'bad_request', 'Only reserved document ids may start with underscore.');
19780var NOT_OPEN = new PouchError(412, 'precondition_failed', 'Database not open');
19781var UNKNOWN_ERROR = new PouchError(500, 'unknown_error', 'Database encountered an unknown error');
19782var BAD_ARG = new PouchError(500, 'badarg', 'Some query argument is invalid');
19783var INVALID_REQUEST = new PouchError(400, 'invalid_request', 'Request was invalid');
19784var QUERY_PARSE_ERROR = new PouchError(400, 'query_parse_error', 'Some query parameter is invalid');
19785var DOC_VALIDATION = new PouchError(500, 'doc_validation', 'Bad special document member');
19786var BAD_REQUEST = new PouchError(400, 'bad_request', 'Something wrong with the request');
19787var NOT_AN_OBJECT = new PouchError(400, 'bad_request', 'Document must be a JSON object');
19788var DB_MISSING = new PouchError(404, 'not_found', 'Database not found');
19789var IDB_ERROR = new PouchError(500, 'indexed_db_went_bad', 'unknown');
19790var WSQ_ERROR = new PouchError(500, 'web_sql_went_bad', 'unknown');
19791var LDB_ERROR = new PouchError(500, 'levelDB_went_went_bad', 'unknown');
19792var FORBIDDEN = new PouchError(403, 'forbidden', 'Forbidden by design doc validate_doc_update function');
19793var INVALID_REV = new PouchError(400, 'bad_request', 'Invalid rev format');
19794var FILE_EXISTS = new PouchError(412, 'file_exists', 'The database could not be created, the file already exists.');
19795var MISSING_STUB = new PouchError(412, 'missing_stub', 'A pre-existing attachment stub wasn\'t found');
19796var INVALID_URL = new PouchError(413, 'invalid_url', 'Provided URL is invalid');
19797
19798function createError(error, reason) {
19799 function CustomPouchError(reason) {
19800 // inherit error properties from our parent error manually
19801 // so as to allow proper JSON parsing.
19802 var names = Object.getOwnPropertyNames(error);
19803 for (var i = 0, len = names.length; i < len; i++) {
19804 if (typeof error[names[i]] !== 'function') {
19805 this[names[i]] = error[names[i]];
19806 }
19807 }
19808
19809 if (this.stack === undefined) {
19810 this.stack = (new Error()).stack;
19811 }
19812
19813 if (reason !== undefined) {
19814 this.reason = reason;
19815 }
19816 }
19817 CustomPouchError.prototype = PouchError.prototype;
19818 return new CustomPouchError(reason);
19819}
19820
19821function generateErrorFromResponse(err) {
19822
19823 if (typeof err !== 'object') {
19824 var data = err;
19825 err = UNKNOWN_ERROR;
19826 err.data = data;
19827 }
19828
19829 if ('error' in err && err.error === 'conflict') {
19830 err.name = 'conflict';
19831 err.status = 409;
19832 }
19833
19834 if (!('name' in err)) {
19835 err.name = err.error || 'unknown';
19836 }
19837
19838 if (!('status' in err)) {
19839 err.status = 500;
19840 }
19841
19842 if (!('message' in err)) {
19843 err.message = err.message || err.reason;
19844 }
19845
19846 if (!('stack' in err)) {
19847 err.stack = (new Error()).stack;
19848 }
19849
19850 return err;
19851}
19852
19853function tryFilter(filter, doc, req) {
19854 try {
19855 return !filter(doc, req);
19856 } catch (err) {
19857 var msg = 'Filter function threw: ' + err.toString();
19858 return createError(BAD_REQUEST, msg);
19859 }
19860}
19861
19862function filterChange(opts) {
19863 var req = {};
19864 var hasFilter = opts.filter && typeof opts.filter === 'function';
19865 req.query = opts.query_params;
19866
19867 return function filter(change) {
19868 if (!change.doc) {
19869 // CSG sends events on the changes feed that don't have documents,
19870 // this hack makes a whole lot of existing code robust.
19871 change.doc = {};
19872 }
19873
19874 var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req);
19875
19876 if (typeof filterReturn === 'object') {
19877 return filterReturn;
19878 }
19879
19880 if (filterReturn) {
19881 return false;
19882 }
19883
19884 if (!opts.include_docs) {
19885 delete change.doc;
19886 } else if (!opts.attachments) {
19887 for (var att in change.doc._attachments) {
19888 /* istanbul ignore else */
19889 if (Object.prototype.hasOwnProperty.call(change.doc._attachments, att)) {
19890 change.doc._attachments[att].stub = true;
19891 }
19892 }
19893 }
19894 return true;
19895 };
19896}
19897
19898// shim for Function.prototype.name,
19899// for browsers that don't support it like IE
19900
19901/* istanbul ignore next */
19902function f() {}
19903
19904var hasName = f.name;
19905var res;
19906
19907// We don't run coverage in IE
19908/* istanbul ignore else */
19909if (hasName) {
19910 res = function (fun) {
19911 return fun.name;
19912 };
19913} else {
19914 res = function (fun) {
19915 var match = fun.toString().match(/^\s*function\s*(?:(\S+)\s*)?\(/);
19916 if (match && match[1]) {
19917 return match[1];
19918 }
19919 else {
19920 return '';
19921 }
19922 };
19923}
19924
19925var functionName = res;
19926
19927// Determine id an ID is valid
19928// - invalid IDs begin with an underescore that does not begin '_design' or
19929// '_local'
19930// - any other string value is a valid id
19931// Returns the specific error object for each case
19932function invalidIdError(id) {
19933 var err;
19934 if (!id) {
19935 err = createError(MISSING_ID);
19936 } else if (typeof id !== 'string') {
19937 err = createError(INVALID_ID);
19938 } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {
19939 err = createError(RESERVED_ID);
19940 }
19941 if (err) {
19942 throw err;
19943 }
19944}
19945
19946// Checks if a PouchDB object is "remote" or not. This is
19947
19948function isRemote(db) {
19949 if (typeof db._remote === 'boolean') {
19950 return db._remote;
19951 }
19952 /* istanbul ignore next */
19953 if (typeof db.type === 'function') {
19954 guardedConsole('warn',
19955 'db.type() is deprecated and will be removed in ' +
19956 'a future version of PouchDB');
19957 return db.type() === 'http';
19958 }
19959 /* istanbul ignore next */
19960 return false;
19961}
19962
19963function listenerCount(ee, type) {
19964 return 'listenerCount' in ee ? ee.listenerCount(type) :
19965 EE.listenerCount(ee, type);
19966}
19967
19968function parseDesignDocFunctionName(s) {
19969 if (!s) {
19970 return null;
19971 }
19972 var parts = s.split('/');
19973 if (parts.length === 2) {
19974 return parts;
19975 }
19976 if (parts.length === 1) {
19977 return [s, s];
19978 }
19979 return null;
19980}
19981
19982function normalizeDesignDocFunctionName(s) {
19983 var normalized = parseDesignDocFunctionName(s);
19984 return normalized ? normalized.join('/') : null;
19985}
19986
19987// originally parseUri 1.2.2, now patched by us
19988
19989// Based on https://github.com/alexdavid/scope-eval v0.0.3
19990// (source: https://unpkg.com/scope-eval@0.0.3/scope_eval.js)
19991// This is basically just a wrapper around new Function()
19992
19993function scopeEval(source, scope) {
19994 var keys = [];
19995 var values = [];
19996 for (var key in scope) {
19997 if (Object.prototype.hasOwnProperty.call(scope, key)) {
19998 keys.push(key);
19999 values.push(scope[key]);
20000 }
20001 }
20002 keys.push(source);
20003 return Function.apply(null, keys).apply(null, values);
20004}
20005
20006// this is essentially the "update sugar" function from daleharvey/pouchdb#1388
20007// the diffFun tells us what delta to apply to the doc. it either returns
20008// the doc, or false if it doesn't need to do an update after all
20009function upsert(db, docId, diffFun) {
20010 return db.get(docId)
20011 .catch(function (err) {
20012 /* istanbul ignore next */
20013 if (err.status !== 404) {
20014 throw err;
20015 }
20016 return {};
20017 })
20018 .then(function (doc) {
20019 // the user might change the _rev, so save it for posterity
20020 var docRev = doc._rev;
20021 var newDoc = diffFun(doc);
20022
20023 if (!newDoc) {
20024 // if the diffFun returns falsy, we short-circuit as
20025 // an optimization
20026 return {updated: false, rev: docRev};
20027 }
20028
20029 // users aren't allowed to modify these values,
20030 // so reset them here
20031 newDoc._id = docId;
20032 newDoc._rev = docRev;
20033 return tryAndPut(db, newDoc, diffFun);
20034 });
20035}
20036
20037function tryAndPut(db, doc, diffFun) {
20038 return db.put(doc).then(function (res) {
20039 return {
20040 updated: true,
20041 rev: res.rev
20042 };
20043 }, function (err) {
20044 /* istanbul ignore next */
20045 if (err.status !== 409) {
20046 throw err;
20047 }
20048 return upsert(db, doc._id, diffFun);
20049 });
20050}
20051
20052var thisAtob = function (str) {
20053 return atob(str);
20054};
20055
20056var thisBtoa = function (str) {
20057 return btoa(str);
20058};
20059
20060// Abstracts constructing a Blob object, so it also works in older
20061// browsers that don't support the native Blob constructor (e.g.
20062// old QtWebKit versions, Android < 4.4).
20063function createBlob(parts, properties) {
20064 /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
20065 parts = parts || [];
20066 properties = properties || {};
20067 try {
20068 return new Blob(parts, properties);
20069 } catch (e) {
20070 if (e.name !== "TypeError") {
20071 throw e;
20072 }
20073 var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
20074 typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
20075 typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
20076 WebKitBlobBuilder;
20077 var builder = new Builder();
20078 for (var i = 0; i < parts.length; i += 1) {
20079 builder.append(parts[i]);
20080 }
20081 return builder.getBlob(properties.type);
20082 }
20083}
20084
20085// From http://stackoverflow.com/questions/14967647/ (continues on next line)
20086// encode-decode-image-with-base64-breaks-image (2013-04-21)
20087function binaryStringToArrayBuffer(bin) {
20088 var length = bin.length;
20089 var buf = new ArrayBuffer(length);
20090 var arr = new Uint8Array(buf);
20091 for (var i = 0; i < length; i++) {
20092 arr[i] = bin.charCodeAt(i);
20093 }
20094 return buf;
20095}
20096
20097function binStringToBluffer(binString, type) {
20098 return createBlob([binaryStringToArrayBuffer(binString)], {type});
20099}
20100
20101//Can't find original post, but this is close
20102//http://stackoverflow.com/questions/6965107/ (continues on next line)
20103//converting-between-strings-and-arraybuffers
20104function arrayBufferToBinaryString(buffer) {
20105 var binary = '';
20106 var bytes = new Uint8Array(buffer);
20107 var length = bytes.byteLength;
20108 for (var i = 0; i < length; i++) {
20109 binary += String.fromCharCode(bytes[i]);
20110 }
20111 return binary;
20112}
20113
20114// shim for browsers that don't support it
20115function readAsBinaryString(blob, callback) {
20116 var reader = new FileReader();
20117 var hasBinaryString = typeof reader.readAsBinaryString === 'function';
20118 reader.onloadend = function (e) {
20119 var result = e.target.result || '';
20120 if (hasBinaryString) {
20121 return callback(result);
20122 }
20123 callback(arrayBufferToBinaryString(result));
20124 };
20125 if (hasBinaryString) {
20126 reader.readAsBinaryString(blob);
20127 } else {
20128 reader.readAsArrayBuffer(blob);
20129 }
20130}
20131
20132// simplified API. universal browser support is assumed
20133function readAsArrayBuffer(blob, callback) {
20134 var reader = new FileReader();
20135 reader.onloadend = function (e) {
20136 var result = e.target.result || new ArrayBuffer(0);
20137 callback(result);
20138 };
20139 reader.readAsArrayBuffer(blob);
20140}
20141
20142// this is not used in the browser
20143
20144var setImmediateShim = self.setImmediate || self.setTimeout;
20145var MD5_CHUNK_SIZE = 32768;
20146
20147function rawToBase64(raw) {
20148 return thisBtoa(raw);
20149}
20150
20151function appendBlob(buffer, blob, start, end, callback) {
20152 if (start > 0 || end < blob.size) {
20153 // only slice blob if we really need to
20154 blob = blob.slice(start, end);
20155 }
20156 readAsArrayBuffer(blob, function (arrayBuffer) {
20157 buffer.append(arrayBuffer);
20158 callback();
20159 });
20160}
20161
20162function appendString(buffer, string, start, end, callback) {
20163 if (start > 0 || end < string.length) {
20164 // only create a substring if we really need to
20165 string = string.substring(start, end);
20166 }
20167 buffer.appendBinary(string);
20168 callback();
20169}
20170
20171function binaryMd5(data, callback) {
20172 var inputIsString = typeof data === 'string';
20173 var len = inputIsString ? data.length : data.size;
20174 var chunkSize = Math.min(MD5_CHUNK_SIZE, len);
20175 var chunks = Math.ceil(len / chunkSize);
20176 var currentChunk = 0;
20177 var buffer = inputIsString ? new Md5() : new Md5.ArrayBuffer();
20178
20179 var append = inputIsString ? appendString : appendBlob;
20180
20181 function next() {
20182 setImmediateShim(loadNextChunk);
20183 }
20184
20185 function done() {
20186 var raw = buffer.end(true);
20187 var base64 = rawToBase64(raw);
20188 callback(base64);
20189 buffer.destroy();
20190 }
20191
20192 function loadNextChunk() {
20193 var start = currentChunk * chunkSize;
20194 var end = start + chunkSize;
20195 currentChunk++;
20196 if (currentChunk < chunks) {
20197 append(buffer, data, start, end, next);
20198 } else {
20199 append(buffer, data, start, end, done);
20200 }
20201 }
20202 loadNextChunk();
20203}
20204
20205function stringMd5(string) {
20206 return Md5.hash(string);
20207}
20208
20209/**
20210 * Creates a new revision string that does NOT include the revision height
20211 * For example '56649f1b0506c6ca9fda0746eb0cacdf'
20212 */
20213function rev(doc, deterministic_revs) {
20214 if (!deterministic_revs) {
20215 return uuid.v4().replace(/-/g, '').toLowerCase();
20216 }
20217
20218 var mutateableDoc = Object.assign({}, doc);
20219 delete mutateableDoc._rev_tree;
20220 return stringMd5(JSON.stringify(mutateableDoc));
20221}
20222
20223var uuid$1 = uuid.v4; // mimic old import, only v4 is ever used elsewhere
20224
20225// We fetch all leafs of the revision tree, and sort them based on tree length
20226// and whether they were deleted, undeleted documents with the longest revision
20227// tree (most edits) win
20228// The final sort algorithm is slightly documented in a sidebar here:
20229// http://guide.couchdb.org/draft/conflicts.html
20230function winningRev(metadata) {
20231 var winningId;
20232 var winningPos;
20233 var winningDeleted;
20234 var toVisit = metadata.rev_tree.slice();
20235 var node;
20236 while ((node = toVisit.pop())) {
20237 var tree = node.ids;
20238 var branches = tree[2];
20239 var pos = node.pos;
20240 if (branches.length) { // non-leaf
20241 for (var i = 0, len = branches.length; i < len; i++) {
20242 toVisit.push({pos: pos + 1, ids: branches[i]});
20243 }
20244 continue;
20245 }
20246 var deleted = !!tree[1].deleted;
20247 var id = tree[0];
20248 // sort by deleted, then pos, then id
20249 if (!winningId || (winningDeleted !== deleted ? winningDeleted :
20250 winningPos !== pos ? winningPos < pos : winningId < id)) {
20251 winningId = id;
20252 winningPos = pos;
20253 winningDeleted = deleted;
20254 }
20255 }
20256
20257 return winningPos + '-' + winningId;
20258}
20259
20260// Pretty much all below can be combined into a higher order function to
20261// traverse revisions
20262// The return value from the callback will be passed as context to all
20263// children of that node
20264function traverseRevTree(revs, callback) {
20265 var toVisit = revs.slice();
20266
20267 var node;
20268 while ((node = toVisit.pop())) {
20269 var pos = node.pos;
20270 var tree = node.ids;
20271 var branches = tree[2];
20272 var newCtx =
20273 callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]);
20274 for (var i = 0, len = branches.length; i < len; i++) {
20275 toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx});
20276 }
20277 }
20278}
20279
20280function sortByPos(a, b) {
20281 return a.pos - b.pos;
20282}
20283
20284function collectLeaves(revs) {
20285 var leaves = [];
20286 traverseRevTree(revs, function (isLeaf, pos, id, acc, opts) {
20287 if (isLeaf) {
20288 leaves.push({rev: pos + "-" + id, pos, opts});
20289 }
20290 });
20291 leaves.sort(sortByPos).reverse();
20292 for (var i = 0, len = leaves.length; i < len; i++) {
20293 delete leaves[i].pos;
20294 }
20295 return leaves;
20296}
20297
20298// returns revs of all conflicts that is leaves such that
20299// 1. are not deleted and
20300// 2. are different than winning revision
20301function collectConflicts(metadata) {
20302 var win = winningRev(metadata);
20303 var leaves = collectLeaves(metadata.rev_tree);
20304 var conflicts = [];
20305 for (var i = 0, len = leaves.length; i < len; i++) {
20306 var leaf = leaves[i];
20307 if (leaf.rev !== win && !leaf.opts.deleted) {
20308 conflicts.push(leaf.rev);
20309 }
20310 }
20311 return conflicts;
20312}
20313
20314// compact a tree by marking its non-leafs as missing,
20315// and return a list of revs to delete
20316function compactTree(metadata) {
20317 var revs = [];
20318 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
20319 revHash, ctx, opts) {
20320 if (opts.status === 'available' && !isLeaf) {
20321 revs.push(pos + '-' + revHash);
20322 opts.status = 'missing';
20323 }
20324 });
20325 return revs;
20326}
20327
20328// `findPathToLeaf()` returns an array of revs that goes from the specified
20329// leaf rev to the root of that leaf’s branch.
20330//
20331// eg. for this rev tree:
20332// 1-9692 ▶ 2-37aa ▶ 3-df22 ▶ 4-6e94 ▶ 5-df4a ▶ 6-6a3a ▶ 7-57e5
20333// ┃ ┗━━━━━━▶ 5-8d8c ▶ 6-65e0
20334// ┗━━━━━━▶ 3-43f6 ▶ 4-a3b4
20335//
20336// For a `targetRev` of '7-57e5', `findPathToLeaf()` would return ['7-57e5', '6-6a3a', '5-df4a']
20337// The `revs` argument has the same structure as what `revs_tree` has on e.g.
20338// the IndexedDB representation of the rev tree datastructure. Please refer to
20339// tests/unit/test.purge.js for examples of what these look like.
20340//
20341// This function will throw an error if:
20342// - The requested revision does not exist
20343// - The requested revision is not a leaf
20344function findPathToLeaf(revs, targetRev) {
20345 let path = [];
20346 const toVisit = revs.slice();
20347
20348 let node;
20349 while ((node = toVisit.pop())) {
20350 const { pos, ids: tree } = node;
20351 const rev = `${pos}-${tree[0]}`;
20352 const branches = tree[2];
20353
20354 // just assuming we're already working on the path up towards our desired leaf.
20355 path.push(rev);
20356
20357 // we've reached the leaf of our dreams, so return the computed path.
20358 if (rev === targetRev) {
20359 //…unleeeeess
20360 if (branches.length !== 0) {
20361 throw new Error('The requested revision is not a leaf');
20362 }
20363 return path.reverse();
20364 }
20365
20366 // this is based on the assumption that after we have a leaf (`branches.length == 0`), we handle the next
20367 // branch. this is true for all branches other than the path leading to the winning rev (which is 7-57e5 in
20368 // the example above. i've added a reset condition for branching nodes (`branches.length > 1`) as well.
20369 if (branches.length === 0 || branches.length > 1) {
20370 path = [];
20371 }
20372
20373 // as a next step, we push the branches of this node to `toVisit` for visiting it during the next iteration
20374 for (let i = 0, len = branches.length; i < len; i++) {
20375 toVisit.push({ pos: pos + 1, ids: branches[i] });
20376 }
20377 }
20378 if (path.length === 0) {
20379 throw new Error('The requested revision does not exist');
20380 }
20381 return path.reverse();
20382}
20383
20384// build up a list of all the paths to the leafs in this revision tree
20385function rootToLeaf(revs) {
20386 var paths = [];
20387 var toVisit = revs.slice();
20388 var node;
20389 while ((node = toVisit.pop())) {
20390 var pos = node.pos;
20391 var tree = node.ids;
20392 var id = tree[0];
20393 var opts = tree[1];
20394 var branches = tree[2];
20395 var isLeaf = branches.length === 0;
20396
20397 var history = node.history ? node.history.slice() : [];
20398 history.push({id, opts});
20399 if (isLeaf) {
20400 paths.push({pos: (pos + 1 - history.length), ids: history});
20401 }
20402 for (var i = 0, len = branches.length; i < len; i++) {
20403 toVisit.push({pos: pos + 1, ids: branches[i], history});
20404 }
20405 }
20406 return paths.reverse();
20407}
20408
20409// for a better overview of what this is doing, read:
20410
20411function sortByPos$1(a, b) {
20412 return a.pos - b.pos;
20413}
20414
20415// classic binary search
20416function binarySearch(arr, item, comparator) {
20417 var low = 0;
20418 var high = arr.length;
20419 var mid;
20420 while (low < high) {
20421 mid = (low + high) >>> 1;
20422 if (comparator(arr[mid], item) < 0) {
20423 low = mid + 1;
20424 } else {
20425 high = mid;
20426 }
20427 }
20428 return low;
20429}
20430
20431// assuming the arr is sorted, insert the item in the proper place
20432function insertSorted(arr, item, comparator) {
20433 var idx = binarySearch(arr, item, comparator);
20434 arr.splice(idx, 0, item);
20435}
20436
20437// Turn a path as a flat array into a tree with a single branch.
20438// If any should be stemmed from the beginning of the array, that's passed
20439// in as the second argument
20440function pathToTree(path, numStemmed) {
20441 var root;
20442 var leaf;
20443 for (var i = numStemmed, len = path.length; i < len; i++) {
20444 var node = path[i];
20445 var currentLeaf = [node.id, node.opts, []];
20446 if (leaf) {
20447 leaf[2].push(currentLeaf);
20448 leaf = currentLeaf;
20449 } else {
20450 root = leaf = currentLeaf;
20451 }
20452 }
20453 return root;
20454}
20455
20456// compare the IDs of two trees
20457function compareTree(a, b) {
20458 return a[0] < b[0] ? -1 : 1;
20459}
20460
20461// Merge two trees together
20462// The roots of tree1 and tree2 must be the same revision
20463function mergeTree(in_tree1, in_tree2) {
20464 var queue = [{tree1: in_tree1, tree2: in_tree2}];
20465 var conflicts = false;
20466 while (queue.length > 0) {
20467 var item = queue.pop();
20468 var tree1 = item.tree1;
20469 var tree2 = item.tree2;
20470
20471 if (tree1[1].status || tree2[1].status) {
20472 tree1[1].status =
20473 (tree1[1].status === 'available' ||
20474 tree2[1].status === 'available') ? 'available' : 'missing';
20475 }
20476
20477 for (var i = 0; i < tree2[2].length; i++) {
20478 if (!tree1[2][0]) {
20479 conflicts = 'new_leaf';
20480 tree1[2][0] = tree2[2][i];
20481 continue;
20482 }
20483
20484 var merged = false;
20485 for (var j = 0; j < tree1[2].length; j++) {
20486 if (tree1[2][j][0] === tree2[2][i][0]) {
20487 queue.push({tree1: tree1[2][j], tree2: tree2[2][i]});
20488 merged = true;
20489 }
20490 }
20491 if (!merged) {
20492 conflicts = 'new_branch';
20493 insertSorted(tree1[2], tree2[2][i], compareTree);
20494 }
20495 }
20496 }
20497 return {conflicts, tree: in_tree1};
20498}
20499
20500function doMerge(tree, path, dontExpand) {
20501 var restree = [];
20502 var conflicts = false;
20503 var merged = false;
20504 var res;
20505
20506 if (!tree.length) {
20507 return {tree: [path], conflicts: 'new_leaf'};
20508 }
20509
20510 for (var i = 0, len = tree.length; i < len; i++) {
20511 var branch = tree[i];
20512 if (branch.pos === path.pos && branch.ids[0] === path.ids[0]) {
20513 // Paths start at the same position and have the same root, so they need
20514 // merged
20515 res = mergeTree(branch.ids, path.ids);
20516 restree.push({pos: branch.pos, ids: res.tree});
20517 conflicts = conflicts || res.conflicts;
20518 merged = true;
20519 } else if (dontExpand !== true) {
20520 // The paths start at a different position, take the earliest path and
20521 // traverse up until it as at the same point from root as the path we
20522 // want to merge. If the keys match we return the longer path with the
20523 // other merged After stemming we don't want to expand the trees
20524
20525 var t1 = branch.pos < path.pos ? branch : path;
20526 var t2 = branch.pos < path.pos ? path : branch;
20527 var diff = t2.pos - t1.pos;
20528
20529 var candidateParents = [];
20530
20531 var trees = [];
20532 trees.push({ids: t1.ids, diff, parent: null, parentIdx: null});
20533 while (trees.length > 0) {
20534 var item = trees.pop();
20535 if (item.diff === 0) {
20536 if (item.ids[0] === t2.ids[0]) {
20537 candidateParents.push(item);
20538 }
20539 continue;
20540 }
20541 var elements = item.ids[2];
20542 for (var j = 0, elementsLen = elements.length; j < elementsLen; j++) {
20543 trees.push({
20544 ids: elements[j],
20545 diff: item.diff - 1,
20546 parent: item.ids,
20547 parentIdx: j
20548 });
20549 }
20550 }
20551
20552 var el = candidateParents[0];
20553
20554 if (!el) {
20555 restree.push(branch);
20556 } else {
20557 res = mergeTree(el.ids, t2.ids);
20558 el.parent[2][el.parentIdx] = res.tree;
20559 restree.push({pos: t1.pos, ids: t1.ids});
20560 conflicts = conflicts || res.conflicts;
20561 merged = true;
20562 }
20563 } else {
20564 restree.push(branch);
20565 }
20566 }
20567
20568 // We didnt find
20569 if (!merged) {
20570 restree.push(path);
20571 }
20572
20573 restree.sort(sortByPos$1);
20574
20575 return {
20576 tree: restree,
20577 conflicts: conflicts || 'internal_node'
20578 };
20579}
20580
20581// To ensure we don't grow the revision tree infinitely, we stem old revisions
20582function stem(tree, depth) {
20583 // First we break out the tree into a complete list of root to leaf paths
20584 var paths = rootToLeaf(tree);
20585 var stemmedRevs;
20586
20587 var result;
20588 for (var i = 0, len = paths.length; i < len; i++) {
20589 // Then for each path, we cut off the start of the path based on the
20590 // `depth` to stem to, and generate a new set of flat trees
20591 var path = paths[i];
20592 var stemmed = path.ids;
20593 var node;
20594 if (stemmed.length > depth) {
20595 // only do the stemming work if we actually need to stem
20596 if (!stemmedRevs) {
20597 stemmedRevs = {}; // avoid allocating this object unnecessarily
20598 }
20599 var numStemmed = stemmed.length - depth;
20600 node = {
20601 pos: path.pos + numStemmed,
20602 ids: pathToTree(stemmed, numStemmed)
20603 };
20604
20605 for (var s = 0; s < numStemmed; s++) {
20606 var rev = (path.pos + s) + '-' + stemmed[s].id;
20607 stemmedRevs[rev] = true;
20608 }
20609 } else { // no need to actually stem
20610 node = {
20611 pos: path.pos,
20612 ids: pathToTree(stemmed, 0)
20613 };
20614 }
20615
20616 // Then we remerge all those flat trees together, ensuring that we don't
20617 // connect trees that would go beyond the depth limit
20618 if (result) {
20619 result = doMerge(result, node, true).tree;
20620 } else {
20621 result = [node];
20622 }
20623 }
20624
20625 // this is memory-heavy per Chrome profiler, avoid unless we actually stemmed
20626 if (stemmedRevs) {
20627 traverseRevTree(result, function (isLeaf, pos, revHash) {
20628 // some revisions may have been removed in a branch but not in another
20629 delete stemmedRevs[pos + '-' + revHash];
20630 });
20631 }
20632
20633 return {
20634 tree: result,
20635 revs: stemmedRevs ? Object.keys(stemmedRevs) : []
20636 };
20637}
20638
20639function merge(tree, path, depth) {
20640 var newTree = doMerge(tree, path);
20641 var stemmed = stem(newTree.tree, depth);
20642 return {
20643 tree: stemmed.tree,
20644 stemmedRevs: stemmed.revs,
20645 conflicts: newTree.conflicts
20646 };
20647}
20648
20649// return true if a rev exists in the rev tree, false otherwise
20650function revExists(revs, rev) {
20651 var toVisit = revs.slice();
20652 var splitRev = rev.split('-');
20653 var targetPos = parseInt(splitRev[0], 10);
20654 var targetId = splitRev[1];
20655
20656 var node;
20657 while ((node = toVisit.pop())) {
20658 if (node.pos === targetPos && node.ids[0] === targetId) {
20659 return true;
20660 }
20661 var branches = node.ids[2];
20662 for (var i = 0, len = branches.length; i < len; i++) {
20663 toVisit.push({pos: node.pos + 1, ids: branches[i]});
20664 }
20665 }
20666 return false;
20667}
20668
20669function getTrees(node) {
20670 return node.ids;
20671}
20672
20673// check if a specific revision of a doc has been deleted
20674// - metadata: the metadata object from the doc store
20675// - rev: (optional) the revision to check. defaults to winning revision
20676function isDeleted(metadata, rev) {
20677 if (!rev) {
20678 rev = winningRev(metadata);
20679 }
20680 var id = rev.substring(rev.indexOf('-') + 1);
20681 var toVisit = metadata.rev_tree.map(getTrees);
20682
20683 var tree;
20684 while ((tree = toVisit.pop())) {
20685 if (tree[0] === id) {
20686 return !!tree[1].deleted;
20687 }
20688 toVisit = toVisit.concat(tree[2]);
20689 }
20690}
20691
20692function isLocalId(id) {
20693 return typeof id === 'string' && id.startsWith('_local/');
20694}
20695
20696// returns the current leaf node for a given revision
20697function latest(rev, metadata) {
20698 var toVisit = metadata.rev_tree.slice();
20699 var node;
20700 while ((node = toVisit.pop())) {
20701 var pos = node.pos;
20702 var tree = node.ids;
20703 var id = tree[0];
20704 var opts = tree[1];
20705 var branches = tree[2];
20706 var isLeaf = branches.length === 0;
20707
20708 var history = node.history ? node.history.slice() : [];
20709 history.push({id, pos, opts});
20710
20711 if (isLeaf) {
20712 for (var i = 0, len = history.length; i < len; i++) {
20713 var historyNode = history[i];
20714 var historyRev = historyNode.pos + '-' + historyNode.id;
20715
20716 if (historyRev === rev) {
20717 // return the rev of this leaf
20718 return pos + '-' + id;
20719 }
20720 }
20721 }
20722
20723 for (var j = 0, l = branches.length; j < l; j++) {
20724 toVisit.push({pos: pos + 1, ids: branches[j], history});
20725 }
20726 }
20727
20728 /* istanbul ignore next */
20729 throw new Error('Unable to resolve latest revision for id ' + metadata.id + ', rev ' + rev);
20730}
20731
20732function tryCatchInChangeListener(self, change, pending, lastSeq) {
20733 // isolate try/catches to avoid V8 deoptimizations
20734 try {
20735 self.emit('change', change, pending, lastSeq);
20736 } catch (e) {
20737 guardedConsole('error', 'Error in .on("change", function):', e);
20738 }
20739}
20740
20741function processChange(doc, metadata, opts) {
20742 var changeList = [{rev: doc._rev}];
20743 if (opts.style === 'all_docs') {
20744 changeList = collectLeaves(metadata.rev_tree)
20745 .map(function (x) { return {rev: x.rev}; });
20746 }
20747 var change = {
20748 id: metadata.id,
20749 changes: changeList,
20750 doc
20751 };
20752
20753 if (isDeleted(metadata, doc._rev)) {
20754 change.deleted = true;
20755 }
20756 if (opts.conflicts) {
20757 change.doc._conflicts = collectConflicts(metadata);
20758 if (!change.doc._conflicts.length) {
20759 delete change.doc._conflicts;
20760 }
20761 }
20762 return change;
20763}
20764
20765class Changes$1 extends EE {
20766 constructor(db, opts, callback) {
20767 super();
20768 this.db = db;
20769 opts = opts ? clone$1(opts) : {};
20770 var complete = opts.complete = once((err, resp) => {
20771 if (err) {
20772 if (listenerCount(this, 'error') > 0) {
20773 this.emit('error', err);
20774 }
20775 } else {
20776 this.emit('complete', resp);
20777 }
20778 this.removeAllListeners();
20779 db.removeListener('destroyed', onDestroy);
20780 });
20781 if (callback) {
20782 this.on('complete', function (resp) {
20783 callback(null, resp);
20784 });
20785 this.on('error', callback);
20786 }
20787 const onDestroy = () => {
20788 this.cancel();
20789 };
20790 db.once('destroyed', onDestroy);
20791
20792 opts.onChange = (change, pending, lastSeq) => {
20793 /* istanbul ignore if */
20794 if (this.isCancelled) {
20795 return;
20796 }
20797 tryCatchInChangeListener(this, change, pending, lastSeq);
20798 };
20799
20800 var promise = new Promise(function (fulfill, reject) {
20801 opts.complete = function (err, res) {
20802 if (err) {
20803 reject(err);
20804 } else {
20805 fulfill(res);
20806 }
20807 };
20808 });
20809 this.once('cancel', function () {
20810 db.removeListener('destroyed', onDestroy);
20811 opts.complete(null, {status: 'cancelled'});
20812 });
20813 this.then = promise.then.bind(promise);
20814 this['catch'] = promise['catch'].bind(promise);
20815 this.then(function (result) {
20816 complete(null, result);
20817 }, complete);
20818
20819
20820
20821 if (!db.taskqueue.isReady) {
20822 db.taskqueue.addTask((failed) => {
20823 if (failed) {
20824 opts.complete(failed);
20825 } else if (this.isCancelled) {
20826 this.emit('cancel');
20827 } else {
20828 this.validateChanges(opts);
20829 }
20830 });
20831 } else {
20832 this.validateChanges(opts);
20833 }
20834 }
20835
20836 cancel() {
20837 this.isCancelled = true;
20838 if (this.db.taskqueue.isReady) {
20839 this.emit('cancel');
20840 }
20841 }
20842
20843 validateChanges(opts) {
20844 var callback = opts.complete;
20845
20846 /* istanbul ignore else */
20847 if (PouchDB$1._changesFilterPlugin) {
20848 PouchDB$1._changesFilterPlugin.validate(opts, (err) => {
20849 if (err) {
20850 return callback(err);
20851 }
20852 this.doChanges(opts);
20853 });
20854 } else {
20855 this.doChanges(opts);
20856 }
20857 }
20858
20859 doChanges(opts) {
20860 var callback = opts.complete;
20861
20862 opts = clone$1(opts);
20863 if ('live' in opts && !('continuous' in opts)) {
20864 opts.continuous = opts.live;
20865 }
20866 opts.processChange = processChange;
20867
20868 if (opts.since === 'latest') {
20869 opts.since = 'now';
20870 }
20871 if (!opts.since) {
20872 opts.since = 0;
20873 }
20874 if (opts.since === 'now') {
20875 this.db.info().then((info) => {
20876 /* istanbul ignore if */
20877 if (this.isCancelled) {
20878 callback(null, {status: 'cancelled'});
20879 return;
20880 }
20881 opts.since = info.update_seq;
20882 this.doChanges(opts);
20883 }, callback);
20884 return;
20885 }
20886
20887 /* istanbul ignore else */
20888 if (PouchDB$1._changesFilterPlugin) {
20889 PouchDB$1._changesFilterPlugin.normalize(opts);
20890 if (PouchDB$1._changesFilterPlugin.shouldFilter(this, opts)) {
20891 return PouchDB$1._changesFilterPlugin.filter(this, opts);
20892 }
20893 } else {
20894 ['doc_ids', 'filter', 'selector', 'view'].forEach(function (key) {
20895 if (key in opts) {
20896 guardedConsole('warn',
20897 'The "' + key + '" option was passed in to changes/replicate, ' +
20898 'but pouchdb-changes-filter plugin is not installed, so it ' +
20899 'was ignored. Please install the plugin to enable filtering.'
20900 );
20901 }
20902 });
20903 }
20904
20905 if (!('descending' in opts)) {
20906 opts.descending = false;
20907 }
20908
20909 // 0 and 1 should return 1 document
20910 opts.limit = opts.limit === 0 ? 1 : opts.limit;
20911 opts.complete = callback;
20912 var newPromise = this.db._changes(opts);
20913 /* istanbul ignore else */
20914 if (newPromise && typeof newPromise.cancel === 'function') {
20915 const cancel = this.cancel;
20916 this.cancel = (...args) => {
20917 newPromise.cancel();
20918 cancel.apply(this, args);
20919 };
20920 }
20921 }
20922}
20923
20924/*
20925 * A generic pouch adapter
20926 */
20927
20928// Wrapper for functions that call the bulkdocs api with a single doc,
20929// if the first result is an error, return an error
20930function yankError(callback, docId) {
20931 return function (err, results) {
20932 if (err || (results[0] && results[0].error)) {
20933 err = err || results[0];
20934 err.docId = docId;
20935 callback(err);
20936 } else {
20937 callback(null, results.length ? results[0] : results);
20938 }
20939 };
20940}
20941
20942// clean docs given to us by the user
20943function cleanDocs(docs) {
20944 for (var i = 0; i < docs.length; i++) {
20945 var doc = docs[i];
20946 if (doc._deleted) {
20947 delete doc._attachments; // ignore atts for deleted docs
20948 } else if (doc._attachments) {
20949 // filter out extraneous keys from _attachments
20950 var atts = Object.keys(doc._attachments);
20951 for (var j = 0; j < atts.length; j++) {
20952 var att = atts[j];
20953 doc._attachments[att] = pick(doc._attachments[att],
20954 ['data', 'digest', 'content_type', 'length', 'revpos', 'stub']);
20955 }
20956 }
20957 }
20958}
20959
20960// compare two docs, first by _id then by _rev
20961function compareByIdThenRev(a, b) {
20962 if (a._id === b._id) {
20963 const aStart = a._revisions ? a._revisions.start : 0;
20964 const bStart = b._revisions ? b._revisions.start : 0;
20965 return aStart - bStart;
20966 }
20967 return a._id < b._id ? -1 : 1;
20968}
20969
20970// for every node in a revision tree computes its distance from the closest
20971// leaf
20972function computeHeight(revs) {
20973 var height = {};
20974 var edges = [];
20975 traverseRevTree(revs, function (isLeaf, pos, id, prnt) {
20976 var rev$$1 = pos + "-" + id;
20977 if (isLeaf) {
20978 height[rev$$1] = 0;
20979 }
20980 if (prnt !== undefined) {
20981 edges.push({from: prnt, to: rev$$1});
20982 }
20983 return rev$$1;
20984 });
20985
20986 edges.reverse();
20987 edges.forEach(function (edge) {
20988 if (height[edge.from] === undefined) {
20989 height[edge.from] = 1 + height[edge.to];
20990 } else {
20991 height[edge.from] = Math.min(height[edge.from], 1 + height[edge.to]);
20992 }
20993 });
20994 return height;
20995}
20996
20997function allDocsKeysParse(opts) {
20998 var keys = ('limit' in opts) ?
20999 opts.keys.slice(opts.skip, opts.limit + opts.skip) :
21000 (opts.skip > 0) ? opts.keys.slice(opts.skip) : opts.keys;
21001 opts.keys = keys;
21002 opts.skip = 0;
21003 delete opts.limit;
21004 if (opts.descending) {
21005 keys.reverse();
21006 opts.descending = false;
21007 }
21008}
21009
21010// all compaction is done in a queue, to avoid attaching
21011// too many listeners at once
21012function doNextCompaction(self) {
21013 var task = self._compactionQueue[0];
21014 var opts = task.opts;
21015 var callback = task.callback;
21016 self.get('_local/compaction').catch(function () {
21017 return false;
21018 }).then(function (doc) {
21019 if (doc && doc.last_seq) {
21020 opts.last_seq = doc.last_seq;
21021 }
21022 self._compact(opts, function (err, res) {
21023 /* istanbul ignore if */
21024 if (err) {
21025 callback(err);
21026 } else {
21027 callback(null, res);
21028 }
21029 nextTick(function () {
21030 self._compactionQueue.shift();
21031 if (self._compactionQueue.length) {
21032 doNextCompaction(self);
21033 }
21034 });
21035 });
21036 });
21037}
21038
21039function appendPurgeSeq(db, docId, rev$$1) {
21040 return db.get('_local/purges').then(function (doc) {
21041 const purgeSeq = doc.purgeSeq + 1;
21042 doc.purges.push({
21043 docId,
21044 rev: rev$$1,
21045 purgeSeq,
21046 });
21047 if (doc.purges.length > self.purged_infos_limit) {
21048 doc.purges.splice(0, doc.purges.length - self.purged_infos_limit);
21049 }
21050 doc.purgeSeq = purgeSeq;
21051 return doc;
21052 }).catch(function (err) {
21053 if (err.status !== 404) {
21054 throw err;
21055 }
21056 return {
21057 _id: '_local/purges',
21058 purges: [{
21059 docId,
21060 rev: rev$$1,
21061 purgeSeq: 0,
21062 }],
21063 purgeSeq: 0,
21064 };
21065 }).then(function (doc) {
21066 return db.put(doc);
21067 });
21068}
21069
21070function attachmentNameError(name) {
21071 if (name.charAt(0) === '_') {
21072 return name + ' is not a valid attachment name, attachment ' +
21073 'names cannot start with \'_\'';
21074 }
21075 return false;
21076}
21077
21078function isNotSingleDoc(doc) {
21079 return doc === null || typeof doc !== 'object' || Array.isArray(doc);
21080}
21081
21082const validRevRegex = /^\d+-[^-]*$/;
21083function isValidRev(rev$$1) {
21084 return typeof rev$$1 === 'string' && validRevRegex.test(rev$$1);
21085}
21086
21087class AbstractPouchDB extends EE {
21088 _setup() {
21089 this.post = adapterFun('post', function (doc, opts, callback) {
21090 if (typeof opts === 'function') {
21091 callback = opts;
21092 opts = {};
21093 }
21094 if (isNotSingleDoc(doc)) {
21095 return callback(createError(NOT_AN_OBJECT));
21096 }
21097 this.bulkDocs({docs: [doc]}, opts, yankError(callback, doc._id));
21098 }).bind(this);
21099
21100 this.put = adapterFun('put', function (doc, opts, cb) {
21101 if (typeof opts === 'function') {
21102 cb = opts;
21103 opts = {};
21104 }
21105 if (isNotSingleDoc(doc)) {
21106 return cb(createError(NOT_AN_OBJECT));
21107 }
21108 invalidIdError(doc._id);
21109 if ('_rev' in doc && !isValidRev(doc._rev)) {
21110 return cb(createError(INVALID_REV));
21111 }
21112 if (isLocalId(doc._id) && typeof this._putLocal === 'function') {
21113 if (doc._deleted) {
21114 return this._removeLocal(doc, cb);
21115 } else {
21116 return this._putLocal(doc, cb);
21117 }
21118 }
21119
21120 const putDoc = (next) => {
21121 if (typeof this._put === 'function' && opts.new_edits !== false) {
21122 this._put(doc, opts, next);
21123 } else {
21124 this.bulkDocs({docs: [doc]}, opts, yankError(next, doc._id));
21125 }
21126 };
21127
21128 if (opts.force && doc._rev) {
21129 transformForceOptionToNewEditsOption();
21130 putDoc(function (err) {
21131 var result = err ? null : {ok: true, id: doc._id, rev: doc._rev};
21132 cb(err, result);
21133 });
21134 } else {
21135 putDoc(cb);
21136 }
21137
21138 function transformForceOptionToNewEditsOption() {
21139 var parts = doc._rev.split('-');
21140 var oldRevId = parts[1];
21141 var oldRevNum = parseInt(parts[0], 10);
21142
21143 var newRevNum = oldRevNum + 1;
21144 var newRevId = rev();
21145
21146 doc._revisions = {
21147 start: newRevNum,
21148 ids: [newRevId, oldRevId]
21149 };
21150 doc._rev = newRevNum + '-' + newRevId;
21151 opts.new_edits = false;
21152 }
21153 }).bind(this);
21154
21155 this.putAttachment = adapterFun('putAttachment', function (docId, attachmentId, rev$$1, blob, type) {
21156 var api = this;
21157 if (typeof type === 'function') {
21158 type = blob;
21159 blob = rev$$1;
21160 rev$$1 = null;
21161 }
21162 // Lets fix in https://github.com/pouchdb/pouchdb/issues/3267
21163 /* istanbul ignore if */
21164 if (typeof type === 'undefined') {
21165 type = blob;
21166 blob = rev$$1;
21167 rev$$1 = null;
21168 }
21169 if (!type) {
21170 guardedConsole('warn', 'Attachment', attachmentId, 'on document', docId, 'is missing content_type');
21171 }
21172
21173 function createAttachment(doc) {
21174 var prevrevpos = '_rev' in doc ? parseInt(doc._rev, 10) : 0;
21175 doc._attachments = doc._attachments || {};
21176 doc._attachments[attachmentId] = {
21177 content_type: type,
21178 data: blob,
21179 revpos: ++prevrevpos
21180 };
21181 return api.put(doc);
21182 }
21183
21184 return api.get(docId).then(function (doc) {
21185 if (doc._rev !== rev$$1) {
21186 throw createError(REV_CONFLICT);
21187 }
21188
21189 return createAttachment(doc);
21190 }, function (err) {
21191 // create new doc
21192 /* istanbul ignore else */
21193 if (err.reason === MISSING_DOC.message) {
21194 return createAttachment({_id: docId});
21195 } else {
21196 throw err;
21197 }
21198 });
21199 }).bind(this);
21200
21201 this.removeAttachment = adapterFun('removeAttachment', function (docId, attachmentId, rev$$1, callback) {
21202 this.get(docId, (err, obj) => {
21203 /* istanbul ignore if */
21204 if (err) {
21205 callback(err);
21206 return;
21207 }
21208 if (obj._rev !== rev$$1) {
21209 callback(createError(REV_CONFLICT));
21210 return;
21211 }
21212 /* istanbul ignore if */
21213 if (!obj._attachments) {
21214 return callback();
21215 }
21216 delete obj._attachments[attachmentId];
21217 if (Object.keys(obj._attachments).length === 0) {
21218 delete obj._attachments;
21219 }
21220 this.put(obj, callback);
21221 });
21222 }).bind(this);
21223
21224 this.remove = adapterFun('remove', function (docOrId, optsOrRev, opts, callback) {
21225 var doc;
21226 if (typeof optsOrRev === 'string') {
21227 // id, rev, opts, callback style
21228 doc = {
21229 _id: docOrId,
21230 _rev: optsOrRev
21231 };
21232 if (typeof opts === 'function') {
21233 callback = opts;
21234 opts = {};
21235 }
21236 } else {
21237 // doc, opts, callback style
21238 doc = docOrId;
21239 if (typeof optsOrRev === 'function') {
21240 callback = optsOrRev;
21241 opts = {};
21242 } else {
21243 callback = opts;
21244 opts = optsOrRev;
21245 }
21246 }
21247 opts = opts || {};
21248 opts.was_delete = true;
21249 var newDoc = {_id: doc._id, _rev: (doc._rev || opts.rev)};
21250 newDoc._deleted = true;
21251 if (isLocalId(newDoc._id) && typeof this._removeLocal === 'function') {
21252 return this._removeLocal(doc, callback);
21253 }
21254 this.bulkDocs({docs: [newDoc]}, opts, yankError(callback, newDoc._id));
21255 }).bind(this);
21256
21257 this.revsDiff = adapterFun('revsDiff', function (req, opts, callback) {
21258 if (typeof opts === 'function') {
21259 callback = opts;
21260 opts = {};
21261 }
21262 var ids = Object.keys(req);
21263
21264 if (!ids.length) {
21265 return callback(null, {});
21266 }
21267
21268 var count = 0;
21269 var missing = new Map();
21270
21271 function addToMissing(id, revId) {
21272 if (!missing.has(id)) {
21273 missing.set(id, {missing: []});
21274 }
21275 missing.get(id).missing.push(revId);
21276 }
21277
21278 function processDoc(id, rev_tree) {
21279 // Is this fast enough? Maybe we should switch to a set simulated by a map
21280 var missingForId = req[id].slice(0);
21281 traverseRevTree(rev_tree, function (isLeaf, pos, revHash, ctx,
21282 opts) {
21283 var rev$$1 = pos + '-' + revHash;
21284 var idx = missingForId.indexOf(rev$$1);
21285 if (idx === -1) {
21286 return;
21287 }
21288
21289 missingForId.splice(idx, 1);
21290 /* istanbul ignore if */
21291 if (opts.status !== 'available') {
21292 addToMissing(id, rev$$1);
21293 }
21294 });
21295
21296 // Traversing the tree is synchronous, so now `missingForId` contains
21297 // revisions that were not found in the tree
21298 missingForId.forEach(function (rev$$1) {
21299 addToMissing(id, rev$$1);
21300 });
21301 }
21302
21303 ids.forEach(function (id) {
21304 this._getRevisionTree(id, function (err, rev_tree) {
21305 if (err && err.status === 404 && err.message === 'missing') {
21306 missing.set(id, {missing: req[id]});
21307 } else if (err) {
21308 /* istanbul ignore next */
21309 return callback(err);
21310 } else {
21311 processDoc(id, rev_tree);
21312 }
21313
21314 if (++count === ids.length) {
21315 // convert LazyMap to object
21316 var missingObj = {};
21317 missing.forEach(function (value, key) {
21318 missingObj[key] = value;
21319 });
21320 return callback(null, missingObj);
21321 }
21322 });
21323 }, this);
21324 }).bind(this);
21325
21326 // _bulk_get API for faster replication, as described in
21327 // https://github.com/apache/couchdb-chttpd/pull/33
21328 // At the "abstract" level, it will just run multiple get()s in
21329 // parallel, because this isn't much of a performance cost
21330 // for local databases (except the cost of multiple transactions, which is
21331 // small). The http adapter overrides this in order
21332 // to do a more efficient single HTTP request.
21333 this.bulkGet = adapterFun('bulkGet', function (opts, callback) {
21334 bulkGet(this, opts, callback);
21335 }).bind(this);
21336
21337 // compact one document and fire callback
21338 // by compacting we mean removing all revisions which
21339 // are further from the leaf in revision tree than max_height
21340 this.compactDocument = adapterFun('compactDocument', function (docId, maxHeight, callback) {
21341 this._getRevisionTree(docId, (err, revTree) => {
21342 /* istanbul ignore if */
21343 if (err) {
21344 return callback(err);
21345 }
21346 var height = computeHeight(revTree);
21347 var candidates = [];
21348 var revs = [];
21349 Object.keys(height).forEach(function (rev$$1) {
21350 if (height[rev$$1] > maxHeight) {
21351 candidates.push(rev$$1);
21352 }
21353 });
21354
21355 traverseRevTree(revTree, function (isLeaf, pos, revHash, ctx, opts) {
21356 var rev$$1 = pos + '-' + revHash;
21357 if (opts.status === 'available' && candidates.indexOf(rev$$1) !== -1) {
21358 revs.push(rev$$1);
21359 }
21360 });
21361 this._doCompaction(docId, revs, callback);
21362 });
21363 }).bind(this);
21364
21365 // compact the whole database using single document
21366 // compaction
21367 this.compact = adapterFun('compact', function (opts, callback) {
21368 if (typeof opts === 'function') {
21369 callback = opts;
21370 opts = {};
21371 }
21372
21373 opts = opts || {};
21374
21375 this._compactionQueue = this._compactionQueue || [];
21376 this._compactionQueue.push({opts, callback});
21377 if (this._compactionQueue.length === 1) {
21378 doNextCompaction(this);
21379 }
21380 }).bind(this);
21381
21382 /* Begin api wrappers. Specific functionality to storage belongs in the _[method] */
21383 this.get = adapterFun('get', function (id, opts, cb) {
21384 if (typeof opts === 'function') {
21385 cb = opts;
21386 opts = {};
21387 }
21388 opts = opts || {};
21389 if (typeof id !== 'string') {
21390 return cb(createError(INVALID_ID));
21391 }
21392 if (isLocalId(id) && typeof this._getLocal === 'function') {
21393 return this._getLocal(id, cb);
21394 }
21395 var leaves = [];
21396
21397 const finishOpenRevs = () => {
21398 var result = [];
21399 var count = leaves.length;
21400 /* istanbul ignore if */
21401 if (!count) {
21402 return cb(null, result);
21403 }
21404
21405 // order with open_revs is unspecified
21406 leaves.forEach((leaf) => {
21407 this.get(id, {
21408 rev: leaf,
21409 revs: opts.revs,
21410 latest: opts.latest,
21411 attachments: opts.attachments,
21412 binary: opts.binary
21413 }, function (err, doc) {
21414 if (!err) {
21415 // using latest=true can produce duplicates
21416 var existing;
21417 for (var i = 0, l = result.length; i < l; i++) {
21418 if (result[i].ok && result[i].ok._rev === doc._rev) {
21419 existing = true;
21420 break;
21421 }
21422 }
21423 if (!existing) {
21424 result.push({ok: doc});
21425 }
21426 } else {
21427 result.push({missing: leaf});
21428 }
21429 count--;
21430 if (!count) {
21431 cb(null, result);
21432 }
21433 });
21434 });
21435 };
21436
21437 if (opts.open_revs) {
21438 if (opts.open_revs === "all") {
21439 this._getRevisionTree(id, function (err, rev_tree) {
21440 /* istanbul ignore if */
21441 if (err) {
21442 return cb(err);
21443 }
21444 leaves = collectLeaves(rev_tree).map(function (leaf) {
21445 return leaf.rev;
21446 });
21447 finishOpenRevs();
21448 });
21449 } else {
21450 if (Array.isArray(opts.open_revs)) {
21451 leaves = opts.open_revs;
21452 for (var i = 0; i < leaves.length; i++) {
21453 var l = leaves[i];
21454 // looks like it's the only thing couchdb checks
21455 if (!isValidRev(l)) {
21456 return cb(createError(INVALID_REV));
21457 }
21458 }
21459 finishOpenRevs();
21460 } else {
21461 return cb(createError(UNKNOWN_ERROR, 'function_clause'));
21462 }
21463 }
21464 return; // open_revs does not like other options
21465 }
21466
21467 return this._get(id, opts, (err, result) => {
21468 if (err) {
21469 err.docId = id;
21470 return cb(err);
21471 }
21472
21473 var doc = result.doc;
21474 var metadata = result.metadata;
21475 var ctx = result.ctx;
21476
21477 if (opts.conflicts) {
21478 var conflicts = collectConflicts(metadata);
21479 if (conflicts.length) {
21480 doc._conflicts = conflicts;
21481 }
21482 }
21483
21484 if (isDeleted(metadata, doc._rev)) {
21485 doc._deleted = true;
21486 }
21487
21488 if (opts.revs || opts.revs_info) {
21489 var splittedRev = doc._rev.split('-');
21490 var revNo = parseInt(splittedRev[0], 10);
21491 var revHash = splittedRev[1];
21492
21493 var paths = rootToLeaf(metadata.rev_tree);
21494 var path = null;
21495
21496 for (var i = 0; i < paths.length; i++) {
21497 var currentPath = paths[i];
21498 const hashIndex = currentPath.ids.findIndex(x => x.id === revHash);
21499 var hashFoundAtRevPos = hashIndex === (revNo - 1);
21500
21501 if (hashFoundAtRevPos || (!path && hashIndex !== -1)) {
21502 path = currentPath;
21503 }
21504 }
21505
21506 /* istanbul ignore if */
21507 if (!path) {
21508 err = new Error('invalid rev tree');
21509 err.docId = id;
21510 return cb(err);
21511 }
21512
21513 const pathId = doc._rev.split('-')[1];
21514 const indexOfRev = path.ids.findIndex(x => x.id === pathId) + 1;
21515 var howMany = path.ids.length - indexOfRev;
21516 path.ids.splice(indexOfRev, howMany);
21517 path.ids.reverse();
21518
21519 if (opts.revs) {
21520 doc._revisions = {
21521 start: (path.pos + path.ids.length) - 1,
21522 ids: path.ids.map(function (rev$$1) {
21523 return rev$$1.id;
21524 })
21525 };
21526 }
21527 if (opts.revs_info) {
21528 var pos = path.pos + path.ids.length;
21529 doc._revs_info = path.ids.map(function (rev$$1) {
21530 pos--;
21531 return {
21532 rev: pos + '-' + rev$$1.id,
21533 status: rev$$1.opts.status
21534 };
21535 });
21536 }
21537 }
21538
21539 if (opts.attachments && doc._attachments) {
21540 var attachments = doc._attachments;
21541 var count = Object.keys(attachments).length;
21542 if (count === 0) {
21543 return cb(null, doc);
21544 }
21545 Object.keys(attachments).forEach((key) => {
21546 this._getAttachment(doc._id, key, attachments[key], {
21547 binary: opts.binary,
21548 metadata,
21549 ctx
21550 }, function (err, data) {
21551 var att = doc._attachments[key];
21552 att.data = data;
21553 delete att.stub;
21554 delete att.length;
21555 if (!--count) {
21556 cb(null, doc);
21557 }
21558 });
21559 });
21560 } else {
21561 if (doc._attachments) {
21562 for (var key in doc._attachments) {
21563 /* istanbul ignore else */
21564 if (Object.prototype.hasOwnProperty.call(doc._attachments, key)) {
21565 doc._attachments[key].stub = true;
21566 }
21567 }
21568 }
21569 cb(null, doc);
21570 }
21571 });
21572 }).bind(this);
21573
21574 // TODO: I don't like this, it forces an extra read for every
21575 // attachment read and enforces a confusing api between
21576 // adapter.js and the adapter implementation
21577 this.getAttachment = adapterFun('getAttachment', function (docId, attachmentId, opts, callback) {
21578 if (opts instanceof Function) {
21579 callback = opts;
21580 opts = {};
21581 }
21582 this._get(docId, opts, (err, res) => {
21583 if (err) {
21584 return callback(err);
21585 }
21586 if (res.doc._attachments && res.doc._attachments[attachmentId]) {
21587 opts.ctx = res.ctx;
21588 opts.binary = true;
21589 opts.metadata = res.metadata;
21590 this._getAttachment(docId, attachmentId,
21591 res.doc._attachments[attachmentId], opts, callback);
21592 } else {
21593 return callback(createError(MISSING_DOC));
21594 }
21595 });
21596 }).bind(this);
21597
21598 this.allDocs = adapterFun('allDocs', function (opts, callback) {
21599 if (typeof opts === 'function') {
21600 callback = opts;
21601 opts = {};
21602 }
21603 opts.skip = typeof opts.skip !== 'undefined' ? opts.skip : 0;
21604 if (opts.start_key) {
21605 opts.startkey = opts.start_key;
21606 }
21607 if (opts.end_key) {
21608 opts.endkey = opts.end_key;
21609 }
21610 if ('keys' in opts) {
21611 if (!Array.isArray(opts.keys)) {
21612 return callback(new TypeError('options.keys must be an array'));
21613 }
21614 var incompatibleOpt =
21615 ['startkey', 'endkey', 'key'].filter(function (incompatibleOpt) {
21616 return incompatibleOpt in opts;
21617 })[0];
21618 if (incompatibleOpt) {
21619 callback(createError(QUERY_PARSE_ERROR,
21620 'Query parameter `' + incompatibleOpt +
21621 '` is not compatible with multi-get'
21622 ));
21623 return;
21624 }
21625 if (!isRemote(this)) {
21626 allDocsKeysParse(opts);
21627 if (opts.keys.length === 0) {
21628 return this._allDocs({limit: 0}, callback);
21629 }
21630 }
21631 }
21632
21633 return this._allDocs(opts, callback);
21634 }).bind(this);
21635
21636 this.close = adapterFun('close', function (callback) {
21637 this._closed = true;
21638 this.emit('closed');
21639 return this._close(callback);
21640 }).bind(this);
21641
21642 this.info = adapterFun('info', function (callback) {
21643 this._info((err, info) => {
21644 if (err) {
21645 return callback(err);
21646 }
21647 // assume we know better than the adapter, unless it informs us
21648 info.db_name = info.db_name || this.name;
21649 info.auto_compaction = !!(this.auto_compaction && !isRemote(this));
21650 info.adapter = this.adapter;
21651 callback(null, info);
21652 });
21653 }).bind(this);
21654
21655 this.id = adapterFun('id', function (callback) {
21656 return this._id(callback);
21657 }).bind(this);
21658
21659 this.bulkDocs = adapterFun('bulkDocs', function (req, opts, callback) {
21660 if (typeof opts === 'function') {
21661 callback = opts;
21662 opts = {};
21663 }
21664
21665 opts = opts || {};
21666
21667 if (Array.isArray(req)) {
21668 req = {
21669 docs: req
21670 };
21671 }
21672
21673 if (!req || !req.docs || !Array.isArray(req.docs)) {
21674 return callback(createError(MISSING_BULK_DOCS));
21675 }
21676
21677 for (var i = 0; i < req.docs.length; ++i) {
21678 const doc = req.docs[i];
21679 if (isNotSingleDoc(doc)) {
21680 return callback(createError(NOT_AN_OBJECT));
21681 }
21682 if ('_rev' in doc && !isValidRev(doc._rev)) {
21683 return callback(createError(INVALID_REV));
21684 }
21685 }
21686
21687 var attachmentError;
21688 req.docs.forEach(function (doc) {
21689 if (doc._attachments) {
21690 Object.keys(doc._attachments).forEach(function (name) {
21691 attachmentError = attachmentError || attachmentNameError(name);
21692 if (!doc._attachments[name].content_type) {
21693 guardedConsole('warn', 'Attachment', name, 'on document', doc._id, 'is missing content_type');
21694 }
21695 });
21696 }
21697 });
21698
21699 if (attachmentError) {
21700 return callback(createError(BAD_REQUEST, attachmentError));
21701 }
21702
21703 if (!('new_edits' in opts)) {
21704 if ('new_edits' in req) {
21705 opts.new_edits = req.new_edits;
21706 } else {
21707 opts.new_edits = true;
21708 }
21709 }
21710
21711 var adapter = this;
21712 if (!opts.new_edits && !isRemote(adapter)) {
21713 // ensure revisions of the same doc are sorted, so that
21714 // the local adapter processes them correctly (#2935)
21715 req.docs.sort(compareByIdThenRev);
21716 }
21717
21718 cleanDocs(req.docs);
21719
21720 // in the case of conflicts, we want to return the _ids to the user
21721 // however, the underlying adapter may destroy the docs array, so
21722 // create a copy here
21723 var ids = req.docs.map(function (doc) {
21724 return doc._id;
21725 });
21726
21727 this._bulkDocs(req, opts, function (err, res) {
21728 if (err) {
21729 return callback(err);
21730 }
21731 if (!opts.new_edits) {
21732 // this is what couch does when new_edits is false
21733 res = res.filter(function (x) {
21734 return x.error;
21735 });
21736 }
21737 // add ids for error/conflict responses (not required for CouchDB)
21738 if (!isRemote(adapter)) {
21739 for (var i = 0, l = res.length; i < l; i++) {
21740 res[i].id = res[i].id || ids[i];
21741 }
21742 }
21743
21744 callback(null, res);
21745 });
21746 }).bind(this);
21747
21748 this.registerDependentDatabase = adapterFun('registerDependentDatabase', function (dependentDb, callback) {
21749 var dbOptions = clone$1(this.__opts);
21750 if (this.__opts.view_adapter) {
21751 dbOptions.adapter = this.__opts.view_adapter;
21752 }
21753
21754 var depDB = new this.constructor(dependentDb, dbOptions);
21755
21756 function diffFun(doc) {
21757 doc.dependentDbs = doc.dependentDbs || {};
21758 if (doc.dependentDbs[dependentDb]) {
21759 return false; // no update required
21760 }
21761 doc.dependentDbs[dependentDb] = true;
21762 return doc;
21763 }
21764 upsert(this, '_local/_pouch_dependentDbs', diffFun).then(function () {
21765 callback(null, {db: depDB});
21766 }).catch(callback);
21767 }).bind(this);
21768
21769 this.destroy = adapterFun('destroy', function (opts, callback) {
21770
21771 if (typeof opts === 'function') {
21772 callback = opts;
21773 opts = {};
21774 }
21775
21776 var usePrefix = 'use_prefix' in this ? this.use_prefix : true;
21777
21778 const destroyDb = () => {
21779 // call destroy method of the particular adaptor
21780 this._destroy(opts, (err, resp) => {
21781 if (err) {
21782 return callback(err);
21783 }
21784 this._destroyed = true;
21785 this.emit('destroyed');
21786 callback(null, resp || { 'ok': true });
21787 });
21788 };
21789
21790 if (isRemote(this)) {
21791 // no need to check for dependent DBs if it's a remote DB
21792 return destroyDb();
21793 }
21794
21795 this.get('_local/_pouch_dependentDbs', (err, localDoc) => {
21796 if (err) {
21797 /* istanbul ignore if */
21798 if (err.status !== 404) {
21799 return callback(err);
21800 } else { // no dependencies
21801 return destroyDb();
21802 }
21803 }
21804 var dependentDbs = localDoc.dependentDbs;
21805 var PouchDB = this.constructor;
21806 var deletedMap = Object.keys(dependentDbs).map((name) => {
21807 // use_prefix is only false in the browser
21808 /* istanbul ignore next */
21809 var trueName = usePrefix ?
21810 name.replace(new RegExp('^' + PouchDB.prefix), '') : name;
21811 return new PouchDB(trueName, this.__opts).destroy();
21812 });
21813 Promise.all(deletedMap).then(destroyDb, callback);
21814 });
21815 }).bind(this);
21816 }
21817
21818 _compact(opts, callback) {
21819 var changesOpts = {
21820 return_docs: false,
21821 last_seq: opts.last_seq || 0,
21822 since: opts.last_seq || 0
21823 };
21824 var promises = [];
21825
21826 var taskId;
21827 var compactedDocs = 0;
21828
21829 const onChange = (row) => {
21830 this.activeTasks.update(taskId, {
21831 completed_items: ++compactedDocs
21832 });
21833 promises.push(this.compactDocument(row.id, 0));
21834 };
21835 const onError = (err) => {
21836 this.activeTasks.remove(taskId, err);
21837 callback(err);
21838 };
21839 const onComplete = (resp) => {
21840 var lastSeq = resp.last_seq;
21841 Promise.all(promises).then(() => {
21842 return upsert(this, '_local/compaction', (doc) => {
21843 if (!doc.last_seq || doc.last_seq < lastSeq) {
21844 doc.last_seq = lastSeq;
21845 return doc;
21846 }
21847 return false; // somebody else got here first, don't update
21848 });
21849 }).then(() => {
21850 this.activeTasks.remove(taskId);
21851 callback(null, {ok: true});
21852 }).catch(onError);
21853 };
21854
21855 this.info().then((info) => {
21856 taskId = this.activeTasks.add({
21857 name: 'database_compaction',
21858 total_items: info.update_seq - changesOpts.last_seq,
21859 });
21860
21861 this.changes(changesOpts)
21862 .on('change', onChange)
21863 .on('complete', onComplete)
21864 .on('error', onError);
21865 });
21866 }
21867
21868 changes(opts, callback) {
21869 if (typeof opts === 'function') {
21870 callback = opts;
21871 opts = {};
21872 }
21873
21874 opts = opts || {};
21875
21876 // By default set return_docs to false if the caller has opts.live = true,
21877 // this will prevent us from collecting the set of changes indefinitely
21878 // resulting in growing memory
21879 opts.return_docs = ('return_docs' in opts) ? opts.return_docs : !opts.live;
21880
21881 return new Changes$1(this, opts, callback);
21882 }
21883
21884 type() {
21885 return (typeof this._type === 'function') ? this._type() : this.adapter;
21886 }
21887}
21888
21889// The abstract purge implementation expects a doc id and the rev of a leaf node in that doc.
21890// It will return errors if the rev doesn’t exist or isn’t a leaf.
21891AbstractPouchDB.prototype.purge = adapterFun('_purge', function (docId, rev$$1, callback) {
21892 if (typeof this._purge === 'undefined') {
21893 return callback(createError(UNKNOWN_ERROR, 'Purge is not implemented in the ' + this.adapter + ' adapter.'));
21894 }
21895 var self = this;
21896
21897 self._getRevisionTree(docId, (error, revs) => {
21898 if (error) {
21899 return callback(error);
21900 }
21901 if (!revs) {
21902 return callback(createError(MISSING_DOC));
21903 }
21904 let path;
21905 try {
21906 path = findPathToLeaf(revs, rev$$1);
21907 } catch (error) {
21908 return callback(error.message || error);
21909 }
21910 self._purge(docId, path, (error, result) => {
21911 if (error) {
21912 return callback(error);
21913 } else {
21914 appendPurgeSeq(self, docId, rev$$1).then(function () {
21915 return callback(null, result);
21916 });
21917 }
21918 });
21919 });
21920});
21921
21922class TaskQueue {
21923 constructor() {
21924 this.isReady = false;
21925 this.failed = false;
21926 this.queue = [];
21927 }
21928
21929 execute() {
21930 var fun;
21931 if (this.failed) {
21932 while ((fun = this.queue.shift())) {
21933 fun(this.failed);
21934 }
21935 } else {
21936 while ((fun = this.queue.shift())) {
21937 fun();
21938 }
21939 }
21940 }
21941
21942 fail(err) {
21943 this.failed = err;
21944 this.execute();
21945 }
21946
21947 ready(db) {
21948 this.isReady = true;
21949 this.db = db;
21950 this.execute();
21951 }
21952
21953 addTask(fun) {
21954 this.queue.push(fun);
21955 if (this.failed) {
21956 this.execute();
21957 }
21958 }
21959}
21960
21961function parseAdapter(name, opts) {
21962 var match = name.match(/([a-z-]*):\/\/(.*)/);
21963 if (match) {
21964 // the http adapter expects the fully qualified name
21965 return {
21966 name: /https?/.test(match[1]) ? match[1] + '://' + match[2] : match[2],
21967 adapter: match[1]
21968 };
21969 }
21970
21971 var adapters = PouchDB$1.adapters;
21972 var preferredAdapters = PouchDB$1.preferredAdapters;
21973 var prefix = PouchDB$1.prefix;
21974 var adapterName = opts.adapter;
21975
21976 if (!adapterName) { // automatically determine adapter
21977 for (var i = 0; i < preferredAdapters.length; ++i) {
21978 adapterName = preferredAdapters[i];
21979 // check for browsers that have been upgraded from websql-only to websql+idb
21980 /* istanbul ignore if */
21981 if (adapterName === 'idb' && 'websql' in adapters &&
21982 hasLocalStorage() && localStorage['_pouch__websqldb_' + prefix + name]) {
21983 // log it, because this can be confusing during development
21984 guardedConsole('log', 'PouchDB is downgrading "' + name + '" to WebSQL to' +
21985 ' avoid data loss, because it was already opened with WebSQL.');
21986 continue; // keep using websql to avoid user data loss
21987 }
21988 break;
21989 }
21990 }
21991
21992 var adapter = adapters[adapterName];
21993
21994 // if adapter is invalid, then an error will be thrown later
21995 var usePrefix = (adapter && 'use_prefix' in adapter) ?
21996 adapter.use_prefix : true;
21997
21998 return {
21999 name: usePrefix ? (prefix + name) : name,
22000 adapter: adapterName
22001 };
22002}
22003
22004function inherits(A, B) {
22005 A.prototype = Object.create(B.prototype, {
22006 constructor: { value: A }
22007 });
22008}
22009
22010function createClass$1(parent, init) {
22011 let klass = function (...args) {
22012 if (!(this instanceof klass)) {
22013 return new klass(...args);
22014 }
22015 init.apply(this, args);
22016 };
22017 inherits(klass, parent);
22018 return klass;
22019}
22020
22021// OK, so here's the deal. Consider this code:
22022// var db1 = new PouchDB('foo');
22023// var db2 = new PouchDB('foo');
22024// db1.destroy();
22025// ^ these two both need to emit 'destroyed' events,
22026// as well as the PouchDB constructor itself.
22027// So we have one db object (whichever one got destroy() called on it)
22028// responsible for emitting the initial event, which then gets emitted
22029// by the constructor, which then broadcasts it to any other dbs
22030// that may have been created with the same name.
22031function prepareForDestruction(self) {
22032
22033 function onDestroyed(from_constructor) {
22034 self.removeListener('closed', onClosed);
22035 if (!from_constructor) {
22036 self.constructor.emit('destroyed', self.name);
22037 }
22038 }
22039
22040 function onClosed() {
22041 self.removeListener('destroyed', onDestroyed);
22042 self.constructor.emit('unref', self);
22043 }
22044
22045 self.once('destroyed', onDestroyed);
22046 self.once('closed', onClosed);
22047 self.constructor.emit('ref', self);
22048}
22049
22050class PouchInternal extends AbstractPouchDB {
22051 constructor(name, opts) {
22052 super();
22053 this._setup(name, opts);
22054 }
22055
22056 _setup(name, opts) {
22057 super._setup();
22058 opts = opts || {};
22059
22060 if (name && typeof name === 'object') {
22061 opts = name;
22062 name = opts.name;
22063 delete opts.name;
22064 }
22065
22066 if (opts.deterministic_revs === undefined) {
22067 opts.deterministic_revs = true;
22068 }
22069
22070 this.__opts = opts = clone$1(opts);
22071
22072 this.auto_compaction = opts.auto_compaction;
22073 this.purged_infos_limit = opts.purged_infos_limit || 1000;
22074 this.prefix = PouchDB$1.prefix;
22075
22076 if (typeof name !== 'string') {
22077 throw new Error('Missing/invalid DB name');
22078 }
22079
22080 var prefixedName = (opts.prefix || '') + name;
22081 var backend = parseAdapter(prefixedName, opts);
22082
22083 opts.name = backend.name;
22084 opts.adapter = opts.adapter || backend.adapter;
22085
22086 this.name = name;
22087 this._adapter = opts.adapter;
22088 PouchDB$1.emit('debug', ['adapter', 'Picked adapter: ', opts.adapter]);
22089
22090 if (!PouchDB$1.adapters[opts.adapter] ||
22091 !PouchDB$1.adapters[opts.adapter].valid()) {
22092 throw new Error('Invalid Adapter: ' + opts.adapter);
22093 }
22094
22095 if (opts.view_adapter) {
22096 if (!PouchDB$1.adapters[opts.view_adapter] ||
22097 !PouchDB$1.adapters[opts.view_adapter].valid()) {
22098 throw new Error('Invalid View Adapter: ' + opts.view_adapter);
22099 }
22100 }
22101
22102 this.taskqueue = new TaskQueue();
22103
22104 this.adapter = opts.adapter;
22105
22106 PouchDB$1.adapters[opts.adapter].call(this, opts, (err) => {
22107 if (err) {
22108 return this.taskqueue.fail(err);
22109 }
22110 prepareForDestruction(this);
22111
22112 this.emit('created', this);
22113 PouchDB$1.emit('created', this.name);
22114 this.taskqueue.ready(this);
22115 });
22116 }
22117}
22118
22119const PouchDB$1 = createClass$1(PouchInternal, function (name, opts) {
22120 PouchInternal.prototype._setup.call(this, name, opts);
22121});
22122
22123var f$1 = fetch;
22124
22125class ActiveTasks {
22126 constructor() {
22127 this.tasks = {};
22128 }
22129
22130 list() {
22131 return Object.values(this.tasks);
22132 }
22133
22134 add(task) {
22135 const id = uuid.v4();
22136 this.tasks[id] = {
22137 id,
22138 name: task.name,
22139 total_items: task.total_items,
22140 created_at: new Date().toJSON()
22141 };
22142 return id;
22143 }
22144
22145 get(id) {
22146 return this.tasks[id];
22147 }
22148
22149 /* eslint-disable no-unused-vars */
22150 remove(id, reason) {
22151 delete this.tasks[id];
22152 return this.tasks;
22153 }
22154
22155 update(id, updatedTask) {
22156 const task = this.tasks[id];
22157 if (typeof task !== 'undefined') {
22158 const mergedTask = {
22159 id: task.id,
22160 name: task.name,
22161 created_at: task.created_at,
22162 total_items: updatedTask.total_items || task.total_items,
22163 completed_items: updatedTask.completed_items || task.completed_items,
22164 updated_at: new Date().toJSON()
22165 };
22166 this.tasks[id] = mergedTask;
22167 }
22168 return this.tasks;
22169 }
22170}
22171
22172PouchDB$1.adapters = {};
22173PouchDB$1.preferredAdapters = [];
22174
22175PouchDB$1.prefix = '_pouch_';
22176
22177var eventEmitter = new EE();
22178
22179function setUpEventEmitter(Pouch) {
22180 Object.keys(EE.prototype).forEach(function (key) {
22181 if (typeof EE.prototype[key] === 'function') {
22182 Pouch[key] = eventEmitter[key].bind(eventEmitter);
22183 }
22184 });
22185
22186 // these are created in constructor.js, and allow us to notify each DB with
22187 // the same name that it was destroyed, via the constructor object
22188 var destructListeners = Pouch._destructionListeners = new Map();
22189
22190 Pouch.on('ref', function onConstructorRef(db) {
22191 if (!destructListeners.has(db.name)) {
22192 destructListeners.set(db.name, []);
22193 }
22194 destructListeners.get(db.name).push(db);
22195 });
22196
22197 Pouch.on('unref', function onConstructorUnref(db) {
22198 if (!destructListeners.has(db.name)) {
22199 return;
22200 }
22201 var dbList = destructListeners.get(db.name);
22202 var pos = dbList.indexOf(db);
22203 if (pos < 0) {
22204 /* istanbul ignore next */
22205 return;
22206 }
22207 dbList.splice(pos, 1);
22208 if (dbList.length > 1) {
22209 /* istanbul ignore next */
22210 destructListeners.set(db.name, dbList);
22211 } else {
22212 destructListeners.delete(db.name);
22213 }
22214 });
22215
22216 Pouch.on('destroyed', function onConstructorDestroyed(name) {
22217 if (!destructListeners.has(name)) {
22218 return;
22219 }
22220 var dbList = destructListeners.get(name);
22221 destructListeners.delete(name);
22222 dbList.forEach(function (db) {
22223 db.emit('destroyed',true);
22224 });
22225 });
22226}
22227
22228setUpEventEmitter(PouchDB$1);
22229
22230PouchDB$1.adapter = function (id, obj, addToPreferredAdapters) {
22231 /* istanbul ignore else */
22232 if (obj.valid()) {
22233 PouchDB$1.adapters[id] = obj;
22234 if (addToPreferredAdapters) {
22235 PouchDB$1.preferredAdapters.push(id);
22236 }
22237 }
22238};
22239
22240PouchDB$1.plugin = function (obj) {
22241 if (typeof obj === 'function') { // function style for plugins
22242 obj(PouchDB$1);
22243 } else if (typeof obj !== 'object' || Object.keys(obj).length === 0) {
22244 throw new Error('Invalid plugin: got "' + obj + '", expected an object or a function');
22245 } else {
22246 Object.keys(obj).forEach(function (id) { // object style for plugins
22247 PouchDB$1.prototype[id] = obj[id];
22248 });
22249 }
22250 if (this.__defaults) {
22251 PouchDB$1.__defaults = Object.assign({}, this.__defaults);
22252 }
22253 return PouchDB$1;
22254};
22255
22256PouchDB$1.defaults = function (defaultOpts) {
22257 let PouchWithDefaults = createClass$1(PouchDB$1, function (name, opts) {
22258 opts = opts || {};
22259
22260 if (name && typeof name === 'object') {
22261 opts = name;
22262 name = opts.name;
22263 delete opts.name;
22264 }
22265
22266 opts = Object.assign({}, PouchWithDefaults.__defaults, opts);
22267 PouchDB$1.call(this, name, opts);
22268 });
22269
22270 PouchWithDefaults.preferredAdapters = PouchDB$1.preferredAdapters.slice();
22271 Object.keys(PouchDB$1).forEach(function (key) {
22272 if (!(key in PouchWithDefaults)) {
22273 PouchWithDefaults[key] = PouchDB$1[key];
22274 }
22275 });
22276
22277 // make default options transitive
22278 // https://github.com/pouchdb/pouchdb/issues/5922
22279 PouchWithDefaults.__defaults = Object.assign({}, this.__defaults, defaultOpts);
22280
22281 return PouchWithDefaults;
22282};
22283
22284PouchDB$1.fetch = function (url, opts) {
22285 return f$1(url, opts);
22286};
22287
22288PouchDB$1.prototype.activeTasks = PouchDB$1.activeTasks = new ActiveTasks();
22289
22290// managed automatically by set-version.js
22291var version$1 = "9.0.0";
22292
22293// this would just be "return doc[field]", but fields
22294// can be "deep" due to dot notation
22295function getFieldFromDoc(doc, parsedField) {
22296 var value = doc;
22297 for (var i = 0, len = parsedField.length; i < len; i++) {
22298 var key = parsedField[i];
22299 value = value[key];
22300 if (!value) {
22301 break;
22302 }
22303 }
22304 return value;
22305}
22306
22307function compare(left, right) {
22308 return left < right ? -1 : left > right ? 1 : 0;
22309}
22310
22311// Converts a string in dot notation to an array of its components, with backslash escaping
22312function parseField(fieldName) {
22313 // fields may be deep (e.g. "foo.bar.baz"), so parse
22314 var fields = [];
22315 var current = '';
22316 for (var i = 0, len = fieldName.length; i < len; i++) {
22317 var ch = fieldName[i];
22318 if (i > 0 && fieldName[i - 1] === '\\' && (ch === '$' || ch === '.')) {
22319 // escaped delimiter
22320 current = current.substring(0, current.length - 1) + ch;
22321 } else if (ch === '.') {
22322 // When `.` is not escaped (above), it is a field delimiter
22323 fields.push(current);
22324 current = '';
22325 } else { // normal character
22326 current += ch;
22327 }
22328 }
22329 fields.push(current);
22330 return fields;
22331}
22332
22333var combinationFields = ['$or', '$nor', '$not'];
22334function isCombinationalField(field) {
22335 return combinationFields.indexOf(field) > -1;
22336}
22337
22338function getKey(obj) {
22339 return Object.keys(obj)[0];
22340}
22341
22342function getValue(obj) {
22343 return obj[getKey(obj)];
22344}
22345
22346
22347// flatten an array of selectors joined by an $and operator
22348function mergeAndedSelectors(selectors) {
22349
22350 // sort to ensure that e.g. if the user specified
22351 // $and: [{$gt: 'a'}, {$gt: 'b'}], then it's collapsed into
22352 // just {$gt: 'b'}
22353 var res = {};
22354 var first = {$or: true, $nor: true};
22355
22356 selectors.forEach(function (selector) {
22357 Object.keys(selector).forEach(function (field) {
22358 var matcher = selector[field];
22359 if (typeof matcher !== 'object') {
22360 matcher = {$eq: matcher};
22361 }
22362
22363 if (isCombinationalField(field)) {
22364 // or, nor
22365 if (matcher instanceof Array) {
22366 if (first[field]) {
22367 first[field] = false;
22368 res[field] = matcher;
22369 return;
22370 }
22371
22372 var entries = [];
22373 res[field].forEach(function (existing) {
22374 Object.keys(matcher).forEach(function (key) {
22375 var m = matcher[key];
22376 var longest = Math.max(Object.keys(existing).length, Object.keys(m).length);
22377 var merged = mergeAndedSelectors([existing, m]);
22378 if (Object.keys(merged).length <= longest) {
22379 // we have a situation like: (a :{$eq :1} || ...) && (a {$eq: 2} || ...)
22380 // merging would produce a $eq 2 when actually we shouldn't ever match against these merged conditions
22381 // merged should always contain more values to be valid
22382 return;
22383 }
22384 entries.push(merged);
22385 });
22386 });
22387 res[field] = entries;
22388 } else {
22389 // not
22390 res[field] = mergeAndedSelectors([matcher]);
22391 }
22392 } else {
22393 var fieldMatchers = res[field] = res[field] || {};
22394 Object.keys(matcher).forEach(function (operator) {
22395 var value = matcher[operator];
22396
22397 if (operator === '$gt' || operator === '$gte') {
22398 return mergeGtGte(operator, value, fieldMatchers);
22399 } else if (operator === '$lt' || operator === '$lte') {
22400 return mergeLtLte(operator, value, fieldMatchers);
22401 } else if (operator === '$ne') {
22402 return mergeNe(value, fieldMatchers);
22403 } else if (operator === '$eq') {
22404 return mergeEq(value, fieldMatchers);
22405 } else if (operator === "$regex") {
22406 return mergeRegex(value, fieldMatchers);
22407 }
22408 fieldMatchers[operator] = value;
22409 });
22410 }
22411 });
22412 });
22413
22414 return res;
22415}
22416
22417
22418
22419// collapse logically equivalent gt/gte values
22420function mergeGtGte(operator, value, fieldMatchers) {
22421 if (typeof fieldMatchers.$eq !== 'undefined') {
22422 return; // do nothing
22423 }
22424 if (typeof fieldMatchers.$gte !== 'undefined') {
22425 if (operator === '$gte') {
22426 if (value > fieldMatchers.$gte) { // more specificity
22427 fieldMatchers.$gte = value;
22428 }
22429 } else { // operator === '$gt'
22430 if (value >= fieldMatchers.$gte) { // more specificity
22431 delete fieldMatchers.$gte;
22432 fieldMatchers.$gt = value;
22433 }
22434 }
22435 } else if (typeof fieldMatchers.$gt !== 'undefined') {
22436 if (operator === '$gte') {
22437 if (value > fieldMatchers.$gt) { // more specificity
22438 delete fieldMatchers.$gt;
22439 fieldMatchers.$gte = value;
22440 }
22441 } else { // operator === '$gt'
22442 if (value > fieldMatchers.$gt) { // more specificity
22443 fieldMatchers.$gt = value;
22444 }
22445 }
22446 } else {
22447 fieldMatchers[operator] = value;
22448 }
22449}
22450
22451// collapse logically equivalent lt/lte values
22452function mergeLtLte(operator, value, fieldMatchers) {
22453 if (typeof fieldMatchers.$eq !== 'undefined') {
22454 return; // do nothing
22455 }
22456 if (typeof fieldMatchers.$lte !== 'undefined') {
22457 if (operator === '$lte') {
22458 if (value < fieldMatchers.$lte) { // more specificity
22459 fieldMatchers.$lte = value;
22460 }
22461 } else { // operator === '$gt'
22462 if (value <= fieldMatchers.$lte) { // more specificity
22463 delete fieldMatchers.$lte;
22464 fieldMatchers.$lt = value;
22465 }
22466 }
22467 } else if (typeof fieldMatchers.$lt !== 'undefined') {
22468 if (operator === '$lte') {
22469 if (value < fieldMatchers.$lt) { // more specificity
22470 delete fieldMatchers.$lt;
22471 fieldMatchers.$lte = value;
22472 }
22473 } else { // operator === '$gt'
22474 if (value < fieldMatchers.$lt) { // more specificity
22475 fieldMatchers.$lt = value;
22476 }
22477 }
22478 } else {
22479 fieldMatchers[operator] = value;
22480 }
22481}
22482
22483// combine $ne values into one array
22484function mergeNe(value, fieldMatchers) {
22485 if ('$ne' in fieldMatchers) {
22486 // there are many things this could "not" be
22487 fieldMatchers.$ne.push(value);
22488 } else { // doesn't exist yet
22489 fieldMatchers.$ne = [value];
22490 }
22491}
22492
22493// add $eq into the mix
22494function mergeEq(value, fieldMatchers) {
22495 // these all have less specificity than the $eq
22496 // TODO: check for user errors here
22497 delete fieldMatchers.$gt;
22498 delete fieldMatchers.$gte;
22499 delete fieldMatchers.$lt;
22500 delete fieldMatchers.$lte;
22501 delete fieldMatchers.$ne;
22502 fieldMatchers.$eq = value;
22503}
22504
22505// combine $regex values into one array
22506function mergeRegex(value, fieldMatchers) {
22507 if ('$regex' in fieldMatchers) {
22508 // a value could match multiple regexes
22509 fieldMatchers.$regex.push(value);
22510 } else { // doesn't exist yet
22511 fieldMatchers.$regex = [value];
22512 }
22513}
22514
22515//#7458: execute function mergeAndedSelectors on nested $and
22516function mergeAndedSelectorsNested(obj) {
22517 for (var prop in obj) {
22518 if (Array.isArray(obj)) {
22519 for (var i in obj) {
22520 if (obj[i]['$and']) {
22521 obj[i] = mergeAndedSelectors(obj[i]['$and']);
22522 }
22523 }
22524 }
22525 var value = obj[prop];
22526 if (typeof value === 'object') {
22527 mergeAndedSelectorsNested(value); // <- recursive call
22528 }
22529 }
22530 return obj;
22531}
22532
22533//#7458: determine id $and is present in selector (at any level)
22534function isAndInSelector(obj, isAnd) {
22535 for (var prop in obj) {
22536 if (prop === '$and') {
22537 isAnd = true;
22538 }
22539 var value = obj[prop];
22540 if (typeof value === 'object') {
22541 isAnd = isAndInSelector(value, isAnd); // <- recursive call
22542 }
22543 }
22544 return isAnd;
22545}
22546
22547//
22548// normalize the selector
22549//
22550function massageSelector(input) {
22551 var result = clone$1(input);
22552
22553 //#7458: if $and is present in selector (at any level) merge nested $and
22554 if (isAndInSelector(result, false)) {
22555 result = mergeAndedSelectorsNested(result);
22556 if ('$and' in result) {
22557 result = mergeAndedSelectors(result['$and']);
22558 }
22559 }
22560
22561 ['$or', '$nor'].forEach(function (orOrNor) {
22562 if (orOrNor in result) {
22563 // message each individual selector
22564 // e.g. {foo: 'bar'} becomes {foo: {$eq: 'bar'}}
22565 result[orOrNor].forEach(function (subSelector) {
22566 var fields = Object.keys(subSelector);
22567 for (var i = 0; i < fields.length; i++) {
22568 var field = fields[i];
22569 var matcher = subSelector[field];
22570 if (typeof matcher !== 'object' || matcher === null) {
22571 subSelector[field] = {$eq: matcher};
22572 }
22573 }
22574 });
22575 }
22576 });
22577
22578 if ('$not' in result) {
22579 //This feels a little like forcing, but it will work for now,
22580 //I would like to come back to this and make the merging of selectors a little more generic
22581 result['$not'] = mergeAndedSelectors([result['$not']]);
22582 }
22583
22584 var fields = Object.keys(result);
22585
22586 for (var i = 0; i < fields.length; i++) {
22587 var field = fields[i];
22588 var matcher = result[field];
22589
22590 if (typeof matcher !== 'object' || matcher === null) {
22591 matcher = {$eq: matcher};
22592 }
22593 result[field] = matcher;
22594 }
22595
22596 normalizeArrayOperators(result);
22597
22598 return result;
22599}
22600
22601//
22602// The $ne and $regex values must be placed in an array because these operators can be used multiple times on the same field.
22603// When $and is used, mergeAndedSelectors takes care of putting some of them into arrays, otherwise it's done here.
22604//
22605function normalizeArrayOperators(selector) {
22606 Object.keys(selector).forEach(function (field) {
22607 var matcher = selector[field];
22608
22609 if (Array.isArray(matcher)) {
22610 matcher.forEach(function (matcherItem) {
22611 if (matcherItem && typeof matcherItem === 'object') {
22612 normalizeArrayOperators(matcherItem);
22613 }
22614 });
22615 } else if (field === '$ne') {
22616 selector.$ne = [matcher];
22617 } else if (field === '$regex') {
22618 selector.$regex = [matcher];
22619 } else if (matcher && typeof matcher === 'object') {
22620 normalizeArrayOperators(matcher);
22621 }
22622 });
22623}
22624
22625function collate(a, b) {
22626
22627 if (a === b) {
22628 return 0;
22629 }
22630
22631 a = normalizeKey(a);
22632 b = normalizeKey(b);
22633
22634 var ai = collationIndex(a);
22635 var bi = collationIndex(b);
22636 if ((ai - bi) !== 0) {
22637 return ai - bi;
22638 }
22639 switch (typeof a) {
22640 case 'number':
22641 return a - b;
22642 case 'boolean':
22643 return a < b ? -1 : 1;
22644 case 'string':
22645 return stringCollate(a, b);
22646 }
22647 return Array.isArray(a) ? arrayCollate(a, b) : objectCollate(a, b);
22648}
22649
22650// couch considers null/NaN/Infinity/-Infinity === undefined,
22651// for the purposes of mapreduce indexes. also, dates get stringified.
22652function normalizeKey(key) {
22653 switch (typeof key) {
22654 case 'undefined':
22655 return null;
22656 case 'number':
22657 if (key === Infinity || key === -Infinity || isNaN(key)) {
22658 return null;
22659 }
22660 return key;
22661 case 'object':
22662 var origKey = key;
22663 if (Array.isArray(key)) {
22664 var len = key.length;
22665 key = new Array(len);
22666 for (var i = 0; i < len; i++) {
22667 key[i] = normalizeKey(origKey[i]);
22668 }
22669 /* istanbul ignore next */
22670 } else if (key instanceof Date) {
22671 return key.toJSON();
22672 } else if (key !== null) { // generic object
22673 key = {};
22674 for (var k in origKey) {
22675 if (Object.prototype.hasOwnProperty.call(origKey, k)) {
22676 var val = origKey[k];
22677 if (typeof val !== 'undefined') {
22678 key[k] = normalizeKey(val);
22679 }
22680 }
22681 }
22682 }
22683 }
22684 return key;
22685}
22686
22687function arrayCollate(a, b) {
22688 var len = Math.min(a.length, b.length);
22689 for (var i = 0; i < len; i++) {
22690 var sort = collate(a[i], b[i]);
22691 if (sort !== 0) {
22692 return sort;
22693 }
22694 }
22695 return (a.length === b.length) ? 0 :
22696 (a.length > b.length) ? 1 : -1;
22697}
22698function stringCollate(a, b) {
22699 // See: https://github.com/daleharvey/pouchdb/issues/40
22700 // This is incompatible with the CouchDB implementation, but its the
22701 // best we can do for now
22702 return (a === b) ? 0 : ((a > b) ? 1 : -1);
22703}
22704function objectCollate(a, b) {
22705 var ak = Object.keys(a), bk = Object.keys(b);
22706 var len = Math.min(ak.length, bk.length);
22707 for (var i = 0; i < len; i++) {
22708 // First sort the keys
22709 var sort = collate(ak[i], bk[i]);
22710 if (sort !== 0) {
22711 return sort;
22712 }
22713 // if the keys are equal sort the values
22714 sort = collate(a[ak[i]], b[bk[i]]);
22715 if (sort !== 0) {
22716 return sort;
22717 }
22718
22719 }
22720 return (ak.length === bk.length) ? 0 :
22721 (ak.length > bk.length) ? 1 : -1;
22722}
22723// The collation is defined by erlangs ordered terms
22724// the atoms null, true, false come first, then numbers, strings,
22725// arrays, then objects
22726// null/undefined/NaN/Infinity/-Infinity are all considered null
22727function collationIndex(x) {
22728 var id = ['boolean', 'number', 'string', 'object'];
22729 var idx = id.indexOf(typeof x);
22730 //false if -1 otherwise true, but fast!!!!1
22731 if (~idx) {
22732 if (x === null) {
22733 return 1;
22734 }
22735 if (Array.isArray(x)) {
22736 return 5;
22737 }
22738 return idx < 3 ? (idx + 2) : (idx + 3);
22739 }
22740 /* istanbul ignore next */
22741 if (Array.isArray(x)) {
22742 return 5;
22743 }
22744}
22745
22746// create a comparator based on the sort object
22747function createFieldSorter(sort) {
22748
22749 function getFieldValuesAsArray(doc) {
22750 return sort.map(function (sorting) {
22751 var fieldName = getKey(sorting);
22752 var parsedField = parseField(fieldName);
22753 var docFieldValue = getFieldFromDoc(doc, parsedField);
22754 return docFieldValue;
22755 });
22756 }
22757
22758 return function (aRow, bRow) {
22759 var aFieldValues = getFieldValuesAsArray(aRow.doc);
22760 var bFieldValues = getFieldValuesAsArray(bRow.doc);
22761 var collation = collate(aFieldValues, bFieldValues);
22762 if (collation !== 0) {
22763 return collation;
22764 }
22765 // this is what mango seems to do
22766 return compare(aRow.doc._id, bRow.doc._id);
22767 };
22768}
22769
22770function filterInMemoryFields(rows, requestDef, inMemoryFields) {
22771 rows = rows.filter(function (row) {
22772 return rowFilter(row.doc, requestDef.selector, inMemoryFields);
22773 });
22774
22775 if (requestDef.sort) {
22776 // in-memory sort
22777 var fieldSorter = createFieldSorter(requestDef.sort);
22778 rows = rows.sort(fieldSorter);
22779 if (typeof requestDef.sort[0] !== 'string' &&
22780 getValue(requestDef.sort[0]) === 'desc') {
22781 rows = rows.reverse();
22782 }
22783 }
22784
22785 if ('limit' in requestDef || 'skip' in requestDef) {
22786 // have to do the limit in-memory
22787 var skip = requestDef.skip || 0;
22788 var limit = ('limit' in requestDef ? requestDef.limit : rows.length) + skip;
22789 rows = rows.slice(skip, limit);
22790 }
22791 return rows;
22792}
22793
22794function rowFilter(doc, selector, inMemoryFields) {
22795 return inMemoryFields.every(function (field) {
22796 var matcher = selector[field];
22797 var parsedField = parseField(field);
22798 var docFieldValue = getFieldFromDoc(doc, parsedField);
22799 if (isCombinationalField(field)) {
22800 return matchCominationalSelector(field, matcher, doc);
22801 }
22802
22803 return matchSelector(matcher, doc, parsedField, docFieldValue);
22804 });
22805}
22806
22807function matchSelector(matcher, doc, parsedField, docFieldValue) {
22808 if (!matcher) {
22809 // no filtering necessary; this field is just needed for sorting
22810 return true;
22811 }
22812
22813 // is matcher an object, if so continue recursion
22814 if (typeof matcher === 'object') {
22815 return Object.keys(matcher).every(function (maybeUserOperator) {
22816 var userValue = matcher[ maybeUserOperator ];
22817 // explicit operator
22818 if (maybeUserOperator.indexOf("$") === 0) {
22819 return match(maybeUserOperator, doc, userValue, parsedField, docFieldValue);
22820 } else {
22821 var subParsedField = parseField(maybeUserOperator);
22822
22823 if (
22824 docFieldValue === undefined &&
22825 typeof userValue !== "object" &&
22826 subParsedField.length > 0
22827 ) {
22828 // the field does not exist, return or getFieldFromDoc will throw
22829 return false;
22830 }
22831
22832 var subDocFieldValue = getFieldFromDoc(docFieldValue, subParsedField);
22833
22834 if (typeof userValue === "object") {
22835 // field value is an object that might contain more operators
22836 return matchSelector(userValue, doc, parsedField, subDocFieldValue);
22837 }
22838
22839 // implicit operator
22840 return match("$eq", doc, userValue, subParsedField, subDocFieldValue);
22841 }
22842 });
22843 }
22844
22845 // no more depth, No need to recurse further
22846 return matcher === docFieldValue;
22847}
22848
22849function matchCominationalSelector(field, matcher, doc) {
22850
22851 if (field === '$or') {
22852 return matcher.some(function (orMatchers) {
22853 return rowFilter(doc, orMatchers, Object.keys(orMatchers));
22854 });
22855 }
22856
22857 if (field === '$not') {
22858 return !rowFilter(doc, matcher, Object.keys(matcher));
22859 }
22860
22861 //`$nor`
22862 return !matcher.find(function (orMatchers) {
22863 return rowFilter(doc, orMatchers, Object.keys(orMatchers));
22864 });
22865
22866}
22867
22868function match(userOperator, doc, userValue, parsedField, docFieldValue) {
22869 if (!matchers[userOperator]) {
22870 /* istanbul ignore next */
22871 throw new Error('unknown operator "' + userOperator +
22872 '" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, ' +
22873 '$nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all');
22874 }
22875 return matchers[userOperator](doc, userValue, parsedField, docFieldValue);
22876}
22877
22878function fieldExists(docFieldValue) {
22879 return typeof docFieldValue !== 'undefined' && docFieldValue !== null;
22880}
22881
22882function fieldIsNotUndefined(docFieldValue) {
22883 return typeof docFieldValue !== 'undefined';
22884}
22885
22886function modField(docFieldValue, userValue) {
22887 if (typeof docFieldValue !== "number" ||
22888 parseInt(docFieldValue, 10) !== docFieldValue) {
22889 return false;
22890 }
22891
22892 var divisor = userValue[0];
22893 var mod = userValue[1];
22894
22895 return docFieldValue % divisor === mod;
22896}
22897
22898function arrayContainsValue(docFieldValue, userValue) {
22899 return userValue.some(function (val) {
22900 if (docFieldValue instanceof Array) {
22901 return docFieldValue.some(function (docFieldValueItem) {
22902 return collate(val, docFieldValueItem) === 0;
22903 });
22904 }
22905
22906 return collate(val, docFieldValue) === 0;
22907 });
22908}
22909
22910function arrayContainsAllValues(docFieldValue, userValue) {
22911 return userValue.every(function (val) {
22912 return docFieldValue.some(function (docFieldValueItem) {
22913 return collate(val, docFieldValueItem) === 0;
22914 });
22915 });
22916}
22917
22918function arraySize(docFieldValue, userValue) {
22919 return docFieldValue.length === userValue;
22920}
22921
22922function regexMatch(docFieldValue, userValue) {
22923 var re = new RegExp(userValue);
22924
22925 return re.test(docFieldValue);
22926}
22927
22928function typeMatch(docFieldValue, userValue) {
22929
22930 switch (userValue) {
22931 case 'null':
22932 return docFieldValue === null;
22933 case 'boolean':
22934 return typeof (docFieldValue) === 'boolean';
22935 case 'number':
22936 return typeof (docFieldValue) === 'number';
22937 case 'string':
22938 return typeof (docFieldValue) === 'string';
22939 case 'array':
22940 return docFieldValue instanceof Array;
22941 case 'object':
22942 return ({}).toString.call(docFieldValue) === '[object Object]';
22943 }
22944}
22945
22946var matchers = {
22947
22948 '$elemMatch': function (doc, userValue, parsedField, docFieldValue) {
22949 if (!Array.isArray(docFieldValue)) {
22950 return false;
22951 }
22952
22953 if (docFieldValue.length === 0) {
22954 return false;
22955 }
22956
22957 if (typeof docFieldValue[0] === 'object' && docFieldValue[0] !== null) {
22958 return docFieldValue.some(function (val) {
22959 return rowFilter(val, userValue, Object.keys(userValue));
22960 });
22961 }
22962
22963 return docFieldValue.some(function (val) {
22964 return matchSelector(userValue, doc, parsedField, val);
22965 });
22966 },
22967
22968 '$allMatch': function (doc, userValue, parsedField, docFieldValue) {
22969 if (!Array.isArray(docFieldValue)) {
22970 return false;
22971 }
22972
22973 /* istanbul ignore next */
22974 if (docFieldValue.length === 0) {
22975 return false;
22976 }
22977
22978 if (typeof docFieldValue[0] === 'object' && docFieldValue[0] !== null) {
22979 return docFieldValue.every(function (val) {
22980 return rowFilter(val, userValue, Object.keys(userValue));
22981 });
22982 }
22983
22984 return docFieldValue.every(function (val) {
22985 return matchSelector(userValue, doc, parsedField, val);
22986 });
22987 },
22988
22989 '$eq': function (doc, userValue, parsedField, docFieldValue) {
22990 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) === 0;
22991 },
22992
22993 '$gte': function (doc, userValue, parsedField, docFieldValue) {
22994 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) >= 0;
22995 },
22996
22997 '$gt': function (doc, userValue, parsedField, docFieldValue) {
22998 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) > 0;
22999 },
23000
23001 '$lte': function (doc, userValue, parsedField, docFieldValue) {
23002 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) <= 0;
23003 },
23004
23005 '$lt': function (doc, userValue, parsedField, docFieldValue) {
23006 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) < 0;
23007 },
23008
23009 '$exists': function (doc, userValue, parsedField, docFieldValue) {
23010 //a field that is null is still considered to exist
23011 if (userValue) {
23012 return fieldIsNotUndefined(docFieldValue);
23013 }
23014
23015 return !fieldIsNotUndefined(docFieldValue);
23016 },
23017
23018 '$mod': function (doc, userValue, parsedField, docFieldValue) {
23019 return fieldExists(docFieldValue) && modField(docFieldValue, userValue);
23020 },
23021
23022 '$ne': function (doc, userValue, parsedField, docFieldValue) {
23023 return userValue.every(function (neValue) {
23024 return collate(docFieldValue, neValue) !== 0;
23025 });
23026 },
23027 '$in': function (doc, userValue, parsedField, docFieldValue) {
23028 return fieldExists(docFieldValue) && arrayContainsValue(docFieldValue, userValue);
23029 },
23030
23031 '$nin': function (doc, userValue, parsedField, docFieldValue) {
23032 return fieldExists(docFieldValue) && !arrayContainsValue(docFieldValue, userValue);
23033 },
23034
23035 '$size': function (doc, userValue, parsedField, docFieldValue) {
23036 return fieldExists(docFieldValue) &&
23037 Array.isArray(docFieldValue) &&
23038 arraySize(docFieldValue, userValue);
23039 },
23040
23041 '$all': function (doc, userValue, parsedField, docFieldValue) {
23042 return Array.isArray(docFieldValue) && arrayContainsAllValues(docFieldValue, userValue);
23043 },
23044
23045 '$regex': function (doc, userValue, parsedField, docFieldValue) {
23046 return fieldExists(docFieldValue) &&
23047 typeof docFieldValue == "string" &&
23048 userValue.every(function (regexValue) {
23049 return regexMatch(docFieldValue, regexValue);
23050 });
23051 },
23052
23053 '$type': function (doc, userValue, parsedField, docFieldValue) {
23054 return typeMatch(docFieldValue, userValue);
23055 }
23056};
23057
23058// return true if the given doc matches the supplied selector
23059function matchesSelector(doc, selector) {
23060 /* istanbul ignore if */
23061 if (typeof selector !== 'object') {
23062 // match the CouchDB error message
23063 throw new Error('Selector error: expected a JSON object');
23064 }
23065
23066 selector = massageSelector(selector);
23067 var row = {
23068 doc
23069 };
23070
23071 var rowsMatched = filterInMemoryFields([row], { selector }, Object.keys(selector));
23072 return rowsMatched && rowsMatched.length === 1;
23073}
23074
23075function evalFilter(input) {
23076 return scopeEval('"use strict";\nreturn ' + input + ';', {});
23077}
23078
23079function evalView(input) {
23080 var code = [
23081 'return function(doc) {',
23082 ' "use strict";',
23083 ' var emitted = false;',
23084 ' var emit = function (a, b) {',
23085 ' emitted = true;',
23086 ' };',
23087 ' var view = ' + input + ';',
23088 ' view(doc);',
23089 ' if (emitted) {',
23090 ' return true;',
23091 ' }',
23092 '};'
23093 ].join('\n');
23094
23095 return scopeEval(code, {});
23096}
23097
23098function validate(opts, callback) {
23099 if (opts.selector) {
23100 if (opts.filter && opts.filter !== '_selector') {
23101 var filterName = typeof opts.filter === 'string' ?
23102 opts.filter : 'function';
23103 return callback(new Error('selector invalid for filter "' + filterName + '"'));
23104 }
23105 }
23106 callback();
23107}
23108
23109function normalize(opts) {
23110 if (opts.view && !opts.filter) {
23111 opts.filter = '_view';
23112 }
23113
23114 if (opts.selector && !opts.filter) {
23115 opts.filter = '_selector';
23116 }
23117
23118 if (opts.filter && typeof opts.filter === 'string') {
23119 if (opts.filter === '_view') {
23120 opts.view = normalizeDesignDocFunctionName(opts.view);
23121 } else {
23122 opts.filter = normalizeDesignDocFunctionName(opts.filter);
23123 }
23124 }
23125}
23126
23127function shouldFilter(changesHandler, opts) {
23128 return opts.filter && typeof opts.filter === 'string' &&
23129 !opts.doc_ids && !isRemote(changesHandler.db);
23130}
23131
23132function filter(changesHandler, opts) {
23133 var callback = opts.complete;
23134 if (opts.filter === '_view') {
23135 if (!opts.view || typeof opts.view !== 'string') {
23136 var err = createError(BAD_REQUEST,
23137 '`view` filter parameter not found or invalid.');
23138 return callback(err);
23139 }
23140 // fetch a view from a design doc, make it behave like a filter
23141 var viewName = parseDesignDocFunctionName(opts.view);
23142 changesHandler.db.get('_design/' + viewName[0], function (err, ddoc) {
23143 /* istanbul ignore if */
23144 if (changesHandler.isCancelled) {
23145 return callback(null, {status: 'cancelled'});
23146 }
23147 /* istanbul ignore next */
23148 if (err) {
23149 return callback(generateErrorFromResponse(err));
23150 }
23151 var mapFun = ddoc && ddoc.views && ddoc.views[viewName[1]] &&
23152 ddoc.views[viewName[1]].map;
23153 if (!mapFun) {
23154 return callback(createError(MISSING_DOC,
23155 (ddoc.views ? 'missing json key: ' + viewName[1] :
23156 'missing json key: views')));
23157 }
23158 opts.filter = evalView(mapFun);
23159 changesHandler.doChanges(opts);
23160 });
23161 } else if (opts.selector) {
23162 opts.filter = function (doc) {
23163 return matchesSelector(doc, opts.selector);
23164 };
23165 changesHandler.doChanges(opts);
23166 } else {
23167 // fetch a filter from a design doc
23168 var filterName = parseDesignDocFunctionName(opts.filter);
23169 changesHandler.db.get('_design/' + filterName[0], function (err, ddoc) {
23170 /* istanbul ignore if */
23171 if (changesHandler.isCancelled) {
23172 return callback(null, {status: 'cancelled'});
23173 }
23174 /* istanbul ignore next */
23175 if (err) {
23176 return callback(generateErrorFromResponse(err));
23177 }
23178 var filterFun = ddoc && ddoc.filters && ddoc.filters[filterName[1]];
23179 if (!filterFun) {
23180 return callback(createError(MISSING_DOC,
23181 ((ddoc && ddoc.filters) ? 'missing json key: ' + filterName[1]
23182 : 'missing json key: filters')));
23183 }
23184 opts.filter = evalFilter(filterFun);
23185 changesHandler.doChanges(opts);
23186 });
23187 }
23188}
23189
23190function applyChangesFilterPlugin(PouchDB) {
23191 PouchDB._changesFilterPlugin = {
23192 validate,
23193 normalize,
23194 shouldFilter,
23195 filter
23196 };
23197}
23198
23199// TODO: remove from pouchdb-core (breaking)
23200PouchDB$1.plugin(applyChangesFilterPlugin);
23201
23202PouchDB$1.version = version$1;
23203
23204function allDocsKeysQuery(api, opts) {
23205 var keys = opts.keys;
23206 var finalResults = {
23207 offset: opts.skip
23208 };
23209 return Promise.all(keys.map(function (key) {
23210 var subOpts = Object.assign({key, deleted: 'ok'}, opts);
23211 ['limit', 'skip', 'keys'].forEach(function (optKey) {
23212 delete subOpts[optKey];
23213 });
23214 return new Promise(function (resolve, reject) {
23215 api._allDocs(subOpts, function (err, res) {
23216 /* istanbul ignore if */
23217 if (err) {
23218 return reject(err);
23219 }
23220 /* istanbul ignore if */
23221 if (opts.update_seq && res.update_seq !== undefined) {
23222 finalResults.update_seq = res.update_seq;
23223 }
23224 finalResults.total_rows = res.total_rows;
23225 resolve(res.rows[0] || {key, error: 'not_found'});
23226 });
23227 });
23228 })).then(function (results) {
23229 finalResults.rows = results;
23230 return finalResults;
23231 });
23232}
23233
23234function toObject(array) {
23235 return array.reduce(function (obj, item) {
23236 obj[item] = true;
23237 return obj;
23238 }, {});
23239}
23240// List of top level reserved words for doc
23241var reservedWords = toObject([
23242 '_id',
23243 '_rev',
23244 '_access',
23245 '_attachments',
23246 '_deleted',
23247 '_revisions',
23248 '_revs_info',
23249 '_conflicts',
23250 '_deleted_conflicts',
23251 '_local_seq',
23252 '_rev_tree',
23253 // replication documents
23254 '_replication_id',
23255 '_replication_state',
23256 '_replication_state_time',
23257 '_replication_state_reason',
23258 '_replication_stats',
23259 // Specific to Couchbase Sync Gateway
23260 '_removed'
23261]);
23262
23263// List of reserved words that should end up in the document
23264var dataWords = toObject([
23265 '_access',
23266 '_attachments',
23267 // replication documents
23268 '_replication_id',
23269 '_replication_state',
23270 '_replication_state_time',
23271 '_replication_state_reason',
23272 '_replication_stats'
23273]);
23274
23275function parseRevisionInfo(rev$$1) {
23276 if (!/^\d+-/.test(rev$$1)) {
23277 return createError(INVALID_REV);
23278 }
23279 var idx = rev$$1.indexOf('-');
23280 var left = rev$$1.substring(0, idx);
23281 var right = rev$$1.substring(idx + 1);
23282 return {
23283 prefix: parseInt(left, 10),
23284 id: right
23285 };
23286}
23287
23288function makeRevTreeFromRevisions(revisions, opts) {
23289 var pos = revisions.start - revisions.ids.length + 1;
23290
23291 var revisionIds = revisions.ids;
23292 var ids = [revisionIds[0], opts, []];
23293
23294 for (var i = 1, len = revisionIds.length; i < len; i++) {
23295 ids = [revisionIds[i], {status: 'missing'}, [ids]];
23296 }
23297
23298 return [{
23299 pos,
23300 ids
23301 }];
23302}
23303
23304// Preprocess documents, parse their revisions, assign an id and a
23305// revision for new writes that are missing them, etc
23306function parseDoc(doc, newEdits, dbOpts) {
23307 if (!dbOpts) {
23308 dbOpts = {
23309 deterministic_revs: true
23310 };
23311 }
23312
23313 var nRevNum;
23314 var newRevId;
23315 var revInfo;
23316 var opts = {status: 'available'};
23317 if (doc._deleted) {
23318 opts.deleted = true;
23319 }
23320
23321 if (newEdits) {
23322 if (!doc._id) {
23323 doc._id = uuid$1();
23324 }
23325 newRevId = rev(doc, dbOpts.deterministic_revs);
23326 if (doc._rev) {
23327 revInfo = parseRevisionInfo(doc._rev);
23328 if (revInfo.error) {
23329 return revInfo;
23330 }
23331 doc._rev_tree = [{
23332 pos: revInfo.prefix,
23333 ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]]
23334 }];
23335 nRevNum = revInfo.prefix + 1;
23336 } else {
23337 doc._rev_tree = [{
23338 pos: 1,
23339 ids : [newRevId, opts, []]
23340 }];
23341 nRevNum = 1;
23342 }
23343 } else {
23344 if (doc._revisions) {
23345 doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts);
23346 nRevNum = doc._revisions.start;
23347 newRevId = doc._revisions.ids[0];
23348 }
23349 if (!doc._rev_tree) {
23350 revInfo = parseRevisionInfo(doc._rev);
23351 if (revInfo.error) {
23352 return revInfo;
23353 }
23354 nRevNum = revInfo.prefix;
23355 newRevId = revInfo.id;
23356 doc._rev_tree = [{
23357 pos: nRevNum,
23358 ids: [newRevId, opts, []]
23359 }];
23360 }
23361 }
23362
23363 invalidIdError(doc._id);
23364
23365 doc._rev = nRevNum + '-' + newRevId;
23366
23367 var result = {metadata : {}, data : {}};
23368 for (var key in doc) {
23369 /* istanbul ignore else */
23370 if (Object.prototype.hasOwnProperty.call(doc, key)) {
23371 var specialKey = key[0] === '_';
23372 if (specialKey && !reservedWords[key]) {
23373 var error = createError(DOC_VALIDATION, key);
23374 error.message = DOC_VALIDATION.message + ': ' + key;
23375 throw error;
23376 } else if (specialKey && !dataWords[key]) {
23377 result.metadata[key.slice(1)] = doc[key];
23378 } else {
23379 result.data[key] = doc[key];
23380 }
23381 }
23382 }
23383 return result;
23384}
23385
23386function updateDoc(revLimit, prev, docInfo, results,
23387 i, cb, writeDoc, newEdits) {
23388
23389 if (revExists(prev.rev_tree, docInfo.metadata.rev) && !newEdits) {
23390 results[i] = docInfo;
23391 return cb();
23392 }
23393
23394 // sometimes this is pre-calculated. historically not always
23395 var previousWinningRev = prev.winningRev || winningRev(prev);
23396 var previouslyDeleted = 'deleted' in prev ? prev.deleted :
23397 isDeleted(prev, previousWinningRev);
23398 var deleted = 'deleted' in docInfo.metadata ? docInfo.metadata.deleted :
23399 isDeleted(docInfo.metadata);
23400 var isRoot = /^1-/.test(docInfo.metadata.rev);
23401
23402 if (previouslyDeleted && !deleted && newEdits && isRoot) {
23403 var newDoc = docInfo.data;
23404 newDoc._rev = previousWinningRev;
23405 newDoc._id = docInfo.metadata.id;
23406 docInfo = parseDoc(newDoc, newEdits);
23407 }
23408
23409 var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit);
23410
23411 var inConflict = newEdits && ((
23412 (previouslyDeleted && deleted && merged.conflicts !== 'new_leaf') ||
23413 (!previouslyDeleted && merged.conflicts !== 'new_leaf') ||
23414 (previouslyDeleted && !deleted && merged.conflicts === 'new_branch')));
23415
23416 if (inConflict) {
23417 var err = createError(REV_CONFLICT);
23418 results[i] = err;
23419 return cb();
23420 }
23421
23422 var newRev = docInfo.metadata.rev;
23423 docInfo.metadata.rev_tree = merged.tree;
23424 docInfo.stemmedRevs = merged.stemmedRevs || [];
23425 /* istanbul ignore else */
23426 if (prev.rev_map) {
23427 docInfo.metadata.rev_map = prev.rev_map; // used only by leveldb
23428 }
23429
23430 // recalculate
23431 var winningRev$$1 = winningRev(docInfo.metadata);
23432 var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev$$1);
23433
23434 // calculate the total number of documents that were added/removed,
23435 // from the perspective of total_rows/doc_count
23436 var delta = (previouslyDeleted === winningRevIsDeleted) ? 0 :
23437 previouslyDeleted < winningRevIsDeleted ? -1 : 1;
23438
23439 var newRevIsDeleted;
23440 if (newRev === winningRev$$1) {
23441 // if the new rev is the same as the winning rev, we can reuse that value
23442 newRevIsDeleted = winningRevIsDeleted;
23443 } else {
23444 // if they're not the same, then we need to recalculate
23445 newRevIsDeleted = isDeleted(docInfo.metadata, newRev);
23446 }
23447
23448 writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
23449 true, delta, i, cb);
23450}
23451
23452function rootIsMissing(docInfo) {
23453 return docInfo.metadata.rev_tree[0].ids[1].status === 'missing';
23454}
23455
23456function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results,
23457 writeDoc, opts, overallCallback) {
23458
23459 // Default to 1000 locally
23460 revLimit = revLimit || 1000;
23461
23462 function insertDoc(docInfo, resultsIdx, callback) {
23463 // Cant insert new deleted documents
23464 var winningRev$$1 = winningRev(docInfo.metadata);
23465 var deleted = isDeleted(docInfo.metadata, winningRev$$1);
23466 if ('was_delete' in opts && deleted) {
23467 results[resultsIdx] = createError(MISSING_DOC, 'deleted');
23468 return callback();
23469 }
23470
23471 // 4712 - detect whether a new document was inserted with a _rev
23472 var inConflict = newEdits && rootIsMissing(docInfo);
23473
23474 if (inConflict) {
23475 var err = createError(REV_CONFLICT);
23476 results[resultsIdx] = err;
23477 return callback();
23478 }
23479
23480 var delta = deleted ? 0 : 1;
23481
23482 writeDoc(docInfo, winningRev$$1, deleted, deleted, false,
23483 delta, resultsIdx, callback);
23484 }
23485
23486 var newEdits = opts.new_edits;
23487 var idsToDocs = new Map();
23488
23489 var docsDone = 0;
23490 var docsToDo = docInfos.length;
23491
23492 function checkAllDocsDone() {
23493 if (++docsDone === docsToDo && overallCallback) {
23494 overallCallback();
23495 }
23496 }
23497
23498 docInfos.forEach(function (currentDoc, resultsIdx) {
23499
23500 if (currentDoc._id && isLocalId(currentDoc._id)) {
23501 var fun = currentDoc._deleted ? '_removeLocal' : '_putLocal';
23502 api[fun](currentDoc, {ctx: tx}, function (err, res) {
23503 results[resultsIdx] = err || res;
23504 checkAllDocsDone();
23505 });
23506 return;
23507 }
23508
23509 var id = currentDoc.metadata.id;
23510 if (idsToDocs.has(id)) {
23511 docsToDo--; // duplicate
23512 idsToDocs.get(id).push([currentDoc, resultsIdx]);
23513 } else {
23514 idsToDocs.set(id, [[currentDoc, resultsIdx]]);
23515 }
23516 });
23517
23518 // in the case of new_edits, the user can provide multiple docs
23519 // with the same id. these need to be processed sequentially
23520 idsToDocs.forEach(function (docs, id) {
23521 var numDone = 0;
23522
23523 function docWritten() {
23524 if (++numDone < docs.length) {
23525 nextDoc();
23526 } else {
23527 checkAllDocsDone();
23528 }
23529 }
23530 function nextDoc() {
23531 var value = docs[numDone];
23532 var currentDoc = value[0];
23533 var resultsIdx = value[1];
23534
23535 if (fetchedDocs.has(id)) {
23536 updateDoc(revLimit, fetchedDocs.get(id), currentDoc, results,
23537 resultsIdx, docWritten, writeDoc, newEdits);
23538 } else {
23539 // Ensure stemming applies to new writes as well
23540 var merged = merge([], currentDoc.metadata.rev_tree[0], revLimit);
23541 currentDoc.metadata.rev_tree = merged.tree;
23542 currentDoc.stemmedRevs = merged.stemmedRevs || [];
23543 insertDoc(currentDoc, resultsIdx, docWritten);
23544 }
23545 }
23546 nextDoc();
23547 });
23548}
23549
23550function safeJsonParse(str) {
23551 // This try/catch guards against stack overflow errors.
23552 // JSON.parse() is faster than vuvuzela.parse() but vuvuzela
23553 // cannot overflow.
23554 try {
23555 return JSON.parse(str);
23556 } catch (e) {
23557 /* istanbul ignore next */
23558 return vuvuzela.parse(str);
23559 }
23560}
23561
23562function safeJsonStringify(json) {
23563 try {
23564 return JSON.stringify(json);
23565 } catch (e) {
23566 /* istanbul ignore next */
23567 return vuvuzela.stringify(json);
23568 }
23569}
23570
23571function readAsBlobOrBuffer(storedObject, type) {
23572 // In the browser, we've stored a binary string. This now comes back as a
23573 // browserified Node-style Buffer (implemented as a typed array),
23574 // but we want a Blob instead.
23575 var byteArray = new Uint8Array(storedObject);
23576 return createBlob([byteArray], {type});
23577}
23578
23579// In the browser, we store a binary string
23580function prepareAttachmentForStorage(attData, cb) {
23581 readAsBinaryString(attData, cb);
23582}
23583
23584function createEmptyBlobOrBuffer(type) {
23585 return createBlob([''], {type});
23586}
23587
23588// similar to an idb or websql transaction object
23589
23590function getCacheFor(transaction, store) {
23591 var prefix = store.prefix()[0];
23592 var cache = transaction._cache;
23593 var subCache = cache.get(prefix);
23594 if (!subCache) {
23595 subCache = new Map();
23596 cache.set(prefix, subCache);
23597 }
23598 return subCache;
23599}
23600
23601class LevelTransaction {
23602 constructor() {
23603 this._batch = [];
23604 this._cache = new Map();
23605 }
23606
23607 get(store, key, callback) {
23608 var cache = getCacheFor(this, store);
23609 var exists = cache.get(key);
23610 if (exists) {
23611 return nextTick(function () {
23612 callback(null, exists);
23613 });
23614 } else if (exists === null) { // deleted marker
23615 /* istanbul ignore next */
23616 return nextTick(function () {
23617 callback({name: 'NotFoundError'});
23618 });
23619 }
23620 store.get(key, function (err, res) {
23621 if (err) {
23622 /* istanbul ignore else */
23623 if (err.name === 'NotFoundError') {
23624 cache.set(key, null);
23625 }
23626 return callback(err);
23627 }
23628 cache.set(key, res);
23629 callback(null, res);
23630 });
23631 }
23632
23633 batch(batch) {
23634 for (var i = 0, len = batch.length; i < len; i++) {
23635 var operation = batch[i];
23636
23637 var cache = getCacheFor(this, operation.prefix);
23638
23639 if (operation.type === 'put') {
23640 cache.set(operation.key, operation.value);
23641 } else {
23642 cache.set(operation.key, null);
23643 }
23644 }
23645 this._batch = this._batch.concat(batch);
23646 }
23647
23648 execute(db, callback) {
23649 var keys = new Set();
23650 var uniqBatches = [];
23651
23652 // remove duplicates; last one wins
23653 for (var i = this._batch.length - 1; i >= 0; i--) {
23654 var operation = this._batch[i];
23655 var lookupKey = operation.prefix.prefix()[0] + '\xff' + operation.key;
23656 if (keys.has(lookupKey)) {
23657 continue;
23658 }
23659 keys.add(lookupKey);
23660 uniqBatches.push(operation);
23661 }
23662
23663 db.batch(uniqBatches, callback);
23664 }
23665}
23666
23667var DOC_STORE = 'document-store';
23668var BY_SEQ_STORE = 'by-sequence';
23669var ATTACHMENT_STORE = 'attach-store';
23670var BINARY_STORE = 'attach-binary-store';
23671var LOCAL_STORE = 'local-store';
23672var META_STORE = 'meta-store';
23673
23674// leveldb barks if we try to open a db multiple times
23675// so we cache opened connections here for initstore()
23676var dbStores = new Map();
23677
23678// store the value of update_seq in the by-sequence store the key name will
23679// never conflict, since the keys in the by-sequence store are integers
23680var UPDATE_SEQ_KEY = '_local_last_update_seq';
23681var DOC_COUNT_KEY = '_local_doc_count';
23682var UUID_KEY = '_local_uuid';
23683
23684var MD5_PREFIX = 'md5-';
23685
23686var safeJsonEncoding = {
23687 encode: safeJsonStringify,
23688 decode: safeJsonParse,
23689 buffer: false,
23690 type: 'cheap-json'
23691};
23692
23693var levelChanges = new Changes();
23694
23695// winningRev and deleted are performance-killers, but
23696// in newer versions of PouchDB, they are cached on the metadata
23697function getWinningRev(metadata) {
23698 return 'winningRev' in metadata ?
23699 metadata.winningRev : winningRev(metadata);
23700}
23701
23702function getIsDeleted(metadata, winningRev$$1) {
23703 return 'deleted' in metadata ?
23704 metadata.deleted : isDeleted(metadata, winningRev$$1);
23705}
23706
23707function fetchAttachment(att, stores, opts) {
23708 var type = att.content_type;
23709 return new Promise(function (resolve, reject) {
23710 stores.binaryStore.get(att.digest, function (err, buffer) {
23711 var data;
23712 if (err) {
23713 /* istanbul ignore if */
23714 if (err.name !== 'NotFoundError') {
23715 return reject(err);
23716 } else {
23717 // empty
23718 if (!opts.binary) {
23719 data = '';
23720 } else {
23721 data = binStringToBluffer('', type);
23722 }
23723 }
23724 } else { // non-empty
23725 if (opts.binary) {
23726 data = readAsBlobOrBuffer(buffer, type);
23727 } else {
23728 data = buffer.toString('base64');
23729 }
23730 }
23731 delete att.stub;
23732 delete att.length;
23733 att.data = data;
23734 resolve();
23735 });
23736 });
23737}
23738
23739function fetchAttachments(results, stores, opts) {
23740 var atts = [];
23741 results.forEach(function (row) {
23742 if (!(row.doc && row.doc._attachments)) {
23743 return;
23744 }
23745 var attNames = Object.keys(row.doc._attachments);
23746 attNames.forEach(function (attName) {
23747 var att = row.doc._attachments[attName];
23748 if (!('data' in att)) {
23749 atts.push(att);
23750 }
23751 });
23752 });
23753
23754 return Promise.all(atts.map(function (att) {
23755 return fetchAttachment(att, stores, opts);
23756 }));
23757}
23758
23759function LevelPouch(opts, callback) {
23760 opts = clone$1(opts);
23761 var api = this;
23762 var instanceId;
23763 var stores = {};
23764 var revLimit = opts.revs_limit;
23765 var db;
23766 var name = opts.name;
23767 // TODO: this is undocumented and unused probably
23768 /* istanbul ignore else */
23769 if (typeof opts.createIfMissing === 'undefined') {
23770 opts.createIfMissing = true;
23771 }
23772
23773 var leveldown = opts.db;
23774
23775 var dbStore;
23776 var leveldownName = functionName(leveldown);
23777 if (dbStores.has(leveldownName)) {
23778 dbStore = dbStores.get(leveldownName);
23779 } else {
23780 dbStore = new Map();
23781 dbStores.set(leveldownName, dbStore);
23782 }
23783 if (dbStore.has(name)) {
23784 db = dbStore.get(name);
23785 afterDBCreated();
23786 } else {
23787 dbStore.set(name, sublevelPouch(levelup(leveldown(name), opts, function (err) {
23788 /* istanbul ignore if */
23789 if (err) {
23790 dbStore.delete(name);
23791 return callback(err);
23792 }
23793 db = dbStore.get(name);
23794 db._docCount = -1;
23795 db._queue = new Deque();
23796 /* istanbul ignore else */
23797 if (typeof opts.migrate === 'object') { // migration for leveldown
23798 opts.migrate.doMigrationOne(name, db, afterDBCreated);
23799 } else {
23800 afterDBCreated();
23801 }
23802 })));
23803 }
23804
23805 function afterDBCreated() {
23806 stores.docStore = db.sublevel(DOC_STORE, {valueEncoding: safeJsonEncoding});
23807 stores.bySeqStore = db.sublevel(BY_SEQ_STORE, {valueEncoding: 'json'});
23808 stores.attachmentStore =
23809 db.sublevel(ATTACHMENT_STORE, {valueEncoding: 'json'});
23810 stores.binaryStore = db.sublevel(BINARY_STORE, {valueEncoding: 'binary'});
23811 stores.localStore = db.sublevel(LOCAL_STORE, {valueEncoding: 'json'});
23812 stores.metaStore = db.sublevel(META_STORE, {valueEncoding: 'json'});
23813 /* istanbul ignore else */
23814 if (typeof opts.migrate === 'object') { // migration for leveldown
23815 opts.migrate.doMigrationTwo(db, stores, afterLastMigration);
23816 } else {
23817 afterLastMigration();
23818 }
23819 }
23820
23821 function afterLastMigration() {
23822 stores.metaStore.get(UPDATE_SEQ_KEY, function (err, value) {
23823 if (typeof db._updateSeq === 'undefined') {
23824 db._updateSeq = value || 0;
23825 }
23826 stores.metaStore.get(DOC_COUNT_KEY, function (err, value) {
23827 db._docCount = !err ? value : 0;
23828 stores.metaStore.get(UUID_KEY, function (err, value) {
23829 instanceId = !err ? value : uuid$1();
23830 stores.metaStore.put(UUID_KEY, instanceId, function () {
23831 nextTick(function () {
23832 callback(null, api);
23833 });
23834 });
23835 });
23836 });
23837 });
23838 }
23839
23840 function countDocs(callback) {
23841 /* istanbul ignore if */
23842 if (db.isClosed()) {
23843 return callback(new Error('database is closed'));
23844 }
23845 return callback(null, db._docCount); // use cached value
23846 }
23847
23848 api._remote = false;
23849 /* istanbul ignore next */
23850 api.type = function () {
23851 return 'leveldb';
23852 };
23853
23854 api._id = function (callback) {
23855 callback(null, instanceId);
23856 };
23857
23858 api._info = function (callback) {
23859 var res = {
23860 doc_count: db._docCount,
23861 update_seq: db._updateSeq,
23862 backend_adapter: functionName(leveldown)
23863 };
23864 return nextTick(function () {
23865 callback(null, res);
23866 });
23867 };
23868
23869 function tryCode(fun, args) {
23870 try {
23871 fun.apply(null, args);
23872 } catch (err) {
23873 args[args.length - 1](err);
23874 }
23875 }
23876
23877 function executeNext() {
23878 var firstTask = db._queue.peekFront();
23879
23880 if (firstTask.type === 'read') {
23881 runReadOperation(firstTask);
23882 } else { // write, only do one at a time
23883 runWriteOperation(firstTask);
23884 }
23885 }
23886
23887 function runReadOperation(firstTask) {
23888 // do multiple reads at once simultaneously, because it's safe
23889
23890 var readTasks = [firstTask];
23891 var i = 1;
23892 var nextTask = db._queue.get(i);
23893 while (typeof nextTask !== 'undefined' && nextTask.type === 'read') {
23894 readTasks.push(nextTask);
23895 i++;
23896 nextTask = db._queue.get(i);
23897 }
23898
23899 var numDone = 0;
23900
23901 readTasks.forEach(function (readTask) {
23902 var args = readTask.args;
23903 var callback = args[args.length - 1];
23904 args[args.length - 1] = function (...cbArgs) {
23905 callback.apply(null, cbArgs);
23906 if (++numDone === readTasks.length) {
23907 nextTick(function () {
23908 // all read tasks have finished
23909 readTasks.forEach(function () {
23910 db._queue.shift();
23911 });
23912 if (db._queue.length) {
23913 executeNext();
23914 }
23915 });
23916 }
23917 };
23918 tryCode(readTask.fun, args);
23919 });
23920 }
23921
23922 function runWriteOperation(firstTask) {
23923 var args = firstTask.args;
23924 var callback = args[args.length - 1];
23925 args[args.length - 1] = function (...cbArgs) {
23926 callback.apply(null, cbArgs);
23927 nextTick(function () {
23928 db._queue.shift();
23929 if (db._queue.length) {
23930 executeNext();
23931 }
23932 });
23933 };
23934 tryCode(firstTask.fun, args);
23935 }
23936
23937 // all read/write operations to the database are done in a queue,
23938 // similar to how websql/idb works. this avoids problems such
23939 // as e.g. compaction needing to have a lock on the database while
23940 // it updates stuff. in the future we can revisit this.
23941 function writeLock(fun) {
23942 return function (...args) {
23943 db._queue.push({
23944 fun,
23945 args,
23946 type: 'write'
23947 });
23948
23949 if (db._queue.length === 1) {
23950 nextTick(executeNext);
23951 }
23952 };
23953 }
23954
23955 // same as the writelock, but multiple can run at once
23956 function readLock(fun) {
23957 return function (...args) {
23958 db._queue.push({
23959 fun,
23960 args,
23961 type: 'read'
23962 });
23963
23964 if (db._queue.length === 1) {
23965 nextTick(executeNext);
23966 }
23967 };
23968 }
23969
23970 function formatSeq(n) {
23971 return ('0000000000000000' + n).slice(-16);
23972 }
23973
23974 function parseSeq(s) {
23975 return parseInt(s, 10);
23976 }
23977
23978 api._get = readLock(function (id, opts, callback) {
23979 opts = clone$1(opts);
23980
23981 stores.docStore.get(id, function (err, metadata) {
23982
23983 if (err || !metadata) {
23984 return callback(createError(MISSING_DOC, 'missing'));
23985 }
23986
23987 var rev$$1;
23988 if (!opts.rev) {
23989 rev$$1 = getWinningRev(metadata);
23990 var deleted = getIsDeleted(metadata, rev$$1);
23991 if (deleted) {
23992 return callback(createError(MISSING_DOC, "deleted"));
23993 }
23994 } else {
23995 rev$$1 = opts.latest ? latest(opts.rev, metadata) : opts.rev;
23996 }
23997
23998 var seq = metadata.rev_map[rev$$1];
23999
24000 stores.bySeqStore.get(formatSeq(seq), function (err, doc) {
24001 if (!doc) {
24002 return callback(createError(MISSING_DOC));
24003 }
24004 /* istanbul ignore if */
24005 if ('_id' in doc && doc._id !== metadata.id) {
24006 // this failing implies something very wrong
24007 return callback(new Error('wrong doc returned'));
24008 }
24009 doc._id = metadata.id;
24010 if ('_rev' in doc) {
24011 /* istanbul ignore if */
24012 if (doc._rev !== rev$$1) {
24013 // this failing implies something very wrong
24014 return callback(new Error('wrong doc returned'));
24015 }
24016 } else {
24017 // we didn't always store this
24018 doc._rev = rev$$1;
24019 }
24020 return callback(null, {doc, metadata});
24021 });
24022 });
24023 });
24024
24025 // not technically part of the spec, but if putAttachment has its own
24026 // method...
24027 api._getAttachment = function (docId, attachId, attachment, opts, callback) {
24028 var digest = attachment.digest;
24029 var type = attachment.content_type;
24030
24031 stores.binaryStore.get(digest, function (err, attach) {
24032 if (err) {
24033 /* istanbul ignore if */
24034 if (err.name !== 'NotFoundError') {
24035 return callback(err);
24036 }
24037 // Empty attachment
24038 return callback(null, opts.binary ? createEmptyBlobOrBuffer(type) : '');
24039 }
24040
24041 if (opts.binary) {
24042 callback(null, readAsBlobOrBuffer(attach, type));
24043 } else {
24044 callback(null, attach.toString('base64'));
24045 }
24046 });
24047 };
24048
24049 api._bulkDocs = writeLock(function (req, opts, callback) {
24050 var newEdits = opts.new_edits;
24051 var results = new Array(req.docs.length);
24052 var fetchedDocs = new Map();
24053 var stemmedRevs = new Map();
24054
24055 var txn = new LevelTransaction();
24056 var docCountDelta = 0;
24057 var newUpdateSeq = db._updateSeq;
24058
24059 // parse the docs and give each a sequence number
24060 var userDocs = req.docs;
24061 var docInfos = userDocs.map(function (doc) {
24062 if (doc._id && isLocalId(doc._id)) {
24063 return doc;
24064 }
24065 var newDoc = parseDoc(doc, newEdits, api.__opts);
24066
24067 if (newDoc.metadata && !newDoc.metadata.rev_map) {
24068 newDoc.metadata.rev_map = {};
24069 }
24070
24071 return newDoc;
24072 });
24073 var infoErrors = docInfos.filter(function (doc) {
24074 return doc.error;
24075 });
24076
24077 if (infoErrors.length) {
24078 return callback(infoErrors[0]);
24079 }
24080
24081 // verify any stub attachments as a precondition test
24082
24083 function verifyAttachment(digest, callback) {
24084 txn.get(stores.attachmentStore, digest, function (levelErr) {
24085 if (levelErr) {
24086 var err = createError(MISSING_STUB,
24087 'unknown stub attachment with digest ' +
24088 digest);
24089 callback(err);
24090 } else {
24091 callback();
24092 }
24093 });
24094 }
24095
24096 function verifyAttachments(finish) {
24097 var digests = [];
24098 userDocs.forEach(function (doc) {
24099 if (doc && doc._attachments) {
24100 Object.keys(doc._attachments).forEach(function (filename) {
24101 var att = doc._attachments[filename];
24102 if (att.stub) {
24103 digests.push(att.digest);
24104 }
24105 });
24106 }
24107 });
24108 if (!digests.length) {
24109 return finish();
24110 }
24111 var numDone = 0;
24112 var err;
24113
24114 digests.forEach(function (digest) {
24115 verifyAttachment(digest, function (attErr) {
24116 if (attErr && !err) {
24117 err = attErr;
24118 }
24119
24120 if (++numDone === digests.length) {
24121 finish(err);
24122 }
24123 });
24124 });
24125 }
24126
24127 function fetchExistingDocs(finish) {
24128 var numDone = 0;
24129 var overallErr;
24130 function checkDone() {
24131 if (++numDone === userDocs.length) {
24132 return finish(overallErr);
24133 }
24134 }
24135
24136 userDocs.forEach(function (doc) {
24137 if (doc._id && isLocalId(doc._id)) {
24138 // skip local docs
24139 return checkDone();
24140 }
24141 txn.get(stores.docStore, doc._id, function (err, info) {
24142 if (err) {
24143 /* istanbul ignore if */
24144 if (err.name !== 'NotFoundError') {
24145 overallErr = err;
24146 }
24147 } else {
24148 fetchedDocs.set(doc._id, info);
24149 }
24150 checkDone();
24151 });
24152 });
24153 }
24154
24155 function compact(revsMap, callback) {
24156 var promise = Promise.resolve();
24157 revsMap.forEach(function (revs, docId) {
24158 // TODO: parallelize, for now need to be sequential to
24159 // pass orphaned attachment tests
24160 promise = promise.then(function () {
24161 return new Promise(function (resolve, reject) {
24162 api._doCompactionNoLock(docId, revs, {ctx: txn}, function (err) {
24163 /* istanbul ignore if */
24164 if (err) {
24165 return reject(err);
24166 }
24167 resolve();
24168 });
24169 });
24170 });
24171 });
24172
24173 promise.then(function () {
24174 callback();
24175 }, callback);
24176 }
24177
24178 function autoCompact(callback) {
24179 var revsMap = new Map();
24180 fetchedDocs.forEach(function (metadata, docId) {
24181 revsMap.set(docId, compactTree(metadata));
24182 });
24183 compact(revsMap, callback);
24184 }
24185
24186 function finish() {
24187 compact(stemmedRevs, function (error) {
24188 /* istanbul ignore if */
24189 if (error) {
24190 complete(error);
24191 }
24192 if (api.auto_compaction) {
24193 return autoCompact(complete);
24194 }
24195 complete();
24196 });
24197 }
24198
24199 function writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
24200 isUpdate, delta, resultsIdx, callback2) {
24201 docCountDelta += delta;
24202
24203 var err = null;
24204 var recv = 0;
24205
24206 docInfo.metadata.winningRev = winningRev$$1;
24207 docInfo.metadata.deleted = winningRevIsDeleted;
24208
24209 docInfo.data._id = docInfo.metadata.id;
24210 docInfo.data._rev = docInfo.metadata.rev;
24211
24212 if (newRevIsDeleted) {
24213 docInfo.data._deleted = true;
24214 }
24215
24216 if (docInfo.stemmedRevs.length) {
24217 stemmedRevs.set(docInfo.metadata.id, docInfo.stemmedRevs);
24218 }
24219
24220 var attachments = docInfo.data._attachments ?
24221 Object.keys(docInfo.data._attachments) :
24222 [];
24223
24224 function attachmentSaved(attachmentErr) {
24225 recv++;
24226 if (!err) {
24227 /* istanbul ignore if */
24228 if (attachmentErr) {
24229 err = attachmentErr;
24230 callback2(err);
24231 } else if (recv === attachments.length) {
24232 finish();
24233 }
24234 }
24235 }
24236
24237 function onMD5Load(doc, key, data, attachmentSaved) {
24238 return function (result) {
24239 saveAttachment(doc, MD5_PREFIX + result, key, data, attachmentSaved);
24240 };
24241 }
24242
24243 function doMD5(doc, key, attachmentSaved) {
24244 return function (data) {
24245 binaryMd5(data, onMD5Load(doc, key, data, attachmentSaved));
24246 };
24247 }
24248
24249 for (var i = 0; i < attachments.length; i++) {
24250 var key = attachments[i];
24251 var att = docInfo.data._attachments[key];
24252
24253 if (att.stub) {
24254 // still need to update the refs mapping
24255 var id = docInfo.data._id;
24256 var rev$$1 = docInfo.data._rev;
24257 saveAttachmentRefs(id, rev$$1, att.digest, attachmentSaved);
24258 continue;
24259 }
24260 var data;
24261 if (typeof att.data === 'string') {
24262 // input is assumed to be a base64 string
24263 try {
24264 data = thisAtob(att.data);
24265 } catch (e) {
24266 callback(createError(BAD_ARG,
24267 'Attachment is not a valid base64 string'));
24268 return;
24269 }
24270 doMD5(docInfo, key, attachmentSaved)(data);
24271 } else {
24272 prepareAttachmentForStorage(att.data,
24273 doMD5(docInfo, key, attachmentSaved));
24274 }
24275 }
24276
24277 function finish() {
24278 var seq = docInfo.metadata.rev_map[docInfo.metadata.rev];
24279 /* istanbul ignore if */
24280 if (seq) {
24281 // check that there aren't any existing revisions with the same
24282 // revision id, else we shouldn't do anything
24283 return callback2();
24284 }
24285 seq = ++newUpdateSeq;
24286 docInfo.metadata.rev_map[docInfo.metadata.rev] =
24287 docInfo.metadata.seq = seq;
24288 var seqKey = formatSeq(seq);
24289 var batch = [{
24290 key: seqKey,
24291 value: docInfo.data,
24292 prefix: stores.bySeqStore,
24293 type: 'put'
24294 }, {
24295 key: docInfo.metadata.id,
24296 value: docInfo.metadata,
24297 prefix: stores.docStore,
24298 type: 'put'
24299 }];
24300 txn.batch(batch);
24301 results[resultsIdx] = {
24302 ok: true,
24303 id: docInfo.metadata.id,
24304 rev: docInfo.metadata.rev
24305 };
24306 fetchedDocs.set(docInfo.metadata.id, docInfo.metadata);
24307 callback2();
24308 }
24309
24310 if (!attachments.length) {
24311 finish();
24312 }
24313 }
24314
24315 // attachments are queued per-digest, otherwise the refs could be
24316 // overwritten by concurrent writes in the same bulkDocs session
24317 var attachmentQueues = {};
24318
24319 function saveAttachmentRefs(id, rev$$1, digest, callback) {
24320
24321 function fetchAtt() {
24322 return new Promise(function (resolve, reject) {
24323 txn.get(stores.attachmentStore, digest, function (err, oldAtt) {
24324 /* istanbul ignore if */
24325 if (err && err.name !== 'NotFoundError') {
24326 return reject(err);
24327 }
24328 resolve(oldAtt);
24329 });
24330 });
24331 }
24332
24333 function saveAtt(oldAtt) {
24334 var ref = [id, rev$$1].join('@');
24335 var newAtt = {};
24336
24337 if (oldAtt) {
24338 if (oldAtt.refs) {
24339 // only update references if this attachment already has them
24340 // since we cannot migrate old style attachments here without
24341 // doing a full db scan for references
24342 newAtt.refs = oldAtt.refs;
24343 newAtt.refs[ref] = true;
24344 }
24345 } else {
24346 newAtt.refs = {};
24347 newAtt.refs[ref] = true;
24348 }
24349
24350 return new Promise(function (resolve) {
24351 txn.batch([{
24352 type: 'put',
24353 prefix: stores.attachmentStore,
24354 key: digest,
24355 value: newAtt
24356 }]);
24357 resolve(!oldAtt);
24358 });
24359 }
24360
24361 // put attachments in a per-digest queue, to avoid two docs with the same
24362 // attachment overwriting each other
24363 var queue = attachmentQueues[digest] || Promise.resolve();
24364 attachmentQueues[digest] = queue.then(function () {
24365 return fetchAtt().then(saveAtt).then(function (isNewAttachment) {
24366 callback(null, isNewAttachment);
24367 }, callback);
24368 });
24369 }
24370
24371 function saveAttachment(docInfo, digest, key, data, callback) {
24372 var att = docInfo.data._attachments[key];
24373 delete att.data;
24374 att.digest = digest;
24375 att.length = data.length;
24376 var id = docInfo.metadata.id;
24377 var rev$$1 = docInfo.metadata.rev;
24378 att.revpos = parseInt(rev$$1, 10);
24379
24380 saveAttachmentRefs(id, rev$$1, digest, function (err, isNewAttachment) {
24381 /* istanbul ignore if */
24382 if (err) {
24383 return callback(err);
24384 }
24385 // do not try to store empty attachments
24386 if (data.length === 0) {
24387 return callback(err);
24388 }
24389 if (!isNewAttachment) {
24390 // small optimization - don't bother writing it again
24391 return callback(err);
24392 }
24393 txn.batch([{
24394 type: 'put',
24395 prefix: stores.binaryStore,
24396 key: digest,
24397 value: Buffer.from(data, 'binary')
24398 }]);
24399 callback();
24400 });
24401 }
24402
24403 function complete(err) {
24404 /* istanbul ignore if */
24405 if (err) {
24406 return nextTick(function () {
24407 callback(err);
24408 });
24409 }
24410 txn.batch([
24411 {
24412 prefix: stores.metaStore,
24413 type: 'put',
24414 key: UPDATE_SEQ_KEY,
24415 value: newUpdateSeq
24416 },
24417 {
24418 prefix: stores.metaStore,
24419 type: 'put',
24420 key: DOC_COUNT_KEY,
24421 value: db._docCount + docCountDelta
24422 }
24423 ]);
24424 txn.execute(db, function (err) {
24425 /* istanbul ignore if */
24426 if (err) {
24427 return callback(err);
24428 }
24429 db._docCount += docCountDelta;
24430 db._updateSeq = newUpdateSeq;
24431 levelChanges.notify(name);
24432 nextTick(function () {
24433 callback(null, results);
24434 });
24435 });
24436 }
24437
24438 if (!docInfos.length) {
24439 return callback(null, []);
24440 }
24441
24442 verifyAttachments(function (err) {
24443 if (err) {
24444 return callback(err);
24445 }
24446 fetchExistingDocs(function (err) {
24447 /* istanbul ignore if */
24448 if (err) {
24449 return callback(err);
24450 }
24451 processDocs(revLimit, docInfos, api, fetchedDocs, txn, results,
24452 writeDoc, opts, finish);
24453 });
24454 });
24455 });
24456 api._allDocs = function (opts, callback) {
24457 if ('keys' in opts) {
24458 return allDocsKeysQuery(this, opts);
24459 }
24460 return readLock(function (opts, callback) {
24461 opts = clone$1(opts);
24462 countDocs(function (err, docCount) {
24463 /* istanbul ignore if */
24464 if (err) {
24465 return callback(err);
24466 }
24467 var readstreamOpts = {};
24468 var skip = opts.skip || 0;
24469 if (opts.startkey) {
24470 readstreamOpts.gte = opts.startkey;
24471 }
24472 if (opts.endkey) {
24473 readstreamOpts.lte = opts.endkey;
24474 }
24475 if (opts.key) {
24476 readstreamOpts.gte = readstreamOpts.lte = opts.key;
24477 }
24478 if (opts.descending) {
24479 readstreamOpts.reverse = true;
24480 // switch start and ends
24481 var tmp = readstreamOpts.lte;
24482 readstreamOpts.lte = readstreamOpts.gte;
24483 readstreamOpts.gte = tmp;
24484 }
24485 var limit;
24486 if (typeof opts.limit === 'number') {
24487 limit = opts.limit;
24488 }
24489 if (limit === 0 ||
24490 ('gte' in readstreamOpts && 'lte' in readstreamOpts &&
24491 readstreamOpts.gte > readstreamOpts.lte)) {
24492 // should return 0 results when start is greater than end.
24493 // normally level would "fix" this for us by reversing the order,
24494 // so short-circuit instead
24495 var returnVal = {
24496 total_rows: docCount,
24497 offset: opts.skip,
24498 rows: []
24499 };
24500 /* istanbul ignore if */
24501 if (opts.update_seq) {
24502 returnVal.update_seq = db._updateSeq;
24503 }
24504 return callback(null, returnVal);
24505 }
24506 var results = [];
24507 var docstream = stores.docStore.readStream(readstreamOpts);
24508
24509 var throughStream = through2.obj(function (entry, _, next) {
24510 var metadata = entry.value;
24511 // winningRev and deleted are performance-killers, but
24512 // in newer versions of PouchDB, they are cached on the metadata
24513 var winningRev$$1 = getWinningRev(metadata);
24514 var deleted = getIsDeleted(metadata, winningRev$$1);
24515 if (!deleted) {
24516 if (skip-- > 0) {
24517 next();
24518 return;
24519 } else if (typeof limit === 'number' && limit-- <= 0) {
24520 docstream.unpipe();
24521 docstream.destroy();
24522 next();
24523 return;
24524 }
24525 } else if (opts.deleted !== 'ok') {
24526 next();
24527 return;
24528 }
24529 function allDocsInner(data) {
24530 var doc = {
24531 id: metadata.id,
24532 key: metadata.id,
24533 value: {
24534 rev: winningRev$$1
24535 }
24536 };
24537 if (opts.include_docs) {
24538 doc.doc = data;
24539 doc.doc._rev = doc.value.rev;
24540 if (opts.conflicts) {
24541 var conflicts = collectConflicts(metadata);
24542 if (conflicts.length) {
24543 doc.doc._conflicts = conflicts;
24544 }
24545 }
24546 for (var att in doc.doc._attachments) {
24547 if (Object.prototype.hasOwnProperty.call(doc.doc._attachments, att)) {
24548 doc.doc._attachments[att].stub = true;
24549 }
24550 }
24551 }
24552 if (opts.inclusive_end === false && metadata.id === opts.endkey) {
24553 return next();
24554 } else if (deleted) {
24555 if (opts.deleted === 'ok') {
24556 doc.value.deleted = true;
24557 doc.doc = null;
24558 } else {
24559 /* istanbul ignore next */
24560 return next();
24561 }
24562 }
24563 results.push(doc);
24564 next();
24565 }
24566 if (opts.include_docs) {
24567 var seq = metadata.rev_map[winningRev$$1];
24568 stores.bySeqStore.get(formatSeq(seq), function (err, data) {
24569 allDocsInner(data);
24570 });
24571 }
24572 else {
24573 allDocsInner();
24574 }
24575 }, function (next) {
24576 Promise.resolve().then(function () {
24577 if (opts.include_docs && opts.attachments) {
24578 return fetchAttachments(results, stores, opts);
24579 }
24580 }).then(function () {
24581 var returnVal = {
24582 total_rows: docCount,
24583 offset: opts.skip,
24584 rows: results
24585 };
24586
24587 /* istanbul ignore if */
24588 if (opts.update_seq) {
24589 returnVal.update_seq = db._updateSeq;
24590 }
24591 callback(null, returnVal);
24592 }, callback);
24593 next();
24594 }).on('unpipe', function () {
24595 throughStream.end();
24596 });
24597
24598 docstream.on('error', callback);
24599
24600 docstream.pipe(throughStream);
24601 });
24602 })(opts, callback);
24603 };
24604
24605 api._changes = function (opts) {
24606 opts = clone$1(opts);
24607
24608 if (opts.continuous) {
24609 var id = name + ':' + uuid$1();
24610 levelChanges.addListener(name, id, api, opts);
24611 levelChanges.notify(name);
24612 return {
24613 cancel: function () {
24614 levelChanges.removeListener(name, id);
24615 }
24616 };
24617 }
24618
24619 var descending = opts.descending;
24620 var results = [];
24621 var lastSeq = opts.since || 0;
24622 var called = 0;
24623 var streamOpts = {
24624 reverse: descending
24625 };
24626 var limit;
24627 if ('limit' in opts && opts.limit > 0) {
24628 limit = opts.limit;
24629 }
24630 if (!streamOpts.reverse) {
24631 streamOpts.start = formatSeq(opts.since || 0);
24632 }
24633
24634 var docIds = opts.doc_ids && new Set(opts.doc_ids);
24635 var filter = filterChange(opts);
24636 var docIdsToMetadata = new Map();
24637
24638 function complete() {
24639 opts.done = true;
24640 if (opts.return_docs && opts.limit) {
24641 /* istanbul ignore if */
24642 if (opts.limit < results.length) {
24643 results.length = opts.limit;
24644 }
24645 }
24646 changeStream.unpipe(throughStream);
24647 changeStream.destroy();
24648 if (!opts.continuous && !opts.cancelled) {
24649 if (opts.include_docs && opts.attachments && opts.return_docs) {
24650 fetchAttachments(results, stores, opts).then(function () {
24651 opts.complete(null, {results, last_seq: lastSeq});
24652 });
24653 } else {
24654 opts.complete(null, {results, last_seq: lastSeq});
24655 }
24656 }
24657 }
24658 var changeStream = stores.bySeqStore.readStream(streamOpts);
24659 var throughStream = through2.obj(function (data, _, next) {
24660 if (limit && called >= limit) {
24661 complete();
24662 return next();
24663 }
24664 if (opts.cancelled || opts.done) {
24665 return next();
24666 }
24667
24668 var seq = parseSeq(data.key);
24669 var doc = data.value;
24670
24671 if (seq === opts.since && !descending) {
24672 // couchdb ignores `since` if descending=true
24673 return next();
24674 }
24675
24676 if (docIds && !docIds.has(doc._id)) {
24677 return next();
24678 }
24679
24680 var metadata;
24681
24682 function onGetMetadata(metadata) {
24683 var winningRev$$1 = getWinningRev(metadata);
24684
24685 function onGetWinningDoc(winningDoc) {
24686
24687 var change = opts.processChange(winningDoc, metadata, opts);
24688 change.seq = metadata.seq;
24689
24690 var filtered = filter(change);
24691 if (typeof filtered === 'object') {
24692 return opts.complete(filtered);
24693 }
24694
24695 if (filtered) {
24696 called++;
24697
24698 if (opts.attachments && opts.include_docs) {
24699 // fetch attachment immediately for the benefit
24700 // of live listeners
24701 fetchAttachments([change], stores, opts).then(function () {
24702 opts.onChange(change);
24703 });
24704 } else {
24705 opts.onChange(change);
24706 }
24707
24708 if (opts.return_docs) {
24709 results.push(change);
24710 }
24711 }
24712 next();
24713 }
24714
24715 if (metadata.seq !== seq) {
24716 // some other seq is later
24717 return next();
24718 }
24719
24720 lastSeq = seq;
24721
24722 if (winningRev$$1 === doc._rev) {
24723 return onGetWinningDoc(doc);
24724 }
24725
24726 // fetch the winner
24727
24728 var winningSeq = metadata.rev_map[winningRev$$1];
24729
24730 stores.bySeqStore.get(formatSeq(winningSeq), function (err, doc) {
24731 onGetWinningDoc(doc);
24732 });
24733 }
24734
24735 metadata = docIdsToMetadata.get(doc._id);
24736 if (metadata) { // cached
24737 return onGetMetadata(metadata);
24738 }
24739 // metadata not cached, have to go fetch it
24740 stores.docStore.get(doc._id, function (err, metadata) {
24741 /* istanbul ignore if */
24742 if (opts.cancelled || opts.done || db.isClosed() ||
24743 isLocalId(metadata.id)) {
24744 return next();
24745 }
24746 docIdsToMetadata.set(doc._id, metadata);
24747 onGetMetadata(metadata);
24748 });
24749 }, function (next) {
24750 if (opts.cancelled) {
24751 return next();
24752 }
24753 if (opts.return_docs && opts.limit) {
24754 /* istanbul ignore if */
24755 if (opts.limit < results.length) {
24756 results.length = opts.limit;
24757 }
24758 }
24759
24760 next();
24761 }).on('unpipe', function () {
24762 throughStream.end();
24763 complete();
24764 });
24765 changeStream.pipe(throughStream);
24766 return {
24767 cancel: function () {
24768 opts.cancelled = true;
24769 complete();
24770 }
24771 };
24772 };
24773
24774 api._close = function (callback) {
24775 /* istanbul ignore if */
24776 if (db.isClosed()) {
24777 return callback(createError(NOT_OPEN));
24778 }
24779 db.close(function (err) {
24780 /* istanbul ignore if */
24781 if (err) {
24782 callback(err);
24783 } else {
24784 dbStore.delete(name);
24785
24786 var adapterName = functionName(leveldown);
24787 var adapterStore = dbStores.get(adapterName);
24788 var viewNamePrefix = PouchDB$1.prefix + name + "-mrview-";
24789 var keys = [...adapterStore.keys()].filter(k => k.includes(viewNamePrefix));
24790 keys.forEach(key => {
24791 var eventEmitter = adapterStore.get(key);
24792 eventEmitter.removeAllListeners();
24793 eventEmitter.close();
24794 adapterStore.delete(key);
24795 });
24796
24797 callback();
24798 }
24799 });
24800 };
24801
24802 api._getRevisionTree = function (docId, callback) {
24803 stores.docStore.get(docId, function (err, metadata) {
24804 if (err) {
24805 callback(createError(MISSING_DOC));
24806 } else {
24807 callback(null, metadata.rev_tree);
24808 }
24809 });
24810 };
24811
24812 api._doCompaction = writeLock(function (docId, revs, opts, callback) {
24813 api._doCompactionNoLock(docId, revs, opts, callback);
24814 });
24815
24816 // the NoLock version is for use by bulkDocs
24817 api._doCompactionNoLock = function (docId, revs, opts, callback) {
24818 if (typeof opts === 'function') {
24819 callback = opts;
24820 opts = {};
24821 }
24822
24823 if (!revs.length) {
24824 return callback();
24825 }
24826 var txn = opts.ctx || new LevelTransaction();
24827
24828 txn.get(stores.docStore, docId, function (err, metadata) {
24829 /* istanbul ignore if */
24830 if (err) {
24831 return callback(err);
24832 }
24833 var seqs = revs.map(function (rev$$1) {
24834 var seq = metadata.rev_map[rev$$1];
24835 delete metadata.rev_map[rev$$1];
24836 return seq;
24837 });
24838 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
24839 revHash, ctx, opts) {
24840 var rev$$1 = pos + '-' + revHash;
24841 if (revs.indexOf(rev$$1) !== -1) {
24842 opts.status = 'missing';
24843 }
24844 });
24845
24846 var batch = [];
24847 batch.push({
24848 key: metadata.id,
24849 value: metadata,
24850 type: 'put',
24851 prefix: stores.docStore
24852 });
24853
24854 var digestMap = {};
24855 var numDone = 0;
24856 var overallErr;
24857 function checkDone(err) {
24858 /* istanbul ignore if */
24859 if (err) {
24860 overallErr = err;
24861 }
24862 if (++numDone === revs.length) { // done
24863 /* istanbul ignore if */
24864 if (overallErr) {
24865 return callback(overallErr);
24866 }
24867 deleteOrphanedAttachments();
24868 }
24869 }
24870
24871 function finish(err) {
24872 /* istanbul ignore if */
24873 if (err) {
24874 return callback(err);
24875 }
24876 txn.batch(batch);
24877 if (opts.ctx) {
24878 // don't execute immediately
24879 return callback();
24880 }
24881 txn.execute(db, callback);
24882 }
24883
24884 function deleteOrphanedAttachments() {
24885 var possiblyOrphanedAttachments = Object.keys(digestMap);
24886 if (!possiblyOrphanedAttachments.length) {
24887 return finish();
24888 }
24889 var numDone = 0;
24890 var overallErr;
24891 function checkDone(err) {
24892 /* istanbul ignore if */
24893 if (err) {
24894 overallErr = err;
24895 }
24896 if (++numDone === possiblyOrphanedAttachments.length) {
24897 finish(overallErr);
24898 }
24899 }
24900 var refsToDelete = new Map();
24901 revs.forEach(function (rev$$1) {
24902 refsToDelete.set(docId + '@' + rev$$1, true);
24903 });
24904 possiblyOrphanedAttachments.forEach(function (digest) {
24905 txn.get(stores.attachmentStore, digest, function (err, attData) {
24906 /* istanbul ignore if */
24907 if (err) {
24908 if (err.name === 'NotFoundError') {
24909 return checkDone();
24910 } else {
24911 return checkDone(err);
24912 }
24913 }
24914 var refs = Object.keys(attData.refs || {}).filter(function (ref) {
24915 return !refsToDelete.has(ref);
24916 });
24917 var newRefs = {};
24918 refs.forEach(function (ref) {
24919 newRefs[ref] = true;
24920 });
24921 if (refs.length) { // not orphaned
24922 batch.push({
24923 key: digest,
24924 type: 'put',
24925 value: {refs: newRefs},
24926 prefix: stores.attachmentStore
24927 });
24928 } else { // orphaned, can safely delete
24929 batch = batch.concat([{
24930 key: digest,
24931 type: 'del',
24932 prefix: stores.attachmentStore
24933 }, {
24934 key: digest,
24935 type: 'del',
24936 prefix: stores.binaryStore
24937 }]);
24938 }
24939 checkDone();
24940 });
24941 });
24942 }
24943
24944 seqs.forEach(function (seq) {
24945 batch.push({
24946 key: formatSeq(seq),
24947 type: 'del',
24948 prefix: stores.bySeqStore
24949 });
24950 txn.get(stores.bySeqStore, formatSeq(seq), function (err, doc) {
24951 /* istanbul ignore if */
24952 if (err) {
24953 if (err.name === 'NotFoundError') {
24954 return checkDone();
24955 } else {
24956 return checkDone(err);
24957 }
24958 }
24959 var atts = Object.keys(doc._attachments || {});
24960 atts.forEach(function (attName) {
24961 var digest = doc._attachments[attName].digest;
24962 digestMap[digest] = true;
24963 });
24964 checkDone();
24965 });
24966 });
24967 });
24968 };
24969
24970 api._getLocal = function (id, callback) {
24971 stores.localStore.get(id, function (err, doc) {
24972 if (err) {
24973 callback(createError(MISSING_DOC));
24974 } else {
24975 callback(null, doc);
24976 }
24977 });
24978 };
24979
24980 api._putLocal = function (doc, opts, callback) {
24981 if (typeof opts === 'function') {
24982 callback = opts;
24983 opts = {};
24984 }
24985 if (opts.ctx) {
24986 api._putLocalNoLock(doc, opts, callback);
24987 } else {
24988 api._putLocalWithLock(doc, opts, callback);
24989 }
24990 };
24991
24992 api._putLocalWithLock = writeLock(function (doc, opts, callback) {
24993 api._putLocalNoLock(doc, opts, callback);
24994 });
24995
24996 // the NoLock version is for use by bulkDocs
24997 api._putLocalNoLock = function (doc, opts, callback) {
24998 delete doc._revisions; // ignore this, trust the rev
24999 var oldRev = doc._rev;
25000 var id = doc._id;
25001
25002 var txn = opts.ctx || new LevelTransaction();
25003
25004 txn.get(stores.localStore, id, function (err, resp) {
25005 if (err && oldRev) {
25006 return callback(createError(REV_CONFLICT));
25007 }
25008 if (resp && resp._rev !== oldRev) {
25009 return callback(createError(REV_CONFLICT));
25010 }
25011 doc._rev =
25012 oldRev ? '0-' + (parseInt(oldRev.split('-')[1], 10) + 1) : '0-1';
25013 var batch = [
25014 {
25015 type: 'put',
25016 prefix: stores.localStore,
25017 key: id,
25018 value: doc
25019 }
25020 ];
25021
25022 txn.batch(batch);
25023 var ret = {ok: true, id: doc._id, rev: doc._rev};
25024
25025 if (opts.ctx) {
25026 // don't execute immediately
25027 return callback(null, ret);
25028 }
25029 txn.execute(db, function (err) {
25030 /* istanbul ignore if */
25031 if (err) {
25032 return callback(err);
25033 }
25034 callback(null, ret);
25035 });
25036 });
25037 };
25038
25039 api._removeLocal = function (doc, opts, callback) {
25040 if (typeof opts === 'function') {
25041 callback = opts;
25042 opts = {};
25043 }
25044 if (opts.ctx) {
25045 api._removeLocalNoLock(doc, opts, callback);
25046 } else {
25047 api._removeLocalWithLock(doc, opts, callback);
25048 }
25049 };
25050
25051 api._removeLocalWithLock = writeLock(function (doc, opts, callback) {
25052 api._removeLocalNoLock(doc, opts, callback);
25053 });
25054
25055 // the NoLock version is for use by bulkDocs
25056 api._removeLocalNoLock = function (doc, opts, callback) {
25057 var txn = opts.ctx || new LevelTransaction();
25058 txn.get(stores.localStore, doc._id, function (err, resp) {
25059 if (err) {
25060 /* istanbul ignore if */
25061 if (err.name !== 'NotFoundError') {
25062 return callback(err);
25063 } else {
25064 return callback(createError(MISSING_DOC));
25065 }
25066 }
25067 if (resp._rev !== doc._rev) {
25068 return callback(createError(REV_CONFLICT));
25069 }
25070 txn.batch([{
25071 prefix: stores.localStore,
25072 type: 'del',
25073 key: doc._id
25074 }]);
25075 var ret = {ok: true, id: doc._id, rev: '0-0'};
25076 if (opts.ctx) {
25077 // don't execute immediately
25078 return callback(null, ret);
25079 }
25080 txn.execute(db, function (err) {
25081 /* istanbul ignore if */
25082 if (err) {
25083 return callback(err);
25084 }
25085 callback(null, ret);
25086 });
25087 });
25088 };
25089
25090 // close and delete open leveldb stores
25091 api._destroy = function (opts, callback) {
25092 var dbStore;
25093 var leveldownName = functionName(leveldown);
25094 /* istanbul ignore else */
25095 if (dbStores.has(leveldownName)) {
25096 dbStore = dbStores.get(leveldownName);
25097 } else {
25098 return callDestroy(name, callback);
25099 }
25100
25101 /* istanbul ignore else */
25102 if (dbStore.has(name)) {
25103 levelChanges.removeAllListeners(name);
25104
25105 dbStore.get(name).close(function () {
25106 dbStore.delete(name);
25107 callDestroy(name, callback);
25108 });
25109 } else {
25110 callDestroy(name, callback);
25111 }
25112 };
25113 function callDestroy(name, cb) {
25114 // May not exist if leveldown is backed by memory adapter
25115 /* istanbul ignore else */
25116 if ('destroy' in leveldown) {
25117 leveldown.destroy(name, cb);
25118 } else {
25119 cb(null);
25120 }
25121 }
25122}
25123
25124function LocalStoragePouch(opts, callback) {
25125 var _opts = Object.assign({
25126 db: localstoragedown
25127 }, opts);
25128
25129 LevelPouch.call(this, _opts, callback);
25130}
25131
25132// overrides for normal LevelDB behavior on Node
25133LocalStoragePouch.valid = function () {
25134 return typeof localStorage !== 'undefined';
25135};
25136LocalStoragePouch.use_prefix = true;
25137
25138function LocalStoragePouchPlugin (PouchDB) {
25139 PouchDB.adapter('localstorage', LocalStoragePouch, true);
25140}
25141
25142// this code only runs in the browser, as its own dist/ script
25143
25144if (typeof PouchDB === 'undefined') {
25145 guardedConsole('error', 'localstorage adapter plugin error: ' +
25146 'Cannot find global "PouchDB" object! ' +
25147 'Did you remember to include pouchdb.js?');
25148} else {
25149 PouchDB.plugin(LocalStoragePouchPlugin);
25150}
25151
25152}).call(this)}).call(this,_dereq_("buffer").Buffer)
25153},{"buffer":9,"double-ended-queue":28,"events":39,"level-codec":56,"levelup":78,"localstorage-down":80,"ltgt":87,"readable-stream":102,"spark-md5":105,"through2":139,"uuid":146,"vuvuzela":161}]},{},[164]);
25154
\No newline at end of file