UNPKG

496 kBJavaScriptView Raw
1// PouchDB in-memory plugin 7.0.0
2// Based on MemDOWN: https://github.com/rvagg/memdown
3//
4// (c) 2012-2018 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'use strict';
10
11module.exports = argsArray;
12
13function argsArray(fun) {
14 return function () {
15 var len = arguments.length;
16 if (len) {
17 var args = [];
18 var i = -1;
19 while (++i < len) {
20 args[i] = arguments[i];
21 }
22 return fun.call(this, args);
23 } else {
24 return fun.call(this, []);
25 }
26 };
27}
28},{}],2:[function(_dereq_,module,exports){
29(function (global){
30'use strict';
31
32// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
33// original notice:
34
35/*!
36 * The buffer module from node.js, for the browser.
37 *
38 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
39 * @license MIT
40 */
41function compare(a, b) {
42 if (a === b) {
43 return 0;
44 }
45
46 var x = a.length;
47 var y = b.length;
48
49 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
50 if (a[i] !== b[i]) {
51 x = a[i];
52 y = b[i];
53 break;
54 }
55 }
56
57 if (x < y) {
58 return -1;
59 }
60 if (y < x) {
61 return 1;
62 }
63 return 0;
64}
65function isBuffer(b) {
66 if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
67 return global.Buffer.isBuffer(b);
68 }
69 return !!(b != null && b._isBuffer);
70}
71
72// based on node assert, original notice:
73
74// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
75//
76// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
77//
78// Originally from narwhal.js (http://narwhaljs.org)
79// Copyright (c) 2009 Thomas Robinson <280north.com>
80//
81// Permission is hereby granted, free of charge, to any person obtaining a copy
82// of this software and associated documentation files (the 'Software'), to
83// deal in the Software without restriction, including without limitation the
84// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
85// sell copies of the Software, and to permit persons to whom the Software is
86// furnished to do so, subject to the following conditions:
87//
88// The above copyright notice and this permission notice shall be included in
89// all copies or substantial portions of the Software.
90//
91// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
92// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
93// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
94// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
95// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
96// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
97
98var util = _dereq_(5);
99var hasOwn = Object.prototype.hasOwnProperty;
100var pSlice = Array.prototype.slice;
101var functionsHaveNames = (function () {
102 return function foo() {}.name === 'foo';
103}());
104function pToString (obj) {
105 return Object.prototype.toString.call(obj);
106}
107function isView(arrbuf) {
108 if (isBuffer(arrbuf)) {
109 return false;
110 }
111 if (typeof global.ArrayBuffer !== 'function') {
112 return false;
113 }
114 if (typeof ArrayBuffer.isView === 'function') {
115 return ArrayBuffer.isView(arrbuf);
116 }
117 if (!arrbuf) {
118 return false;
119 }
120 if (arrbuf instanceof DataView) {
121 return true;
122 }
123 if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
124 return true;
125 }
126 return false;
127}
128// 1. The assert module provides functions that throw
129// AssertionError's when particular conditions are not met. The
130// assert module must conform to the following interface.
131
132var assert = module.exports = ok;
133
134// 2. The AssertionError is defined in assert.
135// new assert.AssertionError({ message: message,
136// actual: actual,
137// expected: expected })
138
139var regex = /\s*function\s+([^\(\s]*)\s*/;
140// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
141function getName(func) {
142 if (!util.isFunction(func)) {
143 return;
144 }
145 if (functionsHaveNames) {
146 return func.name;
147 }
148 var str = func.toString();
149 var match = str.match(regex);
150 return match && match[1];
151}
152assert.AssertionError = function AssertionError(options) {
153 this.name = 'AssertionError';
154 this.actual = options.actual;
155 this.expected = options.expected;
156 this.operator = options.operator;
157 if (options.message) {
158 this.message = options.message;
159 this.generatedMessage = false;
160 } else {
161 this.message = getMessage(this);
162 this.generatedMessage = true;
163 }
164 var stackStartFunction = options.stackStartFunction || fail;
165 if (Error.captureStackTrace) {
166 Error.captureStackTrace(this, stackStartFunction);
167 } else {
168 // non v8 browsers so we can have a stacktrace
169 var err = new Error();
170 if (err.stack) {
171 var out = err.stack;
172
173 // try to strip useless frames
174 var fn_name = getName(stackStartFunction);
175 var idx = out.indexOf('\n' + fn_name);
176 if (idx >= 0) {
177 // once we have located the function frame
178 // we need to strip out everything before it (and its line)
179 var next_line = out.indexOf('\n', idx + 1);
180 out = out.substring(next_line + 1);
181 }
182
183 this.stack = out;
184 }
185 }
186};
187
188// assert.AssertionError instanceof Error
189util.inherits(assert.AssertionError, Error);
190
191function truncate(s, n) {
192 if (typeof s === 'string') {
193 return s.length < n ? s : s.slice(0, n);
194 } else {
195 return s;
196 }
197}
198function inspect(something) {
199 if (functionsHaveNames || !util.isFunction(something)) {
200 return util.inspect(something);
201 }
202 var rawname = getName(something);
203 var name = rawname ? ': ' + rawname : '';
204 return '[Function' + name + ']';
205}
206function getMessage(self) {
207 return truncate(inspect(self.actual), 128) + ' ' +
208 self.operator + ' ' +
209 truncate(inspect(self.expected), 128);
210}
211
212// At present only the three keys mentioned above are used and
213// understood by the spec. Implementations or sub modules can pass
214// other keys to the AssertionError's constructor - they will be
215// ignored.
216
217// 3. All of the following functions must throw an AssertionError
218// when a corresponding condition is not met, with a message that
219// may be undefined if not provided. All assertion methods provide
220// both the actual and expected values to the assertion error for
221// display purposes.
222
223function fail(actual, expected, message, operator, stackStartFunction) {
224 throw new assert.AssertionError({
225 message: message,
226 actual: actual,
227 expected: expected,
228 operator: operator,
229 stackStartFunction: stackStartFunction
230 });
231}
232
233// EXTENSION! allows for well behaved errors defined elsewhere.
234assert.fail = fail;
235
236// 4. Pure assertion tests whether a value is truthy, as determined
237// by !!guard.
238// assert.ok(guard, message_opt);
239// This statement is equivalent to assert.equal(true, !!guard,
240// message_opt);. To test strictly for the value true, use
241// assert.strictEqual(true, guard, message_opt);.
242
243function ok(value, message) {
244 if (!value) fail(value, true, message, '==', assert.ok);
245}
246assert.ok = ok;
247
248// 5. The equality assertion tests shallow, coercive equality with
249// ==.
250// assert.equal(actual, expected, message_opt);
251
252assert.equal = function equal(actual, expected, message) {
253 if (actual != expected) fail(actual, expected, message, '==', assert.equal);
254};
255
256// 6. The non-equality assertion tests for whether two objects are not equal
257// with != assert.notEqual(actual, expected, message_opt);
258
259assert.notEqual = function notEqual(actual, expected, message) {
260 if (actual == expected) {
261 fail(actual, expected, message, '!=', assert.notEqual);
262 }
263};
264
265// 7. The equivalence assertion tests a deep equality relation.
266// assert.deepEqual(actual, expected, message_opt);
267
268assert.deepEqual = function deepEqual(actual, expected, message) {
269 if (!_deepEqual(actual, expected, false)) {
270 fail(actual, expected, message, 'deepEqual', assert.deepEqual);
271 }
272};
273
274assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
275 if (!_deepEqual(actual, expected, true)) {
276 fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
277 }
278};
279
280function _deepEqual(actual, expected, strict, memos) {
281 // 7.1. All identical values are equivalent, as determined by ===.
282 if (actual === expected) {
283 return true;
284 } else if (isBuffer(actual) && isBuffer(expected)) {
285 return compare(actual, expected) === 0;
286
287 // 7.2. If the expected value is a Date object, the actual value is
288 // equivalent if it is also a Date object that refers to the same time.
289 } else if (util.isDate(actual) && util.isDate(expected)) {
290 return actual.getTime() === expected.getTime();
291
292 // 7.3 If the expected value is a RegExp object, the actual value is
293 // equivalent if it is also a RegExp object with the same source and
294 // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
295 } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
296 return actual.source === expected.source &&
297 actual.global === expected.global &&
298 actual.multiline === expected.multiline &&
299 actual.lastIndex === expected.lastIndex &&
300 actual.ignoreCase === expected.ignoreCase;
301
302 // 7.4. Other pairs that do not both pass typeof value == 'object',
303 // equivalence is determined by ==.
304 } else if ((actual === null || typeof actual !== 'object') &&
305 (expected === null || typeof expected !== 'object')) {
306 return strict ? actual === expected : actual == expected;
307
308 // If both values are instances of typed arrays, wrap their underlying
309 // ArrayBuffers in a Buffer each to increase performance
310 // This optimization requires the arrays to have the same type as checked by
311 // Object.prototype.toString (aka pToString). Never perform binary
312 // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
313 // bit patterns are not identical.
314 } else if (isView(actual) && isView(expected) &&
315 pToString(actual) === pToString(expected) &&
316 !(actual instanceof Float32Array ||
317 actual instanceof Float64Array)) {
318 return compare(new Uint8Array(actual.buffer),
319 new Uint8Array(expected.buffer)) === 0;
320
321 // 7.5 For all other Object pairs, including Array objects, equivalence is
322 // determined by having the same number of owned properties (as verified
323 // with Object.prototype.hasOwnProperty.call), the same set of keys
324 // (although not necessarily the same order), equivalent values for every
325 // corresponding key, and an identical 'prototype' property. Note: this
326 // accounts for both named and indexed properties on Arrays.
327 } else if (isBuffer(actual) !== isBuffer(expected)) {
328 return false;
329 } else {
330 memos = memos || {actual: [], expected: []};
331
332 var actualIndex = memos.actual.indexOf(actual);
333 if (actualIndex !== -1) {
334 if (actualIndex === memos.expected.indexOf(expected)) {
335 return true;
336 }
337 }
338
339 memos.actual.push(actual);
340 memos.expected.push(expected);
341
342 return objEquiv(actual, expected, strict, memos);
343 }
344}
345
346function isArguments(object) {
347 return Object.prototype.toString.call(object) == '[object Arguments]';
348}
349
350function objEquiv(a, b, strict, actualVisitedObjects) {
351 if (a === null || a === undefined || b === null || b === undefined)
352 return false;
353 // if one is a primitive, the other must be same
354 if (util.isPrimitive(a) || util.isPrimitive(b))
355 return a === b;
356 if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
357 return false;
358 var aIsArgs = isArguments(a);
359 var bIsArgs = isArguments(b);
360 if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
361 return false;
362 if (aIsArgs) {
363 a = pSlice.call(a);
364 b = pSlice.call(b);
365 return _deepEqual(a, b, strict);
366 }
367 var ka = objectKeys(a);
368 var kb = objectKeys(b);
369 var key, i;
370 // having the same number of owned properties (keys incorporates
371 // hasOwnProperty)
372 if (ka.length !== kb.length)
373 return false;
374 //the same set of keys (although not necessarily the same order),
375 ka.sort();
376 kb.sort();
377 //~~~cheap key test
378 for (i = ka.length - 1; i >= 0; i--) {
379 if (ka[i] !== kb[i])
380 return false;
381 }
382 //equivalent values for every corresponding key, and
383 //~~~possibly expensive deep test
384 for (i = ka.length - 1; i >= 0; i--) {
385 key = ka[i];
386 if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
387 return false;
388 }
389 return true;
390}
391
392// 8. The non-equivalence assertion tests for any deep inequality.
393// assert.notDeepEqual(actual, expected, message_opt);
394
395assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
396 if (_deepEqual(actual, expected, false)) {
397 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
398 }
399};
400
401assert.notDeepStrictEqual = notDeepStrictEqual;
402function notDeepStrictEqual(actual, expected, message) {
403 if (_deepEqual(actual, expected, true)) {
404 fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
405 }
406}
407
408
409// 9. The strict equality assertion tests strict equality, as determined by ===.
410// assert.strictEqual(actual, expected, message_opt);
411
412assert.strictEqual = function strictEqual(actual, expected, message) {
413 if (actual !== expected) {
414 fail(actual, expected, message, '===', assert.strictEqual);
415 }
416};
417
418// 10. The strict non-equality assertion tests for strict inequality, as
419// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
420
421assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
422 if (actual === expected) {
423 fail(actual, expected, message, '!==', assert.notStrictEqual);
424 }
425};
426
427function expectedException(actual, expected) {
428 if (!actual || !expected) {
429 return false;
430 }
431
432 if (Object.prototype.toString.call(expected) == '[object RegExp]') {
433 return expected.test(actual);
434 }
435
436 try {
437 if (actual instanceof expected) {
438 return true;
439 }
440 } catch (e) {
441 // Ignore. The instanceof check doesn't work for arrow functions.
442 }
443
444 if (Error.isPrototypeOf(expected)) {
445 return false;
446 }
447
448 return expected.call({}, actual) === true;
449}
450
451function _tryBlock(block) {
452 var error;
453 try {
454 block();
455 } catch (e) {
456 error = e;
457 }
458 return error;
459}
460
461function _throws(shouldThrow, block, expected, message) {
462 var actual;
463
464 if (typeof block !== 'function') {
465 throw new TypeError('"block" argument must be a function');
466 }
467
468 if (typeof expected === 'string') {
469 message = expected;
470 expected = null;
471 }
472
473 actual = _tryBlock(block);
474
475 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
476 (message ? ' ' + message : '.');
477
478 if (shouldThrow && !actual) {
479 fail(actual, expected, 'Missing expected exception' + message);
480 }
481
482 var userProvidedMessage = typeof message === 'string';
483 var isUnwantedException = !shouldThrow && util.isError(actual);
484 var isUnexpectedException = !shouldThrow && actual && !expected;
485
486 if ((isUnwantedException &&
487 userProvidedMessage &&
488 expectedException(actual, expected)) ||
489 isUnexpectedException) {
490 fail(actual, expected, 'Got unwanted exception' + message);
491 }
492
493 if ((shouldThrow && actual && expected &&
494 !expectedException(actual, expected)) || (!shouldThrow && actual)) {
495 throw actual;
496 }
497}
498
499// 11. Expected to throw an error:
500// assert.throws(block, Error_opt, message_opt);
501
502assert.throws = function(block, /*optional*/error, /*optional*/message) {
503 _throws(true, block, error, message);
504};
505
506// EXTENSION! This is annoying to write outside this module.
507assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
508 _throws(false, block, error, message);
509};
510
511assert.ifError = function(err) { if (err) throw err; };
512
513var objectKeys = Object.keys || function (obj) {
514 var keys = [];
515 for (var key in obj) {
516 if (hasOwn.call(obj, key)) keys.push(key);
517 }
518 return keys;
519};
520
521}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
522},{"5":5}],3:[function(_dereq_,module,exports){
523if (typeof Object.create === 'function') {
524 // implementation from standard node.js 'util' module
525 module.exports = function inherits(ctor, superCtor) {
526 ctor.super_ = superCtor
527 ctor.prototype = Object.create(superCtor.prototype, {
528 constructor: {
529 value: ctor,
530 enumerable: false,
531 writable: true,
532 configurable: true
533 }
534 });
535 };
536} else {
537 // old school shim for old browsers
538 module.exports = function inherits(ctor, superCtor) {
539 ctor.super_ = superCtor
540 var TempCtor = function () {}
541 TempCtor.prototype = superCtor.prototype
542 ctor.prototype = new TempCtor()
543 ctor.prototype.constructor = ctor
544 }
545}
546
547},{}],4:[function(_dereq_,module,exports){
548module.exports = function isBuffer(arg) {
549 return arg && typeof arg === 'object'
550 && typeof arg.copy === 'function'
551 && typeof arg.fill === 'function'
552 && typeof arg.readUInt8 === 'function';
553}
554},{}],5:[function(_dereq_,module,exports){
555(function (process,global){
556// Copyright Joyent, Inc. and other Node contributors.
557//
558// Permission is hereby granted, free of charge, to any person obtaining a
559// copy of this software and associated documentation files (the
560// "Software"), to deal in the Software without restriction, including
561// without limitation the rights to use, copy, modify, merge, publish,
562// distribute, sublicense, and/or sell copies of the Software, and to permit
563// persons to whom the Software is furnished to do so, subject to the
564// following conditions:
565//
566// The above copyright notice and this permission notice shall be included
567// in all copies or substantial portions of the Software.
568//
569// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
570// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
571// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
572// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
573// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
574// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
575// USE OR OTHER DEALINGS IN THE SOFTWARE.
576
577var formatRegExp = /%[sdj%]/g;
578exports.format = function(f) {
579 if (!isString(f)) {
580 var objects = [];
581 for (var i = 0; i < arguments.length; i++) {
582 objects.push(inspect(arguments[i]));
583 }
584 return objects.join(' ');
585 }
586
587 var i = 1;
588 var args = arguments;
589 var len = args.length;
590 var str = String(f).replace(formatRegExp, function(x) {
591 if (x === '%%') return '%';
592 if (i >= len) return x;
593 switch (x) {
594 case '%s': return String(args[i++]);
595 case '%d': return Number(args[i++]);
596 case '%j':
597 try {
598 return JSON.stringify(args[i++]);
599 } catch (_) {
600 return '[Circular]';
601 }
602 default:
603 return x;
604 }
605 });
606 for (var x = args[i]; i < len; x = args[++i]) {
607 if (isNull(x) || !isObject(x)) {
608 str += ' ' + x;
609 } else {
610 str += ' ' + inspect(x);
611 }
612 }
613 return str;
614};
615
616
617// Mark that a method should not be used.
618// Returns a modified function which warns once by default.
619// If --no-deprecation is set, then it is a no-op.
620exports.deprecate = function(fn, msg) {
621 // Allow for deprecating things in the process of starting up.
622 if (isUndefined(global.process)) {
623 return function() {
624 return exports.deprecate(fn, msg).apply(this, arguments);
625 };
626 }
627
628 if (process.noDeprecation === true) {
629 return fn;
630 }
631
632 var warned = false;
633 function deprecated() {
634 if (!warned) {
635 if (process.throwDeprecation) {
636 throw new Error(msg);
637 } else if (process.traceDeprecation) {
638 console.trace(msg);
639 } else {
640 console.error(msg);
641 }
642 warned = true;
643 }
644 return fn.apply(this, arguments);
645 }
646
647 return deprecated;
648};
649
650
651var debugs = {};
652var debugEnviron;
653exports.debuglog = function(set) {
654 if (isUndefined(debugEnviron))
655 debugEnviron = process.env.NODE_DEBUG || '';
656 set = set.toUpperCase();
657 if (!debugs[set]) {
658 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
659 var pid = process.pid;
660 debugs[set] = function() {
661 var msg = exports.format.apply(exports, arguments);
662 console.error('%s %d: %s', set, pid, msg);
663 };
664 } else {
665 debugs[set] = function() {};
666 }
667 }
668 return debugs[set];
669};
670
671
672/**
673 * Echos the value of a value. Trys to print the value out
674 * in the best way possible given the different types.
675 *
676 * @param {Object} obj The object to print out.
677 * @param {Object} opts Optional options object that alters the output.
678 */
679/* legacy: obj, showHidden, depth, colors*/
680function inspect(obj, opts) {
681 // default options
682 var ctx = {
683 seen: [],
684 stylize: stylizeNoColor
685 };
686 // legacy...
687 if (arguments.length >= 3) ctx.depth = arguments[2];
688 if (arguments.length >= 4) ctx.colors = arguments[3];
689 if (isBoolean(opts)) {
690 // legacy...
691 ctx.showHidden = opts;
692 } else if (opts) {
693 // got an "options" object
694 exports._extend(ctx, opts);
695 }
696 // set default options
697 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
698 if (isUndefined(ctx.depth)) ctx.depth = 2;
699 if (isUndefined(ctx.colors)) ctx.colors = false;
700 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
701 if (ctx.colors) ctx.stylize = stylizeWithColor;
702 return formatValue(ctx, obj, ctx.depth);
703}
704exports.inspect = inspect;
705
706
707// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
708inspect.colors = {
709 'bold' : [1, 22],
710 'italic' : [3, 23],
711 'underline' : [4, 24],
712 'inverse' : [7, 27],
713 'white' : [37, 39],
714 'grey' : [90, 39],
715 'black' : [30, 39],
716 'blue' : [34, 39],
717 'cyan' : [36, 39],
718 'green' : [32, 39],
719 'magenta' : [35, 39],
720 'red' : [31, 39],
721 'yellow' : [33, 39]
722};
723
724// Don't use 'blue' not visible on cmd.exe
725inspect.styles = {
726 'special': 'cyan',
727 'number': 'yellow',
728 'boolean': 'yellow',
729 'undefined': 'grey',
730 'null': 'bold',
731 'string': 'green',
732 'date': 'magenta',
733 // "name": intentionally not styling
734 'regexp': 'red'
735};
736
737
738function stylizeWithColor(str, styleType) {
739 var style = inspect.styles[styleType];
740
741 if (style) {
742 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
743 '\u001b[' + inspect.colors[style][1] + 'm';
744 } else {
745 return str;
746 }
747}
748
749
750function stylizeNoColor(str, styleType) {
751 return str;
752}
753
754
755function arrayToHash(array) {
756 var hash = {};
757
758 array.forEach(function(val, idx) {
759 hash[val] = true;
760 });
761
762 return hash;
763}
764
765
766function formatValue(ctx, value, recurseTimes) {
767 // Provide a hook for user-specified inspect functions.
768 // Check that value is an object with an inspect function on it
769 if (ctx.customInspect &&
770 value &&
771 isFunction(value.inspect) &&
772 // Filter out the util module, it's inspect function is special
773 value.inspect !== exports.inspect &&
774 // Also filter out any prototype objects using the circular check.
775 !(value.constructor && value.constructor.prototype === value)) {
776 var ret = value.inspect(recurseTimes, ctx);
777 if (!isString(ret)) {
778 ret = formatValue(ctx, ret, recurseTimes);
779 }
780 return ret;
781 }
782
783 // Primitive types cannot have properties
784 var primitive = formatPrimitive(ctx, value);
785 if (primitive) {
786 return primitive;
787 }
788
789 // Look up the keys of the object.
790 var keys = Object.keys(value);
791 var visibleKeys = arrayToHash(keys);
792
793 if (ctx.showHidden) {
794 keys = Object.getOwnPropertyNames(value);
795 }
796
797 // IE doesn't make error fields non-enumerable
798 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
799 if (isError(value)
800 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
801 return formatError(value);
802 }
803
804 // Some type of object without properties can be shortcutted.
805 if (keys.length === 0) {
806 if (isFunction(value)) {
807 var name = value.name ? ': ' + value.name : '';
808 return ctx.stylize('[Function' + name + ']', 'special');
809 }
810 if (isRegExp(value)) {
811 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
812 }
813 if (isDate(value)) {
814 return ctx.stylize(Date.prototype.toString.call(value), 'date');
815 }
816 if (isError(value)) {
817 return formatError(value);
818 }
819 }
820
821 var base = '', array = false, braces = ['{', '}'];
822
823 // Make Array say that they are Array
824 if (isArray(value)) {
825 array = true;
826 braces = ['[', ']'];
827 }
828
829 // Make functions say that they are functions
830 if (isFunction(value)) {
831 var n = value.name ? ': ' + value.name : '';
832 base = ' [Function' + n + ']';
833 }
834
835 // Make RegExps say that they are RegExps
836 if (isRegExp(value)) {
837 base = ' ' + RegExp.prototype.toString.call(value);
838 }
839
840 // Make dates with properties first say the date
841 if (isDate(value)) {
842 base = ' ' + Date.prototype.toUTCString.call(value);
843 }
844
845 // Make error with message first say the error
846 if (isError(value)) {
847 base = ' ' + formatError(value);
848 }
849
850 if (keys.length === 0 && (!array || value.length == 0)) {
851 return braces[0] + base + braces[1];
852 }
853
854 if (recurseTimes < 0) {
855 if (isRegExp(value)) {
856 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
857 } else {
858 return ctx.stylize('[Object]', 'special');
859 }
860 }
861
862 ctx.seen.push(value);
863
864 var output;
865 if (array) {
866 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
867 } else {
868 output = keys.map(function(key) {
869 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
870 });
871 }
872
873 ctx.seen.pop();
874
875 return reduceToSingleString(output, base, braces);
876}
877
878
879function formatPrimitive(ctx, value) {
880 if (isUndefined(value))
881 return ctx.stylize('undefined', 'undefined');
882 if (isString(value)) {
883 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
884 .replace(/'/g, "\\'")
885 .replace(/\\"/g, '"') + '\'';
886 return ctx.stylize(simple, 'string');
887 }
888 if (isNumber(value))
889 return ctx.stylize('' + value, 'number');
890 if (isBoolean(value))
891 return ctx.stylize('' + value, 'boolean');
892 // For some reason typeof null is "object", so special case here.
893 if (isNull(value))
894 return ctx.stylize('null', 'null');
895}
896
897
898function formatError(value) {
899 return '[' + Error.prototype.toString.call(value) + ']';
900}
901
902
903function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
904 var output = [];
905 for (var i = 0, l = value.length; i < l; ++i) {
906 if (hasOwnProperty(value, String(i))) {
907 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
908 String(i), true));
909 } else {
910 output.push('');
911 }
912 }
913 keys.forEach(function(key) {
914 if (!key.match(/^\d+$/)) {
915 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
916 key, true));
917 }
918 });
919 return output;
920}
921
922
923function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
924 var name, str, desc;
925 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
926 if (desc.get) {
927 if (desc.set) {
928 str = ctx.stylize('[Getter/Setter]', 'special');
929 } else {
930 str = ctx.stylize('[Getter]', 'special');
931 }
932 } else {
933 if (desc.set) {
934 str = ctx.stylize('[Setter]', 'special');
935 }
936 }
937 if (!hasOwnProperty(visibleKeys, key)) {
938 name = '[' + key + ']';
939 }
940 if (!str) {
941 if (ctx.seen.indexOf(desc.value) < 0) {
942 if (isNull(recurseTimes)) {
943 str = formatValue(ctx, desc.value, null);
944 } else {
945 str = formatValue(ctx, desc.value, recurseTimes - 1);
946 }
947 if (str.indexOf('\n') > -1) {
948 if (array) {
949 str = str.split('\n').map(function(line) {
950 return ' ' + line;
951 }).join('\n').substr(2);
952 } else {
953 str = '\n' + str.split('\n').map(function(line) {
954 return ' ' + line;
955 }).join('\n');
956 }
957 }
958 } else {
959 str = ctx.stylize('[Circular]', 'special');
960 }
961 }
962 if (isUndefined(name)) {
963 if (array && key.match(/^\d+$/)) {
964 return str;
965 }
966 name = JSON.stringify('' + key);
967 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
968 name = name.substr(1, name.length - 2);
969 name = ctx.stylize(name, 'name');
970 } else {
971 name = name.replace(/'/g, "\\'")
972 .replace(/\\"/g, '"')
973 .replace(/(^"|"$)/g, "'");
974 name = ctx.stylize(name, 'string');
975 }
976 }
977
978 return name + ': ' + str;
979}
980
981
982function reduceToSingleString(output, base, braces) {
983 var numLinesEst = 0;
984 var length = output.reduce(function(prev, cur) {
985 numLinesEst++;
986 if (cur.indexOf('\n') >= 0) numLinesEst++;
987 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
988 }, 0);
989
990 if (length > 60) {
991 return braces[0] +
992 (base === '' ? '' : base + '\n ') +
993 ' ' +
994 output.join(',\n ') +
995 ' ' +
996 braces[1];
997 }
998
999 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
1000}
1001
1002
1003// NOTE: These type checking functions intentionally don't use `instanceof`
1004// because it is fragile and can be easily faked with `Object.create()`.
1005function isArray(ar) {
1006 return Array.isArray(ar);
1007}
1008exports.isArray = isArray;
1009
1010function isBoolean(arg) {
1011 return typeof arg === 'boolean';
1012}
1013exports.isBoolean = isBoolean;
1014
1015function isNull(arg) {
1016 return arg === null;
1017}
1018exports.isNull = isNull;
1019
1020function isNullOrUndefined(arg) {
1021 return arg == null;
1022}
1023exports.isNullOrUndefined = isNullOrUndefined;
1024
1025function isNumber(arg) {
1026 return typeof arg === 'number';
1027}
1028exports.isNumber = isNumber;
1029
1030function isString(arg) {
1031 return typeof arg === 'string';
1032}
1033exports.isString = isString;
1034
1035function isSymbol(arg) {
1036 return typeof arg === 'symbol';
1037}
1038exports.isSymbol = isSymbol;
1039
1040function isUndefined(arg) {
1041 return arg === void 0;
1042}
1043exports.isUndefined = isUndefined;
1044
1045function isRegExp(re) {
1046 return isObject(re) && objectToString(re) === '[object RegExp]';
1047}
1048exports.isRegExp = isRegExp;
1049
1050function isObject(arg) {
1051 return typeof arg === 'object' && arg !== null;
1052}
1053exports.isObject = isObject;
1054
1055function isDate(d) {
1056 return isObject(d) && objectToString(d) === '[object Date]';
1057}
1058exports.isDate = isDate;
1059
1060function isError(e) {
1061 return isObject(e) &&
1062 (objectToString(e) === '[object Error]' || e instanceof Error);
1063}
1064exports.isError = isError;
1065
1066function isFunction(arg) {
1067 return typeof arg === 'function';
1068}
1069exports.isFunction = isFunction;
1070
1071function isPrimitive(arg) {
1072 return arg === null ||
1073 typeof arg === 'boolean' ||
1074 typeof arg === 'number' ||
1075 typeof arg === 'string' ||
1076 typeof arg === 'symbol' || // ES6 symbol
1077 typeof arg === 'undefined';
1078}
1079exports.isPrimitive = isPrimitive;
1080
1081exports.isBuffer = _dereq_(4);
1082
1083function objectToString(o) {
1084 return Object.prototype.toString.call(o);
1085}
1086
1087
1088function pad(n) {
1089 return n < 10 ? '0' + n.toString(10) : n.toString(10);
1090}
1091
1092
1093var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
1094 'Oct', 'Nov', 'Dec'];
1095
1096// 26 Feb 16:19:34
1097function timestamp() {
1098 var d = new Date();
1099 var time = [pad(d.getHours()),
1100 pad(d.getMinutes()),
1101 pad(d.getSeconds())].join(':');
1102 return [d.getDate(), months[d.getMonth()], time].join(' ');
1103}
1104
1105
1106// log is just a thin wrapper to console.log that prepends a timestamp
1107exports.log = function() {
1108 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
1109};
1110
1111
1112/**
1113 * Inherit the prototype methods from one constructor into another.
1114 *
1115 * The Function.prototype.inherits from lang.js rewritten as a standalone
1116 * function (not on Function.prototype). NOTE: If this file is to be loaded
1117 * during bootstrapping this function needs to be rewritten using some native
1118 * functions as prototype setup using normal JavaScript does not work as
1119 * expected during bootstrapping (see mirror.js in r114903).
1120 *
1121 * @param {function} ctor Constructor function which needs to inherit the
1122 * prototype.
1123 * @param {function} superCtor Constructor function to inherit prototype from.
1124 */
1125exports.inherits = _dereq_(3);
1126
1127exports._extend = function(origin, add) {
1128 // Don't do anything if add isn't an object
1129 if (!add || !isObject(add)) return origin;
1130
1131 var keys = Object.keys(add);
1132 var i = keys.length;
1133 while (i--) {
1134 origin[keys[i]] = add[keys[i]];
1135 }
1136 return origin;
1137};
1138
1139function hasOwnProperty(obj, prop) {
1140 return Object.prototype.hasOwnProperty.call(obj, prop);
1141}
1142
1143}).call(this,_dereq_(62),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
1144},{"3":3,"4":4,"62":62}],6:[function(_dereq_,module,exports){
1145'use strict'
1146
1147exports.byteLength = byteLength
1148exports.toByteArray = toByteArray
1149exports.fromByteArray = fromByteArray
1150
1151var lookup = []
1152var revLookup = []
1153var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
1154
1155var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
1156for (var i = 0, len = code.length; i < len; ++i) {
1157 lookup[i] = code[i]
1158 revLookup[code.charCodeAt(i)] = i
1159}
1160
1161// Support decoding URL-safe base64 strings, as Node.js does.
1162// See: https://en.wikipedia.org/wiki/Base64#URL_applications
1163revLookup['-'.charCodeAt(0)] = 62
1164revLookup['_'.charCodeAt(0)] = 63
1165
1166function getLens (b64) {
1167 var len = b64.length
1168
1169 if (len % 4 > 0) {
1170 throw new Error('Invalid string. Length must be a multiple of 4')
1171 }
1172
1173 // Trim off extra bytes after placeholder bytes are found
1174 // See: https://github.com/beatgammit/base64-js/issues/42
1175 var validLen = b64.indexOf('=')
1176 if (validLen === -1) validLen = len
1177
1178 var placeHoldersLen = validLen === len
1179 ? 0
1180 : 4 - (validLen % 4)
1181
1182 return [validLen, placeHoldersLen]
1183}
1184
1185// base64 is 4/3 + up to two characters of the original data
1186function byteLength (b64) {
1187 var lens = getLens(b64)
1188 var validLen = lens[0]
1189 var placeHoldersLen = lens[1]
1190 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
1191}
1192
1193function _byteLength (b64, validLen, placeHoldersLen) {
1194 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
1195}
1196
1197function toByteArray (b64) {
1198 var tmp
1199 var lens = getLens(b64)
1200 var validLen = lens[0]
1201 var placeHoldersLen = lens[1]
1202
1203 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
1204
1205 var curByte = 0
1206
1207 // if there are placeholders, only get up to the last complete 4 chars
1208 var len = placeHoldersLen > 0
1209 ? validLen - 4
1210 : validLen
1211
1212 for (var i = 0; i < len; i += 4) {
1213 tmp =
1214 (revLookup[b64.charCodeAt(i)] << 18) |
1215 (revLookup[b64.charCodeAt(i + 1)] << 12) |
1216 (revLookup[b64.charCodeAt(i + 2)] << 6) |
1217 revLookup[b64.charCodeAt(i + 3)]
1218 arr[curByte++] = (tmp >> 16) & 0xFF
1219 arr[curByte++] = (tmp >> 8) & 0xFF
1220 arr[curByte++] = tmp & 0xFF
1221 }
1222
1223 if (placeHoldersLen === 2) {
1224 tmp =
1225 (revLookup[b64.charCodeAt(i)] << 2) |
1226 (revLookup[b64.charCodeAt(i + 1)] >> 4)
1227 arr[curByte++] = tmp & 0xFF
1228 }
1229
1230 if (placeHoldersLen === 1) {
1231 tmp =
1232 (revLookup[b64.charCodeAt(i)] << 10) |
1233 (revLookup[b64.charCodeAt(i + 1)] << 4) |
1234 (revLookup[b64.charCodeAt(i + 2)] >> 2)
1235 arr[curByte++] = (tmp >> 8) & 0xFF
1236 arr[curByte++] = tmp & 0xFF
1237 }
1238
1239 return arr
1240}
1241
1242function tripletToBase64 (num) {
1243 return lookup[num >> 18 & 0x3F] +
1244 lookup[num >> 12 & 0x3F] +
1245 lookup[num >> 6 & 0x3F] +
1246 lookup[num & 0x3F]
1247}
1248
1249function encodeChunk (uint8, start, end) {
1250 var tmp
1251 var output = []
1252 for (var i = start; i < end; i += 3) {
1253 tmp =
1254 ((uint8[i] << 16) & 0xFF0000) +
1255 ((uint8[i + 1] << 8) & 0xFF00) +
1256 (uint8[i + 2] & 0xFF)
1257 output.push(tripletToBase64(tmp))
1258 }
1259 return output.join('')
1260}
1261
1262function fromByteArray (uint8) {
1263 var tmp
1264 var len = uint8.length
1265 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
1266 var parts = []
1267 var maxChunkLength = 16383 // must be multiple of 3
1268
1269 // go through the array every three bytes, we'll deal with trailing stuff later
1270 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
1271 parts.push(encodeChunk(
1272 uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
1273 ))
1274 }
1275
1276 // pad the end with zeros, but make sure to not forget the extra bytes
1277 if (extraBytes === 1) {
1278 tmp = uint8[len - 1]
1279 parts.push(
1280 lookup[tmp >> 2] +
1281 lookup[(tmp << 4) & 0x3F] +
1282 '=='
1283 )
1284 } else if (extraBytes === 2) {
1285 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
1286 parts.push(
1287 lookup[tmp >> 10] +
1288 lookup[(tmp >> 4) & 0x3F] +
1289 lookup[(tmp << 2) & 0x3F] +
1290 '='
1291 )
1292 }
1293
1294 return parts.join('')
1295}
1296
1297},{}],7:[function(_dereq_,module,exports){
1298
1299},{}],8:[function(_dereq_,module,exports){
1300(function (Buffer){
1301var toString = Object.prototype.toString
1302
1303var isModern = (
1304 typeof Buffer.alloc === 'function' &&
1305 typeof Buffer.allocUnsafe === 'function' &&
1306 typeof Buffer.from === 'function'
1307)
1308
1309function isArrayBuffer (input) {
1310 return toString.call(input).slice(8, -1) === 'ArrayBuffer'
1311}
1312
1313function fromArrayBuffer (obj, byteOffset, length) {
1314 byteOffset >>>= 0
1315
1316 var maxLength = obj.byteLength - byteOffset
1317
1318 if (maxLength < 0) {
1319 throw new RangeError("'offset' is out of bounds")
1320 }
1321
1322 if (length === undefined) {
1323 length = maxLength
1324 } else {
1325 length >>>= 0
1326
1327 if (length > maxLength) {
1328 throw new RangeError("'length' is out of bounds")
1329 }
1330 }
1331
1332 return isModern
1333 ? Buffer.from(obj.slice(byteOffset, byteOffset + length))
1334 : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
1335}
1336
1337function fromString (string, encoding) {
1338 if (typeof encoding !== 'string' || encoding === '') {
1339 encoding = 'utf8'
1340 }
1341
1342 if (!Buffer.isEncoding(encoding)) {
1343 throw new TypeError('"encoding" must be a valid string encoding')
1344 }
1345
1346 return isModern
1347 ? Buffer.from(string, encoding)
1348 : new Buffer(string, encoding)
1349}
1350
1351function bufferFrom (value, encodingOrOffset, length) {
1352 if (typeof value === 'number') {
1353 throw new TypeError('"value" argument must not be a number')
1354 }
1355
1356 if (isArrayBuffer(value)) {
1357 return fromArrayBuffer(value, encodingOrOffset, length)
1358 }
1359
1360 if (typeof value === 'string') {
1361 return fromString(value, encodingOrOffset)
1362 }
1363
1364 return isModern
1365 ? Buffer.from(value)
1366 : new Buffer(value)
1367}
1368
1369module.exports = bufferFrom
1370
1371}).call(this,_dereq_(9).Buffer)
1372},{"9":9}],9:[function(_dereq_,module,exports){
1373/*!
1374 * The buffer module from node.js, for the browser.
1375 *
1376 * @author Feross Aboukhadijeh <https://feross.org>
1377 * @license MIT
1378 */
1379/* eslint-disable no-proto */
1380
1381'use strict'
1382
1383var base64 = _dereq_(6)
1384var ieee754 = _dereq_(16)
1385
1386exports.Buffer = Buffer
1387exports.SlowBuffer = SlowBuffer
1388exports.INSPECT_MAX_BYTES = 50
1389
1390var K_MAX_LENGTH = 0x7fffffff
1391exports.kMaxLength = K_MAX_LENGTH
1392
1393/**
1394 * If `Buffer.TYPED_ARRAY_SUPPORT`:
1395 * === true Use Uint8Array implementation (fastest)
1396 * === false Print warning and recommend using `buffer` v4.x which has an Object
1397 * implementation (most compatible, even IE6)
1398 *
1399 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
1400 * Opera 11.6+, iOS 4.2+.
1401 *
1402 * We report that the browser does not support typed arrays if the are not subclassable
1403 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
1404 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
1405 * for __proto__ and has a buggy typed array implementation.
1406 */
1407Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
1408
1409if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
1410 typeof console.error === 'function') {
1411 console.error(
1412 'This browser lacks typed array (Uint8Array) support which is required by ' +
1413 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
1414 )
1415}
1416
1417function typedArraySupport () {
1418 // Can typed array instances can be augmented?
1419 try {
1420 var arr = new Uint8Array(1)
1421 arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
1422 return arr.foo() === 42
1423 } catch (e) {
1424 return false
1425 }
1426}
1427
1428Object.defineProperty(Buffer.prototype, 'parent', {
1429 get: function () {
1430 if (!(this instanceof Buffer)) {
1431 return undefined
1432 }
1433 return this.buffer
1434 }
1435})
1436
1437Object.defineProperty(Buffer.prototype, 'offset', {
1438 get: function () {
1439 if (!(this instanceof Buffer)) {
1440 return undefined
1441 }
1442 return this.byteOffset
1443 }
1444})
1445
1446function createBuffer (length) {
1447 if (length > K_MAX_LENGTH) {
1448 throw new RangeError('Invalid typed array length')
1449 }
1450 // Return an augmented `Uint8Array` instance
1451 var buf = new Uint8Array(length)
1452 buf.__proto__ = Buffer.prototype
1453 return buf
1454}
1455
1456/**
1457 * The Buffer constructor returns instances of `Uint8Array` that have their
1458 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
1459 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
1460 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
1461 * returns a single octet.
1462 *
1463 * The `Uint8Array` prototype remains unmodified.
1464 */
1465
1466function Buffer (arg, encodingOrOffset, length) {
1467 // Common case.
1468 if (typeof arg === 'number') {
1469 if (typeof encodingOrOffset === 'string') {
1470 throw new Error(
1471 'If encoding is specified then the first argument must be a string'
1472 )
1473 }
1474 return allocUnsafe(arg)
1475 }
1476 return from(arg, encodingOrOffset, length)
1477}
1478
1479// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
1480if (typeof Symbol !== 'undefined' && Symbol.species &&
1481 Buffer[Symbol.species] === Buffer) {
1482 Object.defineProperty(Buffer, Symbol.species, {
1483 value: null,
1484 configurable: true,
1485 enumerable: false,
1486 writable: false
1487 })
1488}
1489
1490Buffer.poolSize = 8192 // not used by this implementation
1491
1492function from (value, encodingOrOffset, length) {
1493 if (typeof value === 'number') {
1494 throw new TypeError('"value" argument must not be a number')
1495 }
1496
1497 if (isArrayBuffer(value) || (value && isArrayBuffer(value.buffer))) {
1498 return fromArrayBuffer(value, encodingOrOffset, length)
1499 }
1500
1501 if (typeof value === 'string') {
1502 return fromString(value, encodingOrOffset)
1503 }
1504
1505 return fromObject(value)
1506}
1507
1508/**
1509 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
1510 * if value is a number.
1511 * Buffer.from(str[, encoding])
1512 * Buffer.from(array)
1513 * Buffer.from(buffer)
1514 * Buffer.from(arrayBuffer[, byteOffset[, length]])
1515 **/
1516Buffer.from = function (value, encodingOrOffset, length) {
1517 return from(value, encodingOrOffset, length)
1518}
1519
1520// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
1521// https://github.com/feross/buffer/pull/148
1522Buffer.prototype.__proto__ = Uint8Array.prototype
1523Buffer.__proto__ = Uint8Array
1524
1525function assertSize (size) {
1526 if (typeof size !== 'number') {
1527 throw new TypeError('"size" argument must be of type number')
1528 } else if (size < 0) {
1529 throw new RangeError('"size" argument must not be negative')
1530 }
1531}
1532
1533function alloc (size, fill, encoding) {
1534 assertSize(size)
1535 if (size <= 0) {
1536 return createBuffer(size)
1537 }
1538 if (fill !== undefined) {
1539 // Only pay attention to encoding if it's a string. This
1540 // prevents accidentally sending in a number that would
1541 // be interpretted as a start offset.
1542 return typeof encoding === 'string'
1543 ? createBuffer(size).fill(fill, encoding)
1544 : createBuffer(size).fill(fill)
1545 }
1546 return createBuffer(size)
1547}
1548
1549/**
1550 * Creates a new filled Buffer instance.
1551 * alloc(size[, fill[, encoding]])
1552 **/
1553Buffer.alloc = function (size, fill, encoding) {
1554 return alloc(size, fill, encoding)
1555}
1556
1557function allocUnsafe (size) {
1558 assertSize(size)
1559 return createBuffer(size < 0 ? 0 : checked(size) | 0)
1560}
1561
1562/**
1563 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
1564 * */
1565Buffer.allocUnsafe = function (size) {
1566 return allocUnsafe(size)
1567}
1568/**
1569 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
1570 */
1571Buffer.allocUnsafeSlow = function (size) {
1572 return allocUnsafe(size)
1573}
1574
1575function fromString (string, encoding) {
1576 if (typeof encoding !== 'string' || encoding === '') {
1577 encoding = 'utf8'
1578 }
1579
1580 if (!Buffer.isEncoding(encoding)) {
1581 throw new TypeError('Unknown encoding: ' + encoding)
1582 }
1583
1584 var length = byteLength(string, encoding) | 0
1585 var buf = createBuffer(length)
1586
1587 var actual = buf.write(string, encoding)
1588
1589 if (actual !== length) {
1590 // Writing a hex string, for example, that contains invalid characters will
1591 // cause everything after the first invalid character to be ignored. (e.g.
1592 // 'abxxcd' will be treated as 'ab')
1593 buf = buf.slice(0, actual)
1594 }
1595
1596 return buf
1597}
1598
1599function fromArrayLike (array) {
1600 var length = array.length < 0 ? 0 : checked(array.length) | 0
1601 var buf = createBuffer(length)
1602 for (var i = 0; i < length; i += 1) {
1603 buf[i] = array[i] & 255
1604 }
1605 return buf
1606}
1607
1608function fromArrayBuffer (array, byteOffset, length) {
1609 if (byteOffset < 0 || array.byteLength < byteOffset) {
1610 throw new RangeError('"offset" is outside of buffer bounds')
1611 }
1612
1613 if (array.byteLength < byteOffset + (length || 0)) {
1614 throw new RangeError('"length" is outside of buffer bounds')
1615 }
1616
1617 var buf
1618 if (byteOffset === undefined && length === undefined) {
1619 buf = new Uint8Array(array)
1620 } else if (length === undefined) {
1621 buf = new Uint8Array(array, byteOffset)
1622 } else {
1623 buf = new Uint8Array(array, byteOffset, length)
1624 }
1625
1626 // Return an augmented `Uint8Array` instance
1627 buf.__proto__ = Buffer.prototype
1628 return buf
1629}
1630
1631function fromObject (obj) {
1632 if (Buffer.isBuffer(obj)) {
1633 var len = checked(obj.length) | 0
1634 var buf = createBuffer(len)
1635
1636 if (buf.length === 0) {
1637 return buf
1638 }
1639
1640 obj.copy(buf, 0, 0, len)
1641 return buf
1642 }
1643
1644 if (obj) {
1645 if (ArrayBuffer.isView(obj) || 'length' in obj) {
1646 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
1647 return createBuffer(0)
1648 }
1649 return fromArrayLike(obj)
1650 }
1651
1652 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
1653 return fromArrayLike(obj.data)
1654 }
1655 }
1656
1657 throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object.')
1658}
1659
1660function checked (length) {
1661 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
1662 // length is NaN (which is otherwise coerced to zero.)
1663 if (length >= K_MAX_LENGTH) {
1664 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
1665 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
1666 }
1667 return length | 0
1668}
1669
1670function SlowBuffer (length) {
1671 if (+length != length) { // eslint-disable-line eqeqeq
1672 length = 0
1673 }
1674 return Buffer.alloc(+length)
1675}
1676
1677Buffer.isBuffer = function isBuffer (b) {
1678 return b != null && b._isBuffer === true
1679}
1680
1681Buffer.compare = function compare (a, b) {
1682 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
1683 throw new TypeError('Arguments must be Buffers')
1684 }
1685
1686 if (a === b) return 0
1687
1688 var x = a.length
1689 var y = b.length
1690
1691 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
1692 if (a[i] !== b[i]) {
1693 x = a[i]
1694 y = b[i]
1695 break
1696 }
1697 }
1698
1699 if (x < y) return -1
1700 if (y < x) return 1
1701 return 0
1702}
1703
1704Buffer.isEncoding = function isEncoding (encoding) {
1705 switch (String(encoding).toLowerCase()) {
1706 case 'hex':
1707 case 'utf8':
1708 case 'utf-8':
1709 case 'ascii':
1710 case 'latin1':
1711 case 'binary':
1712 case 'base64':
1713 case 'ucs2':
1714 case 'ucs-2':
1715 case 'utf16le':
1716 case 'utf-16le':
1717 return true
1718 default:
1719 return false
1720 }
1721}
1722
1723Buffer.concat = function concat (list, length) {
1724 if (!Array.isArray(list)) {
1725 throw new TypeError('"list" argument must be an Array of Buffers')
1726 }
1727
1728 if (list.length === 0) {
1729 return Buffer.alloc(0)
1730 }
1731
1732 var i
1733 if (length === undefined) {
1734 length = 0
1735 for (i = 0; i < list.length; ++i) {
1736 length += list[i].length
1737 }
1738 }
1739
1740 var buffer = Buffer.allocUnsafe(length)
1741 var pos = 0
1742 for (i = 0; i < list.length; ++i) {
1743 var buf = list[i]
1744 if (ArrayBuffer.isView(buf)) {
1745 buf = Buffer.from(buf)
1746 }
1747 if (!Buffer.isBuffer(buf)) {
1748 throw new TypeError('"list" argument must be an Array of Buffers')
1749 }
1750 buf.copy(buffer, pos)
1751 pos += buf.length
1752 }
1753 return buffer
1754}
1755
1756function byteLength (string, encoding) {
1757 if (Buffer.isBuffer(string)) {
1758 return string.length
1759 }
1760 if (ArrayBuffer.isView(string) || isArrayBuffer(string)) {
1761 return string.byteLength
1762 }
1763 if (typeof string !== 'string') {
1764 string = '' + string
1765 }
1766
1767 var len = string.length
1768 if (len === 0) return 0
1769
1770 // Use a for loop to avoid recursion
1771 var loweredCase = false
1772 for (;;) {
1773 switch (encoding) {
1774 case 'ascii':
1775 case 'latin1':
1776 case 'binary':
1777 return len
1778 case 'utf8':
1779 case 'utf-8':
1780 case undefined:
1781 return utf8ToBytes(string).length
1782 case 'ucs2':
1783 case 'ucs-2':
1784 case 'utf16le':
1785 case 'utf-16le':
1786 return len * 2
1787 case 'hex':
1788 return len >>> 1
1789 case 'base64':
1790 return base64ToBytes(string).length
1791 default:
1792 if (loweredCase) return utf8ToBytes(string).length // assume utf8
1793 encoding = ('' + encoding).toLowerCase()
1794 loweredCase = true
1795 }
1796 }
1797}
1798Buffer.byteLength = byteLength
1799
1800function slowToString (encoding, start, end) {
1801 var loweredCase = false
1802
1803 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
1804 // property of a typed array.
1805
1806 // This behaves neither like String nor Uint8Array in that we set start/end
1807 // to their upper/lower bounds if the value passed is out of range.
1808 // undefined is handled specially as per ECMA-262 6th Edition,
1809 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
1810 if (start === undefined || start < 0) {
1811 start = 0
1812 }
1813 // Return early if start > this.length. Done here to prevent potential uint32
1814 // coercion fail below.
1815 if (start > this.length) {
1816 return ''
1817 }
1818
1819 if (end === undefined || end > this.length) {
1820 end = this.length
1821 }
1822
1823 if (end <= 0) {
1824 return ''
1825 }
1826
1827 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
1828 end >>>= 0
1829 start >>>= 0
1830
1831 if (end <= start) {
1832 return ''
1833 }
1834
1835 if (!encoding) encoding = 'utf8'
1836
1837 while (true) {
1838 switch (encoding) {
1839 case 'hex':
1840 return hexSlice(this, start, end)
1841
1842 case 'utf8':
1843 case 'utf-8':
1844 return utf8Slice(this, start, end)
1845
1846 case 'ascii':
1847 return asciiSlice(this, start, end)
1848
1849 case 'latin1':
1850 case 'binary':
1851 return latin1Slice(this, start, end)
1852
1853 case 'base64':
1854 return base64Slice(this, start, end)
1855
1856 case 'ucs2':
1857 case 'ucs-2':
1858 case 'utf16le':
1859 case 'utf-16le':
1860 return utf16leSlice(this, start, end)
1861
1862 default:
1863 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1864 encoding = (encoding + '').toLowerCase()
1865 loweredCase = true
1866 }
1867 }
1868}
1869
1870// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
1871// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
1872// reliably in a browserify context because there could be multiple different
1873// copies of the 'buffer' package in use. This method works even for Buffer
1874// instances that were created from another copy of the `buffer` package.
1875// See: https://github.com/feross/buffer/issues/154
1876Buffer.prototype._isBuffer = true
1877
1878function swap (b, n, m) {
1879 var i = b[n]
1880 b[n] = b[m]
1881 b[m] = i
1882}
1883
1884Buffer.prototype.swap16 = function swap16 () {
1885 var len = this.length
1886 if (len % 2 !== 0) {
1887 throw new RangeError('Buffer size must be a multiple of 16-bits')
1888 }
1889 for (var i = 0; i < len; i += 2) {
1890 swap(this, i, i + 1)
1891 }
1892 return this
1893}
1894
1895Buffer.prototype.swap32 = function swap32 () {
1896 var len = this.length
1897 if (len % 4 !== 0) {
1898 throw new RangeError('Buffer size must be a multiple of 32-bits')
1899 }
1900 for (var i = 0; i < len; i += 4) {
1901 swap(this, i, i + 3)
1902 swap(this, i + 1, i + 2)
1903 }
1904 return this
1905}
1906
1907Buffer.prototype.swap64 = function swap64 () {
1908 var len = this.length
1909 if (len % 8 !== 0) {
1910 throw new RangeError('Buffer size must be a multiple of 64-bits')
1911 }
1912 for (var i = 0; i < len; i += 8) {
1913 swap(this, i, i + 7)
1914 swap(this, i + 1, i + 6)
1915 swap(this, i + 2, i + 5)
1916 swap(this, i + 3, i + 4)
1917 }
1918 return this
1919}
1920
1921Buffer.prototype.toString = function toString () {
1922 var length = this.length
1923 if (length === 0) return ''
1924 if (arguments.length === 0) return utf8Slice(this, 0, length)
1925 return slowToString.apply(this, arguments)
1926}
1927
1928Buffer.prototype.toLocaleString = Buffer.prototype.toString
1929
1930Buffer.prototype.equals = function equals (b) {
1931 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
1932 if (this === b) return true
1933 return Buffer.compare(this, b) === 0
1934}
1935
1936Buffer.prototype.inspect = function inspect () {
1937 var str = ''
1938 var max = exports.INSPECT_MAX_BYTES
1939 if (this.length > 0) {
1940 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
1941 if (this.length > max) str += ' ... '
1942 }
1943 return '<Buffer ' + str + '>'
1944}
1945
1946Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
1947 if (!Buffer.isBuffer(target)) {
1948 throw new TypeError('Argument must be a Buffer')
1949 }
1950
1951 if (start === undefined) {
1952 start = 0
1953 }
1954 if (end === undefined) {
1955 end = target ? target.length : 0
1956 }
1957 if (thisStart === undefined) {
1958 thisStart = 0
1959 }
1960 if (thisEnd === undefined) {
1961 thisEnd = this.length
1962 }
1963
1964 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
1965 throw new RangeError('out of range index')
1966 }
1967
1968 if (thisStart >= thisEnd && start >= end) {
1969 return 0
1970 }
1971 if (thisStart >= thisEnd) {
1972 return -1
1973 }
1974 if (start >= end) {
1975 return 1
1976 }
1977
1978 start >>>= 0
1979 end >>>= 0
1980 thisStart >>>= 0
1981 thisEnd >>>= 0
1982
1983 if (this === target) return 0
1984
1985 var x = thisEnd - thisStart
1986 var y = end - start
1987 var len = Math.min(x, y)
1988
1989 var thisCopy = this.slice(thisStart, thisEnd)
1990 var targetCopy = target.slice(start, end)
1991
1992 for (var i = 0; i < len; ++i) {
1993 if (thisCopy[i] !== targetCopy[i]) {
1994 x = thisCopy[i]
1995 y = targetCopy[i]
1996 break
1997 }
1998 }
1999
2000 if (x < y) return -1
2001 if (y < x) return 1
2002 return 0
2003}
2004
2005// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
2006// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
2007//
2008// Arguments:
2009// - buffer - a Buffer to search
2010// - val - a string, Buffer, or number
2011// - byteOffset - an index into `buffer`; will be clamped to an int32
2012// - encoding - an optional encoding, relevant is val is a string
2013// - dir - true for indexOf, false for lastIndexOf
2014function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
2015 // Empty buffer means no match
2016 if (buffer.length === 0) return -1
2017
2018 // Normalize byteOffset
2019 if (typeof byteOffset === 'string') {
2020 encoding = byteOffset
2021 byteOffset = 0
2022 } else if (byteOffset > 0x7fffffff) {
2023 byteOffset = 0x7fffffff
2024 } else if (byteOffset < -0x80000000) {
2025 byteOffset = -0x80000000
2026 }
2027 byteOffset = +byteOffset // Coerce to Number.
2028 if (numberIsNaN(byteOffset)) {
2029 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
2030 byteOffset = dir ? 0 : (buffer.length - 1)
2031 }
2032
2033 // Normalize byteOffset: negative offsets start from the end of the buffer
2034 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
2035 if (byteOffset >= buffer.length) {
2036 if (dir) return -1
2037 else byteOffset = buffer.length - 1
2038 } else if (byteOffset < 0) {
2039 if (dir) byteOffset = 0
2040 else return -1
2041 }
2042
2043 // Normalize val
2044 if (typeof val === 'string') {
2045 val = Buffer.from(val, encoding)
2046 }
2047
2048 // Finally, search either indexOf (if dir is true) or lastIndexOf
2049 if (Buffer.isBuffer(val)) {
2050 // Special case: looking for empty string/buffer always fails
2051 if (val.length === 0) {
2052 return -1
2053 }
2054 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
2055 } else if (typeof val === 'number') {
2056 val = val & 0xFF // Search for a byte value [0-255]
2057 if (typeof Uint8Array.prototype.indexOf === 'function') {
2058 if (dir) {
2059 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
2060 } else {
2061 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
2062 }
2063 }
2064 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
2065 }
2066
2067 throw new TypeError('val must be string, number or Buffer')
2068}
2069
2070function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
2071 var indexSize = 1
2072 var arrLength = arr.length
2073 var valLength = val.length
2074
2075 if (encoding !== undefined) {
2076 encoding = String(encoding).toLowerCase()
2077 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
2078 encoding === 'utf16le' || encoding === 'utf-16le') {
2079 if (arr.length < 2 || val.length < 2) {
2080 return -1
2081 }
2082 indexSize = 2
2083 arrLength /= 2
2084 valLength /= 2
2085 byteOffset /= 2
2086 }
2087 }
2088
2089 function read (buf, i) {
2090 if (indexSize === 1) {
2091 return buf[i]
2092 } else {
2093 return buf.readUInt16BE(i * indexSize)
2094 }
2095 }
2096
2097 var i
2098 if (dir) {
2099 var foundIndex = -1
2100 for (i = byteOffset; i < arrLength; i++) {
2101 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
2102 if (foundIndex === -1) foundIndex = i
2103 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
2104 } else {
2105 if (foundIndex !== -1) i -= i - foundIndex
2106 foundIndex = -1
2107 }
2108 }
2109 } else {
2110 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
2111 for (i = byteOffset; i >= 0; i--) {
2112 var found = true
2113 for (var j = 0; j < valLength; j++) {
2114 if (read(arr, i + j) !== read(val, j)) {
2115 found = false
2116 break
2117 }
2118 }
2119 if (found) return i
2120 }
2121 }
2122
2123 return -1
2124}
2125
2126Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
2127 return this.indexOf(val, byteOffset, encoding) !== -1
2128}
2129
2130Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
2131 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
2132}
2133
2134Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
2135 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
2136}
2137
2138function hexWrite (buf, string, offset, length) {
2139 offset = Number(offset) || 0
2140 var remaining = buf.length - offset
2141 if (!length) {
2142 length = remaining
2143 } else {
2144 length = Number(length)
2145 if (length > remaining) {
2146 length = remaining
2147 }
2148 }
2149
2150 var strLen = string.length
2151
2152 if (length > strLen / 2) {
2153 length = strLen / 2
2154 }
2155 for (var i = 0; i < length; ++i) {
2156 var parsed = parseInt(string.substr(i * 2, 2), 16)
2157 if (numberIsNaN(parsed)) return i
2158 buf[offset + i] = parsed
2159 }
2160 return i
2161}
2162
2163function utf8Write (buf, string, offset, length) {
2164 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
2165}
2166
2167function asciiWrite (buf, string, offset, length) {
2168 return blitBuffer(asciiToBytes(string), buf, offset, length)
2169}
2170
2171function latin1Write (buf, string, offset, length) {
2172 return asciiWrite(buf, string, offset, length)
2173}
2174
2175function base64Write (buf, string, offset, length) {
2176 return blitBuffer(base64ToBytes(string), buf, offset, length)
2177}
2178
2179function ucs2Write (buf, string, offset, length) {
2180 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
2181}
2182
2183Buffer.prototype.write = function write (string, offset, length, encoding) {
2184 // Buffer#write(string)
2185 if (offset === undefined) {
2186 encoding = 'utf8'
2187 length = this.length
2188 offset = 0
2189 // Buffer#write(string, encoding)
2190 } else if (length === undefined && typeof offset === 'string') {
2191 encoding = offset
2192 length = this.length
2193 offset = 0
2194 // Buffer#write(string, offset[, length][, encoding])
2195 } else if (isFinite(offset)) {
2196 offset = offset >>> 0
2197 if (isFinite(length)) {
2198 length = length >>> 0
2199 if (encoding === undefined) encoding = 'utf8'
2200 } else {
2201 encoding = length
2202 length = undefined
2203 }
2204 } else {
2205 throw new Error(
2206 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
2207 )
2208 }
2209
2210 var remaining = this.length - offset
2211 if (length === undefined || length > remaining) length = remaining
2212
2213 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
2214 throw new RangeError('Attempt to write outside buffer bounds')
2215 }
2216
2217 if (!encoding) encoding = 'utf8'
2218
2219 var loweredCase = false
2220 for (;;) {
2221 switch (encoding) {
2222 case 'hex':
2223 return hexWrite(this, string, offset, length)
2224
2225 case 'utf8':
2226 case 'utf-8':
2227 return utf8Write(this, string, offset, length)
2228
2229 case 'ascii':
2230 return asciiWrite(this, string, offset, length)
2231
2232 case 'latin1':
2233 case 'binary':
2234 return latin1Write(this, string, offset, length)
2235
2236 case 'base64':
2237 // Warning: maxLength not taken into account in base64Write
2238 return base64Write(this, string, offset, length)
2239
2240 case 'ucs2':
2241 case 'ucs-2':
2242 case 'utf16le':
2243 case 'utf-16le':
2244 return ucs2Write(this, string, offset, length)
2245
2246 default:
2247 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
2248 encoding = ('' + encoding).toLowerCase()
2249 loweredCase = true
2250 }
2251 }
2252}
2253
2254Buffer.prototype.toJSON = function toJSON () {
2255 return {
2256 type: 'Buffer',
2257 data: Array.prototype.slice.call(this._arr || this, 0)
2258 }
2259}
2260
2261function base64Slice (buf, start, end) {
2262 if (start === 0 && end === buf.length) {
2263 return base64.fromByteArray(buf)
2264 } else {
2265 return base64.fromByteArray(buf.slice(start, end))
2266 }
2267}
2268
2269function utf8Slice (buf, start, end) {
2270 end = Math.min(buf.length, end)
2271 var res = []
2272
2273 var i = start
2274 while (i < end) {
2275 var firstByte = buf[i]
2276 var codePoint = null
2277 var bytesPerSequence = (firstByte > 0xEF) ? 4
2278 : (firstByte > 0xDF) ? 3
2279 : (firstByte > 0xBF) ? 2
2280 : 1
2281
2282 if (i + bytesPerSequence <= end) {
2283 var secondByte, thirdByte, fourthByte, tempCodePoint
2284
2285 switch (bytesPerSequence) {
2286 case 1:
2287 if (firstByte < 0x80) {
2288 codePoint = firstByte
2289 }
2290 break
2291 case 2:
2292 secondByte = buf[i + 1]
2293 if ((secondByte & 0xC0) === 0x80) {
2294 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
2295 if (tempCodePoint > 0x7F) {
2296 codePoint = tempCodePoint
2297 }
2298 }
2299 break
2300 case 3:
2301 secondByte = buf[i + 1]
2302 thirdByte = buf[i + 2]
2303 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
2304 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
2305 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
2306 codePoint = tempCodePoint
2307 }
2308 }
2309 break
2310 case 4:
2311 secondByte = buf[i + 1]
2312 thirdByte = buf[i + 2]
2313 fourthByte = buf[i + 3]
2314 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
2315 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
2316 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
2317 codePoint = tempCodePoint
2318 }
2319 }
2320 }
2321 }
2322
2323 if (codePoint === null) {
2324 // we did not generate a valid codePoint so insert a
2325 // replacement char (U+FFFD) and advance only 1 byte
2326 codePoint = 0xFFFD
2327 bytesPerSequence = 1
2328 } else if (codePoint > 0xFFFF) {
2329 // encode to utf16 (surrogate pair dance)
2330 codePoint -= 0x10000
2331 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
2332 codePoint = 0xDC00 | codePoint & 0x3FF
2333 }
2334
2335 res.push(codePoint)
2336 i += bytesPerSequence
2337 }
2338
2339 return decodeCodePointsArray(res)
2340}
2341
2342// Based on http://stackoverflow.com/a/22747272/680742, the browser with
2343// the lowest limit is Chrome, with 0x10000 args.
2344// We go 1 magnitude less, for safety
2345var MAX_ARGUMENTS_LENGTH = 0x1000
2346
2347function decodeCodePointsArray (codePoints) {
2348 var len = codePoints.length
2349 if (len <= MAX_ARGUMENTS_LENGTH) {
2350 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
2351 }
2352
2353 // Decode in chunks to avoid "call stack size exceeded".
2354 var res = ''
2355 var i = 0
2356 while (i < len) {
2357 res += String.fromCharCode.apply(
2358 String,
2359 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
2360 )
2361 }
2362 return res
2363}
2364
2365function asciiSlice (buf, start, end) {
2366 var ret = ''
2367 end = Math.min(buf.length, end)
2368
2369 for (var i = start; i < end; ++i) {
2370 ret += String.fromCharCode(buf[i] & 0x7F)
2371 }
2372 return ret
2373}
2374
2375function latin1Slice (buf, start, end) {
2376 var ret = ''
2377 end = Math.min(buf.length, end)
2378
2379 for (var i = start; i < end; ++i) {
2380 ret += String.fromCharCode(buf[i])
2381 }
2382 return ret
2383}
2384
2385function hexSlice (buf, start, end) {
2386 var len = buf.length
2387
2388 if (!start || start < 0) start = 0
2389 if (!end || end < 0 || end > len) end = len
2390
2391 var out = ''
2392 for (var i = start; i < end; ++i) {
2393 out += toHex(buf[i])
2394 }
2395 return out
2396}
2397
2398function utf16leSlice (buf, start, end) {
2399 var bytes = buf.slice(start, end)
2400 var res = ''
2401 for (var i = 0; i < bytes.length; i += 2) {
2402 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
2403 }
2404 return res
2405}
2406
2407Buffer.prototype.slice = function slice (start, end) {
2408 var len = this.length
2409 start = ~~start
2410 end = end === undefined ? len : ~~end
2411
2412 if (start < 0) {
2413 start += len
2414 if (start < 0) start = 0
2415 } else if (start > len) {
2416 start = len
2417 }
2418
2419 if (end < 0) {
2420 end += len
2421 if (end < 0) end = 0
2422 } else if (end > len) {
2423 end = len
2424 }
2425
2426 if (end < start) end = start
2427
2428 var newBuf = this.subarray(start, end)
2429 // Return an augmented `Uint8Array` instance
2430 newBuf.__proto__ = Buffer.prototype
2431 return newBuf
2432}
2433
2434/*
2435 * Need to make sure that buffer isn't trying to write out of bounds.
2436 */
2437function checkOffset (offset, ext, length) {
2438 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
2439 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
2440}
2441
2442Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
2443 offset = offset >>> 0
2444 byteLength = byteLength >>> 0
2445 if (!noAssert) checkOffset(offset, byteLength, this.length)
2446
2447 var val = this[offset]
2448 var mul = 1
2449 var i = 0
2450 while (++i < byteLength && (mul *= 0x100)) {
2451 val += this[offset + i] * mul
2452 }
2453
2454 return val
2455}
2456
2457Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
2458 offset = offset >>> 0
2459 byteLength = byteLength >>> 0
2460 if (!noAssert) {
2461 checkOffset(offset, byteLength, this.length)
2462 }
2463
2464 var val = this[offset + --byteLength]
2465 var mul = 1
2466 while (byteLength > 0 && (mul *= 0x100)) {
2467 val += this[offset + --byteLength] * mul
2468 }
2469
2470 return val
2471}
2472
2473Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
2474 offset = offset >>> 0
2475 if (!noAssert) checkOffset(offset, 1, this.length)
2476 return this[offset]
2477}
2478
2479Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
2480 offset = offset >>> 0
2481 if (!noAssert) checkOffset(offset, 2, this.length)
2482 return this[offset] | (this[offset + 1] << 8)
2483}
2484
2485Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
2486 offset = offset >>> 0
2487 if (!noAssert) checkOffset(offset, 2, this.length)
2488 return (this[offset] << 8) | this[offset + 1]
2489}
2490
2491Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
2492 offset = offset >>> 0
2493 if (!noAssert) checkOffset(offset, 4, this.length)
2494
2495 return ((this[offset]) |
2496 (this[offset + 1] << 8) |
2497 (this[offset + 2] << 16)) +
2498 (this[offset + 3] * 0x1000000)
2499}
2500
2501Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
2502 offset = offset >>> 0
2503 if (!noAssert) checkOffset(offset, 4, this.length)
2504
2505 return (this[offset] * 0x1000000) +
2506 ((this[offset + 1] << 16) |
2507 (this[offset + 2] << 8) |
2508 this[offset + 3])
2509}
2510
2511Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
2512 offset = offset >>> 0
2513 byteLength = byteLength >>> 0
2514 if (!noAssert) checkOffset(offset, byteLength, this.length)
2515
2516 var val = this[offset]
2517 var mul = 1
2518 var i = 0
2519 while (++i < byteLength && (mul *= 0x100)) {
2520 val += this[offset + i] * mul
2521 }
2522 mul *= 0x80
2523
2524 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
2525
2526 return val
2527}
2528
2529Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
2530 offset = offset >>> 0
2531 byteLength = byteLength >>> 0
2532 if (!noAssert) checkOffset(offset, byteLength, this.length)
2533
2534 var i = byteLength
2535 var mul = 1
2536 var val = this[offset + --i]
2537 while (i > 0 && (mul *= 0x100)) {
2538 val += this[offset + --i] * mul
2539 }
2540 mul *= 0x80
2541
2542 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
2543
2544 return val
2545}
2546
2547Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
2548 offset = offset >>> 0
2549 if (!noAssert) checkOffset(offset, 1, this.length)
2550 if (!(this[offset] & 0x80)) return (this[offset])
2551 return ((0xff - this[offset] + 1) * -1)
2552}
2553
2554Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
2555 offset = offset >>> 0
2556 if (!noAssert) checkOffset(offset, 2, this.length)
2557 var val = this[offset] | (this[offset + 1] << 8)
2558 return (val & 0x8000) ? val | 0xFFFF0000 : val
2559}
2560
2561Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
2562 offset = offset >>> 0
2563 if (!noAssert) checkOffset(offset, 2, this.length)
2564 var val = this[offset + 1] | (this[offset] << 8)
2565 return (val & 0x8000) ? val | 0xFFFF0000 : val
2566}
2567
2568Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
2569 offset = offset >>> 0
2570 if (!noAssert) checkOffset(offset, 4, this.length)
2571
2572 return (this[offset]) |
2573 (this[offset + 1] << 8) |
2574 (this[offset + 2] << 16) |
2575 (this[offset + 3] << 24)
2576}
2577
2578Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
2579 offset = offset >>> 0
2580 if (!noAssert) checkOffset(offset, 4, this.length)
2581
2582 return (this[offset] << 24) |
2583 (this[offset + 1] << 16) |
2584 (this[offset + 2] << 8) |
2585 (this[offset + 3])
2586}
2587
2588Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
2589 offset = offset >>> 0
2590 if (!noAssert) checkOffset(offset, 4, this.length)
2591 return ieee754.read(this, offset, true, 23, 4)
2592}
2593
2594Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
2595 offset = offset >>> 0
2596 if (!noAssert) checkOffset(offset, 4, this.length)
2597 return ieee754.read(this, offset, false, 23, 4)
2598}
2599
2600Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
2601 offset = offset >>> 0
2602 if (!noAssert) checkOffset(offset, 8, this.length)
2603 return ieee754.read(this, offset, true, 52, 8)
2604}
2605
2606Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
2607 offset = offset >>> 0
2608 if (!noAssert) checkOffset(offset, 8, this.length)
2609 return ieee754.read(this, offset, false, 52, 8)
2610}
2611
2612function checkInt (buf, value, offset, ext, max, min) {
2613 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
2614 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
2615 if (offset + ext > buf.length) throw new RangeError('Index out of range')
2616}
2617
2618Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
2619 value = +value
2620 offset = offset >>> 0
2621 byteLength = byteLength >>> 0
2622 if (!noAssert) {
2623 var maxBytes = Math.pow(2, 8 * byteLength) - 1
2624 checkInt(this, value, offset, byteLength, maxBytes, 0)
2625 }
2626
2627 var mul = 1
2628 var i = 0
2629 this[offset] = value & 0xFF
2630 while (++i < byteLength && (mul *= 0x100)) {
2631 this[offset + i] = (value / mul) & 0xFF
2632 }
2633
2634 return offset + byteLength
2635}
2636
2637Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
2638 value = +value
2639 offset = offset >>> 0
2640 byteLength = byteLength >>> 0
2641 if (!noAssert) {
2642 var maxBytes = Math.pow(2, 8 * byteLength) - 1
2643 checkInt(this, value, offset, byteLength, maxBytes, 0)
2644 }
2645
2646 var i = byteLength - 1
2647 var mul = 1
2648 this[offset + i] = value & 0xFF
2649 while (--i >= 0 && (mul *= 0x100)) {
2650 this[offset + i] = (value / mul) & 0xFF
2651 }
2652
2653 return offset + byteLength
2654}
2655
2656Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
2657 value = +value
2658 offset = offset >>> 0
2659 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
2660 this[offset] = (value & 0xff)
2661 return offset + 1
2662}
2663
2664Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
2665 value = +value
2666 offset = offset >>> 0
2667 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
2668 this[offset] = (value & 0xff)
2669 this[offset + 1] = (value >>> 8)
2670 return offset + 2
2671}
2672
2673Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
2674 value = +value
2675 offset = offset >>> 0
2676 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
2677 this[offset] = (value >>> 8)
2678 this[offset + 1] = (value & 0xff)
2679 return offset + 2
2680}
2681
2682Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
2683 value = +value
2684 offset = offset >>> 0
2685 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
2686 this[offset + 3] = (value >>> 24)
2687 this[offset + 2] = (value >>> 16)
2688 this[offset + 1] = (value >>> 8)
2689 this[offset] = (value & 0xff)
2690 return offset + 4
2691}
2692
2693Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
2694 value = +value
2695 offset = offset >>> 0
2696 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
2697 this[offset] = (value >>> 24)
2698 this[offset + 1] = (value >>> 16)
2699 this[offset + 2] = (value >>> 8)
2700 this[offset + 3] = (value & 0xff)
2701 return offset + 4
2702}
2703
2704Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
2705 value = +value
2706 offset = offset >>> 0
2707 if (!noAssert) {
2708 var limit = Math.pow(2, (8 * byteLength) - 1)
2709
2710 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2711 }
2712
2713 var i = 0
2714 var mul = 1
2715 var sub = 0
2716 this[offset] = value & 0xFF
2717 while (++i < byteLength && (mul *= 0x100)) {
2718 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
2719 sub = 1
2720 }
2721 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2722 }
2723
2724 return offset + byteLength
2725}
2726
2727Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
2728 value = +value
2729 offset = offset >>> 0
2730 if (!noAssert) {
2731 var limit = Math.pow(2, (8 * byteLength) - 1)
2732
2733 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2734 }
2735
2736 var i = byteLength - 1
2737 var mul = 1
2738 var sub = 0
2739 this[offset + i] = value & 0xFF
2740 while (--i >= 0 && (mul *= 0x100)) {
2741 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
2742 sub = 1
2743 }
2744 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2745 }
2746
2747 return offset + byteLength
2748}
2749
2750Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
2751 value = +value
2752 offset = offset >>> 0
2753 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
2754 if (value < 0) value = 0xff + value + 1
2755 this[offset] = (value & 0xff)
2756 return offset + 1
2757}
2758
2759Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
2760 value = +value
2761 offset = offset >>> 0
2762 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2763 this[offset] = (value & 0xff)
2764 this[offset + 1] = (value >>> 8)
2765 return offset + 2
2766}
2767
2768Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
2769 value = +value
2770 offset = offset >>> 0
2771 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2772 this[offset] = (value >>> 8)
2773 this[offset + 1] = (value & 0xff)
2774 return offset + 2
2775}
2776
2777Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
2778 value = +value
2779 offset = offset >>> 0
2780 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2781 this[offset] = (value & 0xff)
2782 this[offset + 1] = (value >>> 8)
2783 this[offset + 2] = (value >>> 16)
2784 this[offset + 3] = (value >>> 24)
2785 return offset + 4
2786}
2787
2788Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
2789 value = +value
2790 offset = offset >>> 0
2791 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2792 if (value < 0) value = 0xffffffff + value + 1
2793 this[offset] = (value >>> 24)
2794 this[offset + 1] = (value >>> 16)
2795 this[offset + 2] = (value >>> 8)
2796 this[offset + 3] = (value & 0xff)
2797 return offset + 4
2798}
2799
2800function checkIEEE754 (buf, value, offset, ext, max, min) {
2801 if (offset + ext > buf.length) throw new RangeError('Index out of range')
2802 if (offset < 0) throw new RangeError('Index out of range')
2803}
2804
2805function writeFloat (buf, value, offset, littleEndian, noAssert) {
2806 value = +value
2807 offset = offset >>> 0
2808 if (!noAssert) {
2809 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
2810 }
2811 ieee754.write(buf, value, offset, littleEndian, 23, 4)
2812 return offset + 4
2813}
2814
2815Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
2816 return writeFloat(this, value, offset, true, noAssert)
2817}
2818
2819Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
2820 return writeFloat(this, value, offset, false, noAssert)
2821}
2822
2823function writeDouble (buf, value, offset, littleEndian, noAssert) {
2824 value = +value
2825 offset = offset >>> 0
2826 if (!noAssert) {
2827 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
2828 }
2829 ieee754.write(buf, value, offset, littleEndian, 52, 8)
2830 return offset + 8
2831}
2832
2833Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
2834 return writeDouble(this, value, offset, true, noAssert)
2835}
2836
2837Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
2838 return writeDouble(this, value, offset, false, noAssert)
2839}
2840
2841// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
2842Buffer.prototype.copy = function copy (target, targetStart, start, end) {
2843 if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
2844 if (!start) start = 0
2845 if (!end && end !== 0) end = this.length
2846 if (targetStart >= target.length) targetStart = target.length
2847 if (!targetStart) targetStart = 0
2848 if (end > 0 && end < start) end = start
2849
2850 // Copy 0 bytes; we're done
2851 if (end === start) return 0
2852 if (target.length === 0 || this.length === 0) return 0
2853
2854 // Fatal error conditions
2855 if (targetStart < 0) {
2856 throw new RangeError('targetStart out of bounds')
2857 }
2858 if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
2859 if (end < 0) throw new RangeError('sourceEnd out of bounds')
2860
2861 // Are we oob?
2862 if (end > this.length) end = this.length
2863 if (target.length - targetStart < end - start) {
2864 end = target.length - targetStart + start
2865 }
2866
2867 var len = end - start
2868
2869 if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
2870 // Use built-in when available, missing from IE11
2871 this.copyWithin(targetStart, start, end)
2872 } else if (this === target && start < targetStart && targetStart < end) {
2873 // descending copy from end
2874 for (var i = len - 1; i >= 0; --i) {
2875 target[i + targetStart] = this[i + start]
2876 }
2877 } else {
2878 Uint8Array.prototype.set.call(
2879 target,
2880 this.subarray(start, end),
2881 targetStart
2882 )
2883 }
2884
2885 return len
2886}
2887
2888// Usage:
2889// buffer.fill(number[, offset[, end]])
2890// buffer.fill(buffer[, offset[, end]])
2891// buffer.fill(string[, offset[, end]][, encoding])
2892Buffer.prototype.fill = function fill (val, start, end, encoding) {
2893 // Handle string cases:
2894 if (typeof val === 'string') {
2895 if (typeof start === 'string') {
2896 encoding = start
2897 start = 0
2898 end = this.length
2899 } else if (typeof end === 'string') {
2900 encoding = end
2901 end = this.length
2902 }
2903 if (encoding !== undefined && typeof encoding !== 'string') {
2904 throw new TypeError('encoding must be a string')
2905 }
2906 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
2907 throw new TypeError('Unknown encoding: ' + encoding)
2908 }
2909 if (val.length === 1) {
2910 var code = val.charCodeAt(0)
2911 if ((encoding === 'utf8' && code < 128) ||
2912 encoding === 'latin1') {
2913 // Fast path: If `val` fits into a single byte, use that numeric value.
2914 val = code
2915 }
2916 }
2917 } else if (typeof val === 'number') {
2918 val = val & 255
2919 }
2920
2921 // Invalid ranges are not set to a default, so can range check early.
2922 if (start < 0 || this.length < start || this.length < end) {
2923 throw new RangeError('Out of range index')
2924 }
2925
2926 if (end <= start) {
2927 return this
2928 }
2929
2930 start = start >>> 0
2931 end = end === undefined ? this.length : end >>> 0
2932
2933 if (!val) val = 0
2934
2935 var i
2936 if (typeof val === 'number') {
2937 for (i = start; i < end; ++i) {
2938 this[i] = val
2939 }
2940 } else {
2941 var bytes = Buffer.isBuffer(val)
2942 ? val
2943 : new Buffer(val, encoding)
2944 var len = bytes.length
2945 if (len === 0) {
2946 throw new TypeError('The value "' + val +
2947 '" is invalid for argument "value"')
2948 }
2949 for (i = 0; i < end - start; ++i) {
2950 this[i + start] = bytes[i % len]
2951 }
2952 }
2953
2954 return this
2955}
2956
2957// HELPER FUNCTIONS
2958// ================
2959
2960var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
2961
2962function base64clean (str) {
2963 // Node takes equal signs as end of the Base64 encoding
2964 str = str.split('=')[0]
2965 // Node strips out invalid characters like \n and \t from the string, base64-js does not
2966 str = str.trim().replace(INVALID_BASE64_RE, '')
2967 // Node converts strings with length < 2 to ''
2968 if (str.length < 2) return ''
2969 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
2970 while (str.length % 4 !== 0) {
2971 str = str + '='
2972 }
2973 return str
2974}
2975
2976function toHex (n) {
2977 if (n < 16) return '0' + n.toString(16)
2978 return n.toString(16)
2979}
2980
2981function utf8ToBytes (string, units) {
2982 units = units || Infinity
2983 var codePoint
2984 var length = string.length
2985 var leadSurrogate = null
2986 var bytes = []
2987
2988 for (var i = 0; i < length; ++i) {
2989 codePoint = string.charCodeAt(i)
2990
2991 // is surrogate component
2992 if (codePoint > 0xD7FF && codePoint < 0xE000) {
2993 // last char was a lead
2994 if (!leadSurrogate) {
2995 // no lead yet
2996 if (codePoint > 0xDBFF) {
2997 // unexpected trail
2998 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2999 continue
3000 } else if (i + 1 === length) {
3001 // unpaired lead
3002 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3003 continue
3004 }
3005
3006 // valid lead
3007 leadSurrogate = codePoint
3008
3009 continue
3010 }
3011
3012 // 2 leads in a row
3013 if (codePoint < 0xDC00) {
3014 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3015 leadSurrogate = codePoint
3016 continue
3017 }
3018
3019 // valid surrogate pair
3020 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
3021 } else if (leadSurrogate) {
3022 // valid bmp char, but last char was a lead
3023 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3024 }
3025
3026 leadSurrogate = null
3027
3028 // encode utf8
3029 if (codePoint < 0x80) {
3030 if ((units -= 1) < 0) break
3031 bytes.push(codePoint)
3032 } else if (codePoint < 0x800) {
3033 if ((units -= 2) < 0) break
3034 bytes.push(
3035 codePoint >> 0x6 | 0xC0,
3036 codePoint & 0x3F | 0x80
3037 )
3038 } else if (codePoint < 0x10000) {
3039 if ((units -= 3) < 0) break
3040 bytes.push(
3041 codePoint >> 0xC | 0xE0,
3042 codePoint >> 0x6 & 0x3F | 0x80,
3043 codePoint & 0x3F | 0x80
3044 )
3045 } else if (codePoint < 0x110000) {
3046 if ((units -= 4) < 0) break
3047 bytes.push(
3048 codePoint >> 0x12 | 0xF0,
3049 codePoint >> 0xC & 0x3F | 0x80,
3050 codePoint >> 0x6 & 0x3F | 0x80,
3051 codePoint & 0x3F | 0x80
3052 )
3053 } else {
3054 throw new Error('Invalid code point')
3055 }
3056 }
3057
3058 return bytes
3059}
3060
3061function asciiToBytes (str) {
3062 var byteArray = []
3063 for (var i = 0; i < str.length; ++i) {
3064 // Node's code seems to be doing this and not & 0x7F..
3065 byteArray.push(str.charCodeAt(i) & 0xFF)
3066 }
3067 return byteArray
3068}
3069
3070function utf16leToBytes (str, units) {
3071 var c, hi, lo
3072 var byteArray = []
3073 for (var i = 0; i < str.length; ++i) {
3074 if ((units -= 2) < 0) break
3075
3076 c = str.charCodeAt(i)
3077 hi = c >> 8
3078 lo = c % 256
3079 byteArray.push(lo)
3080 byteArray.push(hi)
3081 }
3082
3083 return byteArray
3084}
3085
3086function base64ToBytes (str) {
3087 return base64.toByteArray(base64clean(str))
3088}
3089
3090function blitBuffer (src, dst, offset, length) {
3091 for (var i = 0; i < length; ++i) {
3092 if ((i + offset >= dst.length) || (i >= src.length)) break
3093 dst[i + offset] = src[i]
3094 }
3095 return i
3096}
3097
3098// ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check
3099// but they should be treated as valid. See: https://github.com/feross/buffer/issues/166
3100function isArrayBuffer (obj) {
3101 return obj instanceof ArrayBuffer ||
3102 (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' &&
3103 typeof obj.byteLength === 'number')
3104}
3105
3106function numberIsNaN (obj) {
3107 return obj !== obj // eslint-disable-line no-self-compare
3108}
3109
3110},{"16":16,"6":6}],10:[function(_dereq_,module,exports){
3111(function (Buffer){
3112// Copyright Joyent, Inc. and other Node contributors.
3113//
3114// Permission is hereby granted, free of charge, to any person obtaining a
3115// copy of this software and associated documentation files (the
3116// "Software"), to deal in the Software without restriction, including
3117// without limitation the rights to use, copy, modify, merge, publish,
3118// distribute, sublicense, and/or sell copies of the Software, and to permit
3119// persons to whom the Software is furnished to do so, subject to the
3120// following conditions:
3121//
3122// The above copyright notice and this permission notice shall be included
3123// in all copies or substantial portions of the Software.
3124//
3125// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3126// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3127// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3128// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3129// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3130// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3131// USE OR OTHER DEALINGS IN THE SOFTWARE.
3132
3133// NOTE: These type checking functions intentionally don't use `instanceof`
3134// because it is fragile and can be easily faked with `Object.create()`.
3135
3136function isArray(arg) {
3137 if (Array.isArray) {
3138 return Array.isArray(arg);
3139 }
3140 return objectToString(arg) === '[object Array]';
3141}
3142exports.isArray = isArray;
3143
3144function isBoolean(arg) {
3145 return typeof arg === 'boolean';
3146}
3147exports.isBoolean = isBoolean;
3148
3149function isNull(arg) {
3150 return arg === null;
3151}
3152exports.isNull = isNull;
3153
3154function isNullOrUndefined(arg) {
3155 return arg == null;
3156}
3157exports.isNullOrUndefined = isNullOrUndefined;
3158
3159function isNumber(arg) {
3160 return typeof arg === 'number';
3161}
3162exports.isNumber = isNumber;
3163
3164function isString(arg) {
3165 return typeof arg === 'string';
3166}
3167exports.isString = isString;
3168
3169function isSymbol(arg) {
3170 return typeof arg === 'symbol';
3171}
3172exports.isSymbol = isSymbol;
3173
3174function isUndefined(arg) {
3175 return arg === void 0;
3176}
3177exports.isUndefined = isUndefined;
3178
3179function isRegExp(re) {
3180 return objectToString(re) === '[object RegExp]';
3181}
3182exports.isRegExp = isRegExp;
3183
3184function isObject(arg) {
3185 return typeof arg === 'object' && arg !== null;
3186}
3187exports.isObject = isObject;
3188
3189function isDate(d) {
3190 return objectToString(d) === '[object Date]';
3191}
3192exports.isDate = isDate;
3193
3194function isError(e) {
3195 return (objectToString(e) === '[object Error]' || e instanceof Error);
3196}
3197exports.isError = isError;
3198
3199function isFunction(arg) {
3200 return typeof arg === 'function';
3201}
3202exports.isFunction = isFunction;
3203
3204function isPrimitive(arg) {
3205 return arg === null ||
3206 typeof arg === 'boolean' ||
3207 typeof arg === 'number' ||
3208 typeof arg === 'string' ||
3209 typeof arg === 'symbol' || // ES6 symbol
3210 typeof arg === 'undefined';
3211}
3212exports.isPrimitive = isPrimitive;
3213
3214exports.isBuffer = Buffer.isBuffer;
3215
3216function objectToString(o) {
3217 return Object.prototype.toString.call(o);
3218}
3219
3220}).call(this,{"isBuffer":_dereq_(19)})
3221},{"19":19}],11:[function(_dereq_,module,exports){
3222/**
3223 * Copyright (c) 2013 Petka Antonov
3224 *
3225 * Permission is hereby granted, free of charge, to any person obtaining a copy
3226 * of this software and associated documentation files (the "Software"), to deal
3227 * in the Software without restriction, including without limitation the rights
3228 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
3229 * copies of the Software, and to permit persons to whom the Software is
3230 * furnished to do so, subject to the following conditions:</p>
3231 *
3232 * The above copyright notice and this permission notice shall be included in
3233 * all copies or substantial portions of the Software.
3234 *
3235 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
3236 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
3237 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
3238 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
3239 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
3240 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
3241 * THE SOFTWARE.
3242 */
3243"use strict";
3244function Deque(capacity) {
3245 this._capacity = getCapacity(capacity);
3246 this._length = 0;
3247 this._front = 0;
3248 if (isArray(capacity)) {
3249 var len = capacity.length;
3250 for (var i = 0; i < len; ++i) {
3251 this[i] = capacity[i];
3252 }
3253 this._length = len;
3254 }
3255}
3256
3257Deque.prototype.toArray = function Deque$toArray() {
3258 var len = this._length;
3259 var ret = new Array(len);
3260 var front = this._front;
3261 var capacity = this._capacity;
3262 for (var j = 0; j < len; ++j) {
3263 ret[j] = this[(front + j) & (capacity - 1)];
3264 }
3265 return ret;
3266};
3267
3268Deque.prototype.push = function Deque$push(item) {
3269 var argsLength = arguments.length;
3270 var length = this._length;
3271 if (argsLength > 1) {
3272 var capacity = this._capacity;
3273 if (length + argsLength > capacity) {
3274 for (var i = 0; i < argsLength; ++i) {
3275 this._checkCapacity(length + 1);
3276 var j = (this._front + length) & (this._capacity - 1);
3277 this[j] = arguments[i];
3278 length++;
3279 this._length = length;
3280 }
3281 return length;
3282 }
3283 else {
3284 var j = this._front;
3285 for (var i = 0; i < argsLength; ++i) {
3286 this[(j + length) & (capacity - 1)] = arguments[i];
3287 j++;
3288 }
3289 this._length = length + argsLength;
3290 return length + argsLength;
3291 }
3292
3293 }
3294
3295 if (argsLength === 0) return length;
3296
3297 this._checkCapacity(length + 1);
3298 var i = (this._front + length) & (this._capacity - 1);
3299 this[i] = item;
3300 this._length = length + 1;
3301 return length + 1;
3302};
3303
3304Deque.prototype.pop = function Deque$pop() {
3305 var length = this._length;
3306 if (length === 0) {
3307 return void 0;
3308 }
3309 var i = (this._front + length - 1) & (this._capacity - 1);
3310 var ret = this[i];
3311 this[i] = void 0;
3312 this._length = length - 1;
3313 return ret;
3314};
3315
3316Deque.prototype.shift = function Deque$shift() {
3317 var length = this._length;
3318 if (length === 0) {
3319 return void 0;
3320 }
3321 var front = this._front;
3322 var ret = this[front];
3323 this[front] = void 0;
3324 this._front = (front + 1) & (this._capacity - 1);
3325 this._length = length - 1;
3326 return ret;
3327};
3328
3329Deque.prototype.unshift = function Deque$unshift(item) {
3330 var length = this._length;
3331 var argsLength = arguments.length;
3332
3333
3334 if (argsLength > 1) {
3335 var capacity = this._capacity;
3336 if (length + argsLength > capacity) {
3337 for (var i = argsLength - 1; i >= 0; i--) {
3338 this._checkCapacity(length + 1);
3339 var capacity = this._capacity;
3340 var j = (((( this._front - 1 ) &
3341 ( capacity - 1) ) ^ capacity ) - capacity );
3342 this[j] = arguments[i];
3343 length++;
3344 this._length = length;
3345 this._front = j;
3346 }
3347 return length;
3348 }
3349 else {
3350 var front = this._front;
3351 for (var i = argsLength - 1; i >= 0; i--) {
3352 var j = (((( front - 1 ) &
3353 ( capacity - 1) ) ^ capacity ) - capacity );
3354 this[j] = arguments[i];
3355 front = j;
3356 }
3357 this._front = front;
3358 this._length = length + argsLength;
3359 return length + argsLength;
3360 }
3361 }
3362
3363 if (argsLength === 0) return length;
3364
3365 this._checkCapacity(length + 1);
3366 var capacity = this._capacity;
3367 var i = (((( this._front - 1 ) &
3368 ( capacity - 1) ) ^ capacity ) - capacity );
3369 this[i] = item;
3370 this._length = length + 1;
3371 this._front = i;
3372 return length + 1;
3373};
3374
3375Deque.prototype.peekBack = function Deque$peekBack() {
3376 var length = this._length;
3377 if (length === 0) {
3378 return void 0;
3379 }
3380 var index = (this._front + length - 1) & (this._capacity - 1);
3381 return this[index];
3382};
3383
3384Deque.prototype.peekFront = function Deque$peekFront() {
3385 if (this._length === 0) {
3386 return void 0;
3387 }
3388 return this[this._front];
3389};
3390
3391Deque.prototype.get = function Deque$get(index) {
3392 var i = index;
3393 if ((i !== (i | 0))) {
3394 return void 0;
3395 }
3396 var len = this._length;
3397 if (i < 0) {
3398 i = i + len;
3399 }
3400 if (i < 0 || i >= len) {
3401 return void 0;
3402 }
3403 return this[(this._front + i) & (this._capacity - 1)];
3404};
3405
3406Deque.prototype.isEmpty = function Deque$isEmpty() {
3407 return this._length === 0;
3408};
3409
3410Deque.prototype.clear = function Deque$clear() {
3411 var len = this._length;
3412 var front = this._front;
3413 var capacity = this._capacity;
3414 for (var j = 0; j < len; ++j) {
3415 this[(front + j) & (capacity - 1)] = void 0;
3416 }
3417 this._length = 0;
3418 this._front = 0;
3419};
3420
3421Deque.prototype.toString = function Deque$toString() {
3422 return this.toArray().toString();
3423};
3424
3425Deque.prototype.valueOf = Deque.prototype.toString;
3426Deque.prototype.removeFront = Deque.prototype.shift;
3427Deque.prototype.removeBack = Deque.prototype.pop;
3428Deque.prototype.insertFront = Deque.prototype.unshift;
3429Deque.prototype.insertBack = Deque.prototype.push;
3430Deque.prototype.enqueue = Deque.prototype.push;
3431Deque.prototype.dequeue = Deque.prototype.shift;
3432Deque.prototype.toJSON = Deque.prototype.toArray;
3433
3434Object.defineProperty(Deque.prototype, "length", {
3435 get: function() {
3436 return this._length;
3437 },
3438 set: function() {
3439 throw new RangeError("");
3440 }
3441});
3442
3443Deque.prototype._checkCapacity = function Deque$_checkCapacity(size) {
3444 if (this._capacity < size) {
3445 this._resizeTo(getCapacity(this._capacity * 1.5 + 16));
3446 }
3447};
3448
3449Deque.prototype._resizeTo = function Deque$_resizeTo(capacity) {
3450 var oldCapacity = this._capacity;
3451 this._capacity = capacity;
3452 var front = this._front;
3453 var length = this._length;
3454 if (front + length > oldCapacity) {
3455 var moveItemsCount = (front + length) & (oldCapacity - 1);
3456 arrayMove(this, 0, this, oldCapacity, moveItemsCount);
3457 }
3458};
3459
3460
3461var isArray = Array.isArray;
3462
3463function arrayMove(src, srcIndex, dst, dstIndex, len) {
3464 for (var j = 0; j < len; ++j) {
3465 dst[j + dstIndex] = src[j + srcIndex];
3466 src[j + srcIndex] = void 0;
3467 }
3468}
3469
3470function pow2AtLeast(n) {
3471 n = n >>> 0;
3472 n = n - 1;
3473 n = n | (n >> 1);
3474 n = n | (n >> 2);
3475 n = n | (n >> 4);
3476 n = n | (n >> 8);
3477 n = n | (n >> 16);
3478 return n + 1;
3479}
3480
3481function getCapacity(capacity) {
3482 if (typeof capacity !== "number") {
3483 if (isArray(capacity)) {
3484 capacity = capacity.length;
3485 }
3486 else {
3487 return 16;
3488 }
3489 }
3490 return pow2AtLeast(
3491 Math.min(
3492 Math.max(16, capacity), 1073741824)
3493 );
3494}
3495
3496module.exports = Deque;
3497
3498},{}],12:[function(_dereq_,module,exports){
3499var prr = _dereq_(63)
3500
3501function init (type, message, cause) {
3502 if (!!message && typeof message != 'string') {
3503 message = message.message || message.name
3504 }
3505 prr(this, {
3506 type : type
3507 , name : type
3508 // can be passed just a 'cause'
3509 , cause : typeof message != 'string' ? message : cause
3510 , message : message
3511 }, 'ewr')
3512}
3513
3514// generic prototype, not intended to be actually used - helpful for `instanceof`
3515function CustomError (message, cause) {
3516 Error.call(this)
3517 if (Error.captureStackTrace)
3518 Error.captureStackTrace(this, this.constructor)
3519 init.call(this, 'CustomError', message, cause)
3520}
3521
3522CustomError.prototype = new Error()
3523
3524function createError (errno, type, proto) {
3525 var err = function (message, cause) {
3526 init.call(this, type, message, cause)
3527 //TODO: the specificity here is stupid, errno should be available everywhere
3528 if (type == 'FilesystemError') {
3529 this.code = this.cause.code
3530 this.path = this.cause.path
3531 this.errno = this.cause.errno
3532 this.message =
3533 (errno.errno[this.cause.errno]
3534 ? errno.errno[this.cause.errno].description
3535 : this.cause.message)
3536 + (this.cause.path ? ' [' + this.cause.path + ']' : '')
3537 }
3538 Error.call(this)
3539 if (Error.captureStackTrace)
3540 Error.captureStackTrace(this, err)
3541 }
3542 err.prototype = !!proto ? new proto() : new CustomError()
3543 return err
3544}
3545
3546module.exports = function (errno) {
3547 var ce = function (type, proto) {
3548 return createError(errno, type, proto)
3549 }
3550 return {
3551 CustomError : CustomError
3552 , FilesystemError : ce('FilesystemError')
3553 , createError : ce
3554 }
3555}
3556
3557},{"63":63}],13:[function(_dereq_,module,exports){
3558var all = module.exports.all = [
3559 {
3560 errno: -2,
3561 code: 'ENOENT',
3562 description: 'no such file or directory'
3563 },
3564 {
3565 errno: -1,
3566 code: 'UNKNOWN',
3567 description: 'unknown error'
3568 },
3569 {
3570 errno: 0,
3571 code: 'OK',
3572 description: 'success'
3573 },
3574 {
3575 errno: 1,
3576 code: 'EOF',
3577 description: 'end of file'
3578 },
3579 {
3580 errno: 2,
3581 code: 'EADDRINFO',
3582 description: 'getaddrinfo error'
3583 },
3584 {
3585 errno: 3,
3586 code: 'EACCES',
3587 description: 'permission denied'
3588 },
3589 {
3590 errno: 4,
3591 code: 'EAGAIN',
3592 description: 'resource temporarily unavailable'
3593 },
3594 {
3595 errno: 5,
3596 code: 'EADDRINUSE',
3597 description: 'address already in use'
3598 },
3599 {
3600 errno: 6,
3601 code: 'EADDRNOTAVAIL',
3602 description: 'address not available'
3603 },
3604 {
3605 errno: 7,
3606 code: 'EAFNOSUPPORT',
3607 description: 'address family not supported'
3608 },
3609 {
3610 errno: 8,
3611 code: 'EALREADY',
3612 description: 'connection already in progress'
3613 },
3614 {
3615 errno: 9,
3616 code: 'EBADF',
3617 description: 'bad file descriptor'
3618 },
3619 {
3620 errno: 10,
3621 code: 'EBUSY',
3622 description: 'resource busy or locked'
3623 },
3624 {
3625 errno: 11,
3626 code: 'ECONNABORTED',
3627 description: 'software caused connection abort'
3628 },
3629 {
3630 errno: 12,
3631 code: 'ECONNREFUSED',
3632 description: 'connection refused'
3633 },
3634 {
3635 errno: 13,
3636 code: 'ECONNRESET',
3637 description: 'connection reset by peer'
3638 },
3639 {
3640 errno: 14,
3641 code: 'EDESTADDRREQ',
3642 description: 'destination address required'
3643 },
3644 {
3645 errno: 15,
3646 code: 'EFAULT',
3647 description: 'bad address in system call argument'
3648 },
3649 {
3650 errno: 16,
3651 code: 'EHOSTUNREACH',
3652 description: 'host is unreachable'
3653 },
3654 {
3655 errno: 17,
3656 code: 'EINTR',
3657 description: 'interrupted system call'
3658 },
3659 {
3660 errno: 18,
3661 code: 'EINVAL',
3662 description: 'invalid argument'
3663 },
3664 {
3665 errno: 19,
3666 code: 'EISCONN',
3667 description: 'socket is already connected'
3668 },
3669 {
3670 errno: 20,
3671 code: 'EMFILE',
3672 description: 'too many open files'
3673 },
3674 {
3675 errno: 21,
3676 code: 'EMSGSIZE',
3677 description: 'message too long'
3678 },
3679 {
3680 errno: 22,
3681 code: 'ENETDOWN',
3682 description: 'network is down'
3683 },
3684 {
3685 errno: 23,
3686 code: 'ENETUNREACH',
3687 description: 'network is unreachable'
3688 },
3689 {
3690 errno: 24,
3691 code: 'ENFILE',
3692 description: 'file table overflow'
3693 },
3694 {
3695 errno: 25,
3696 code: 'ENOBUFS',
3697 description: 'no buffer space available'
3698 },
3699 {
3700 errno: 26,
3701 code: 'ENOMEM',
3702 description: 'not enough memory'
3703 },
3704 {
3705 errno: 27,
3706 code: 'ENOTDIR',
3707 description: 'not a directory'
3708 },
3709 {
3710 errno: 28,
3711 code: 'EISDIR',
3712 description: 'illegal operation on a directory'
3713 },
3714 {
3715 errno: 29,
3716 code: 'ENONET',
3717 description: 'machine is not on the network'
3718 },
3719 {
3720 errno: 31,
3721 code: 'ENOTCONN',
3722 description: 'socket is not connected'
3723 },
3724 {
3725 errno: 32,
3726 code: 'ENOTSOCK',
3727 description: 'socket operation on non-socket'
3728 },
3729 {
3730 errno: 33,
3731 code: 'ENOTSUP',
3732 description: 'operation not supported on socket'
3733 },
3734 {
3735 errno: 34,
3736 code: 'ENOENT',
3737 description: 'no such file or directory'
3738 },
3739 {
3740 errno: 35,
3741 code: 'ENOSYS',
3742 description: 'function not implemented'
3743 },
3744 {
3745 errno: 36,
3746 code: 'EPIPE',
3747 description: 'broken pipe'
3748 },
3749 {
3750 errno: 37,
3751 code: 'EPROTO',
3752 description: 'protocol error'
3753 },
3754 {
3755 errno: 38,
3756 code: 'EPROTONOSUPPORT',
3757 description: 'protocol not supported'
3758 },
3759 {
3760 errno: 39,
3761 code: 'EPROTOTYPE',
3762 description: 'protocol wrong type for socket'
3763 },
3764 {
3765 errno: 40,
3766 code: 'ETIMEDOUT',
3767 description: 'connection timed out'
3768 },
3769 {
3770 errno: 41,
3771 code: 'ECHARSET',
3772 description: 'invalid Unicode character'
3773 },
3774 {
3775 errno: 42,
3776 code: 'EAIFAMNOSUPPORT',
3777 description: 'address family for hostname not supported'
3778 },
3779 {
3780 errno: 44,
3781 code: 'EAISERVICE',
3782 description: 'servname not supported for ai_socktype'
3783 },
3784 {
3785 errno: 45,
3786 code: 'EAISOCKTYPE',
3787 description: 'ai_socktype not supported'
3788 },
3789 {
3790 errno: 46,
3791 code: 'ESHUTDOWN',
3792 description: 'cannot send after transport endpoint shutdown'
3793 },
3794 {
3795 errno: 47,
3796 code: 'EEXIST',
3797 description: 'file already exists'
3798 },
3799 {
3800 errno: 48,
3801 code: 'ESRCH',
3802 description: 'no such process'
3803 },
3804 {
3805 errno: 49,
3806 code: 'ENAMETOOLONG',
3807 description: 'name too long'
3808 },
3809 {
3810 errno: 50,
3811 code: 'EPERM',
3812 description: 'operation not permitted'
3813 },
3814 {
3815 errno: 51,
3816 code: 'ELOOP',
3817 description: 'too many symbolic links encountered'
3818 },
3819 {
3820 errno: 52,
3821 code: 'EXDEV',
3822 description: 'cross-device link not permitted'
3823 },
3824 {
3825 errno: 53,
3826 code: 'ENOTEMPTY',
3827 description: 'directory not empty'
3828 },
3829 {
3830 errno: 54,
3831 code: 'ENOSPC',
3832 description: 'no space left on device'
3833 },
3834 {
3835 errno: 55,
3836 code: 'EIO',
3837 description: 'i/o error'
3838 },
3839 {
3840 errno: 56,
3841 code: 'EROFS',
3842 description: 'read-only file system'
3843 },
3844 {
3845 errno: 57,
3846 code: 'ENODEV',
3847 description: 'no such device'
3848 },
3849 {
3850 errno: 58,
3851 code: 'ESPIPE',
3852 description: 'invalid seek'
3853 },
3854 {
3855 errno: 59,
3856 code: 'ECANCELED',
3857 description: 'operation canceled'
3858 }
3859]
3860
3861module.exports.errno = {}
3862module.exports.code = {}
3863
3864all.forEach(function (error) {
3865 module.exports.errno[error.errno] = error
3866 module.exports.code[error.code] = error
3867})
3868
3869module.exports.custom = _dereq_(12)(module.exports)
3870module.exports.create = module.exports.custom.createError
3871
3872},{"12":12}],14:[function(_dereq_,module,exports){
3873// Copyright Joyent, Inc. and other Node contributors.
3874//
3875// Permission is hereby granted, free of charge, to any person obtaining a
3876// copy of this software and associated documentation files (the
3877// "Software"), to deal in the Software without restriction, including
3878// without limitation the rights to use, copy, modify, merge, publish,
3879// distribute, sublicense, and/or sell copies of the Software, and to permit
3880// persons to whom the Software is furnished to do so, subject to the
3881// following conditions:
3882//
3883// The above copyright notice and this permission notice shall be included
3884// in all copies or substantial portions of the Software.
3885//
3886// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3887// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3888// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3889// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3890// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3891// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3892// USE OR OTHER DEALINGS IN THE SOFTWARE.
3893
3894var objectCreate = Object.create || objectCreatePolyfill
3895var objectKeys = Object.keys || objectKeysPolyfill
3896var bind = Function.prototype.bind || functionBindPolyfill
3897
3898function EventEmitter() {
3899 if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
3900 this._events = objectCreate(null);
3901 this._eventsCount = 0;
3902 }
3903
3904 this._maxListeners = this._maxListeners || undefined;
3905}
3906module.exports = EventEmitter;
3907
3908// Backwards-compat with node 0.10.x
3909EventEmitter.EventEmitter = EventEmitter;
3910
3911EventEmitter.prototype._events = undefined;
3912EventEmitter.prototype._maxListeners = undefined;
3913
3914// By default EventEmitters will print a warning if more than 10 listeners are
3915// added to it. This is a useful default which helps finding memory leaks.
3916var defaultMaxListeners = 10;
3917
3918var hasDefineProperty;
3919try {
3920 var o = {};
3921 if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
3922 hasDefineProperty = o.x === 0;
3923} catch (err) { hasDefineProperty = false }
3924if (hasDefineProperty) {
3925 Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
3926 enumerable: true,
3927 get: function() {
3928 return defaultMaxListeners;
3929 },
3930 set: function(arg) {
3931 // check whether the input is a positive number (whose value is zero or
3932 // greater and not a NaN).
3933 if (typeof arg !== 'number' || arg < 0 || arg !== arg)
3934 throw new TypeError('"defaultMaxListeners" must be a positive number');
3935 defaultMaxListeners = arg;
3936 }
3937 });
3938} else {
3939 EventEmitter.defaultMaxListeners = defaultMaxListeners;
3940}
3941
3942// Obviously not all Emitters should be limited to 10. This function allows
3943// that to be increased. Set to zero for unlimited.
3944EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
3945 if (typeof n !== 'number' || n < 0 || isNaN(n))
3946 throw new TypeError('"n" argument must be a positive number');
3947 this._maxListeners = n;
3948 return this;
3949};
3950
3951function $getMaxListeners(that) {
3952 if (that._maxListeners === undefined)
3953 return EventEmitter.defaultMaxListeners;
3954 return that._maxListeners;
3955}
3956
3957EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
3958 return $getMaxListeners(this);
3959};
3960
3961// These standalone emit* functions are used to optimize calling of event
3962// handlers for fast cases because emit() itself often has a variable number of
3963// arguments and can be deoptimized because of that. These functions always have
3964// the same number of arguments and thus do not get deoptimized, so the code
3965// inside them can execute faster.
3966function emitNone(handler, isFn, self) {
3967 if (isFn)
3968 handler.call(self);
3969 else {
3970 var len = handler.length;
3971 var listeners = arrayClone(handler, len);
3972 for (var i = 0; i < len; ++i)
3973 listeners[i].call(self);
3974 }
3975}
3976function emitOne(handler, isFn, self, arg1) {
3977 if (isFn)
3978 handler.call(self, arg1);
3979 else {
3980 var len = handler.length;
3981 var listeners = arrayClone(handler, len);
3982 for (var i = 0; i < len; ++i)
3983 listeners[i].call(self, arg1);
3984 }
3985}
3986function emitTwo(handler, isFn, self, arg1, arg2) {
3987 if (isFn)
3988 handler.call(self, arg1, arg2);
3989 else {
3990 var len = handler.length;
3991 var listeners = arrayClone(handler, len);
3992 for (var i = 0; i < len; ++i)
3993 listeners[i].call(self, arg1, arg2);
3994 }
3995}
3996function emitThree(handler, isFn, self, arg1, arg2, arg3) {
3997 if (isFn)
3998 handler.call(self, arg1, arg2, arg3);
3999 else {
4000 var len = handler.length;
4001 var listeners = arrayClone(handler, len);
4002 for (var i = 0; i < len; ++i)
4003 listeners[i].call(self, arg1, arg2, arg3);
4004 }
4005}
4006
4007function emitMany(handler, isFn, self, args) {
4008 if (isFn)
4009 handler.apply(self, args);
4010 else {
4011 var len = handler.length;
4012 var listeners = arrayClone(handler, len);
4013 for (var i = 0; i < len; ++i)
4014 listeners[i].apply(self, args);
4015 }
4016}
4017
4018EventEmitter.prototype.emit = function emit(type) {
4019 var er, handler, len, args, i, events;
4020 var doError = (type === 'error');
4021
4022 events = this._events;
4023 if (events)
4024 doError = (doError && events.error == null);
4025 else if (!doError)
4026 return false;
4027
4028 // If there is no 'error' event listener then throw.
4029 if (doError) {
4030 if (arguments.length > 1)
4031 er = arguments[1];
4032 if (er instanceof Error) {
4033 throw er; // Unhandled 'error' event
4034 } else {
4035 // At least give some kind of context to the user
4036 var err = new Error('Unhandled "error" event. (' + er + ')');
4037 err.context = er;
4038 throw err;
4039 }
4040 return false;
4041 }
4042
4043 handler = events[type];
4044
4045 if (!handler)
4046 return false;
4047
4048 var isFn = typeof handler === 'function';
4049 len = arguments.length;
4050 switch (len) {
4051 // fast cases
4052 case 1:
4053 emitNone(handler, isFn, this);
4054 break;
4055 case 2:
4056 emitOne(handler, isFn, this, arguments[1]);
4057 break;
4058 case 3:
4059 emitTwo(handler, isFn, this, arguments[1], arguments[2]);
4060 break;
4061 case 4:
4062 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
4063 break;
4064 // slower
4065 default:
4066 args = new Array(len - 1);
4067 for (i = 1; i < len; i++)
4068 args[i - 1] = arguments[i];
4069 emitMany(handler, isFn, this, args);
4070 }
4071
4072 return true;
4073};
4074
4075function _addListener(target, type, listener, prepend) {
4076 var m;
4077 var events;
4078 var existing;
4079
4080 if (typeof listener !== 'function')
4081 throw new TypeError('"listener" argument must be a function');
4082
4083 events = target._events;
4084 if (!events) {
4085 events = target._events = objectCreate(null);
4086 target._eventsCount = 0;
4087 } else {
4088 // To avoid recursion in the case that type === "newListener"! Before
4089 // adding it to the listeners, first emit "newListener".
4090 if (events.newListener) {
4091 target.emit('newListener', type,
4092 listener.listener ? listener.listener : listener);
4093
4094 // Re-assign `events` because a newListener handler could have caused the
4095 // this._events to be assigned to a new object
4096 events = target._events;
4097 }
4098 existing = events[type];
4099 }
4100
4101 if (!existing) {
4102 // Optimize the case of one listener. Don't need the extra array object.
4103 existing = events[type] = listener;
4104 ++target._eventsCount;
4105 } else {
4106 if (typeof existing === 'function') {
4107 // Adding the second element, need to change to array.
4108 existing = events[type] =
4109 prepend ? [listener, existing] : [existing, listener];
4110 } else {
4111 // If we've already got an array, just append.
4112 if (prepend) {
4113 existing.unshift(listener);
4114 } else {
4115 existing.push(listener);
4116 }
4117 }
4118
4119 // Check for listener leak
4120 if (!existing.warned) {
4121 m = $getMaxListeners(target);
4122 if (m && m > 0 && existing.length > m) {
4123 existing.warned = true;
4124 var w = new Error('Possible EventEmitter memory leak detected. ' +
4125 existing.length + ' "' + String(type) + '" listeners ' +
4126 'added. Use emitter.setMaxListeners() to ' +
4127 'increase limit.');
4128 w.name = 'MaxListenersExceededWarning';
4129 w.emitter = target;
4130 w.type = type;
4131 w.count = existing.length;
4132 if (typeof console === 'object' && console.warn) {
4133 console.warn('%s: %s', w.name, w.message);
4134 }
4135 }
4136 }
4137 }
4138
4139 return target;
4140}
4141
4142EventEmitter.prototype.addListener = function addListener(type, listener) {
4143 return _addListener(this, type, listener, false);
4144};
4145
4146EventEmitter.prototype.on = EventEmitter.prototype.addListener;
4147
4148EventEmitter.prototype.prependListener =
4149 function prependListener(type, listener) {
4150 return _addListener(this, type, listener, true);
4151 };
4152
4153function onceWrapper() {
4154 if (!this.fired) {
4155 this.target.removeListener(this.type, this.wrapFn);
4156 this.fired = true;
4157 switch (arguments.length) {
4158 case 0:
4159 return this.listener.call(this.target);
4160 case 1:
4161 return this.listener.call(this.target, arguments[0]);
4162 case 2:
4163 return this.listener.call(this.target, arguments[0], arguments[1]);
4164 case 3:
4165 return this.listener.call(this.target, arguments[0], arguments[1],
4166 arguments[2]);
4167 default:
4168 var args = new Array(arguments.length);
4169 for (var i = 0; i < args.length; ++i)
4170 args[i] = arguments[i];
4171 this.listener.apply(this.target, args);
4172 }
4173 }
4174}
4175
4176function _onceWrap(target, type, listener) {
4177 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
4178 var wrapped = bind.call(onceWrapper, state);
4179 wrapped.listener = listener;
4180 state.wrapFn = wrapped;
4181 return wrapped;
4182}
4183
4184EventEmitter.prototype.once = function once(type, listener) {
4185 if (typeof listener !== 'function')
4186 throw new TypeError('"listener" argument must be a function');
4187 this.on(type, _onceWrap(this, type, listener));
4188 return this;
4189};
4190
4191EventEmitter.prototype.prependOnceListener =
4192 function prependOnceListener(type, listener) {
4193 if (typeof listener !== 'function')
4194 throw new TypeError('"listener" argument must be a function');
4195 this.prependListener(type, _onceWrap(this, type, listener));
4196 return this;
4197 };
4198
4199// Emits a 'removeListener' event if and only if the listener was removed.
4200EventEmitter.prototype.removeListener =
4201 function removeListener(type, listener) {
4202 var list, events, position, i, originalListener;
4203
4204 if (typeof listener !== 'function')
4205 throw new TypeError('"listener" argument must be a function');
4206
4207 events = this._events;
4208 if (!events)
4209 return this;
4210
4211 list = events[type];
4212 if (!list)
4213 return this;
4214
4215 if (list === listener || list.listener === listener) {
4216 if (--this._eventsCount === 0)
4217 this._events = objectCreate(null);
4218 else {
4219 delete events[type];
4220 if (events.removeListener)
4221 this.emit('removeListener', type, list.listener || listener);
4222 }
4223 } else if (typeof list !== 'function') {
4224 position = -1;
4225
4226 for (i = list.length - 1; i >= 0; i--) {
4227 if (list[i] === listener || list[i].listener === listener) {
4228 originalListener = list[i].listener;
4229 position = i;
4230 break;
4231 }
4232 }
4233
4234 if (position < 0)
4235 return this;
4236
4237 if (position === 0)
4238 list.shift();
4239 else
4240 spliceOne(list, position);
4241
4242 if (list.length === 1)
4243 events[type] = list[0];
4244
4245 if (events.removeListener)
4246 this.emit('removeListener', type, originalListener || listener);
4247 }
4248
4249 return this;
4250 };
4251
4252EventEmitter.prototype.removeAllListeners =
4253 function removeAllListeners(type) {
4254 var listeners, events, i;
4255
4256 events = this._events;
4257 if (!events)
4258 return this;
4259
4260 // not listening for removeListener, no need to emit
4261 if (!events.removeListener) {
4262 if (arguments.length === 0) {
4263 this._events = objectCreate(null);
4264 this._eventsCount = 0;
4265 } else if (events[type]) {
4266 if (--this._eventsCount === 0)
4267 this._events = objectCreate(null);
4268 else
4269 delete events[type];
4270 }
4271 return this;
4272 }
4273
4274 // emit removeListener for all listeners on all events
4275 if (arguments.length === 0) {
4276 var keys = objectKeys(events);
4277 var key;
4278 for (i = 0; i < keys.length; ++i) {
4279 key = keys[i];
4280 if (key === 'removeListener') continue;
4281 this.removeAllListeners(key);
4282 }
4283 this.removeAllListeners('removeListener');
4284 this._events = objectCreate(null);
4285 this._eventsCount = 0;
4286 return this;
4287 }
4288
4289 listeners = events[type];
4290
4291 if (typeof listeners === 'function') {
4292 this.removeListener(type, listeners);
4293 } else if (listeners) {
4294 // LIFO order
4295 for (i = listeners.length - 1; i >= 0; i--) {
4296 this.removeListener(type, listeners[i]);
4297 }
4298 }
4299
4300 return this;
4301 };
4302
4303function _listeners(target, type, unwrap) {
4304 var events = target._events;
4305
4306 if (!events)
4307 return [];
4308
4309 var evlistener = events[type];
4310 if (!evlistener)
4311 return [];
4312
4313 if (typeof evlistener === 'function')
4314 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
4315
4316 return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
4317}
4318
4319EventEmitter.prototype.listeners = function listeners(type) {
4320 return _listeners(this, type, true);
4321};
4322
4323EventEmitter.prototype.rawListeners = function rawListeners(type) {
4324 return _listeners(this, type, false);
4325};
4326
4327EventEmitter.listenerCount = function(emitter, type) {
4328 if (typeof emitter.listenerCount === 'function') {
4329 return emitter.listenerCount(type);
4330 } else {
4331 return listenerCount.call(emitter, type);
4332 }
4333};
4334
4335EventEmitter.prototype.listenerCount = listenerCount;
4336function listenerCount(type) {
4337 var events = this._events;
4338
4339 if (events) {
4340 var evlistener = events[type];
4341
4342 if (typeof evlistener === 'function') {
4343 return 1;
4344 } else if (evlistener) {
4345 return evlistener.length;
4346 }
4347 }
4348
4349 return 0;
4350}
4351
4352EventEmitter.prototype.eventNames = function eventNames() {
4353 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
4354};
4355
4356// About 1.5x faster than the two-arg version of Array#splice().
4357function spliceOne(list, index) {
4358 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
4359 list[i] = list[k];
4360 list.pop();
4361}
4362
4363function arrayClone(arr, n) {
4364 var copy = new Array(n);
4365 for (var i = 0; i < n; ++i)
4366 copy[i] = arr[i];
4367 return copy;
4368}
4369
4370function unwrapListeners(arr) {
4371 var ret = new Array(arr.length);
4372 for (var i = 0; i < ret.length; ++i) {
4373 ret[i] = arr[i].listener || arr[i];
4374 }
4375 return ret;
4376}
4377
4378function objectCreatePolyfill(proto) {
4379 var F = function() {};
4380 F.prototype = proto;
4381 return new F;
4382}
4383function objectKeysPolyfill(obj) {
4384 var keys = [];
4385 for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
4386 keys.push(k);
4387 }
4388 return k;
4389}
4390function functionBindPolyfill(context) {
4391 var fn = this;
4392 return function () {
4393 return fn.apply(context, arguments);
4394 };
4395}
4396
4397},{}],15:[function(_dereq_,module,exports){
4398"use strict"
4399
4400module.exports = createRBTree
4401
4402var RED = 0
4403var BLACK = 1
4404
4405function RBNode(color, key, value, left, right, count) {
4406 this._color = color
4407 this.key = key
4408 this.value = value
4409 this.left = left
4410 this.right = right
4411 this._count = count
4412}
4413
4414function cloneNode(node) {
4415 return new RBNode(node._color, node.key, node.value, node.left, node.right, node._count)
4416}
4417
4418function repaint(color, node) {
4419 return new RBNode(color, node.key, node.value, node.left, node.right, node._count)
4420}
4421
4422function recount(node) {
4423 node._count = 1 + (node.left ? node.left._count : 0) + (node.right ? node.right._count : 0)
4424}
4425
4426function RedBlackTree(compare, root) {
4427 this._compare = compare
4428 this.root = root
4429}
4430
4431var proto = RedBlackTree.prototype
4432
4433Object.defineProperty(proto, "keys", {
4434 get: function() {
4435 var result = []
4436 this.forEach(function(k,v) {
4437 result.push(k)
4438 })
4439 return result
4440 }
4441})
4442
4443Object.defineProperty(proto, "values", {
4444 get: function() {
4445 var result = []
4446 this.forEach(function(k,v) {
4447 result.push(v)
4448 })
4449 return result
4450 }
4451})
4452
4453//Returns the number of nodes in the tree
4454Object.defineProperty(proto, "length", {
4455 get: function() {
4456 if(this.root) {
4457 return this.root._count
4458 }
4459 return 0
4460 }
4461})
4462
4463//Insert a new item into the tree
4464proto.insert = function(key, value) {
4465 var cmp = this._compare
4466 //Find point to insert new node at
4467 var n = this.root
4468 var n_stack = []
4469 var d_stack = []
4470 while(n) {
4471 var d = cmp(key, n.key)
4472 n_stack.push(n)
4473 d_stack.push(d)
4474 if(d <= 0) {
4475 n = n.left
4476 } else {
4477 n = n.right
4478 }
4479 }
4480 //Rebuild path to leaf node
4481 n_stack.push(new RBNode(RED, key, value, null, null, 1))
4482 for(var s=n_stack.length-2; s>=0; --s) {
4483 var n = n_stack[s]
4484 if(d_stack[s] <= 0) {
4485 n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s+1], n.right, n._count+1)
4486 } else {
4487 n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s+1], n._count+1)
4488 }
4489 }
4490 //Rebalance tree using rotations
4491 //console.log("start insert", key, d_stack)
4492 for(var s=n_stack.length-1; s>1; --s) {
4493 var p = n_stack[s-1]
4494 var n = n_stack[s]
4495 if(p._color === BLACK || n._color === BLACK) {
4496 break
4497 }
4498 var pp = n_stack[s-2]
4499 if(pp.left === p) {
4500 if(p.left === n) {
4501 var y = pp.right
4502 if(y && y._color === RED) {
4503 //console.log("LLr")
4504 p._color = BLACK
4505 pp.right = repaint(BLACK, y)
4506 pp._color = RED
4507 s -= 1
4508 } else {
4509 //console.log("LLb")
4510 pp._color = RED
4511 pp.left = p.right
4512 p._color = BLACK
4513 p.right = pp
4514 n_stack[s-2] = p
4515 n_stack[s-1] = n
4516 recount(pp)
4517 recount(p)
4518 if(s >= 3) {
4519 var ppp = n_stack[s-3]
4520 if(ppp.left === pp) {
4521 ppp.left = p
4522 } else {
4523 ppp.right = p
4524 }
4525 }
4526 break
4527 }
4528 } else {
4529 var y = pp.right
4530 if(y && y._color === RED) {
4531 //console.log("LRr")
4532 p._color = BLACK
4533 pp.right = repaint(BLACK, y)
4534 pp._color = RED
4535 s -= 1
4536 } else {
4537 //console.log("LRb")
4538 p.right = n.left
4539 pp._color = RED
4540 pp.left = n.right
4541 n._color = BLACK
4542 n.left = p
4543 n.right = pp
4544 n_stack[s-2] = n
4545 n_stack[s-1] = p
4546 recount(pp)
4547 recount(p)
4548 recount(n)
4549 if(s >= 3) {
4550 var ppp = n_stack[s-3]
4551 if(ppp.left === pp) {
4552 ppp.left = n
4553 } else {
4554 ppp.right = n
4555 }
4556 }
4557 break
4558 }
4559 }
4560 } else {
4561 if(p.right === n) {
4562 var y = pp.left
4563 if(y && y._color === RED) {
4564 //console.log("RRr", y.key)
4565 p._color = BLACK
4566 pp.left = repaint(BLACK, y)
4567 pp._color = RED
4568 s -= 1
4569 } else {
4570 //console.log("RRb")
4571 pp._color = RED
4572 pp.right = p.left
4573 p._color = BLACK
4574 p.left = pp
4575 n_stack[s-2] = p
4576 n_stack[s-1] = n
4577 recount(pp)
4578 recount(p)
4579 if(s >= 3) {
4580 var ppp = n_stack[s-3]
4581 if(ppp.right === pp) {
4582 ppp.right = p
4583 } else {
4584 ppp.left = p
4585 }
4586 }
4587 break
4588 }
4589 } else {
4590 var y = pp.left
4591 if(y && y._color === RED) {
4592 //console.log("RLr")
4593 p._color = BLACK
4594 pp.left = repaint(BLACK, y)
4595 pp._color = RED
4596 s -= 1
4597 } else {
4598 //console.log("RLb")
4599 p.left = n.right
4600 pp._color = RED
4601 pp.right = n.left
4602 n._color = BLACK
4603 n.right = p
4604 n.left = pp
4605 n_stack[s-2] = n
4606 n_stack[s-1] = p
4607 recount(pp)
4608 recount(p)
4609 recount(n)
4610 if(s >= 3) {
4611 var ppp = n_stack[s-3]
4612 if(ppp.right === pp) {
4613 ppp.right = n
4614 } else {
4615 ppp.left = n
4616 }
4617 }
4618 break
4619 }
4620 }
4621 }
4622 }
4623 //Return new tree
4624 n_stack[0]._color = BLACK
4625 return new RedBlackTree(cmp, n_stack[0])
4626}
4627
4628
4629//Visit all nodes inorder
4630function doVisitFull(visit, node) {
4631 if(node.left) {
4632 var v = doVisitFull(visit, node.left)
4633 if(v) { return v }
4634 }
4635 var v = visit(node.key, node.value)
4636 if(v) { return v }
4637 if(node.right) {
4638 return doVisitFull(visit, node.right)
4639 }
4640}
4641
4642//Visit half nodes in order
4643function doVisitHalf(lo, compare, visit, node) {
4644 var l = compare(lo, node.key)
4645 if(l <= 0) {
4646 if(node.left) {
4647 var v = doVisitHalf(lo, compare, visit, node.left)
4648 if(v) { return v }
4649 }
4650 var v = visit(node.key, node.value)
4651 if(v) { return v }
4652 }
4653 if(node.right) {
4654 return doVisitHalf(lo, compare, visit, node.right)
4655 }
4656}
4657
4658//Visit all nodes within a range
4659function doVisit(lo, hi, compare, visit, node) {
4660 var l = compare(lo, node.key)
4661 var h = compare(hi, node.key)
4662 var v
4663 if(l <= 0) {
4664 if(node.left) {
4665 v = doVisit(lo, hi, compare, visit, node.left)
4666 if(v) { return v }
4667 }
4668 if(h > 0) {
4669 v = visit(node.key, node.value)
4670 if(v) { return v }
4671 }
4672 }
4673 if(h > 0 && node.right) {
4674 return doVisit(lo, hi, compare, visit, node.right)
4675 }
4676}
4677
4678
4679proto.forEach = function rbTreeForEach(visit, lo, hi) {
4680 if(!this.root) {
4681 return
4682 }
4683 switch(arguments.length) {
4684 case 1:
4685 return doVisitFull(visit, this.root)
4686 break
4687
4688 case 2:
4689 return doVisitHalf(lo, this._compare, visit, this.root)
4690 break
4691
4692 case 3:
4693 if(this._compare(lo, hi) >= 0) {
4694 return
4695 }
4696 return doVisit(lo, hi, this._compare, visit, this.root)
4697 break
4698 }
4699}
4700
4701//First item in list
4702Object.defineProperty(proto, "begin", {
4703 get: function() {
4704 var stack = []
4705 var n = this.root
4706 while(n) {
4707 stack.push(n)
4708 n = n.left
4709 }
4710 return new RedBlackTreeIterator(this, stack)
4711 }
4712})
4713
4714//Last item in list
4715Object.defineProperty(proto, "end", {
4716 get: function() {
4717 var stack = []
4718 var n = this.root
4719 while(n) {
4720 stack.push(n)
4721 n = n.right
4722 }
4723 return new RedBlackTreeIterator(this, stack)
4724 }
4725})
4726
4727//Find the ith item in the tree
4728proto.at = function(idx) {
4729 if(idx < 0) {
4730 return new RedBlackTreeIterator(this, [])
4731 }
4732 var n = this.root
4733 var stack = []
4734 while(true) {
4735 stack.push(n)
4736 if(n.left) {
4737 if(idx < n.left._count) {
4738 n = n.left
4739 continue
4740 }
4741 idx -= n.left._count
4742 }
4743 if(!idx) {
4744 return new RedBlackTreeIterator(this, stack)
4745 }
4746 idx -= 1
4747 if(n.right) {
4748 if(idx >= n.right._count) {
4749 break
4750 }
4751 n = n.right
4752 } else {
4753 break
4754 }
4755 }
4756 return new RedBlackTreeIterator(this, [])
4757}
4758
4759proto.ge = function(key) {
4760 var cmp = this._compare
4761 var n = this.root
4762 var stack = []
4763 var last_ptr = 0
4764 while(n) {
4765 var d = cmp(key, n.key)
4766 stack.push(n)
4767 if(d <= 0) {
4768 last_ptr = stack.length
4769 }
4770 if(d <= 0) {
4771 n = n.left
4772 } else {
4773 n = n.right
4774 }
4775 }
4776 stack.length = last_ptr
4777 return new RedBlackTreeIterator(this, stack)
4778}
4779
4780proto.gt = function(key) {
4781 var cmp = this._compare
4782 var n = this.root
4783 var stack = []
4784 var last_ptr = 0
4785 while(n) {
4786 var d = cmp(key, n.key)
4787 stack.push(n)
4788 if(d < 0) {
4789 last_ptr = stack.length
4790 }
4791 if(d < 0) {
4792 n = n.left
4793 } else {
4794 n = n.right
4795 }
4796 }
4797 stack.length = last_ptr
4798 return new RedBlackTreeIterator(this, stack)
4799}
4800
4801proto.lt = function(key) {
4802 var cmp = this._compare
4803 var n = this.root
4804 var stack = []
4805 var last_ptr = 0
4806 while(n) {
4807 var d = cmp(key, n.key)
4808 stack.push(n)
4809 if(d > 0) {
4810 last_ptr = stack.length
4811 }
4812 if(d <= 0) {
4813 n = n.left
4814 } else {
4815 n = n.right
4816 }
4817 }
4818 stack.length = last_ptr
4819 return new RedBlackTreeIterator(this, stack)
4820}
4821
4822proto.le = function(key) {
4823 var cmp = this._compare
4824 var n = this.root
4825 var stack = []
4826 var last_ptr = 0
4827 while(n) {
4828 var d = cmp(key, n.key)
4829 stack.push(n)
4830 if(d >= 0) {
4831 last_ptr = stack.length
4832 }
4833 if(d < 0) {
4834 n = n.left
4835 } else {
4836 n = n.right
4837 }
4838 }
4839 stack.length = last_ptr
4840 return new RedBlackTreeIterator(this, stack)
4841}
4842
4843//Finds the item with key if it exists
4844proto.find = function(key) {
4845 var cmp = this._compare
4846 var n = this.root
4847 var stack = []
4848 while(n) {
4849 var d = cmp(key, n.key)
4850 stack.push(n)
4851 if(d === 0) {
4852 return new RedBlackTreeIterator(this, stack)
4853 }
4854 if(d <= 0) {
4855 n = n.left
4856 } else {
4857 n = n.right
4858 }
4859 }
4860 return new RedBlackTreeIterator(this, [])
4861}
4862
4863//Removes item with key from tree
4864proto.remove = function(key) {
4865 var iter = this.find(key)
4866 if(iter) {
4867 return iter.remove()
4868 }
4869 return this
4870}
4871
4872//Returns the item at `key`
4873proto.get = function(key) {
4874 var cmp = this._compare
4875 var n = this.root
4876 while(n) {
4877 var d = cmp(key, n.key)
4878 if(d === 0) {
4879 return n.value
4880 }
4881 if(d <= 0) {
4882 n = n.left
4883 } else {
4884 n = n.right
4885 }
4886 }
4887 return
4888}
4889
4890//Iterator for red black tree
4891function RedBlackTreeIterator(tree, stack) {
4892 this.tree = tree
4893 this._stack = stack
4894}
4895
4896var iproto = RedBlackTreeIterator.prototype
4897
4898//Test if iterator is valid
4899Object.defineProperty(iproto, "valid", {
4900 get: function() {
4901 return this._stack.length > 0
4902 }
4903})
4904
4905//Node of the iterator
4906Object.defineProperty(iproto, "node", {
4907 get: function() {
4908 if(this._stack.length > 0) {
4909 return this._stack[this._stack.length-1]
4910 }
4911 return null
4912 },
4913 enumerable: true
4914})
4915
4916//Makes a copy of an iterator
4917iproto.clone = function() {
4918 return new RedBlackTreeIterator(this.tree, this._stack.slice())
4919}
4920
4921//Swaps two nodes
4922function swapNode(n, v) {
4923 n.key = v.key
4924 n.value = v.value
4925 n.left = v.left
4926 n.right = v.right
4927 n._color = v._color
4928 n._count = v._count
4929}
4930
4931//Fix up a double black node in a tree
4932function fixDoubleBlack(stack) {
4933 var n, p, s, z
4934 for(var i=stack.length-1; i>=0; --i) {
4935 n = stack[i]
4936 if(i === 0) {
4937 n._color = BLACK
4938 return
4939 }
4940 //console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key)
4941 p = stack[i-1]
4942 if(p.left === n) {
4943 //console.log("left child")
4944 s = p.right
4945 if(s.right && s.right._color === RED) {
4946 //console.log("case 1: right sibling child red")
4947 s = p.right = cloneNode(s)
4948 z = s.right = cloneNode(s.right)
4949 p.right = s.left
4950 s.left = p
4951 s.right = z
4952 s._color = p._color
4953 n._color = BLACK
4954 p._color = BLACK
4955 z._color = BLACK
4956 recount(p)
4957 recount(s)
4958 if(i > 1) {
4959 var pp = stack[i-2]
4960 if(pp.left === p) {
4961 pp.left = s
4962 } else {
4963 pp.right = s
4964 }
4965 }
4966 stack[i-1] = s
4967 return
4968 } else if(s.left && s.left._color === RED) {
4969 //console.log("case 1: left sibling child red")
4970 s = p.right = cloneNode(s)
4971 z = s.left = cloneNode(s.left)
4972 p.right = z.left
4973 s.left = z.right
4974 z.left = p
4975 z.right = s
4976 z._color = p._color
4977 p._color = BLACK
4978 s._color = BLACK
4979 n._color = BLACK
4980 recount(p)
4981 recount(s)
4982 recount(z)
4983 if(i > 1) {
4984 var pp = stack[i-2]
4985 if(pp.left === p) {
4986 pp.left = z
4987 } else {
4988 pp.right = z
4989 }
4990 }
4991 stack[i-1] = z
4992 return
4993 }
4994 if(s._color === BLACK) {
4995 if(p._color === RED) {
4996 //console.log("case 2: black sibling, red parent", p.right.value)
4997 p._color = BLACK
4998 p.right = repaint(RED, s)
4999 return
5000 } else {
5001 //console.log("case 2: black sibling, black parent", p.right.value)
5002 p.right = repaint(RED, s)
5003 continue
5004 }
5005 } else {
5006 //console.log("case 3: red sibling")
5007 s = cloneNode(s)
5008 p.right = s.left
5009 s.left = p
5010 s._color = p._color
5011 p._color = RED
5012 recount(p)
5013 recount(s)
5014 if(i > 1) {
5015 var pp = stack[i-2]
5016 if(pp.left === p) {
5017 pp.left = s
5018 } else {
5019 pp.right = s
5020 }
5021 }
5022 stack[i-1] = s
5023 stack[i] = p
5024 if(i+1 < stack.length) {
5025 stack[i+1] = n
5026 } else {
5027 stack.push(n)
5028 }
5029 i = i+2
5030 }
5031 } else {
5032 //console.log("right child")
5033 s = p.left
5034 if(s.left && s.left._color === RED) {
5035 //console.log("case 1: left sibling child red", p.value, p._color)
5036 s = p.left = cloneNode(s)
5037 z = s.left = cloneNode(s.left)
5038 p.left = s.right
5039 s.right = p
5040 s.left = z
5041 s._color = p._color
5042 n._color = BLACK
5043 p._color = BLACK
5044 z._color = BLACK
5045 recount(p)
5046 recount(s)
5047 if(i > 1) {
5048 var pp = stack[i-2]
5049 if(pp.right === p) {
5050 pp.right = s
5051 } else {
5052 pp.left = s
5053 }
5054 }
5055 stack[i-1] = s
5056 return
5057 } else if(s.right && s.right._color === RED) {
5058 //console.log("case 1: right sibling child red")
5059 s = p.left = cloneNode(s)
5060 z = s.right = cloneNode(s.right)
5061 p.left = z.right
5062 s.right = z.left
5063 z.right = p
5064 z.left = s
5065 z._color = p._color
5066 p._color = BLACK
5067 s._color = BLACK
5068 n._color = BLACK
5069 recount(p)
5070 recount(s)
5071 recount(z)
5072 if(i > 1) {
5073 var pp = stack[i-2]
5074 if(pp.right === p) {
5075 pp.right = z
5076 } else {
5077 pp.left = z
5078 }
5079 }
5080 stack[i-1] = z
5081 return
5082 }
5083 if(s._color === BLACK) {
5084 if(p._color === RED) {
5085 //console.log("case 2: black sibling, red parent")
5086 p._color = BLACK
5087 p.left = repaint(RED, s)
5088 return
5089 } else {
5090 //console.log("case 2: black sibling, black parent")
5091 p.left = repaint(RED, s)
5092 continue
5093 }
5094 } else {
5095 //console.log("case 3: red sibling")
5096 s = cloneNode(s)
5097 p.left = s.right
5098 s.right = p
5099 s._color = p._color
5100 p._color = RED
5101 recount(p)
5102 recount(s)
5103 if(i > 1) {
5104 var pp = stack[i-2]
5105 if(pp.right === p) {
5106 pp.right = s
5107 } else {
5108 pp.left = s
5109 }
5110 }
5111 stack[i-1] = s
5112 stack[i] = p
5113 if(i+1 < stack.length) {
5114 stack[i+1] = n
5115 } else {
5116 stack.push(n)
5117 }
5118 i = i+2
5119 }
5120 }
5121 }
5122}
5123
5124//Removes item at iterator from tree
5125iproto.remove = function() {
5126 var stack = this._stack
5127 if(stack.length === 0) {
5128 return this.tree
5129 }
5130 //First copy path to node
5131 var cstack = new Array(stack.length)
5132 var n = stack[stack.length-1]
5133 cstack[cstack.length-1] = new RBNode(n._color, n.key, n.value, n.left, n.right, n._count)
5134 for(var i=stack.length-2; i>=0; --i) {
5135 var n = stack[i]
5136 if(n.left === stack[i+1]) {
5137 cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count)
5138 } else {
5139 cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
5140 }
5141 }
5142
5143 //Get node
5144 n = cstack[cstack.length-1]
5145 //console.log("start remove: ", n.value)
5146
5147 //If not leaf, then swap with previous node
5148 if(n.left && n.right) {
5149 //console.log("moving to leaf")
5150
5151 //First walk to previous leaf
5152 var split = cstack.length
5153 n = n.left
5154 while(n.right) {
5155 cstack.push(n)
5156 n = n.right
5157 }
5158 //Copy path to leaf
5159 var v = cstack[split-1]
5160 cstack.push(new RBNode(n._color, v.key, v.value, n.left, n.right, n._count))
5161 cstack[split-1].key = n.key
5162 cstack[split-1].value = n.value
5163
5164 //Fix up stack
5165 for(var i=cstack.length-2; i>=split; --i) {
5166 n = cstack[i]
5167 cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
5168 }
5169 cstack[split-1].left = cstack[split]
5170 }
5171 //console.log("stack=", cstack.map(function(v) { return v.value }))
5172
5173 //Remove leaf node
5174 n = cstack[cstack.length-1]
5175 if(n._color === RED) {
5176 //Easy case: removing red leaf
5177 //console.log("RED leaf")
5178 var p = cstack[cstack.length-2]
5179 if(p.left === n) {
5180 p.left = null
5181 } else if(p.right === n) {
5182 p.right = null
5183 }
5184 cstack.pop()
5185 for(var i=0; i<cstack.length; ++i) {
5186 cstack[i]._count--
5187 }
5188 return new RedBlackTree(this.tree._compare, cstack[0])
5189 } else {
5190 if(n.left || n.right) {
5191 //Second easy case: Single child black parent
5192 //console.log("BLACK single child")
5193 if(n.left) {
5194 swapNode(n, n.left)
5195 } else if(n.right) {
5196 swapNode(n, n.right)
5197 }
5198 //Child must be red, so repaint it black to balance color
5199 n._color = BLACK
5200 for(var i=0; i<cstack.length-1; ++i) {
5201 cstack[i]._count--
5202 }
5203 return new RedBlackTree(this.tree._compare, cstack[0])
5204 } else if(cstack.length === 1) {
5205 //Third easy case: root
5206 //console.log("ROOT")
5207 return new RedBlackTree(this.tree._compare, null)
5208 } else {
5209 //Hard case: Repaint n, and then do some nasty stuff
5210 //console.log("BLACK leaf no children")
5211 for(var i=0; i<cstack.length; ++i) {
5212 cstack[i]._count--
5213 }
5214 var parent = cstack[cstack.length-2]
5215 fixDoubleBlack(cstack)
5216 //Fix up links
5217 if(parent.left === n) {
5218 parent.left = null
5219 } else {
5220 parent.right = null
5221 }
5222 }
5223 }
5224 return new RedBlackTree(this.tree._compare, cstack[0])
5225}
5226
5227//Returns key
5228Object.defineProperty(iproto, "key", {
5229 get: function() {
5230 if(this._stack.length > 0) {
5231 return this._stack[this._stack.length-1].key
5232 }
5233 return
5234 },
5235 enumerable: true
5236})
5237
5238//Returns value
5239Object.defineProperty(iproto, "value", {
5240 get: function() {
5241 if(this._stack.length > 0) {
5242 return this._stack[this._stack.length-1].value
5243 }
5244 return
5245 },
5246 enumerable: true
5247})
5248
5249
5250//Returns the position of this iterator in the sorted list
5251Object.defineProperty(iproto, "index", {
5252 get: function() {
5253 var idx = 0
5254 var stack = this._stack
5255 if(stack.length === 0) {
5256 var r = this.tree.root
5257 if(r) {
5258 return r._count
5259 }
5260 return 0
5261 } else if(stack[stack.length-1].left) {
5262 idx = stack[stack.length-1].left._count
5263 }
5264 for(var s=stack.length-2; s>=0; --s) {
5265 if(stack[s+1] === stack[s].right) {
5266 ++idx
5267 if(stack[s].left) {
5268 idx += stack[s].left._count
5269 }
5270 }
5271 }
5272 return idx
5273 },
5274 enumerable: true
5275})
5276
5277//Advances iterator to next element in list
5278iproto.next = function() {
5279 var stack = this._stack
5280 if(stack.length === 0) {
5281 return
5282 }
5283 var n = stack[stack.length-1]
5284 if(n.right) {
5285 n = n.right
5286 while(n) {
5287 stack.push(n)
5288 n = n.left
5289 }
5290 } else {
5291 stack.pop()
5292 while(stack.length > 0 && stack[stack.length-1].right === n) {
5293 n = stack[stack.length-1]
5294 stack.pop()
5295 }
5296 }
5297}
5298
5299//Checks if iterator is at end of tree
5300Object.defineProperty(iproto, "hasNext", {
5301 get: function() {
5302 var stack = this._stack
5303 if(stack.length === 0) {
5304 return false
5305 }
5306 if(stack[stack.length-1].right) {
5307 return true
5308 }
5309 for(var s=stack.length-1; s>0; --s) {
5310 if(stack[s-1].left === stack[s]) {
5311 return true
5312 }
5313 }
5314 return false
5315 }
5316})
5317
5318//Update value
5319iproto.update = function(value) {
5320 var stack = this._stack
5321 if(stack.length === 0) {
5322 throw new Error("Can't update empty node!")
5323 }
5324 var cstack = new Array(stack.length)
5325 var n = stack[stack.length-1]
5326 cstack[cstack.length-1] = new RBNode(n._color, n.key, value, n.left, n.right, n._count)
5327 for(var i=stack.length-2; i>=0; --i) {
5328 n = stack[i]
5329 if(n.left === stack[i+1]) {
5330 cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count)
5331 } else {
5332 cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
5333 }
5334 }
5335 return new RedBlackTree(this.tree._compare, cstack[0])
5336}
5337
5338//Moves iterator backward one element
5339iproto.prev = function() {
5340 var stack = this._stack
5341 if(stack.length === 0) {
5342 return
5343 }
5344 var n = stack[stack.length-1]
5345 if(n.left) {
5346 n = n.left
5347 while(n) {
5348 stack.push(n)
5349 n = n.right
5350 }
5351 } else {
5352 stack.pop()
5353 while(stack.length > 0 && stack[stack.length-1].left === n) {
5354 n = stack[stack.length-1]
5355 stack.pop()
5356 }
5357 }
5358}
5359
5360//Checks if iterator is at start of tree
5361Object.defineProperty(iproto, "hasPrev", {
5362 get: function() {
5363 var stack = this._stack
5364 if(stack.length === 0) {
5365 return false
5366 }
5367 if(stack[stack.length-1].left) {
5368 return true
5369 }
5370 for(var s=stack.length-1; s>0; --s) {
5371 if(stack[s-1].right === stack[s]) {
5372 return true
5373 }
5374 }
5375 return false
5376 }
5377})
5378
5379//Default comparison function
5380function defaultCompare(a, b) {
5381 if(a < b) {
5382 return -1
5383 }
5384 if(a > b) {
5385 return 1
5386 }
5387 return 0
5388}
5389
5390//Build a tree
5391function createRBTree(compare) {
5392 return new RedBlackTree(compare || defaultCompare, null)
5393}
5394},{}],16:[function(_dereq_,module,exports){
5395exports.read = function (buffer, offset, isLE, mLen, nBytes) {
5396 var e, m
5397 var eLen = (nBytes * 8) - mLen - 1
5398 var eMax = (1 << eLen) - 1
5399 var eBias = eMax >> 1
5400 var nBits = -7
5401 var i = isLE ? (nBytes - 1) : 0
5402 var d = isLE ? -1 : 1
5403 var s = buffer[offset + i]
5404
5405 i += d
5406
5407 e = s & ((1 << (-nBits)) - 1)
5408 s >>= (-nBits)
5409 nBits += eLen
5410 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
5411
5412 m = e & ((1 << (-nBits)) - 1)
5413 e >>= (-nBits)
5414 nBits += mLen
5415 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
5416
5417 if (e === 0) {
5418 e = 1 - eBias
5419 } else if (e === eMax) {
5420 return m ? NaN : ((s ? -1 : 1) * Infinity)
5421 } else {
5422 m = m + Math.pow(2, mLen)
5423 e = e - eBias
5424 }
5425 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
5426}
5427
5428exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
5429 var e, m, c
5430 var eLen = (nBytes * 8) - mLen - 1
5431 var eMax = (1 << eLen) - 1
5432 var eBias = eMax >> 1
5433 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
5434 var i = isLE ? 0 : (nBytes - 1)
5435 var d = isLE ? 1 : -1
5436 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
5437
5438 value = Math.abs(value)
5439
5440 if (isNaN(value) || value === Infinity) {
5441 m = isNaN(value) ? 1 : 0
5442 e = eMax
5443 } else {
5444 e = Math.floor(Math.log(value) / Math.LN2)
5445 if (value * (c = Math.pow(2, -e)) < 1) {
5446 e--
5447 c *= 2
5448 }
5449 if (e + eBias >= 1) {
5450 value += rt / c
5451 } else {
5452 value += rt * Math.pow(2, 1 - eBias)
5453 }
5454 if (value * c >= 2) {
5455 e++
5456 c /= 2
5457 }
5458
5459 if (e + eBias >= eMax) {
5460 m = 0
5461 e = eMax
5462 } else if (e + eBias >= 1) {
5463 m = ((value * c) - 1) * Math.pow(2, mLen)
5464 e = e + eBias
5465 } else {
5466 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
5467 e = 0
5468 }
5469 }
5470
5471 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
5472
5473 e = (e << mLen) | m
5474 eLen += mLen
5475 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
5476
5477 buffer[offset + i - d] |= s * 128
5478}
5479
5480},{}],17:[function(_dereq_,module,exports){
5481(function (global){
5482'use strict';
5483var Mutation = global.MutationObserver || global.WebKitMutationObserver;
5484
5485var scheduleDrain;
5486
5487{
5488 if (Mutation) {
5489 var called = 0;
5490 var observer = new Mutation(nextTick);
5491 var element = global.document.createTextNode('');
5492 observer.observe(element, {
5493 characterData: true
5494 });
5495 scheduleDrain = function () {
5496 element.data = (called = ++called % 2);
5497 };
5498 } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
5499 var channel = new global.MessageChannel();
5500 channel.port1.onmessage = nextTick;
5501 scheduleDrain = function () {
5502 channel.port2.postMessage(0);
5503 };
5504 } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
5505 scheduleDrain = function () {
5506
5507 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
5508 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
5509 var scriptEl = global.document.createElement('script');
5510 scriptEl.onreadystatechange = function () {
5511 nextTick();
5512
5513 scriptEl.onreadystatechange = null;
5514 scriptEl.parentNode.removeChild(scriptEl);
5515 scriptEl = null;
5516 };
5517 global.document.documentElement.appendChild(scriptEl);
5518 };
5519 } else {
5520 scheduleDrain = function () {
5521 setTimeout(nextTick, 0);
5522 };
5523 }
5524}
5525
5526var draining;
5527var queue = [];
5528//named nextTick for less confusing stack traces
5529function nextTick() {
5530 draining = true;
5531 var i, oldQueue;
5532 var len = queue.length;
5533 while (len) {
5534 oldQueue = queue;
5535 queue = [];
5536 i = -1;
5537 while (++i < len) {
5538 oldQueue[i]();
5539 }
5540 len = queue.length;
5541 }
5542 draining = false;
5543}
5544
5545module.exports = immediate;
5546function immediate(task) {
5547 if (queue.push(task) === 1 && !draining) {
5548 scheduleDrain();
5549 }
5550}
5551
5552}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5553},{}],18:[function(_dereq_,module,exports){
5554arguments[4][3][0].apply(exports,arguments)
5555},{"3":3}],19:[function(_dereq_,module,exports){
5556/*!
5557 * Determine if an object is a Buffer
5558 *
5559 * @author Feross Aboukhadijeh <https://feross.org>
5560 * @license MIT
5561 */
5562
5563// The _isBuffer check is for Safari 5-7 support, because it's missing
5564// Object.prototype.constructor. Remove this eventually
5565module.exports = function (obj) {
5566 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
5567}
5568
5569function isBuffer (obj) {
5570 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
5571}
5572
5573// For Node v0.10 support. Remove this eventually.
5574function isSlowBuffer (obj) {
5575 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
5576}
5577
5578},{}],20:[function(_dereq_,module,exports){
5579var toString = {}.toString;
5580
5581module.exports = Array.isArray || function (arr) {
5582 return toString.call(arr) == '[object Array]';
5583};
5584
5585},{}],21:[function(_dereq_,module,exports){
5586var encodings = _dereq_(22);
5587
5588module.exports = Codec;
5589
5590function Codec(opts){
5591 this.opts = opts || {};
5592 this.encodings = encodings;
5593}
5594
5595Codec.prototype._encoding = function(encoding){
5596 if (typeof encoding == 'string') encoding = encodings[encoding];
5597 if (!encoding) encoding = encodings.id;
5598 return encoding;
5599};
5600
5601Codec.prototype._keyEncoding = function(opts, batchOpts){
5602 return this._encoding(batchOpts && batchOpts.keyEncoding
5603 || opts && opts.keyEncoding
5604 || this.opts.keyEncoding);
5605};
5606
5607Codec.prototype._valueEncoding = function(opts, batchOpts){
5608 return this._encoding(
5609 batchOpts && (batchOpts.valueEncoding || batchOpts.encoding)
5610 || opts && (opts.valueEncoding || opts.encoding)
5611 || (this.opts.valueEncoding || this.opts.encoding));
5612};
5613
5614Codec.prototype.encodeKey = function(key, opts, batchOpts){
5615 return this._keyEncoding(opts, batchOpts).encode(key);
5616};
5617
5618Codec.prototype.encodeValue = function(value, opts, batchOpts){
5619 return this._valueEncoding(opts, batchOpts).encode(value);
5620};
5621
5622Codec.prototype.decodeKey = function(key, opts){
5623 return this._keyEncoding(opts).decode(key);
5624};
5625
5626Codec.prototype.decodeValue = function(value, opts){
5627 return this._valueEncoding(opts).decode(value);
5628};
5629
5630Codec.prototype.encodeBatch = function(ops, opts){
5631 var self = this;
5632
5633 return ops.map(function(_op){
5634 var op = {
5635 type: _op.type,
5636 key: self.encodeKey(_op.key, opts, _op)
5637 };
5638 if (self.keyAsBuffer(opts, _op)) op.keyEncoding = 'binary';
5639 if (_op.prefix) op.prefix = _op.prefix;
5640 if ('value' in _op) {
5641 op.value = self.encodeValue(_op.value, opts, _op);
5642 if (self.valueAsBuffer(opts, _op)) op.valueEncoding = 'binary';
5643 }
5644 return op;
5645 });
5646};
5647
5648var ltgtKeys = ['lt', 'gt', 'lte', 'gte', 'start', 'end'];
5649
5650Codec.prototype.encodeLtgt = function(ltgt){
5651 var self = this;
5652 var ret = {};
5653 Object.keys(ltgt).forEach(function(key){
5654 ret[key] = ltgtKeys.indexOf(key) > -1
5655 ? self.encodeKey(ltgt[key], ltgt)
5656 : ltgt[key]
5657 });
5658 return ret;
5659};
5660
5661Codec.prototype.createStreamDecoder = function(opts){
5662 var self = this;
5663
5664 if (opts.keys && opts.values) {
5665 return function(key, value){
5666 return {
5667 key: self.decodeKey(key, opts),
5668 value: self.decodeValue(value, opts)
5669 };
5670 };
5671 } else if (opts.keys) {
5672 return function(key) {
5673 return self.decodeKey(key, opts);
5674 };
5675 } else if (opts.values) {
5676 return function(_, value){
5677 return self.decodeValue(value, opts);
5678 }
5679 } else {
5680 return function(){};
5681 }
5682};
5683
5684Codec.prototype.keyAsBuffer = function(opts){
5685 return this._keyEncoding(opts).buffer;
5686};
5687
5688Codec.prototype.valueAsBuffer = function(opts){
5689 return this._valueEncoding(opts).buffer;
5690};
5691
5692
5693},{"22":22}],22:[function(_dereq_,module,exports){
5694(function (Buffer){
5695exports.utf8 = exports['utf-8'] = {
5696 encode: function(data){
5697 return isBinary(data)
5698 ? data
5699 : String(data);
5700 },
5701 decode: function(data){
5702 return typeof data === 'string'
5703 ? data
5704 : String(data)
5705 },
5706 buffer: false,
5707 type: 'utf8'
5708};
5709
5710exports.json = {
5711 encode: JSON.stringify,
5712 decode: JSON.parse,
5713 buffer: false,
5714 type: 'json'
5715};
5716
5717exports.binary = {
5718 encode: function(data){
5719 return isBinary(data)
5720 ? data
5721 : new Buffer(data);
5722 },
5723 decode: identity,
5724 buffer: true,
5725 type: 'binary'
5726};
5727
5728exports.none = {
5729 encode: identity,
5730 decode: identity,
5731 buffer: false,
5732 type: 'id'
5733};
5734
5735exports.id = exports.none;
5736
5737var bufferEncodings = [
5738 'hex',
5739 'ascii',
5740 'base64',
5741 'ucs2',
5742 'ucs-2',
5743 'utf16le',
5744 'utf-16le'
5745];
5746
5747bufferEncodings.forEach(function(type){
5748 exports[type] = {
5749 encode: function(data){
5750 return isBinary(data)
5751 ? data
5752 : new Buffer(data, type);
5753 },
5754 decode: function(buffer){
5755 return buffer.toString(type);
5756 },
5757 buffer: true,
5758 type: type
5759 };
5760});
5761
5762function identity(value){
5763 return value;
5764}
5765
5766function isBinary(data){
5767 return data === undefined
5768 || data === null
5769 || Buffer.isBuffer(data);
5770}
5771
5772}).call(this,_dereq_(9).Buffer)
5773},{"9":9}],23:[function(_dereq_,module,exports){
5774var inherits = _dereq_(18)
5775var Readable = _dereq_(32).Readable
5776var extend = _dereq_(33)
5777
5778module.exports = ReadStream
5779inherits(ReadStream, Readable)
5780
5781function ReadStream (iterator, options) {
5782 if (!(this instanceof ReadStream)) return new ReadStream(iterator, options)
5783 options = options || {}
5784 Readable.call(this, extend(options, {
5785 objectMode: true
5786 }))
5787 this._iterator = iterator
5788 this._destroyed = false
5789 this._options = options
5790 this.on('end', this._cleanup.bind(this))
5791}
5792
5793ReadStream.prototype._read = function () {
5794 var self = this
5795 var options = this._options
5796 if (this._destroyed) return
5797
5798 this._iterator.next(function (err, key, value) {
5799 if (self._destroyed) return
5800 if (err) return self.emit('error', err)
5801 if (key === undefined && value === undefined) {
5802 self.push(null)
5803 } else if (options.keys !== false && options.values === false) {
5804 self.push(key)
5805 } else if (options.keys === false && options.values !== false) {
5806 self.push(value)
5807 } else {
5808 self.push({ key: key, value: value })
5809 }
5810 })
5811}
5812
5813ReadStream.prototype.destroy =
5814ReadStream.prototype._cleanup = function () {
5815 var self = this
5816 if (this._destroyed) return
5817 this._destroyed = true
5818
5819 this._iterator.end(function (err) {
5820 if (err) return self.emit('error', err)
5821 self.emit('close')
5822 })
5823}
5824
5825},{"18":18,"32":32,"33":33}],24:[function(_dereq_,module,exports){
5826// Copyright Joyent, Inc. and other Node contributors.
5827//
5828// Permission is hereby granted, free of charge, to any person obtaining a
5829// copy of this software and associated documentation files (the
5830// "Software"), to deal in the Software without restriction, including
5831// without limitation the rights to use, copy, modify, merge, publish,
5832// distribute, sublicense, and/or sell copies of the Software, and to permit
5833// persons to whom the Software is furnished to do so, subject to the
5834// following conditions:
5835//
5836// The above copyright notice and this permission notice shall be included
5837// in all copies or substantial portions of the Software.
5838//
5839// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5840// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5841// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5842// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5843// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5844// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5845// USE OR OTHER DEALINGS IN THE SOFTWARE.
5846
5847// a duplex stream is just a stream that is both readable and writable.
5848// Since JS doesn't have multiple prototypal inheritance, this class
5849// prototypally inherits from Readable, and then parasitically from
5850// Writable.
5851
5852'use strict';
5853
5854/*<replacement>*/
5855
5856var pna = _dereq_(61);
5857/*</replacement>*/
5858
5859/*<replacement>*/
5860var objectKeys = Object.keys || function (obj) {
5861 var keys = [];
5862 for (var key in obj) {
5863 keys.push(key);
5864 }return keys;
5865};
5866/*</replacement>*/
5867
5868module.exports = Duplex;
5869
5870/*<replacement>*/
5871var util = _dereq_(10);
5872util.inherits = _dereq_(18);
5873/*</replacement>*/
5874
5875var Readable = _dereq_(26);
5876var Writable = _dereq_(28);
5877
5878util.inherits(Duplex, Readable);
5879
5880{
5881 // avoid scope creep, the keys array can then be collected
5882 var keys = objectKeys(Writable.prototype);
5883 for (var v = 0; v < keys.length; v++) {
5884 var method = keys[v];
5885 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
5886 }
5887}
5888
5889function Duplex(options) {
5890 if (!(this instanceof Duplex)) return new Duplex(options);
5891
5892 Readable.call(this, options);
5893 Writable.call(this, options);
5894
5895 if (options && options.readable === false) this.readable = false;
5896
5897 if (options && options.writable === false) this.writable = false;
5898
5899 this.allowHalfOpen = true;
5900 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
5901
5902 this.once('end', onend);
5903}
5904
5905Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
5906 // making it explicit this property is not enumerable
5907 // because otherwise some prototype manipulation in
5908 // userland will fail
5909 enumerable: false,
5910 get: function () {
5911 return this._writableState.highWaterMark;
5912 }
5913});
5914
5915// the no-half-open enforcer
5916function onend() {
5917 // if we allow half-open state, or if the writable side ended,
5918 // then we're ok.
5919 if (this.allowHalfOpen || this._writableState.ended) return;
5920
5921 // no more data can be written.
5922 // But allow more writes to happen in this tick.
5923 pna.nextTick(onEndNT, this);
5924}
5925
5926function onEndNT(self) {
5927 self.end();
5928}
5929
5930Object.defineProperty(Duplex.prototype, 'destroyed', {
5931 get: function () {
5932 if (this._readableState === undefined || this._writableState === undefined) {
5933 return false;
5934 }
5935 return this._readableState.destroyed && this._writableState.destroyed;
5936 },
5937 set: function (value) {
5938 // we ignore the value if the stream
5939 // has not been initialized yet
5940 if (this._readableState === undefined || this._writableState === undefined) {
5941 return;
5942 }
5943
5944 // backward compatibility, the user is explicitly
5945 // managing destroyed
5946 this._readableState.destroyed = value;
5947 this._writableState.destroyed = value;
5948 }
5949});
5950
5951Duplex.prototype._destroy = function (err, cb) {
5952 this.push(null);
5953 this.end();
5954
5955 pna.nextTick(cb, err);
5956};
5957},{"10":10,"18":18,"26":26,"28":28,"61":61}],25:[function(_dereq_,module,exports){
5958// Copyright Joyent, Inc. and other Node contributors.
5959//
5960// Permission is hereby granted, free of charge, to any person obtaining a
5961// copy of this software and associated documentation files (the
5962// "Software"), to deal in the Software without restriction, including
5963// without limitation the rights to use, copy, modify, merge, publish,
5964// distribute, sublicense, and/or sell copies of the Software, and to permit
5965// persons to whom the Software is furnished to do so, subject to the
5966// following conditions:
5967//
5968// The above copyright notice and this permission notice shall be included
5969// in all copies or substantial portions of the Software.
5970//
5971// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5972// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5973// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5974// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5975// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5976// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5977// USE OR OTHER DEALINGS IN THE SOFTWARE.
5978
5979// a passthrough stream.
5980// basically just the most minimal sort of Transform stream.
5981// Every written chunk gets output as-is.
5982
5983'use strict';
5984
5985module.exports = PassThrough;
5986
5987var Transform = _dereq_(27);
5988
5989/*<replacement>*/
5990var util = _dereq_(10);
5991util.inherits = _dereq_(18);
5992/*</replacement>*/
5993
5994util.inherits(PassThrough, Transform);
5995
5996function PassThrough(options) {
5997 if (!(this instanceof PassThrough)) return new PassThrough(options);
5998
5999 Transform.call(this, options);
6000}
6001
6002PassThrough.prototype._transform = function (chunk, encoding, cb) {
6003 cb(null, chunk);
6004};
6005},{"10":10,"18":18,"27":27}],26:[function(_dereq_,module,exports){
6006(function (process,global){
6007// Copyright Joyent, Inc. and other Node contributors.
6008//
6009// Permission is hereby granted, free of charge, to any person obtaining a
6010// copy of this software and associated documentation files (the
6011// "Software"), to deal in the Software without restriction, including
6012// without limitation the rights to use, copy, modify, merge, publish,
6013// distribute, sublicense, and/or sell copies of the Software, and to permit
6014// persons to whom the Software is furnished to do so, subject to the
6015// following conditions:
6016//
6017// The above copyright notice and this permission notice shall be included
6018// in all copies or substantial portions of the Software.
6019//
6020// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6021// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6022// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6023// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6024// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6025// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6026// USE OR OTHER DEALINGS IN THE SOFTWARE.
6027
6028'use strict';
6029
6030/*<replacement>*/
6031
6032var pna = _dereq_(61);
6033/*</replacement>*/
6034
6035module.exports = Readable;
6036
6037/*<replacement>*/
6038var isArray = _dereq_(20);
6039/*</replacement>*/
6040
6041/*<replacement>*/
6042var Duplex;
6043/*</replacement>*/
6044
6045Readable.ReadableState = ReadableState;
6046
6047/*<replacement>*/
6048var EE = _dereq_(14).EventEmitter;
6049
6050var EElistenerCount = function (emitter, type) {
6051 return emitter.listeners(type).length;
6052};
6053/*</replacement>*/
6054
6055/*<replacement>*/
6056var Stream = _dereq_(31);
6057/*</replacement>*/
6058
6059/*<replacement>*/
6060
6061var Buffer = _dereq_(72).Buffer;
6062var OurUint8Array = global.Uint8Array || function () {};
6063function _uint8ArrayToBuffer(chunk) {
6064 return Buffer.from(chunk);
6065}
6066function _isUint8Array(obj) {
6067 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
6068}
6069
6070/*</replacement>*/
6071
6072/*<replacement>*/
6073var util = _dereq_(10);
6074util.inherits = _dereq_(18);
6075/*</replacement>*/
6076
6077/*<replacement>*/
6078var debugUtil = _dereq_(7);
6079var debug = void 0;
6080if (debugUtil && debugUtil.debuglog) {
6081 debug = debugUtil.debuglog('stream');
6082} else {
6083 debug = function () {};
6084}
6085/*</replacement>*/
6086
6087var BufferList = _dereq_(29);
6088var destroyImpl = _dereq_(30);
6089var StringDecoder;
6090
6091util.inherits(Readable, Stream);
6092
6093var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
6094
6095function prependListener(emitter, event, fn) {
6096 // Sadly this is not cacheable as some libraries bundle their own
6097 // event emitter implementation with them.
6098 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
6099
6100 // This is a hack to make sure that our error handler is attached before any
6101 // userland ones. NEVER DO THIS. This is here only because this code needs
6102 // to continue to work with older versions of Node.js that do not include
6103 // the prependListener() method. The goal is to eventually remove this hack.
6104 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]];
6105}
6106
6107function ReadableState(options, stream) {
6108 Duplex = Duplex || _dereq_(24);
6109
6110 options = options || {};
6111
6112 // Duplex streams are both readable and writable, but share
6113 // the same options object.
6114 // However, some cases require setting options to different
6115 // values for the readable and the writable sides of the duplex stream.
6116 // These options can be provided separately as readableXXX and writableXXX.
6117 var isDuplex = stream instanceof Duplex;
6118
6119 // object stream flag. Used to make read(n) ignore n and to
6120 // make all the buffer merging and length checks go away
6121 this.objectMode = !!options.objectMode;
6122
6123 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
6124
6125 // the point at which it stops calling _read() to fill the buffer
6126 // Note: 0 is a valid value, means "don't call _read preemptively ever"
6127 var hwm = options.highWaterMark;
6128 var readableHwm = options.readableHighWaterMark;
6129 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
6130
6131 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
6132
6133 // cast to ints.
6134 this.highWaterMark = Math.floor(this.highWaterMark);
6135
6136 // A linked list is used to store data chunks instead of an array because the
6137 // linked list can remove elements from the beginning faster than
6138 // array.shift()
6139 this.buffer = new BufferList();
6140 this.length = 0;
6141 this.pipes = null;
6142 this.pipesCount = 0;
6143 this.flowing = null;
6144 this.ended = false;
6145 this.endEmitted = false;
6146 this.reading = false;
6147
6148 // a flag to be able to tell if the event 'readable'/'data' is emitted
6149 // immediately, or on a later tick. We set this to true at first, because
6150 // any actions that shouldn't happen until "later" should generally also
6151 // not happen before the first read call.
6152 this.sync = true;
6153
6154 // whenever we return null, then we set a flag to say
6155 // that we're awaiting a 'readable' event emission.
6156 this.needReadable = false;
6157 this.emittedReadable = false;
6158 this.readableListening = false;
6159 this.resumeScheduled = false;
6160
6161 // has it been destroyed
6162 this.destroyed = false;
6163
6164 // Crypto is kind of old and crusty. Historically, its default string
6165 // encoding is 'binary' so we have to make this configurable.
6166 // Everything else in the universe uses 'utf8', though.
6167 this.defaultEncoding = options.defaultEncoding || 'utf8';
6168
6169 // the number of writers that are awaiting a drain event in .pipe()s
6170 this.awaitDrain = 0;
6171
6172 // if true, a maybeReadMore has been scheduled
6173 this.readingMore = false;
6174
6175 this.decoder = null;
6176 this.encoding = null;
6177 if (options.encoding) {
6178 if (!StringDecoder) StringDecoder = _dereq_(88).StringDecoder;
6179 this.decoder = new StringDecoder(options.encoding);
6180 this.encoding = options.encoding;
6181 }
6182}
6183
6184function Readable(options) {
6185 Duplex = Duplex || _dereq_(24);
6186
6187 if (!(this instanceof Readable)) return new Readable(options);
6188
6189 this._readableState = new ReadableState(options, this);
6190
6191 // legacy
6192 this.readable = true;
6193
6194 if (options) {
6195 if (typeof options.read === 'function') this._read = options.read;
6196
6197 if (typeof options.destroy === 'function') this._destroy = options.destroy;
6198 }
6199
6200 Stream.call(this);
6201}
6202
6203Object.defineProperty(Readable.prototype, 'destroyed', {
6204 get: function () {
6205 if (this._readableState === undefined) {
6206 return false;
6207 }
6208 return this._readableState.destroyed;
6209 },
6210 set: function (value) {
6211 // we ignore the value if the stream
6212 // has not been initialized yet
6213 if (!this._readableState) {
6214 return;
6215 }
6216
6217 // backward compatibility, the user is explicitly
6218 // managing destroyed
6219 this._readableState.destroyed = value;
6220 }
6221});
6222
6223Readable.prototype.destroy = destroyImpl.destroy;
6224Readable.prototype._undestroy = destroyImpl.undestroy;
6225Readable.prototype._destroy = function (err, cb) {
6226 this.push(null);
6227 cb(err);
6228};
6229
6230// Manually shove something into the read() buffer.
6231// This returns true if the highWaterMark has not been hit yet,
6232// similar to how Writable.write() returns true if you should
6233// write() some more.
6234Readable.prototype.push = function (chunk, encoding) {
6235 var state = this._readableState;
6236 var skipChunkCheck;
6237
6238 if (!state.objectMode) {
6239 if (typeof chunk === 'string') {
6240 encoding = encoding || state.defaultEncoding;
6241 if (encoding !== state.encoding) {
6242 chunk = Buffer.from(chunk, encoding);
6243 encoding = '';
6244 }
6245 skipChunkCheck = true;
6246 }
6247 } else {
6248 skipChunkCheck = true;
6249 }
6250
6251 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
6252};
6253
6254// Unshift should *always* be something directly out of read()
6255Readable.prototype.unshift = function (chunk) {
6256 return readableAddChunk(this, chunk, null, true, false);
6257};
6258
6259function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
6260 var state = stream._readableState;
6261 if (chunk === null) {
6262 state.reading = false;
6263 onEofChunk(stream, state);
6264 } else {
6265 var er;
6266 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
6267 if (er) {
6268 stream.emit('error', er);
6269 } else if (state.objectMode || chunk && chunk.length > 0) {
6270 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
6271 chunk = _uint8ArrayToBuffer(chunk);
6272 }
6273
6274 if (addToFront) {
6275 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
6276 } else if (state.ended) {
6277 stream.emit('error', new Error('stream.push() after EOF'));
6278 } else {
6279 state.reading = false;
6280 if (state.decoder && !encoding) {
6281 chunk = state.decoder.write(chunk);
6282 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
6283 } else {
6284 addChunk(stream, state, chunk, false);
6285 }
6286 }
6287 } else if (!addToFront) {
6288 state.reading = false;
6289 }
6290 }
6291
6292 return needMoreData(state);
6293}
6294
6295function addChunk(stream, state, chunk, addToFront) {
6296 if (state.flowing && state.length === 0 && !state.sync) {
6297 stream.emit('data', chunk);
6298 stream.read(0);
6299 } else {
6300 // update the buffer info.
6301 state.length += state.objectMode ? 1 : chunk.length;
6302 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
6303
6304 if (state.needReadable) emitReadable(stream);
6305 }
6306 maybeReadMore(stream, state);
6307}
6308
6309function chunkInvalid(state, chunk) {
6310 var er;
6311 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
6312 er = new TypeError('Invalid non-string/buffer chunk');
6313 }
6314 return er;
6315}
6316
6317// if it's past the high water mark, we can push in some more.
6318// Also, if we have no data yet, we can stand some
6319// more bytes. This is to work around cases where hwm=0,
6320// such as the repl. Also, if the push() triggered a
6321// readable event, and the user called read(largeNumber) such that
6322// needReadable was set, then we ought to push more, so that another
6323// 'readable' event will be triggered.
6324function needMoreData(state) {
6325 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
6326}
6327
6328Readable.prototype.isPaused = function () {
6329 return this._readableState.flowing === false;
6330};
6331
6332// backwards compatibility.
6333Readable.prototype.setEncoding = function (enc) {
6334 if (!StringDecoder) StringDecoder = _dereq_(88).StringDecoder;
6335 this._readableState.decoder = new StringDecoder(enc);
6336 this._readableState.encoding = enc;
6337 return this;
6338};
6339
6340// Don't raise the hwm > 8MB
6341var MAX_HWM = 0x800000;
6342function computeNewHighWaterMark(n) {
6343 if (n >= MAX_HWM) {
6344 n = MAX_HWM;
6345 } else {
6346 // Get the next highest power of 2 to prevent increasing hwm excessively in
6347 // tiny amounts
6348 n--;
6349 n |= n >>> 1;
6350 n |= n >>> 2;
6351 n |= n >>> 4;
6352 n |= n >>> 8;
6353 n |= n >>> 16;
6354 n++;
6355 }
6356 return n;
6357}
6358
6359// This function is designed to be inlinable, so please take care when making
6360// changes to the function body.
6361function howMuchToRead(n, state) {
6362 if (n <= 0 || state.length === 0 && state.ended) return 0;
6363 if (state.objectMode) return 1;
6364 if (n !== n) {
6365 // Only flow one buffer at a time
6366 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
6367 }
6368 // If we're asking for more than the current hwm, then raise the hwm.
6369 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
6370 if (n <= state.length) return n;
6371 // Don't have enough
6372 if (!state.ended) {
6373 state.needReadable = true;
6374 return 0;
6375 }
6376 return state.length;
6377}
6378
6379// you can override either this method, or the async _read(n) below.
6380Readable.prototype.read = function (n) {
6381 debug('read', n);
6382 n = parseInt(n, 10);
6383 var state = this._readableState;
6384 var nOrig = n;
6385
6386 if (n !== 0) state.emittedReadable = false;
6387
6388 // if we're doing read(0) to trigger a readable event, but we
6389 // already have a bunch of data in the buffer, then just trigger
6390 // the 'readable' event and move on.
6391 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
6392 debug('read: emitReadable', state.length, state.ended);
6393 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
6394 return null;
6395 }
6396
6397 n = howMuchToRead(n, state);
6398
6399 // if we've ended, and we're now clear, then finish it up.
6400 if (n === 0 && state.ended) {
6401 if (state.length === 0) endReadable(this);
6402 return null;
6403 }
6404
6405 // All the actual chunk generation logic needs to be
6406 // *below* the call to _read. The reason is that in certain
6407 // synthetic stream cases, such as passthrough streams, _read
6408 // may be a completely synchronous operation which may change
6409 // the state of the read buffer, providing enough data when
6410 // before there was *not* enough.
6411 //
6412 // So, the steps are:
6413 // 1. Figure out what the state of things will be after we do
6414 // a read from the buffer.
6415 //
6416 // 2. If that resulting state will trigger a _read, then call _read.
6417 // Note that this may be asynchronous, or synchronous. Yes, it is
6418 // deeply ugly to write APIs this way, but that still doesn't mean
6419 // that the Readable class should behave improperly, as streams are
6420 // designed to be sync/async agnostic.
6421 // Take note if the _read call is sync or async (ie, if the read call
6422 // has returned yet), so that we know whether or not it's safe to emit
6423 // 'readable' etc.
6424 //
6425 // 3. Actually pull the requested chunks out of the buffer and return.
6426
6427 // if we need a readable event, then we need to do some reading.
6428 var doRead = state.needReadable;
6429 debug('need readable', doRead);
6430
6431 // if we currently have less than the highWaterMark, then also read some
6432 if (state.length === 0 || state.length - n < state.highWaterMark) {
6433 doRead = true;
6434 debug('length less than watermark', doRead);
6435 }
6436
6437 // however, if we've ended, then there's no point, and if we're already
6438 // reading, then it's unnecessary.
6439 if (state.ended || state.reading) {
6440 doRead = false;
6441 debug('reading or ended', doRead);
6442 } else if (doRead) {
6443 debug('do read');
6444 state.reading = true;
6445 state.sync = true;
6446 // if the length is currently zero, then we *need* a readable event.
6447 if (state.length === 0) state.needReadable = true;
6448 // call internal read method
6449 this._read(state.highWaterMark);
6450 state.sync = false;
6451 // If _read pushed data synchronously, then `reading` will be false,
6452 // and we need to re-evaluate how much data we can return to the user.
6453 if (!state.reading) n = howMuchToRead(nOrig, state);
6454 }
6455
6456 var ret;
6457 if (n > 0) ret = fromList(n, state);else ret = null;
6458
6459 if (ret === null) {
6460 state.needReadable = true;
6461 n = 0;
6462 } else {
6463 state.length -= n;
6464 }
6465
6466 if (state.length === 0) {
6467 // If we have nothing in the buffer, then we want to know
6468 // as soon as we *do* get something into the buffer.
6469 if (!state.ended) state.needReadable = true;
6470
6471 // If we tried to read() past the EOF, then emit end on the next tick.
6472 if (nOrig !== n && state.ended) endReadable(this);
6473 }
6474
6475 if (ret !== null) this.emit('data', ret);
6476
6477 return ret;
6478};
6479
6480function onEofChunk(stream, state) {
6481 if (state.ended) return;
6482 if (state.decoder) {
6483 var chunk = state.decoder.end();
6484 if (chunk && chunk.length) {
6485 state.buffer.push(chunk);
6486 state.length += state.objectMode ? 1 : chunk.length;
6487 }
6488 }
6489 state.ended = true;
6490
6491 // emit 'readable' now to make sure it gets picked up.
6492 emitReadable(stream);
6493}
6494
6495// Don't emit readable right away in sync mode, because this can trigger
6496// another read() call => stack overflow. This way, it might trigger
6497// a nextTick recursion warning, but that's not so bad.
6498function emitReadable(stream) {
6499 var state = stream._readableState;
6500 state.needReadable = false;
6501 if (!state.emittedReadable) {
6502 debug('emitReadable', state.flowing);
6503 state.emittedReadable = true;
6504 if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
6505 }
6506}
6507
6508function emitReadable_(stream) {
6509 debug('emit readable');
6510 stream.emit('readable');
6511 flow(stream);
6512}
6513
6514// at this point, the user has presumably seen the 'readable' event,
6515// and called read() to consume some data. that may have triggered
6516// in turn another _read(n) call, in which case reading = true if
6517// it's in progress.
6518// However, if we're not ended, or reading, and the length < hwm,
6519// then go ahead and try to read some more preemptively.
6520function maybeReadMore(stream, state) {
6521 if (!state.readingMore) {
6522 state.readingMore = true;
6523 pna.nextTick(maybeReadMore_, stream, state);
6524 }
6525}
6526
6527function maybeReadMore_(stream, state) {
6528 var len = state.length;
6529 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
6530 debug('maybeReadMore read 0');
6531 stream.read(0);
6532 if (len === state.length)
6533 // didn't get any data, stop spinning.
6534 break;else len = state.length;
6535 }
6536 state.readingMore = false;
6537}
6538
6539// abstract method. to be overridden in specific implementation classes.
6540// call cb(er, data) where data is <= n in length.
6541// for virtual (non-string, non-buffer) streams, "length" is somewhat
6542// arbitrary, and perhaps not very meaningful.
6543Readable.prototype._read = function (n) {
6544 this.emit('error', new Error('_read() is not implemented'));
6545};
6546
6547Readable.prototype.pipe = function (dest, pipeOpts) {
6548 var src = this;
6549 var state = this._readableState;
6550
6551 switch (state.pipesCount) {
6552 case 0:
6553 state.pipes = dest;
6554 break;
6555 case 1:
6556 state.pipes = [state.pipes, dest];
6557 break;
6558 default:
6559 state.pipes.push(dest);
6560 break;
6561 }
6562 state.pipesCount += 1;
6563 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
6564
6565 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
6566
6567 var endFn = doEnd ? onend : unpipe;
6568 if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
6569
6570 dest.on('unpipe', onunpipe);
6571 function onunpipe(readable, unpipeInfo) {
6572 debug('onunpipe');
6573 if (readable === src) {
6574 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
6575 unpipeInfo.hasUnpiped = true;
6576 cleanup();
6577 }
6578 }
6579 }
6580
6581 function onend() {
6582 debug('onend');
6583 dest.end();
6584 }
6585
6586 // when the dest drains, it reduces the awaitDrain counter
6587 // on the source. This would be more elegant with a .once()
6588 // handler in flow(), but adding and removing repeatedly is
6589 // too slow.
6590 var ondrain = pipeOnDrain(src);
6591 dest.on('drain', ondrain);
6592
6593 var cleanedUp = false;
6594 function cleanup() {
6595 debug('cleanup');
6596 // cleanup event handlers once the pipe is broken
6597 dest.removeListener('close', onclose);
6598 dest.removeListener('finish', onfinish);
6599 dest.removeListener('drain', ondrain);
6600 dest.removeListener('error', onerror);
6601 dest.removeListener('unpipe', onunpipe);
6602 src.removeListener('end', onend);
6603 src.removeListener('end', unpipe);
6604 src.removeListener('data', ondata);
6605
6606 cleanedUp = true;
6607
6608 // if the reader is waiting for a drain event from this
6609 // specific writer, then it would cause it to never start
6610 // flowing again.
6611 // So, if this is awaiting a drain, then we just call it now.
6612 // If we don't know, then assume that we are waiting for one.
6613 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
6614 }
6615
6616 // If the user pushes more data while we're writing to dest then we'll end up
6617 // in ondata again. However, we only want to increase awaitDrain once because
6618 // dest will only emit one 'drain' event for the multiple writes.
6619 // => Introduce a guard on increasing awaitDrain.
6620 var increasedAwaitDrain = false;
6621 src.on('data', ondata);
6622 function ondata(chunk) {
6623 debug('ondata');
6624 increasedAwaitDrain = false;
6625 var ret = dest.write(chunk);
6626 if (false === ret && !increasedAwaitDrain) {
6627 // If the user unpiped during `dest.write()`, it is possible
6628 // to get stuck in a permanently paused state if that write
6629 // also returned false.
6630 // => Check whether `dest` is still a piping destination.
6631 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
6632 debug('false write response, pause', src._readableState.awaitDrain);
6633 src._readableState.awaitDrain++;
6634 increasedAwaitDrain = true;
6635 }
6636 src.pause();
6637 }
6638 }
6639
6640 // if the dest has an error, then stop piping into it.
6641 // however, don't suppress the throwing behavior for this.
6642 function onerror(er) {
6643 debug('onerror', er);
6644 unpipe();
6645 dest.removeListener('error', onerror);
6646 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
6647 }
6648
6649 // Make sure our error handler is attached before userland ones.
6650 prependListener(dest, 'error', onerror);
6651
6652 // Both close and finish should trigger unpipe, but only once.
6653 function onclose() {
6654 dest.removeListener('finish', onfinish);
6655 unpipe();
6656 }
6657 dest.once('close', onclose);
6658 function onfinish() {
6659 debug('onfinish');
6660 dest.removeListener('close', onclose);
6661 unpipe();
6662 }
6663 dest.once('finish', onfinish);
6664
6665 function unpipe() {
6666 debug('unpipe');
6667 src.unpipe(dest);
6668 }
6669
6670 // tell the dest that it's being piped to
6671 dest.emit('pipe', src);
6672
6673 // start the flow if it hasn't been started already.
6674 if (!state.flowing) {
6675 debug('pipe resume');
6676 src.resume();
6677 }
6678
6679 return dest;
6680};
6681
6682function pipeOnDrain(src) {
6683 return function () {
6684 var state = src._readableState;
6685 debug('pipeOnDrain', state.awaitDrain);
6686 if (state.awaitDrain) state.awaitDrain--;
6687 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
6688 state.flowing = true;
6689 flow(src);
6690 }
6691 };
6692}
6693
6694Readable.prototype.unpipe = function (dest) {
6695 var state = this._readableState;
6696 var unpipeInfo = { hasUnpiped: false };
6697
6698 // if we're not piping anywhere, then do nothing.
6699 if (state.pipesCount === 0) return this;
6700
6701 // just one destination. most common case.
6702 if (state.pipesCount === 1) {
6703 // passed in one, but it's not the right one.
6704 if (dest && dest !== state.pipes) return this;
6705
6706 if (!dest) dest = state.pipes;
6707
6708 // got a match.
6709 state.pipes = null;
6710 state.pipesCount = 0;
6711 state.flowing = false;
6712 if (dest) dest.emit('unpipe', this, unpipeInfo);
6713 return this;
6714 }
6715
6716 // slow case. multiple pipe destinations.
6717
6718 if (!dest) {
6719 // remove all.
6720 var dests = state.pipes;
6721 var len = state.pipesCount;
6722 state.pipes = null;
6723 state.pipesCount = 0;
6724 state.flowing = false;
6725
6726 for (var i = 0; i < len; i++) {
6727 dests[i].emit('unpipe', this, unpipeInfo);
6728 }return this;
6729 }
6730
6731 // try to find the right one.
6732 var index = indexOf(state.pipes, dest);
6733 if (index === -1) return this;
6734
6735 state.pipes.splice(index, 1);
6736 state.pipesCount -= 1;
6737 if (state.pipesCount === 1) state.pipes = state.pipes[0];
6738
6739 dest.emit('unpipe', this, unpipeInfo);
6740
6741 return this;
6742};
6743
6744// set up data events if they are asked for
6745// Ensure readable listeners eventually get something
6746Readable.prototype.on = function (ev, fn) {
6747 var res = Stream.prototype.on.call(this, ev, fn);
6748
6749 if (ev === 'data') {
6750 // Start flowing on next tick if stream isn't explicitly paused
6751 if (this._readableState.flowing !== false) this.resume();
6752 } else if (ev === 'readable') {
6753 var state = this._readableState;
6754 if (!state.endEmitted && !state.readableListening) {
6755 state.readableListening = state.needReadable = true;
6756 state.emittedReadable = false;
6757 if (!state.reading) {
6758 pna.nextTick(nReadingNextTick, this);
6759 } else if (state.length) {
6760 emitReadable(this);
6761 }
6762 }
6763 }
6764
6765 return res;
6766};
6767Readable.prototype.addListener = Readable.prototype.on;
6768
6769function nReadingNextTick(self) {
6770 debug('readable nexttick read 0');
6771 self.read(0);
6772}
6773
6774// pause() and resume() are remnants of the legacy readable stream API
6775// If the user uses them, then switch into old mode.
6776Readable.prototype.resume = function () {
6777 var state = this._readableState;
6778 if (!state.flowing) {
6779 debug('resume');
6780 state.flowing = true;
6781 resume(this, state);
6782 }
6783 return this;
6784};
6785
6786function resume(stream, state) {
6787 if (!state.resumeScheduled) {
6788 state.resumeScheduled = true;
6789 pna.nextTick(resume_, stream, state);
6790 }
6791}
6792
6793function resume_(stream, state) {
6794 if (!state.reading) {
6795 debug('resume read 0');
6796 stream.read(0);
6797 }
6798
6799 state.resumeScheduled = false;
6800 state.awaitDrain = 0;
6801 stream.emit('resume');
6802 flow(stream);
6803 if (state.flowing && !state.reading) stream.read(0);
6804}
6805
6806Readable.prototype.pause = function () {
6807 debug('call pause flowing=%j', this._readableState.flowing);
6808 if (false !== this._readableState.flowing) {
6809 debug('pause');
6810 this._readableState.flowing = false;
6811 this.emit('pause');
6812 }
6813 return this;
6814};
6815
6816function flow(stream) {
6817 var state = stream._readableState;
6818 debug('flow', state.flowing);
6819 while (state.flowing && stream.read() !== null) {}
6820}
6821
6822// wrap an old-style stream as the async data source.
6823// This is *not* part of the readable stream interface.
6824// It is an ugly unfortunate mess of history.
6825Readable.prototype.wrap = function (stream) {
6826 var _this = this;
6827
6828 var state = this._readableState;
6829 var paused = false;
6830
6831 stream.on('end', function () {
6832 debug('wrapped end');
6833 if (state.decoder && !state.ended) {
6834 var chunk = state.decoder.end();
6835 if (chunk && chunk.length) _this.push(chunk);
6836 }
6837
6838 _this.push(null);
6839 });
6840
6841 stream.on('data', function (chunk) {
6842 debug('wrapped data');
6843 if (state.decoder) chunk = state.decoder.write(chunk);
6844
6845 // don't skip over falsy values in objectMode
6846 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
6847
6848 var ret = _this.push(chunk);
6849 if (!ret) {
6850 paused = true;
6851 stream.pause();
6852 }
6853 });
6854
6855 // proxy all the other methods.
6856 // important when wrapping filters and duplexes.
6857 for (var i in stream) {
6858 if (this[i] === undefined && typeof stream[i] === 'function') {
6859 this[i] = function (method) {
6860 return function () {
6861 return stream[method].apply(stream, arguments);
6862 };
6863 }(i);
6864 }
6865 }
6866
6867 // proxy certain important events.
6868 for (var n = 0; n < kProxyEvents.length; n++) {
6869 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
6870 }
6871
6872 // when we try to consume some more bytes, simply unpause the
6873 // underlying stream.
6874 this._read = function (n) {
6875 debug('wrapped _read', n);
6876 if (paused) {
6877 paused = false;
6878 stream.resume();
6879 }
6880 };
6881
6882 return this;
6883};
6884
6885Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
6886 // making it explicit this property is not enumerable
6887 // because otherwise some prototype manipulation in
6888 // userland will fail
6889 enumerable: false,
6890 get: function () {
6891 return this._readableState.highWaterMark;
6892 }
6893});
6894
6895// exposed for testing purposes only.
6896Readable._fromList = fromList;
6897
6898// Pluck off n bytes from an array of buffers.
6899// Length is the combined lengths of all the buffers in the list.
6900// This function is designed to be inlinable, so please take care when making
6901// changes to the function body.
6902function fromList(n, state) {
6903 // nothing buffered
6904 if (state.length === 0) return null;
6905
6906 var ret;
6907 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
6908 // read it all, truncate the list
6909 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);
6910 state.buffer.clear();
6911 } else {
6912 // read part of list
6913 ret = fromListPartial(n, state.buffer, state.decoder);
6914 }
6915
6916 return ret;
6917}
6918
6919// Extracts only enough buffered data to satisfy the amount requested.
6920// This function is designed to be inlinable, so please take care when making
6921// changes to the function body.
6922function fromListPartial(n, list, hasStrings) {
6923 var ret;
6924 if (n < list.head.data.length) {
6925 // slice is the same for buffers and strings
6926 ret = list.head.data.slice(0, n);
6927 list.head.data = list.head.data.slice(n);
6928 } else if (n === list.head.data.length) {
6929 // first chunk is a perfect match
6930 ret = list.shift();
6931 } else {
6932 // result spans more than one buffer
6933 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
6934 }
6935 return ret;
6936}
6937
6938// Copies a specified amount of characters from the list of buffered data
6939// chunks.
6940// This function is designed to be inlinable, so please take care when making
6941// changes to the function body.
6942function copyFromBufferString(n, list) {
6943 var p = list.head;
6944 var c = 1;
6945 var ret = p.data;
6946 n -= ret.length;
6947 while (p = p.next) {
6948 var str = p.data;
6949 var nb = n > str.length ? str.length : n;
6950 if (nb === str.length) ret += str;else ret += str.slice(0, n);
6951 n -= nb;
6952 if (n === 0) {
6953 if (nb === str.length) {
6954 ++c;
6955 if (p.next) list.head = p.next;else list.head = list.tail = null;
6956 } else {
6957 list.head = p;
6958 p.data = str.slice(nb);
6959 }
6960 break;
6961 }
6962 ++c;
6963 }
6964 list.length -= c;
6965 return ret;
6966}
6967
6968// Copies a specified amount of bytes from the list of buffered data chunks.
6969// This function is designed to be inlinable, so please take care when making
6970// changes to the function body.
6971function copyFromBuffer(n, list) {
6972 var ret = Buffer.allocUnsafe(n);
6973 var p = list.head;
6974 var c = 1;
6975 p.data.copy(ret);
6976 n -= p.data.length;
6977 while (p = p.next) {
6978 var buf = p.data;
6979 var nb = n > buf.length ? buf.length : n;
6980 buf.copy(ret, ret.length - n, 0, nb);
6981 n -= nb;
6982 if (n === 0) {
6983 if (nb === buf.length) {
6984 ++c;
6985 if (p.next) list.head = p.next;else list.head = list.tail = null;
6986 } else {
6987 list.head = p;
6988 p.data = buf.slice(nb);
6989 }
6990 break;
6991 }
6992 ++c;
6993 }
6994 list.length -= c;
6995 return ret;
6996}
6997
6998function endReadable(stream) {
6999 var state = stream._readableState;
7000
7001 // If we get here before consuming all the bytes, then that is a
7002 // bug in node. Should never happen.
7003 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
7004
7005 if (!state.endEmitted) {
7006 state.ended = true;
7007 pna.nextTick(endReadableNT, state, stream);
7008 }
7009}
7010
7011function endReadableNT(state, stream) {
7012 // Check that we didn't get one last unshift.
7013 if (!state.endEmitted && state.length === 0) {
7014 state.endEmitted = true;
7015 stream.readable = false;
7016 stream.emit('end');
7017 }
7018}
7019
7020function indexOf(xs, x) {
7021 for (var i = 0, l = xs.length; i < l; i++) {
7022 if (xs[i] === x) return i;
7023 }
7024 return -1;
7025}
7026}).call(this,_dereq_(62),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
7027},{"10":10,"14":14,"18":18,"20":20,"24":24,"29":29,"30":30,"31":31,"61":61,"62":62,"7":7,"72":72,"88":88}],27:[function(_dereq_,module,exports){
7028// Copyright Joyent, Inc. and other Node contributors.
7029//
7030// Permission is hereby granted, free of charge, to any person obtaining a
7031// copy of this software and associated documentation files (the
7032// "Software"), to deal in the Software without restriction, including
7033// without limitation the rights to use, copy, modify, merge, publish,
7034// distribute, sublicense, and/or sell copies of the Software, and to permit
7035// persons to whom the Software is furnished to do so, subject to the
7036// following conditions:
7037//
7038// The above copyright notice and this permission notice shall be included
7039// in all copies or substantial portions of the Software.
7040//
7041// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7042// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7043// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7044// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7045// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7046// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7047// USE OR OTHER DEALINGS IN THE SOFTWARE.
7048
7049// a transform stream is a readable/writable stream where you do
7050// something with the data. Sometimes it's called a "filter",
7051// but that's not a great name for it, since that implies a thing where
7052// some bits pass through, and others are simply ignored. (That would
7053// be a valid example of a transform, of course.)
7054//
7055// While the output is causally related to the input, it's not a
7056// necessarily symmetric or synchronous transformation. For example,
7057// a zlib stream might take multiple plain-text writes(), and then
7058// emit a single compressed chunk some time in the future.
7059//
7060// Here's how this works:
7061//
7062// The Transform stream has all the aspects of the readable and writable
7063// stream classes. When you write(chunk), that calls _write(chunk,cb)
7064// internally, and returns false if there's a lot of pending writes
7065// buffered up. When you call read(), that calls _read(n) until
7066// there's enough pending readable data buffered up.
7067//
7068// In a transform stream, the written data is placed in a buffer. When
7069// _read(n) is called, it transforms the queued up data, calling the
7070// buffered _write cb's as it consumes chunks. If consuming a single
7071// written chunk would result in multiple output chunks, then the first
7072// outputted bit calls the readcb, and subsequent chunks just go into
7073// the read buffer, and will cause it to emit 'readable' if necessary.
7074//
7075// This way, back-pressure is actually determined by the reading side,
7076// since _read has to be called to start processing a new chunk. However,
7077// a pathological inflate type of transform can cause excessive buffering
7078// here. For example, imagine a stream where every byte of input is
7079// interpreted as an integer from 0-255, and then results in that many
7080// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
7081// 1kb of data being output. In this case, you could write a very small
7082// amount of input, and end up with a very large amount of output. In
7083// such a pathological inflating mechanism, there'd be no way to tell
7084// the system to stop doing the transform. A single 4MB write could
7085// cause the system to run out of memory.
7086//
7087// However, even in such a pathological case, only a single written chunk
7088// would be consumed, and then the rest would wait (un-transformed) until
7089// the results of the previous transformed chunk were consumed.
7090
7091'use strict';
7092
7093module.exports = Transform;
7094
7095var Duplex = _dereq_(24);
7096
7097/*<replacement>*/
7098var util = _dereq_(10);
7099util.inherits = _dereq_(18);
7100/*</replacement>*/
7101
7102util.inherits(Transform, Duplex);
7103
7104function afterTransform(er, data) {
7105 var ts = this._transformState;
7106 ts.transforming = false;
7107
7108 var cb = ts.writecb;
7109
7110 if (!cb) {
7111 return this.emit('error', new Error('write callback called multiple times'));
7112 }
7113
7114 ts.writechunk = null;
7115 ts.writecb = null;
7116
7117 if (data != null) // single equals check for both `null` and `undefined`
7118 this.push(data);
7119
7120 cb(er);
7121
7122 var rs = this._readableState;
7123 rs.reading = false;
7124 if (rs.needReadable || rs.length < rs.highWaterMark) {
7125 this._read(rs.highWaterMark);
7126 }
7127}
7128
7129function Transform(options) {
7130 if (!(this instanceof Transform)) return new Transform(options);
7131
7132 Duplex.call(this, options);
7133
7134 this._transformState = {
7135 afterTransform: afterTransform.bind(this),
7136 needTransform: false,
7137 transforming: false,
7138 writecb: null,
7139 writechunk: null,
7140 writeencoding: null
7141 };
7142
7143 // start out asking for a readable event once data is transformed.
7144 this._readableState.needReadable = true;
7145
7146 // we have implemented the _read method, and done the other things
7147 // that Readable wants before the first _read call, so unset the
7148 // sync guard flag.
7149 this._readableState.sync = false;
7150
7151 if (options) {
7152 if (typeof options.transform === 'function') this._transform = options.transform;
7153
7154 if (typeof options.flush === 'function') this._flush = options.flush;
7155 }
7156
7157 // When the writable side finishes, then flush out anything remaining.
7158 this.on('prefinish', prefinish);
7159}
7160
7161function prefinish() {
7162 var _this = this;
7163
7164 if (typeof this._flush === 'function') {
7165 this._flush(function (er, data) {
7166 done(_this, er, data);
7167 });
7168 } else {
7169 done(this, null, null);
7170 }
7171}
7172
7173Transform.prototype.push = function (chunk, encoding) {
7174 this._transformState.needTransform = false;
7175 return Duplex.prototype.push.call(this, chunk, encoding);
7176};
7177
7178// This is the part where you do stuff!
7179// override this function in implementation classes.
7180// 'chunk' is an input chunk.
7181//
7182// Call `push(newChunk)` to pass along transformed output
7183// to the readable side. You may call 'push' zero or more times.
7184//
7185// Call `cb(err)` when you are done with this chunk. If you pass
7186// an error, then that'll put the hurt on the whole operation. If you
7187// never call cb(), then you'll never get another chunk.
7188Transform.prototype._transform = function (chunk, encoding, cb) {
7189 throw new Error('_transform() is not implemented');
7190};
7191
7192Transform.prototype._write = function (chunk, encoding, cb) {
7193 var ts = this._transformState;
7194 ts.writecb = cb;
7195 ts.writechunk = chunk;
7196 ts.writeencoding = encoding;
7197 if (!ts.transforming) {
7198 var rs = this._readableState;
7199 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
7200 }
7201};
7202
7203// Doesn't matter what the args are here.
7204// _transform does all the work.
7205// That we got here means that the readable side wants more data.
7206Transform.prototype._read = function (n) {
7207 var ts = this._transformState;
7208
7209 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
7210 ts.transforming = true;
7211 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
7212 } else {
7213 // mark that we need a transform, so that any data that comes in
7214 // will get processed, now that we've asked for it.
7215 ts.needTransform = true;
7216 }
7217};
7218
7219Transform.prototype._destroy = function (err, cb) {
7220 var _this2 = this;
7221
7222 Duplex.prototype._destroy.call(this, err, function (err2) {
7223 cb(err2);
7224 _this2.emit('close');
7225 });
7226};
7227
7228function done(stream, er, data) {
7229 if (er) return stream.emit('error', er);
7230
7231 if (data != null) // single equals check for both `null` and `undefined`
7232 stream.push(data);
7233
7234 // if there's nothing in the write buffer, then that means
7235 // that nothing more will ever be provided
7236 if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
7237
7238 if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
7239
7240 return stream.push(null);
7241}
7242},{"10":10,"18":18,"24":24}],28:[function(_dereq_,module,exports){
7243(function (process,global,setImmediate){
7244// Copyright Joyent, Inc. and other Node contributors.
7245//
7246// Permission is hereby granted, free of charge, to any person obtaining a
7247// copy of this software and associated documentation files (the
7248// "Software"), to deal in the Software without restriction, including
7249// without limitation the rights to use, copy, modify, merge, publish,
7250// distribute, sublicense, and/or sell copies of the Software, and to permit
7251// persons to whom the Software is furnished to do so, subject to the
7252// following conditions:
7253//
7254// The above copyright notice and this permission notice shall be included
7255// in all copies or substantial portions of the Software.
7256//
7257// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7258// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7259// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7260// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7261// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7262// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7263// USE OR OTHER DEALINGS IN THE SOFTWARE.
7264
7265// A bit simpler than readable streams.
7266// Implement an async ._write(chunk, encoding, cb), and it'll handle all
7267// the drain event emission and buffering.
7268
7269'use strict';
7270
7271/*<replacement>*/
7272
7273var pna = _dereq_(61);
7274/*</replacement>*/
7275
7276module.exports = Writable;
7277
7278/* <replacement> */
7279function WriteReq(chunk, encoding, cb) {
7280 this.chunk = chunk;
7281 this.encoding = encoding;
7282 this.callback = cb;
7283 this.next = null;
7284}
7285
7286// It seems a linked list but it is not
7287// there will be only 2 of these for each stream
7288function CorkedRequest(state) {
7289 var _this = this;
7290
7291 this.next = null;
7292 this.entry = null;
7293 this.finish = function () {
7294 onCorkedFinish(_this, state);
7295 };
7296}
7297/* </replacement> */
7298
7299/*<replacement>*/
7300var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
7301/*</replacement>*/
7302
7303/*<replacement>*/
7304var Duplex;
7305/*</replacement>*/
7306
7307Writable.WritableState = WritableState;
7308
7309/*<replacement>*/
7310var util = _dereq_(10);
7311util.inherits = _dereq_(18);
7312/*</replacement>*/
7313
7314/*<replacement>*/
7315var internalUtil = {
7316 deprecate: _dereq_(102)
7317};
7318/*</replacement>*/
7319
7320/*<replacement>*/
7321var Stream = _dereq_(31);
7322/*</replacement>*/
7323
7324/*<replacement>*/
7325
7326var Buffer = _dereq_(72).Buffer;
7327var OurUint8Array = global.Uint8Array || function () {};
7328function _uint8ArrayToBuffer(chunk) {
7329 return Buffer.from(chunk);
7330}
7331function _isUint8Array(obj) {
7332 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
7333}
7334
7335/*</replacement>*/
7336
7337var destroyImpl = _dereq_(30);
7338
7339util.inherits(Writable, Stream);
7340
7341function nop() {}
7342
7343function WritableState(options, stream) {
7344 Duplex = Duplex || _dereq_(24);
7345
7346 options = options || {};
7347
7348 // Duplex streams are both readable and writable, but share
7349 // the same options object.
7350 // However, some cases require setting options to different
7351 // values for the readable and the writable sides of the duplex stream.
7352 // These options can be provided separately as readableXXX and writableXXX.
7353 var isDuplex = stream instanceof Duplex;
7354
7355 // object stream flag to indicate whether or not this stream
7356 // contains buffers or objects.
7357 this.objectMode = !!options.objectMode;
7358
7359 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
7360
7361 // the point at which write() starts returning false
7362 // Note: 0 is a valid value, means that we always return false if
7363 // the entire buffer is not flushed immediately on write()
7364 var hwm = options.highWaterMark;
7365 var writableHwm = options.writableHighWaterMark;
7366 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
7367
7368 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
7369
7370 // cast to ints.
7371 this.highWaterMark = Math.floor(this.highWaterMark);
7372
7373 // if _final has been called
7374 this.finalCalled = false;
7375
7376 // drain event flag.
7377 this.needDrain = false;
7378 // at the start of calling end()
7379 this.ending = false;
7380 // when end() has been called, and returned
7381 this.ended = false;
7382 // when 'finish' is emitted
7383 this.finished = false;
7384
7385 // has it been destroyed
7386 this.destroyed = false;
7387
7388 // should we decode strings into buffers before passing to _write?
7389 // this is here so that some node-core streams can optimize string
7390 // handling at a lower level.
7391 var noDecode = options.decodeStrings === false;
7392 this.decodeStrings = !noDecode;
7393
7394 // Crypto is kind of old and crusty. Historically, its default string
7395 // encoding is 'binary' so we have to make this configurable.
7396 // Everything else in the universe uses 'utf8', though.
7397 this.defaultEncoding = options.defaultEncoding || 'utf8';
7398
7399 // not an actual buffer we keep track of, but a measurement
7400 // of how much we're waiting to get pushed to some underlying
7401 // socket or file.
7402 this.length = 0;
7403
7404 // a flag to see when we're in the middle of a write.
7405 this.writing = false;
7406
7407 // when true all writes will be buffered until .uncork() call
7408 this.corked = 0;
7409
7410 // a flag to be able to tell if the onwrite cb is called immediately,
7411 // or on a later tick. We set this to true at first, because any
7412 // actions that shouldn't happen until "later" should generally also
7413 // not happen before the first write call.
7414 this.sync = true;
7415
7416 // a flag to know if we're processing previously buffered items, which
7417 // may call the _write() callback in the same tick, so that we don't
7418 // end up in an overlapped onwrite situation.
7419 this.bufferProcessing = false;
7420
7421 // the callback that's passed to _write(chunk,cb)
7422 this.onwrite = function (er) {
7423 onwrite(stream, er);
7424 };
7425
7426 // the callback that the user supplies to write(chunk,encoding,cb)
7427 this.writecb = null;
7428
7429 // the amount that is being written when _write is called.
7430 this.writelen = 0;
7431
7432 this.bufferedRequest = null;
7433 this.lastBufferedRequest = null;
7434
7435 // number of pending user-supplied write callbacks
7436 // this must be 0 before 'finish' can be emitted
7437 this.pendingcb = 0;
7438
7439 // emit prefinish if the only thing we're waiting for is _write cbs
7440 // This is relevant for synchronous Transform streams
7441 this.prefinished = false;
7442
7443 // True if the error was already emitted and should not be thrown again
7444 this.errorEmitted = false;
7445
7446 // count buffered requests
7447 this.bufferedRequestCount = 0;
7448
7449 // allocate the first CorkedRequest, there is always
7450 // one allocated and free to use, and we maintain at most two
7451 this.corkedRequestsFree = new CorkedRequest(this);
7452}
7453
7454WritableState.prototype.getBuffer = function getBuffer() {
7455 var current = this.bufferedRequest;
7456 var out = [];
7457 while (current) {
7458 out.push(current);
7459 current = current.next;
7460 }
7461 return out;
7462};
7463
7464(function () {
7465 try {
7466 Object.defineProperty(WritableState.prototype, 'buffer', {
7467 get: internalUtil.deprecate(function () {
7468 return this.getBuffer();
7469 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
7470 });
7471 } catch (_) {}
7472})();
7473
7474// Test _writableState for inheritance to account for Duplex streams,
7475// whose prototype chain only points to Readable.
7476var realHasInstance;
7477if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
7478 realHasInstance = Function.prototype[Symbol.hasInstance];
7479 Object.defineProperty(Writable, Symbol.hasInstance, {
7480 value: function (object) {
7481 if (realHasInstance.call(this, object)) return true;
7482 if (this !== Writable) return false;
7483
7484 return object && object._writableState instanceof WritableState;
7485 }
7486 });
7487} else {
7488 realHasInstance = function (object) {
7489 return object instanceof this;
7490 };
7491}
7492
7493function Writable(options) {
7494 Duplex = Duplex || _dereq_(24);
7495
7496 // Writable ctor is applied to Duplexes, too.
7497 // `realHasInstance` is necessary because using plain `instanceof`
7498 // would return false, as no `_writableState` property is attached.
7499
7500 // Trying to use the custom `instanceof` for Writable here will also break the
7501 // Node.js LazyTransform implementation, which has a non-trivial getter for
7502 // `_writableState` that would lead to infinite recursion.
7503 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
7504 return new Writable(options);
7505 }
7506
7507 this._writableState = new WritableState(options, this);
7508
7509 // legacy.
7510 this.writable = true;
7511
7512 if (options) {
7513 if (typeof options.write === 'function') this._write = options.write;
7514
7515 if (typeof options.writev === 'function') this._writev = options.writev;
7516
7517 if (typeof options.destroy === 'function') this._destroy = options.destroy;
7518
7519 if (typeof options.final === 'function') this._final = options.final;
7520 }
7521
7522 Stream.call(this);
7523}
7524
7525// Otherwise people can pipe Writable streams, which is just wrong.
7526Writable.prototype.pipe = function () {
7527 this.emit('error', new Error('Cannot pipe, not readable'));
7528};
7529
7530function writeAfterEnd(stream, cb) {
7531 var er = new Error('write after end');
7532 // TODO: defer error events consistently everywhere, not just the cb
7533 stream.emit('error', er);
7534 pna.nextTick(cb, er);
7535}
7536
7537// Checks that a user-supplied chunk is valid, especially for the particular
7538// mode the stream is in. Currently this means that `null` is never accepted
7539// and undefined/non-string values are only allowed in object mode.
7540function validChunk(stream, state, chunk, cb) {
7541 var valid = true;
7542 var er = false;
7543
7544 if (chunk === null) {
7545 er = new TypeError('May not write null values to stream');
7546 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
7547 er = new TypeError('Invalid non-string/buffer chunk');
7548 }
7549 if (er) {
7550 stream.emit('error', er);
7551 pna.nextTick(cb, er);
7552 valid = false;
7553 }
7554 return valid;
7555}
7556
7557Writable.prototype.write = function (chunk, encoding, cb) {
7558 var state = this._writableState;
7559 var ret = false;
7560 var isBuf = !state.objectMode && _isUint8Array(chunk);
7561
7562 if (isBuf && !Buffer.isBuffer(chunk)) {
7563 chunk = _uint8ArrayToBuffer(chunk);
7564 }
7565
7566 if (typeof encoding === 'function') {
7567 cb = encoding;
7568 encoding = null;
7569 }
7570
7571 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
7572
7573 if (typeof cb !== 'function') cb = nop;
7574
7575 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
7576 state.pendingcb++;
7577 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
7578 }
7579
7580 return ret;
7581};
7582
7583Writable.prototype.cork = function () {
7584 var state = this._writableState;
7585
7586 state.corked++;
7587};
7588
7589Writable.prototype.uncork = function () {
7590 var state = this._writableState;
7591
7592 if (state.corked) {
7593 state.corked--;
7594
7595 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
7596 }
7597};
7598
7599Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
7600 // node::ParseEncoding() requires lower case.
7601 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
7602 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);
7603 this._writableState.defaultEncoding = encoding;
7604 return this;
7605};
7606
7607function decodeChunk(state, chunk, encoding) {
7608 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
7609 chunk = Buffer.from(chunk, encoding);
7610 }
7611 return chunk;
7612}
7613
7614Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
7615 // making it explicit this property is not enumerable
7616 // because otherwise some prototype manipulation in
7617 // userland will fail
7618 enumerable: false,
7619 get: function () {
7620 return this._writableState.highWaterMark;
7621 }
7622});
7623
7624// if we're already writing something, then just put this
7625// in the queue, and wait our turn. Otherwise, call _write
7626// If we return false, then we need a drain event, so set that flag.
7627function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
7628 if (!isBuf) {
7629 var newChunk = decodeChunk(state, chunk, encoding);
7630 if (chunk !== newChunk) {
7631 isBuf = true;
7632 encoding = 'buffer';
7633 chunk = newChunk;
7634 }
7635 }
7636 var len = state.objectMode ? 1 : chunk.length;
7637
7638 state.length += len;
7639
7640 var ret = state.length < state.highWaterMark;
7641 // we must ensure that previous needDrain will not be reset to false.
7642 if (!ret) state.needDrain = true;
7643
7644 if (state.writing || state.corked) {
7645 var last = state.lastBufferedRequest;
7646 state.lastBufferedRequest = {
7647 chunk: chunk,
7648 encoding: encoding,
7649 isBuf: isBuf,
7650 callback: cb,
7651 next: null
7652 };
7653 if (last) {
7654 last.next = state.lastBufferedRequest;
7655 } else {
7656 state.bufferedRequest = state.lastBufferedRequest;
7657 }
7658 state.bufferedRequestCount += 1;
7659 } else {
7660 doWrite(stream, state, false, len, chunk, encoding, cb);
7661 }
7662
7663 return ret;
7664}
7665
7666function doWrite(stream, state, writev, len, chunk, encoding, cb) {
7667 state.writelen = len;
7668 state.writecb = cb;
7669 state.writing = true;
7670 state.sync = true;
7671 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
7672 state.sync = false;
7673}
7674
7675function onwriteError(stream, state, sync, er, cb) {
7676 --state.pendingcb;
7677
7678 if (sync) {
7679 // defer the callback if we are being called synchronously
7680 // to avoid piling up things on the stack
7681 pna.nextTick(cb, er);
7682 // this can emit finish, and it will always happen
7683 // after error
7684 pna.nextTick(finishMaybe, stream, state);
7685 stream._writableState.errorEmitted = true;
7686 stream.emit('error', er);
7687 } else {
7688 // the caller expect this to happen before if
7689 // it is async
7690 cb(er);
7691 stream._writableState.errorEmitted = true;
7692 stream.emit('error', er);
7693 // this can emit finish, but finish must
7694 // always follow error
7695 finishMaybe(stream, state);
7696 }
7697}
7698
7699function onwriteStateUpdate(state) {
7700 state.writing = false;
7701 state.writecb = null;
7702 state.length -= state.writelen;
7703 state.writelen = 0;
7704}
7705
7706function onwrite(stream, er) {
7707 var state = stream._writableState;
7708 var sync = state.sync;
7709 var cb = state.writecb;
7710
7711 onwriteStateUpdate(state);
7712
7713 if (er) onwriteError(stream, state, sync, er, cb);else {
7714 // Check if we're actually ready to finish, but don't emit yet
7715 var finished = needFinish(state);
7716
7717 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
7718 clearBuffer(stream, state);
7719 }
7720
7721 if (sync) {
7722 /*<replacement>*/
7723 asyncWrite(afterWrite, stream, state, finished, cb);
7724 /*</replacement>*/
7725 } else {
7726 afterWrite(stream, state, finished, cb);
7727 }
7728 }
7729}
7730
7731function afterWrite(stream, state, finished, cb) {
7732 if (!finished) onwriteDrain(stream, state);
7733 state.pendingcb--;
7734 cb();
7735 finishMaybe(stream, state);
7736}
7737
7738// Must force callback to be called on nextTick, so that we don't
7739// emit 'drain' before the write() consumer gets the 'false' return
7740// value, and has a chance to attach a 'drain' listener.
7741function onwriteDrain(stream, state) {
7742 if (state.length === 0 && state.needDrain) {
7743 state.needDrain = false;
7744 stream.emit('drain');
7745 }
7746}
7747
7748// if there's something in the buffer waiting, then process it
7749function clearBuffer(stream, state) {
7750 state.bufferProcessing = true;
7751 var entry = state.bufferedRequest;
7752
7753 if (stream._writev && entry && entry.next) {
7754 // Fast case, write everything using _writev()
7755 var l = state.bufferedRequestCount;
7756 var buffer = new Array(l);
7757 var holder = state.corkedRequestsFree;
7758 holder.entry = entry;
7759
7760 var count = 0;
7761 var allBuffers = true;
7762 while (entry) {
7763 buffer[count] = entry;
7764 if (!entry.isBuf) allBuffers = false;
7765 entry = entry.next;
7766 count += 1;
7767 }
7768 buffer.allBuffers = allBuffers;
7769
7770 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
7771
7772 // doWrite is almost always async, defer these to save a bit of time
7773 // as the hot path ends with doWrite
7774 state.pendingcb++;
7775 state.lastBufferedRequest = null;
7776 if (holder.next) {
7777 state.corkedRequestsFree = holder.next;
7778 holder.next = null;
7779 } else {
7780 state.corkedRequestsFree = new CorkedRequest(state);
7781 }
7782 state.bufferedRequestCount = 0;
7783 } else {
7784 // Slow case, write chunks one-by-one
7785 while (entry) {
7786 var chunk = entry.chunk;
7787 var encoding = entry.encoding;
7788 var cb = entry.callback;
7789 var len = state.objectMode ? 1 : chunk.length;
7790
7791 doWrite(stream, state, false, len, chunk, encoding, cb);
7792 entry = entry.next;
7793 state.bufferedRequestCount--;
7794 // if we didn't call the onwrite immediately, then
7795 // it means that we need to wait until it does.
7796 // also, that means that the chunk and cb are currently
7797 // being processed, so move the buffer counter past them.
7798 if (state.writing) {
7799 break;
7800 }
7801 }
7802
7803 if (entry === null) state.lastBufferedRequest = null;
7804 }
7805
7806 state.bufferedRequest = entry;
7807 state.bufferProcessing = false;
7808}
7809
7810Writable.prototype._write = function (chunk, encoding, cb) {
7811 cb(new Error('_write() is not implemented'));
7812};
7813
7814Writable.prototype._writev = null;
7815
7816Writable.prototype.end = function (chunk, encoding, cb) {
7817 var state = this._writableState;
7818
7819 if (typeof chunk === 'function') {
7820 cb = chunk;
7821 chunk = null;
7822 encoding = null;
7823 } else if (typeof encoding === 'function') {
7824 cb = encoding;
7825 encoding = null;
7826 }
7827
7828 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
7829
7830 // .end() fully uncorks
7831 if (state.corked) {
7832 state.corked = 1;
7833 this.uncork();
7834 }
7835
7836 // ignore unnecessary end() calls.
7837 if (!state.ending && !state.finished) endWritable(this, state, cb);
7838};
7839
7840function needFinish(state) {
7841 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
7842}
7843function callFinal(stream, state) {
7844 stream._final(function (err) {
7845 state.pendingcb--;
7846 if (err) {
7847 stream.emit('error', err);
7848 }
7849 state.prefinished = true;
7850 stream.emit('prefinish');
7851 finishMaybe(stream, state);
7852 });
7853}
7854function prefinish(stream, state) {
7855 if (!state.prefinished && !state.finalCalled) {
7856 if (typeof stream._final === 'function') {
7857 state.pendingcb++;
7858 state.finalCalled = true;
7859 pna.nextTick(callFinal, stream, state);
7860 } else {
7861 state.prefinished = true;
7862 stream.emit('prefinish');
7863 }
7864 }
7865}
7866
7867function finishMaybe(stream, state) {
7868 var need = needFinish(state);
7869 if (need) {
7870 prefinish(stream, state);
7871 if (state.pendingcb === 0) {
7872 state.finished = true;
7873 stream.emit('finish');
7874 }
7875 }
7876 return need;
7877}
7878
7879function endWritable(stream, state, cb) {
7880 state.ending = true;
7881 finishMaybe(stream, state);
7882 if (cb) {
7883 if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
7884 }
7885 state.ended = true;
7886 stream.writable = false;
7887}
7888
7889function onCorkedFinish(corkReq, state, err) {
7890 var entry = corkReq.entry;
7891 corkReq.entry = null;
7892 while (entry) {
7893 var cb = entry.callback;
7894 state.pendingcb--;
7895 cb(err);
7896 entry = entry.next;
7897 }
7898 if (state.corkedRequestsFree) {
7899 state.corkedRequestsFree.next = corkReq;
7900 } else {
7901 state.corkedRequestsFree = corkReq;
7902 }
7903}
7904
7905Object.defineProperty(Writable.prototype, 'destroyed', {
7906 get: function () {
7907 if (this._writableState === undefined) {
7908 return false;
7909 }
7910 return this._writableState.destroyed;
7911 },
7912 set: function (value) {
7913 // we ignore the value if the stream
7914 // has not been initialized yet
7915 if (!this._writableState) {
7916 return;
7917 }
7918
7919 // backward compatibility, the user is explicitly
7920 // managing destroyed
7921 this._writableState.destroyed = value;
7922 }
7923});
7924
7925Writable.prototype.destroy = destroyImpl.destroy;
7926Writable.prototype._undestroy = destroyImpl.undestroy;
7927Writable.prototype._destroy = function (err, cb) {
7928 this.end();
7929 cb(err);
7930};
7931}).call(this,_dereq_(62),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_(101).setImmediate)
7932},{"10":10,"101":101,"102":102,"18":18,"24":24,"30":30,"31":31,"61":61,"62":62,"72":72}],29:[function(_dereq_,module,exports){
7933'use strict';
7934
7935function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
7936
7937var Buffer = _dereq_(72).Buffer;
7938var util = _dereq_(7);
7939
7940function copyBuffer(src, target, offset) {
7941 src.copy(target, offset);
7942}
7943
7944module.exports = function () {
7945 function BufferList() {
7946 _classCallCheck(this, BufferList);
7947
7948 this.head = null;
7949 this.tail = null;
7950 this.length = 0;
7951 }
7952
7953 BufferList.prototype.push = function push(v) {
7954 var entry = { data: v, next: null };
7955 if (this.length > 0) this.tail.next = entry;else this.head = entry;
7956 this.tail = entry;
7957 ++this.length;
7958 };
7959
7960 BufferList.prototype.unshift = function unshift(v) {
7961 var entry = { data: v, next: this.head };
7962 if (this.length === 0) this.tail = entry;
7963 this.head = entry;
7964 ++this.length;
7965 };
7966
7967 BufferList.prototype.shift = function shift() {
7968 if (this.length === 0) return;
7969 var ret = this.head.data;
7970 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
7971 --this.length;
7972 return ret;
7973 };
7974
7975 BufferList.prototype.clear = function clear() {
7976 this.head = this.tail = null;
7977 this.length = 0;
7978 };
7979
7980 BufferList.prototype.join = function join(s) {
7981 if (this.length === 0) return '';
7982 var p = this.head;
7983 var ret = '' + p.data;
7984 while (p = p.next) {
7985 ret += s + p.data;
7986 }return ret;
7987 };
7988
7989 BufferList.prototype.concat = function concat(n) {
7990 if (this.length === 0) return Buffer.alloc(0);
7991 if (this.length === 1) return this.head.data;
7992 var ret = Buffer.allocUnsafe(n >>> 0);
7993 var p = this.head;
7994 var i = 0;
7995 while (p) {
7996 copyBuffer(p.data, ret, i);
7997 i += p.data.length;
7998 p = p.next;
7999 }
8000 return ret;
8001 };
8002
8003 return BufferList;
8004}();
8005
8006if (util && util.inspect && util.inspect.custom) {
8007 module.exports.prototype[util.inspect.custom] = function () {
8008 var obj = util.inspect({ length: this.length });
8009 return this.constructor.name + ' ' + obj;
8010 };
8011}
8012},{"7":7,"72":72}],30:[function(_dereq_,module,exports){
8013'use strict';
8014
8015/*<replacement>*/
8016
8017var pna = _dereq_(61);
8018/*</replacement>*/
8019
8020// undocumented cb() API, needed for core, not for public API
8021function destroy(err, cb) {
8022 var _this = this;
8023
8024 var readableDestroyed = this._readableState && this._readableState.destroyed;
8025 var writableDestroyed = this._writableState && this._writableState.destroyed;
8026
8027 if (readableDestroyed || writableDestroyed) {
8028 if (cb) {
8029 cb(err);
8030 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
8031 pna.nextTick(emitErrorNT, this, err);
8032 }
8033 return this;
8034 }
8035
8036 // we set destroyed to true before firing error callbacks in order
8037 // to make it re-entrance safe in case destroy() is called within callbacks
8038
8039 if (this._readableState) {
8040 this._readableState.destroyed = true;
8041 }
8042
8043 // if this is a duplex stream mark the writable part as destroyed as well
8044 if (this._writableState) {
8045 this._writableState.destroyed = true;
8046 }
8047
8048 this._destroy(err || null, function (err) {
8049 if (!cb && err) {
8050 pna.nextTick(emitErrorNT, _this, err);
8051 if (_this._writableState) {
8052 _this._writableState.errorEmitted = true;
8053 }
8054 } else if (cb) {
8055 cb(err);
8056 }
8057 });
8058
8059 return this;
8060}
8061
8062function undestroy() {
8063 if (this._readableState) {
8064 this._readableState.destroyed = false;
8065 this._readableState.reading = false;
8066 this._readableState.ended = false;
8067 this._readableState.endEmitted = false;
8068 }
8069
8070 if (this._writableState) {
8071 this._writableState.destroyed = false;
8072 this._writableState.ended = false;
8073 this._writableState.ending = false;
8074 this._writableState.finished = false;
8075 this._writableState.errorEmitted = false;
8076 }
8077}
8078
8079function emitErrorNT(self, err) {
8080 self.emit('error', err);
8081}
8082
8083module.exports = {
8084 destroy: destroy,
8085 undestroy: undestroy
8086};
8087},{"61":61}],31:[function(_dereq_,module,exports){
8088module.exports = _dereq_(14).EventEmitter;
8089
8090},{"14":14}],32:[function(_dereq_,module,exports){
8091exports = module.exports = _dereq_(26);
8092exports.Stream = exports;
8093exports.Readable = exports;
8094exports.Writable = _dereq_(28);
8095exports.Duplex = _dereq_(24);
8096exports.Transform = _dereq_(27);
8097exports.PassThrough = _dereq_(25);
8098
8099},{"24":24,"25":25,"26":26,"27":27,"28":28}],33:[function(_dereq_,module,exports){
8100module.exports = extend
8101
8102var hasOwnProperty = Object.prototype.hasOwnProperty;
8103
8104function extend() {
8105 var target = {}
8106
8107 for (var i = 0; i < arguments.length; i++) {
8108 var source = arguments[i]
8109
8110 for (var key in source) {
8111 if (hasOwnProperty.call(source, key)) {
8112 target[key] = source[key]
8113 }
8114 }
8115 }
8116
8117 return target
8118}
8119
8120},{}],34:[function(_dereq_,module,exports){
8121/* Copyright (c) 2012-2018 LevelUP contributors
8122 * See list at <https://github.com/level/levelup#contributing>
8123 * MIT License
8124 * <https://github.com/level/levelup/blob/master/LICENSE.md>
8125 */
8126
8127var WriteError = _dereq_(43).WriteError
8128var promisify = _dereq_(36)
8129
8130function Batch (levelup) {
8131 this._levelup = levelup
8132 this.batch = levelup.db.batch()
8133 this.ops = []
8134 this.length = 0
8135}
8136
8137Batch.prototype.put = function (key, value) {
8138 try {
8139 this.batch.put(key, value)
8140 } catch (e) {
8141 throw new WriteError(e)
8142 }
8143
8144 this.ops.push({ type: 'put', key: key, value: value })
8145 this.length++
8146
8147 return this
8148}
8149
8150Batch.prototype.del = function (key) {
8151 try {
8152 this.batch.del(key)
8153 } catch (err) {
8154 throw new WriteError(err)
8155 }
8156
8157 this.ops.push({ type: 'del', key: key })
8158 this.length++
8159
8160 return this
8161}
8162
8163Batch.prototype.clear = function () {
8164 try {
8165 this.batch.clear()
8166 } catch (err) {
8167 throw new WriteError(err)
8168 }
8169
8170 this.ops = []
8171 this.length = 0
8172
8173 return this
8174}
8175
8176Batch.prototype.write = function (callback) {
8177 var levelup = this._levelup
8178 var ops = this.ops
8179 var promise
8180
8181 if (!callback) {
8182 callback = promisify()
8183 promise = callback.promise
8184 }
8185
8186 try {
8187 this.batch.write(function (err) {
8188 if (err) { return callback(new WriteError(err)) }
8189 levelup.emit('batch', ops)
8190 callback()
8191 })
8192 } catch (err) {
8193 throw new WriteError(err)
8194 }
8195
8196 return promise
8197}
8198
8199module.exports = Batch
8200
8201},{"36":36,"43":43}],35:[function(_dereq_,module,exports){
8202(function (process){
8203/* Copyright (c) 2012-2018 LevelUP contributors
8204 * See list at <https://github.com/level/levelup#contributing>
8205 * MIT License
8206 * <https://github.com/level/levelup/blob/master/LICENSE.md>
8207 */
8208
8209var EventEmitter = _dereq_(14).EventEmitter
8210var inherits = _dereq_(104).inherits
8211var extend = _dereq_(44)
8212var DeferredLevelDOWN = _dereq_(42)
8213var IteratorStream = _dereq_(23)
8214var Batch = _dereq_(34)
8215var errors = _dereq_(43)
8216var assert = _dereq_(2)
8217var promisify = _dereq_(36)
8218
8219var WriteError = errors.WriteError
8220var ReadError = errors.ReadError
8221var NotFoundError = errors.NotFoundError
8222var OpenError = errors.OpenError
8223var InitializationError = errors.InitializationError
8224
8225// Possible AbstractLevelDOWN#status values:
8226// - 'new' - newly created, not opened or closed
8227// - 'opening' - waiting for the database to be opened, post open()
8228// - 'open' - successfully opened the database, available for use
8229// - 'closing' - waiting for the database to be closed, post close()
8230// - 'closed' - database has been successfully closed, should not be
8231// used except for another open() operation
8232
8233function LevelUP (db, options, callback) {
8234 if (!(this instanceof LevelUP)) {
8235 return new LevelUP(db, options, callback)
8236 }
8237
8238 var error
8239
8240 EventEmitter.call(this)
8241 this.setMaxListeners(Infinity)
8242
8243 if (typeof options === 'function') {
8244 callback = options
8245 options = {}
8246 }
8247
8248 options = options || {}
8249
8250 if (!db || typeof db !== 'object') {
8251 error = new InitializationError('First argument must be an abstract-leveldown compliant store')
8252 if (typeof callback === 'function') {
8253 return process.nextTick(callback, error)
8254 }
8255 throw error
8256 }
8257
8258 assert.equal(typeof db.status, 'string', '.status required, old abstract-leveldown')
8259
8260 this.options = getOptions(options)
8261 this._db = db
8262 this.db = new DeferredLevelDOWN(db)
8263 this.open(callback)
8264}
8265
8266LevelUP.prototype.emit = EventEmitter.prototype.emit
8267LevelUP.prototype.once = EventEmitter.prototype.once
8268inherits(LevelUP, EventEmitter)
8269
8270LevelUP.prototype.open = function (callback) {
8271 var self = this
8272 var promise
8273
8274 if (!callback) {
8275 callback = promisify()
8276 promise = callback.promise
8277 }
8278
8279 if (this.isOpen()) {
8280 process.nextTick(callback, null, self)
8281 return promise
8282 }
8283
8284 if (this._isOpening()) {
8285 this.once('open', function () { callback(null, self) })
8286 return promise
8287 }
8288
8289 this.emit('opening')
8290
8291 this.db.open(this.options, function (err) {
8292 if (err) {
8293 return callback(new OpenError(err))
8294 }
8295 self.db = self._db
8296 callback(null, self)
8297 self.emit('open')
8298 self.emit('ready')
8299 })
8300
8301 return promise
8302}
8303
8304LevelUP.prototype.close = function (callback) {
8305 var self = this
8306 var promise
8307
8308 if (!callback) {
8309 callback = promisify()
8310 promise = callback.promise
8311 }
8312
8313 if (this.isOpen()) {
8314 this.db.close(function () {
8315 self.emit('closed')
8316 callback.apply(null, arguments)
8317 })
8318 this.emit('closing')
8319 this.db = new DeferredLevelDOWN(this._db)
8320 } else if (this.isClosed()) {
8321 process.nextTick(callback)
8322 } else if (this.db.status === 'closing') {
8323 this.once('closed', callback)
8324 } else if (this._isOpening()) {
8325 this.once('open', function () {
8326 self.close(callback)
8327 })
8328 }
8329
8330 return promise
8331}
8332
8333LevelUP.prototype.isOpen = function () {
8334 return this.db.status === 'open'
8335}
8336
8337LevelUP.prototype._isOpening = function () {
8338 return this.db.status === 'opening'
8339}
8340
8341LevelUP.prototype.isClosed = function () {
8342 return (/^clos|new/).test(this.db.status)
8343}
8344
8345LevelUP.prototype.get = function (key, options, callback) {
8346 if (key === null || key === undefined) {
8347 throw new ReadError('get() requires a key argument')
8348 }
8349
8350 var promise
8351
8352 callback = getCallback(options, callback)
8353
8354 if (!callback) {
8355 callback = promisify()
8356 promise = callback.promise
8357 }
8358
8359 if (maybeError(this, callback)) { return promise }
8360
8361 options = getOptions(options)
8362
8363 this.db.get(key, options, function (err, value) {
8364 if (err) {
8365 if ((/notfound/i).test(err) || err.notFound) {
8366 err = new NotFoundError('Key not found in database [' + key + ']', err)
8367 } else {
8368 err = new ReadError(err)
8369 }
8370 return callback(err)
8371 }
8372 callback(null, value)
8373 })
8374
8375 return promise
8376}
8377
8378LevelUP.prototype.put = function (key, value, options, callback) {
8379 if (key === null || key === undefined) {
8380 throw new WriteError('put() requires a key argument')
8381 }
8382
8383 var self = this
8384 var promise
8385
8386 callback = getCallback(options, callback)
8387
8388 if (!callback) {
8389 callback = promisify()
8390 promise = callback.promise
8391 }
8392
8393 if (maybeError(this, callback)) { return promise }
8394
8395 options = getOptions(options)
8396
8397 this.db.put(key, value, options, function (err) {
8398 if (err) {
8399 return callback(new WriteError(err))
8400 }
8401 self.emit('put', key, value)
8402 callback()
8403 })
8404
8405 return promise
8406}
8407
8408LevelUP.prototype.del = function (key, options, callback) {
8409 if (key === null || key === undefined) {
8410 throw new WriteError('del() requires a key argument')
8411 }
8412
8413 var self = this
8414 var promise
8415
8416 callback = getCallback(options, callback)
8417
8418 if (!callback) {
8419 callback = promisify()
8420 promise = callback.promise
8421 }
8422
8423 if (maybeError(this, callback)) { return promise }
8424
8425 options = getOptions(options)
8426
8427 this.db.del(key, options, function (err) {
8428 if (err) {
8429 return callback(new WriteError(err))
8430 }
8431 self.emit('del', key)
8432 callback()
8433 })
8434
8435 return promise
8436}
8437
8438LevelUP.prototype.batch = function (arr, options, callback) {
8439 if (!arguments.length) {
8440 return new Batch(this)
8441 }
8442
8443 if (!Array.isArray(arr)) {
8444 throw new WriteError('batch() requires an array argument')
8445 }
8446
8447 var self = this
8448 var promise
8449
8450 callback = getCallback(options, callback)
8451
8452 if (!callback) {
8453 callback = promisify()
8454 promise = callback.promise
8455 }
8456
8457 if (maybeError(this, callback)) { return promise }
8458
8459 options = getOptions(options)
8460
8461 this.db.batch(arr, options, function (err) {
8462 if (err) {
8463 return callback(new WriteError(err))
8464 }
8465 self.emit('batch', arr)
8466 callback()
8467 })
8468
8469 return promise
8470}
8471
8472LevelUP.prototype.readStream =
8473LevelUP.prototype.createReadStream = function (options) {
8474 options = extend({ keys: true, values: true }, options)
8475 if (typeof options.limit !== 'number') { options.limit = -1 }
8476 return new IteratorStream(this.db.iterator(options), options)
8477}
8478
8479LevelUP.prototype.keyStream =
8480LevelUP.prototype.createKeyStream = function (options) {
8481 return this.createReadStream(extend(options, { keys: true, values: false }))
8482}
8483
8484LevelUP.prototype.valueStream =
8485LevelUP.prototype.createValueStream = function (options) {
8486 return this.createReadStream(extend(options, { keys: false, values: true }))
8487}
8488
8489LevelUP.prototype.toString = function () {
8490 return 'LevelUP'
8491}
8492
8493function getCallback (options, callback) {
8494 return typeof options === 'function' ? options : callback
8495}
8496
8497function getOptions (options) {
8498 return typeof options === 'object' && options !== null ? options : {}
8499}
8500
8501function maybeError (db, callback) {
8502 if (!db._isOpening() && !db.isOpen()) {
8503 process.nextTick(callback, new ReadError('Database is not open'))
8504 return true
8505 }
8506}
8507
8508LevelUP.errors = errors
8509module.exports = LevelUP.default = LevelUP
8510
8511}).call(this,_dereq_(62))
8512},{"104":104,"14":14,"2":2,"23":23,"34":34,"36":36,"42":42,"43":43,"44":44,"62":62}],36:[function(_dereq_,module,exports){
8513/* Copyright (c) 2012-2018 LevelUP contributors
8514 * See list at <https://github.com/level/levelup#contributing>
8515 * MIT License
8516 * <https://github.com/level/levelup/blob/master/LICENSE.md>
8517 */
8518
8519function promisify () {
8520 var callback
8521 var promise = new Promise(function (resolve, reject) {
8522 callback = function callback (err, value) {
8523 if (err) reject(err)
8524 else resolve(value)
8525 }
8526 })
8527 callback.promise = promise
8528 return callback
8529}
8530
8531module.exports = promisify
8532
8533},{}],37:[function(_dereq_,module,exports){
8534(function (process){
8535/* Copyright (c) 2017 Rod Vagg, MIT License */
8536
8537function AbstractChainedBatch (db) {
8538 this._db = db
8539 this._operations = []
8540 this._written = false
8541}
8542
8543AbstractChainedBatch.prototype._serializeKey = function (key) {
8544 return this._db._serializeKey(key)
8545}
8546
8547AbstractChainedBatch.prototype._serializeValue = function (value) {
8548 return this._db._serializeValue(value)
8549}
8550
8551AbstractChainedBatch.prototype._checkWritten = function () {
8552 if (this._written) {
8553 throw new Error('write() already called on this batch')
8554 }
8555}
8556
8557AbstractChainedBatch.prototype.put = function (key, value) {
8558 this._checkWritten()
8559
8560 var err = this._db._checkKey(key, 'key')
8561 if (err) { throw err }
8562
8563 key = this._serializeKey(key)
8564 value = this._serializeValue(value)
8565
8566 this._put(key, value)
8567
8568 return this
8569}
8570
8571AbstractChainedBatch.prototype._put = function (key, value) {
8572 this._operations.push({ type: 'put', key: key, value: value })
8573}
8574
8575AbstractChainedBatch.prototype.del = function (key) {
8576 this._checkWritten()
8577
8578 var err = this._db._checkKey(key, 'key')
8579 if (err) { throw err }
8580
8581 key = this._serializeKey(key)
8582 this._del(key)
8583
8584 return this
8585}
8586
8587AbstractChainedBatch.prototype._del = function (key) {
8588 this._operations.push({ type: 'del', key: key })
8589}
8590
8591AbstractChainedBatch.prototype.clear = function () {
8592 this._checkWritten()
8593 this._operations = []
8594 this._clear()
8595
8596 return this
8597}
8598
8599AbstractChainedBatch.prototype._clear = function noop () {}
8600
8601AbstractChainedBatch.prototype.write = function (options, callback) {
8602 this._checkWritten()
8603
8604 if (typeof options === 'function') { callback = options }
8605 if (typeof callback !== 'function') {
8606 throw new Error('write() requires a callback argument')
8607 }
8608 if (typeof options !== 'object') { options = {} }
8609
8610 this._written = true
8611
8612 // @ts-ignore
8613 if (typeof this._write === 'function') { return this._write(callback) }
8614
8615 if (typeof this._db._batch === 'function') {
8616 return this._db._batch(this._operations, options, callback)
8617 }
8618
8619 process.nextTick(callback)
8620}
8621
8622module.exports = AbstractChainedBatch
8623
8624}).call(this,_dereq_(62))
8625},{"62":62}],38:[function(_dereq_,module,exports){
8626(function (process){
8627/* Copyright (c) 2017 Rod Vagg, MIT License */
8628
8629function AbstractIterator (db) {
8630 this.db = db
8631 this._ended = false
8632 this._nexting = false
8633}
8634
8635AbstractIterator.prototype.next = function (callback) {
8636 var self = this
8637
8638 if (typeof callback !== 'function') {
8639 throw new Error('next() requires a callback argument')
8640 }
8641
8642 if (self._ended) {
8643 process.nextTick(callback, new Error('cannot call next() after end()'))
8644 return self
8645 }
8646
8647 if (self._nexting) {
8648 process.nextTick(callback, new Error('cannot call next() before previous next() has completed'))
8649 return self
8650 }
8651
8652 self._nexting = true
8653 self._next(function () {
8654 self._nexting = false
8655 callback.apply(null, arguments)
8656 })
8657
8658 return self
8659}
8660
8661AbstractIterator.prototype._next = function (callback) {
8662 process.nextTick(callback)
8663}
8664
8665AbstractIterator.prototype.end = function (callback) {
8666 if (typeof callback !== 'function') {
8667 throw new Error('end() requires a callback argument')
8668 }
8669
8670 if (this._ended) {
8671 return process.nextTick(callback, new Error('end() already called on iterator'))
8672 }
8673
8674 this._ended = true
8675 this._end(callback)
8676}
8677
8678AbstractIterator.prototype._end = function (callback) {
8679 process.nextTick(callback)
8680}
8681
8682module.exports = AbstractIterator
8683
8684}).call(this,_dereq_(62))
8685},{"62":62}],39:[function(_dereq_,module,exports){
8686(function (Buffer,process){
8687/* Copyright (c) 2017 Rod Vagg, MIT License */
8688
8689var xtend = _dereq_(44)
8690var AbstractIterator = _dereq_(38)
8691var AbstractChainedBatch = _dereq_(37)
8692var hasOwnProperty = Object.prototype.hasOwnProperty
8693var rangeOptions = 'start end gt gte lt lte'.split(' ')
8694
8695function AbstractLevelDOWN (location) {
8696 if (!arguments.length || location === undefined) {
8697 throw new Error('constructor requires at least a location argument')
8698 }
8699
8700 if (typeof location !== 'string') {
8701 throw new Error('constructor requires a location string argument')
8702 }
8703
8704 this.location = location
8705 this.status = 'new'
8706}
8707
8708AbstractLevelDOWN.prototype.open = function (options, callback) {
8709 var self = this
8710 var oldStatus = this.status
8711
8712 if (typeof options === 'function') { callback = options }
8713
8714 if (typeof callback !== 'function') {
8715 throw new Error('open() requires a callback argument')
8716 }
8717
8718 if (typeof options !== 'object') { options = {} }
8719
8720 options.createIfMissing = options.createIfMissing !== false
8721 options.errorIfExists = !!options.errorIfExists
8722
8723 this.status = 'opening'
8724 this._open(options, function (err) {
8725 if (err) {
8726 self.status = oldStatus
8727 return callback(err)
8728 }
8729 self.status = 'open'
8730 callback()
8731 })
8732}
8733
8734AbstractLevelDOWN.prototype._open = function (options, callback) {
8735 process.nextTick(callback)
8736}
8737
8738AbstractLevelDOWN.prototype.close = function (callback) {
8739 var self = this
8740 var oldStatus = this.status
8741
8742 if (typeof callback !== 'function') {
8743 throw new Error('close() requires a callback argument')
8744 }
8745
8746 this.status = 'closing'
8747 this._close(function (err) {
8748 if (err) {
8749 self.status = oldStatus
8750 return callback(err)
8751 }
8752 self.status = 'closed'
8753 callback()
8754 })
8755}
8756
8757AbstractLevelDOWN.prototype._close = function (callback) {
8758 process.nextTick(callback)
8759}
8760
8761AbstractLevelDOWN.prototype.get = function (key, options, callback) {
8762 if (typeof options === 'function') { callback = options }
8763
8764 if (typeof callback !== 'function') {
8765 throw new Error('get() requires a callback argument')
8766 }
8767
8768 var err = this._checkKey(key, 'key')
8769 if (err) return process.nextTick(callback, err)
8770
8771 key = this._serializeKey(key)
8772
8773 if (typeof options !== 'object') { options = {} }
8774
8775 options.asBuffer = options.asBuffer !== false
8776
8777 this._get(key, options, callback)
8778}
8779
8780AbstractLevelDOWN.prototype._get = function (key, options, callback) {
8781 process.nextTick(function () { callback(new Error('NotFound')) })
8782}
8783
8784AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
8785 if (typeof options === 'function') { callback = options }
8786
8787 if (typeof callback !== 'function') {
8788 throw new Error('put() requires a callback argument')
8789 }
8790
8791 var err = this._checkKey(key, 'key')
8792 if (err) return process.nextTick(callback, err)
8793
8794 key = this._serializeKey(key)
8795 value = this._serializeValue(value)
8796
8797 if (typeof options !== 'object') { options = {} }
8798
8799 this._put(key, value, options, callback)
8800}
8801
8802AbstractLevelDOWN.prototype._put = function (key, value, options, callback) {
8803 process.nextTick(callback)
8804}
8805
8806AbstractLevelDOWN.prototype.del = function (key, options, callback) {
8807 if (typeof options === 'function') { callback = options }
8808
8809 if (typeof callback !== 'function') {
8810 throw new Error('del() requires a callback argument')
8811 }
8812
8813 var err = this._checkKey(key, 'key')
8814 if (err) return process.nextTick(callback, err)
8815
8816 key = this._serializeKey(key)
8817
8818 if (typeof options !== 'object') { options = {} }
8819
8820 this._del(key, options, callback)
8821}
8822
8823AbstractLevelDOWN.prototype._del = function (key, options, callback) {
8824 process.nextTick(callback)
8825}
8826
8827AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
8828 if (!arguments.length) { return this._chainedBatch() }
8829
8830 if (typeof options === 'function') { callback = options }
8831
8832 if (typeof array === 'function') { callback = array }
8833
8834 if (typeof callback !== 'function') {
8835 throw new Error('batch(array) requires a callback argument')
8836 }
8837
8838 if (!Array.isArray(array)) {
8839 return process.nextTick(callback, new Error('batch(array) requires an array argument'))
8840 }
8841
8842 if (!options || typeof options !== 'object') { options = {} }
8843
8844 var serialized = new Array(array.length)
8845
8846 for (var i = 0; i < array.length; i++) {
8847 if (typeof array[i] !== 'object' || array[i] === null) {
8848 return process.nextTick(callback, new Error('batch(array) element must be an object and not `null`'))
8849 }
8850
8851 var e = xtend(array[i])
8852
8853 if (e.type !== 'put' && e.type !== 'del') {
8854 return process.nextTick(callback, new Error("`type` must be 'put' or 'del'"))
8855 }
8856
8857 var err = this._checkKey(e.key, 'key')
8858 if (err) return process.nextTick(callback, err)
8859
8860 e.key = this._serializeKey(e.key)
8861
8862 if (e.type === 'put') { e.value = this._serializeValue(e.value) }
8863
8864 serialized[i] = e
8865 }
8866
8867 this._batch(serialized, options, callback)
8868}
8869
8870AbstractLevelDOWN.prototype._batch = function (array, options, callback) {
8871 process.nextTick(callback)
8872}
8873
8874AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
8875 options = cleanRangeOptions(options)
8876
8877 options.reverse = !!options.reverse
8878 options.keys = options.keys !== false
8879 options.values = options.values !== false
8880 options.limit = 'limit' in options ? options.limit : -1
8881 options.keyAsBuffer = options.keyAsBuffer !== false
8882 options.valueAsBuffer = options.valueAsBuffer !== false
8883
8884 return options
8885}
8886
8887function cleanRangeOptions (options) {
8888 var result = {}
8889
8890 for (var k in options) {
8891 if (!hasOwnProperty.call(options, k)) continue
8892 if (isRangeOption(k) && isEmptyRangeOption(options[k])) continue
8893
8894 result[k] = options[k]
8895 }
8896
8897 return result
8898}
8899
8900function isRangeOption (k) {
8901 return rangeOptions.indexOf(k) !== -1
8902}
8903
8904function isEmptyRangeOption (v) {
8905 return v === '' || v == null || isEmptyBuffer(v)
8906}
8907
8908function isEmptyBuffer (v) {
8909 return Buffer.isBuffer(v) && v.length === 0
8910}
8911
8912AbstractLevelDOWN.prototype.iterator = function (options) {
8913 if (typeof options !== 'object') { options = {} }
8914 options = this._setupIteratorOptions(options)
8915 return this._iterator(options)
8916}
8917
8918AbstractLevelDOWN.prototype._iterator = function (options) {
8919 return new AbstractIterator(this)
8920}
8921
8922AbstractLevelDOWN.prototype._chainedBatch = function () {
8923 return new AbstractChainedBatch(this)
8924}
8925
8926AbstractLevelDOWN.prototype._serializeKey = function (key) {
8927 return Buffer.isBuffer(key) ? key : String(key)
8928}
8929
8930AbstractLevelDOWN.prototype._serializeValue = function (value) {
8931 if (value == null) return ''
8932 return Buffer.isBuffer(value) || process.browser ? value : String(value)
8933}
8934
8935AbstractLevelDOWN.prototype._checkKey = function (obj, type) {
8936 if (obj === null || obj === undefined) {
8937 return new Error(type + ' cannot be `null` or `undefined`')
8938 }
8939
8940 if (Buffer.isBuffer(obj) && obj.length === 0) {
8941 return new Error(type + ' cannot be an empty Buffer')
8942 }
8943
8944 if (String(obj) === '') {
8945 return new Error(type + ' cannot be an empty String')
8946 }
8947}
8948
8949module.exports = AbstractLevelDOWN
8950
8951}).call(this,{"isBuffer":_dereq_(19)},_dereq_(62))
8952},{"19":19,"37":37,"38":38,"44":44,"62":62}],40:[function(_dereq_,module,exports){
8953exports.AbstractLevelDOWN = _dereq_(39)
8954exports.AbstractIterator = _dereq_(38)
8955exports.AbstractChainedBatch = _dereq_(37)
8956
8957},{"37":37,"38":38,"39":39}],41:[function(_dereq_,module,exports){
8958var AbstractIterator = _dereq_(40).AbstractIterator
8959var inherits = _dereq_(18)
8960
8961function DeferredIterator (options) {
8962 AbstractIterator.call(this, options)
8963
8964 this._options = options
8965 this._iterator = null
8966 this._operations = []
8967}
8968
8969inherits(DeferredIterator, AbstractIterator)
8970
8971DeferredIterator.prototype.setDb = function (db) {
8972 var it = this._iterator = db.iterator(this._options)
8973 this._operations.forEach(function (op) {
8974 it[op.method].apply(it, op.args)
8975 })
8976}
8977
8978DeferredIterator.prototype._operation = function (method, args) {
8979 if (this._iterator) return this._iterator[method].apply(this._iterator, args)
8980 this._operations.push({ method: method, args: args })
8981}
8982
8983'next end'.split(' ').forEach(function (m) {
8984 DeferredIterator.prototype['_' + m] = function () {
8985 this._operation(m, arguments)
8986 }
8987})
8988
8989module.exports = DeferredIterator
8990
8991},{"18":18,"40":40}],42:[function(_dereq_,module,exports){
8992var AbstractLevelDOWN = _dereq_(40).AbstractLevelDOWN
8993var inherits = _dereq_(18)
8994var DeferredIterator = _dereq_(41)
8995var deferrables = 'put get del batch'.split(' ')
8996
8997function DeferredLevelDOWN (db) {
8998 AbstractLevelDOWN.call(this, '')
8999 this._db = db
9000 this._operations = []
9001 this._iterators = []
9002 closed(this)
9003}
9004
9005inherits(DeferredLevelDOWN, AbstractLevelDOWN)
9006
9007DeferredLevelDOWN.prototype._open = function (options, callback) {
9008 var self = this
9009
9010 this._db.open(options, function (err) {
9011 if (err) return callback(err)
9012
9013 self._operations.forEach(function (op) {
9014 self._db[op.method].apply(self._db, op.args)
9015 })
9016 self._operations = []
9017 self._iterators.forEach(function (it) {
9018 it.setDb(self._db)
9019 })
9020 self._iterators = []
9021 open(self)
9022 callback()
9023 })
9024}
9025
9026DeferredLevelDOWN.prototype._close = function (callback) {
9027 var self = this
9028
9029 this._db.close(function (err) {
9030 if (err) return callback(err)
9031 closed(self)
9032 callback()
9033 })
9034}
9035
9036function open (self) {
9037 deferrables.concat('iterator').forEach(function (m) {
9038 self['_' + m] = function () {
9039 return this._db[m].apply(this._db, arguments)
9040 }
9041 })
9042 if (self._db.approximateSize) {
9043 self.approximateSize = function () {
9044 return this._db.approximateSize.apply(this._db, arguments)
9045 }
9046 }
9047}
9048
9049function closed (self) {
9050 deferrables.forEach(function (m) {
9051 self['_' + m] = function () {
9052 this._operations.push({ method: m, args: arguments })
9053 }
9054 })
9055 if (typeof self._db.approximateSize === 'function') {
9056 self.approximateSize = function () {
9057 this._operations.push({
9058 method: 'approximateSize',
9059 args: arguments
9060 })
9061 }
9062 }
9063 self._iterator = function (options) {
9064 var it = new DeferredIterator(options)
9065 this._iterators.push(it)
9066 return it
9067 }
9068}
9069
9070DeferredLevelDOWN.prototype._serializeKey = function (key) {
9071 return key
9072}
9073
9074DeferredLevelDOWN.prototype._serializeValue = function (value) {
9075 return value
9076}
9077
9078module.exports = DeferredLevelDOWN
9079module.exports.DeferredIterator = DeferredIterator
9080
9081},{"18":18,"40":40,"41":41}],43:[function(_dereq_,module,exports){
9082/* Copyright (c) 2012-2017 LevelUP contributors
9083 * See list at <https://github.com/rvagg/node-levelup#contributing>
9084 * MIT License
9085 * <https://github.com/rvagg/node-levelup/blob/master/LICENSE.md>
9086 */
9087
9088var createError = _dereq_(13).create
9089var LevelUPError = createError('LevelUPError')
9090var NotFoundError = createError('NotFoundError', LevelUPError)
9091
9092NotFoundError.prototype.notFound = true
9093NotFoundError.prototype.status = 404
9094
9095module.exports = {
9096 LevelUPError: LevelUPError,
9097 InitializationError: createError('InitializationError', LevelUPError),
9098 OpenError: createError('OpenError', LevelUPError),
9099 ReadError: createError('ReadError', LevelUPError),
9100 WriteError: createError('WriteError', LevelUPError),
9101 NotFoundError: NotFoundError,
9102 EncodingError: createError('EncodingError', LevelUPError)
9103}
9104
9105},{"13":13}],44:[function(_dereq_,module,exports){
9106arguments[4][33][0].apply(exports,arguments)
9107},{"33":33}],45:[function(_dereq_,module,exports){
9108(function (Buffer){
9109
9110exports.compare = function (a, b) {
9111
9112 if(Buffer.isBuffer(a)) {
9113 var l = Math.min(a.length, b.length)
9114 for(var i = 0; i < l; i++) {
9115 var cmp = a[i] - b[i]
9116 if(cmp) return cmp
9117 }
9118 return a.length - b.length
9119 }
9120
9121 return a < b ? -1 : a > b ? 1 : 0
9122}
9123
9124// to be compatible with the current abstract-leveldown tests
9125// nullish or empty strings.
9126// I could use !!val but I want to permit numbers and booleans,
9127// if possible.
9128
9129function isDef (val) {
9130 return val !== undefined && val !== ''
9131}
9132
9133function has (range, name) {
9134 return Object.hasOwnProperty.call(range, name)
9135}
9136
9137function hasKey(range, name) {
9138 return Object.hasOwnProperty.call(range, name) && name
9139}
9140
9141var lowerBoundKey = exports.lowerBoundKey = function (range) {
9142 return (
9143 hasKey(range, 'gt')
9144 || hasKey(range, 'gte')
9145 || hasKey(range, 'min')
9146 || (range.reverse ? hasKey(range, 'end') : hasKey(range, 'start'))
9147 || undefined
9148 )
9149}
9150
9151var lowerBound = exports.lowerBound = function (range, def) {
9152 var k = lowerBoundKey(range)
9153 return k ? range[k] : def
9154}
9155
9156var lowerBoundInclusive = exports.lowerBoundInclusive = function (range) {
9157 return has(range, 'gt') ? false : true
9158}
9159
9160var upperBoundInclusive = exports.upperBoundInclusive =
9161 function (range) {
9162 return (has(range, 'lt') /*&& !range.maxEx*/) ? false : true
9163 }
9164
9165var lowerBoundExclusive = exports.lowerBoundExclusive =
9166 function (range) {
9167 return !lowerBoundInclusive(range)
9168 }
9169
9170var upperBoundExclusive = exports.upperBoundExclusive =
9171 function (range) {
9172 return !upperBoundInclusive(range)
9173 }
9174
9175var upperBoundKey = exports.upperBoundKey = function (range) {
9176 return (
9177 hasKey(range, 'lt')
9178 || hasKey(range, 'lte')
9179 || hasKey(range, 'max')
9180 || (range.reverse ? hasKey(range, 'start') : hasKey(range, 'end'))
9181 || undefined
9182 )
9183}
9184
9185var upperBound = exports.upperBound = function (range, def) {
9186 var k = upperBoundKey(range)
9187 return k ? range[k] : def
9188}
9189
9190exports.start = function (range, def) {
9191 return range.reverse ? upperBound(range, def) : lowerBound(range, def)
9192}
9193exports.end = function (range, def) {
9194 return range.reverse ? lowerBound(range, def) : upperBound(range, def)
9195}
9196exports.startInclusive = function (range) {
9197 return (
9198 range.reverse
9199 ? upperBoundInclusive(range)
9200 : lowerBoundInclusive(range)
9201 )
9202}
9203exports.endInclusive = function (range) {
9204 return (
9205 range.reverse
9206 ? lowerBoundInclusive(range)
9207 : upperBoundInclusive(range)
9208 )
9209}
9210
9211function id (e) { return e }
9212
9213exports.toLtgt = function (range, _range, map, lower, upper) {
9214 _range = _range || {}
9215 map = map || id
9216 var defaults = arguments.length > 3
9217 var lb = exports.lowerBoundKey(range)
9218 var ub = exports.upperBoundKey(range)
9219 if(lb) {
9220 if(lb === 'gt') _range.gt = map(range.gt, false)
9221 else _range.gte = map(range[lb], false)
9222 }
9223 else if(defaults)
9224 _range.gte = map(lower, false)
9225
9226 if(ub) {
9227 if(ub === 'lt') _range.lt = map(range.lt, true)
9228 else _range.lte = map(range[ub], true)
9229 }
9230 else if(defaults)
9231 _range.lte = map(upper, true)
9232
9233 if(range.reverse != null)
9234 _range.reverse = !!range.reverse
9235
9236 //if range was used mutably
9237 //(in level-sublevel it's part of an options object
9238 //that has more properties on it.)
9239 if(has(_range, 'max')) delete _range.max
9240 if(has(_range, 'min')) delete _range.min
9241 if(has(_range, 'start')) delete _range.start
9242 if(has(_range, 'end')) delete _range.end
9243
9244 return _range
9245}
9246
9247exports.contains = function (range, key, compare) {
9248 compare = compare || exports.compare
9249
9250 var lb = lowerBound(range)
9251 if(isDef(lb)) {
9252 var cmp = compare(key, lb)
9253 if(cmp < 0 || (cmp === 0 && lowerBoundExclusive(range)))
9254 return false
9255 }
9256
9257 var ub = upperBound(range)
9258 if(isDef(ub)) {
9259 var cmp = compare(key, ub)
9260 if(cmp > 0 || (cmp === 0) && upperBoundExclusive(range))
9261 return false
9262 }
9263
9264 return true
9265}
9266
9267exports.filter = function (range, compare) {
9268 return function (key) {
9269 return exports.contains(range, key, compare)
9270 }
9271}
9272
9273
9274
9275}).call(this,{"isBuffer":_dereq_(19)})
9276},{"19":19}],46:[function(_dereq_,module,exports){
9277module.exports = _dereq_(53)
9278
9279},{"53":53}],47:[function(_dereq_,module,exports){
9280(function (Buffer){
9281var inherits = _dereq_(18)
9282 , AbstractLevelDOWN = _dereq_(51).AbstractLevelDOWN
9283 , AbstractIterator = _dereq_(51).AbstractIterator
9284 , ltgt = _dereq_(59)
9285 , createRBT = _dereq_(15)
9286 , globalStore = {}
9287
9288// In Node, use global.setImmediate. In the browser, use a consistent
9289// microtask library to give consistent microtask experience to all browsers
9290var setImmediate = _dereq_(46)
9291
9292function gt(value) {
9293 return ltgt.compare(value, this._end) > 0
9294}
9295
9296function gte(value) {
9297 return ltgt.compare(value, this._end) >= 0
9298}
9299
9300function lt(value) {
9301 return ltgt.compare(value, this._end) < 0
9302}
9303
9304function lte(value) {
9305 return ltgt.compare(value, this._end) <= 0
9306}
9307
9308
9309function MemIterator (db, options) {
9310 AbstractIterator.call(this, db)
9311 this._limit = options.limit
9312
9313 if (this._limit === -1)
9314 this._limit = Infinity
9315
9316 var tree = db._store[db._location]
9317
9318 this.keyAsBuffer = options.keyAsBuffer !== false
9319 this.valueAsBuffer = options.valueAsBuffer !== false
9320 this._reverse = options.reverse
9321 this._options = options
9322 this._done = 0
9323
9324 if (!this._reverse) {
9325 this._incr = 'next'
9326 this._start = ltgt.lowerBound(options)
9327 this._end = ltgt.upperBound(options)
9328
9329 if (typeof this._start === 'undefined')
9330 this._tree = tree.begin
9331 else if (ltgt.lowerBoundInclusive(options))
9332 this._tree = tree.ge(this._start)
9333 else
9334 this._tree = tree.gt(this._start)
9335
9336 if (this._end) {
9337 if (ltgt.upperBoundInclusive(options))
9338 this._test = lte
9339 else
9340 this._test = lt
9341 }
9342
9343 } else {
9344 this._incr = 'prev'
9345 this._start = ltgt.upperBound(options)
9346 this._end = ltgt.lowerBound(options)
9347
9348 if (typeof this._start === 'undefined')
9349 this._tree = tree.end
9350 else if (ltgt.upperBoundInclusive(options))
9351 this._tree = tree.le(this._start)
9352 else
9353 this._tree = tree.lt(this._start)
9354
9355 if (this._end) {
9356 if (ltgt.lowerBoundInclusive(options))
9357 this._test = gte
9358 else
9359 this._test = gt
9360 }
9361
9362 }
9363
9364}
9365
9366inherits(MemIterator, AbstractIterator)
9367
9368MemIterator.prototype._next = function (callback) {
9369 var key
9370 , value
9371
9372 if (this._done++ >= this._limit)
9373 return setImmediate(callback)
9374
9375 if (!this._tree.valid)
9376 return setImmediate(callback)
9377
9378 key = this._tree.key
9379 value = this._tree.value
9380
9381 if (!this._test(key))
9382 return setImmediate(callback)
9383
9384 if (this.keyAsBuffer)
9385 key = new Buffer(key)
9386
9387 if (this.valueAsBuffer)
9388 value = new Buffer(value)
9389
9390 this._tree[this._incr]()
9391
9392 setImmediate(function callNext() {
9393 callback(null, key, value)
9394 })
9395}
9396
9397MemIterator.prototype._test = function () {return true}
9398
9399function MemDOWN (location) {
9400 if (!(this instanceof MemDOWN))
9401 return new MemDOWN(location)
9402
9403 AbstractLevelDOWN.call(this, typeof location == 'string' ? location : '')
9404
9405 this._location = this.location ? ('$' + this.location) : '_tree'
9406 this._store = this.location ? globalStore: this
9407 this._store[this._location] = this._store[this._location] || createRBT(ltgt.compare)
9408}
9409
9410MemDOWN.clearGlobalStore = function (strict) {
9411 if (strict) {
9412 Object.keys(globalStore).forEach(function (key) {
9413 delete globalStore[key]
9414 })
9415 } else {
9416 globalStore = {}
9417 }
9418}
9419
9420inherits(MemDOWN, AbstractLevelDOWN)
9421
9422MemDOWN.prototype._open = function (options, callback) {
9423 var self = this
9424 setImmediate(function callNext() { callback(null, self) })
9425}
9426
9427MemDOWN.prototype._put = function (key, value, options, callback) {
9428 if (typeof value === 'undefined' || value === null) value = ''
9429
9430 var iter = this._store[this._location].find(key)
9431
9432 if (iter.valid) {
9433 this._store[this._location] = iter.update(value)
9434 } else {
9435 this._store[this._location] = this._store[this._location].insert(key, value)
9436 }
9437
9438 setImmediate(callback)
9439}
9440
9441MemDOWN.prototype._get = function (key, options, callback) {
9442 var value = this._store[this._location].get(key)
9443
9444 if (typeof value === 'undefined') {
9445 // 'NotFound' error, consistent with LevelDOWN API
9446 return setImmediate(function callNext() { callback(new Error('NotFound')) })
9447 }
9448
9449 if (options.asBuffer !== false && !this._isBuffer(value))
9450 value = new Buffer(String(value))
9451
9452 setImmediate(function callNext () {
9453 callback(null, value)
9454 })
9455
9456}
9457
9458MemDOWN.prototype._del = function (key, options, callback) {
9459 this._store[this._location] = this._store[this._location].remove(key)
9460 setImmediate(callback)
9461}
9462
9463MemDOWN.prototype._batch = function (array, options, callback) {
9464 var i = -1
9465 , key
9466 , value
9467 , iter
9468 , len = array.length
9469 , tree = this._store[this._location]
9470
9471 while (++i < len) {
9472 if (!array[i])
9473 continue
9474
9475 key = this._isBuffer(array[i].key) ? array[i].key : String(array[i].key)
9476 iter = tree.find(key)
9477
9478 if (array[i].type === 'put') {
9479 value = this._isBuffer(array[i].value) ? array[i].value : String(array[i].value)
9480 tree = iter.valid ? iter.update(value) : tree.insert(key, value)
9481 } else {
9482 tree = iter.remove()
9483 }
9484 }
9485
9486 this._store[this._location] = tree
9487
9488 setImmediate(callback)
9489}
9490
9491MemDOWN.prototype._iterator = function (options) {
9492 return new MemIterator(this, options)
9493}
9494
9495MemDOWN.prototype._isBuffer = function (obj) {
9496 return Buffer.isBuffer(obj)
9497}
9498
9499MemDOWN.destroy = function (name, callback) {
9500 var key = '$' + name
9501
9502 if (key in globalStore)
9503 delete globalStore[key]
9504
9505 setImmediate(callback)
9506}
9507
9508module.exports = MemDOWN
9509
9510}).call(this,_dereq_(9).Buffer)
9511},{"15":15,"18":18,"46":46,"51":51,"59":59,"9":9}],48:[function(_dereq_,module,exports){
9512(function (process){
9513/* Copyright (c) 2013 Rod Vagg, MIT License */
9514
9515function AbstractChainedBatch (db) {
9516 this._db = db
9517 this._operations = []
9518 this._written = false
9519}
9520
9521AbstractChainedBatch.prototype._checkWritten = function () {
9522 if (this._written)
9523 throw new Error('write() already called on this batch')
9524}
9525
9526AbstractChainedBatch.prototype.put = function (key, value) {
9527 this._checkWritten()
9528
9529 var err = this._db._checkKey(key, 'key', this._db._isBuffer)
9530 if (err)
9531 throw err
9532
9533 if (!this._db._isBuffer(key)) key = String(key)
9534 if (!this._db._isBuffer(value)) value = String(value)
9535
9536 if (typeof this._put == 'function' )
9537 this._put(key, value)
9538 else
9539 this._operations.push({ type: 'put', key: key, value: value })
9540
9541 return this
9542}
9543
9544AbstractChainedBatch.prototype.del = function (key) {
9545 this._checkWritten()
9546
9547 var err = this._db._checkKey(key, 'key', this._db._isBuffer)
9548 if (err) throw err
9549
9550 if (!this._db._isBuffer(key)) key = String(key)
9551
9552 if (typeof this._del == 'function' )
9553 this._del(key)
9554 else
9555 this._operations.push({ type: 'del', key: key })
9556
9557 return this
9558}
9559
9560AbstractChainedBatch.prototype.clear = function () {
9561 this._checkWritten()
9562
9563 this._operations = []
9564
9565 if (typeof this._clear == 'function' )
9566 this._clear()
9567
9568 return this
9569}
9570
9571AbstractChainedBatch.prototype.write = function (options, callback) {
9572 this._checkWritten()
9573
9574 if (typeof options == 'function')
9575 callback = options
9576 if (typeof callback != 'function')
9577 throw new Error('write() requires a callback argument')
9578 if (typeof options != 'object')
9579 options = {}
9580
9581 this._written = true
9582
9583 if (typeof this._write == 'function' )
9584 return this._write(callback)
9585
9586 if (typeof this._db._batch == 'function')
9587 return this._db._batch(this._operations, options, callback)
9588
9589 process.nextTick(callback)
9590}
9591
9592module.exports = AbstractChainedBatch
9593}).call(this,_dereq_(62))
9594},{"62":62}],49:[function(_dereq_,module,exports){
9595(function (process){
9596/* Copyright (c) 2013 Rod Vagg, MIT License */
9597
9598function AbstractIterator (db) {
9599 this.db = db
9600 this._ended = false
9601 this._nexting = false
9602}
9603
9604AbstractIterator.prototype.next = function (callback) {
9605 var self = this
9606
9607 if (typeof callback != 'function')
9608 throw new Error('next() requires a callback argument')
9609
9610 if (self._ended)
9611 return callback(new Error('cannot call next() after end()'))
9612 if (self._nexting)
9613 return callback(new Error('cannot call next() before previous next() has completed'))
9614
9615 self._nexting = true
9616 if (typeof self._next == 'function') {
9617 return self._next(function () {
9618 self._nexting = false
9619 callback.apply(null, arguments)
9620 })
9621 }
9622
9623 process.nextTick(function () {
9624 self._nexting = false
9625 callback()
9626 })
9627}
9628
9629AbstractIterator.prototype.end = function (callback) {
9630 if (typeof callback != 'function')
9631 throw new Error('end() requires a callback argument')
9632
9633 if (this._ended)
9634 return callback(new Error('end() already called on iterator'))
9635
9636 this._ended = true
9637
9638 if (typeof this._end == 'function')
9639 return this._end(callback)
9640
9641 process.nextTick(callback)
9642}
9643
9644module.exports = AbstractIterator
9645
9646}).call(this,_dereq_(62))
9647},{"62":62}],50:[function(_dereq_,module,exports){
9648(function (Buffer,process){
9649/* Copyright (c) 2013 Rod Vagg, MIT License */
9650
9651var xtend = _dereq_(60)
9652 , AbstractIterator = _dereq_(49)
9653 , AbstractChainedBatch = _dereq_(48)
9654
9655function AbstractLevelDOWN (location) {
9656 if (!arguments.length || location === undefined)
9657 throw new Error('constructor requires at least a location argument')
9658
9659 if (typeof location != 'string')
9660 throw new Error('constructor requires a location string argument')
9661
9662 this.location = location
9663 this.status = 'new'
9664}
9665
9666AbstractLevelDOWN.prototype.open = function (options, callback) {
9667 var self = this
9668 , oldStatus = this.status
9669
9670 if (typeof options == 'function')
9671 callback = options
9672
9673 if (typeof callback != 'function')
9674 throw new Error('open() requires a callback argument')
9675
9676 if (typeof options != 'object')
9677 options = {}
9678
9679 options.createIfMissing = options.createIfMissing != false
9680 options.errorIfExists = !!options.errorIfExists
9681
9682 if (typeof this._open == 'function') {
9683 this.status = 'opening'
9684 this._open(options, function (err) {
9685 if (err) {
9686 self.status = oldStatus
9687 return callback(err)
9688 }
9689 self.status = 'open'
9690 callback()
9691 })
9692 } else {
9693 this.status = 'open'
9694 process.nextTick(callback)
9695 }
9696}
9697
9698AbstractLevelDOWN.prototype.close = function (callback) {
9699 var self = this
9700 , oldStatus = this.status
9701
9702 if (typeof callback != 'function')
9703 throw new Error('close() requires a callback argument')
9704
9705 if (typeof this._close == 'function') {
9706 this.status = 'closing'
9707 this._close(function (err) {
9708 if (err) {
9709 self.status = oldStatus
9710 return callback(err)
9711 }
9712 self.status = 'closed'
9713 callback()
9714 })
9715 } else {
9716 this.status = 'closed'
9717 process.nextTick(callback)
9718 }
9719}
9720
9721AbstractLevelDOWN.prototype.get = function (key, options, callback) {
9722 var err
9723
9724 if (typeof options == 'function')
9725 callback = options
9726
9727 if (typeof callback != 'function')
9728 throw new Error('get() requires a callback argument')
9729
9730 if (err = this._checkKey(key, 'key', this._isBuffer))
9731 return callback(err)
9732
9733 if (!this._isBuffer(key))
9734 key = String(key)
9735
9736 if (typeof options != 'object')
9737 options = {}
9738
9739 options.asBuffer = options.asBuffer != false
9740
9741 if (typeof this._get == 'function')
9742 return this._get(key, options, callback)
9743
9744 process.nextTick(function () { callback(new Error('NotFound')) })
9745}
9746
9747AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
9748 var err
9749
9750 if (typeof options == 'function')
9751 callback = options
9752
9753 if (typeof callback != 'function')
9754 throw new Error('put() requires a callback argument')
9755
9756 if (err = this._checkKey(key, 'key', this._isBuffer))
9757 return callback(err)
9758
9759 if (!this._isBuffer(key))
9760 key = String(key)
9761
9762 // coerce value to string in node, don't touch it in browser
9763 // (indexeddb can store any JS type)
9764 if (value != null && !this._isBuffer(value) && !process.browser)
9765 value = String(value)
9766
9767 if (typeof options != 'object')
9768 options = {}
9769
9770 if (typeof this._put == 'function')
9771 return this._put(key, value, options, callback)
9772
9773 process.nextTick(callback)
9774}
9775
9776AbstractLevelDOWN.prototype.del = function (key, options, callback) {
9777 var err
9778
9779 if (typeof options == 'function')
9780 callback = options
9781
9782 if (typeof callback != 'function')
9783 throw new Error('del() requires a callback argument')
9784
9785 if (err = this._checkKey(key, 'key', this._isBuffer))
9786 return callback(err)
9787
9788 if (!this._isBuffer(key))
9789 key = String(key)
9790
9791 if (typeof options != 'object')
9792 options = {}
9793
9794 if (typeof this._del == 'function')
9795 return this._del(key, options, callback)
9796
9797 process.nextTick(callback)
9798}
9799
9800AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
9801 if (!arguments.length)
9802 return this._chainedBatch()
9803
9804 if (typeof options == 'function')
9805 callback = options
9806
9807 if (typeof array == 'function')
9808 callback = array
9809
9810 if (typeof callback != 'function')
9811 throw new Error('batch(array) requires a callback argument')
9812
9813 if (!Array.isArray(array))
9814 return callback(new Error('batch(array) requires an array argument'))
9815
9816 if (!options || typeof options != 'object')
9817 options = {}
9818
9819 var i = 0
9820 , l = array.length
9821 , e
9822 , err
9823
9824 for (; i < l; i++) {
9825 e = array[i]
9826 if (typeof e != 'object')
9827 continue
9828
9829 if (err = this._checkKey(e.type, 'type', this._isBuffer))
9830 return callback(err)
9831
9832 if (err = this._checkKey(e.key, 'key', this._isBuffer))
9833 return callback(err)
9834 }
9835
9836 if (typeof this._batch == 'function')
9837 return this._batch(array, options, callback)
9838
9839 process.nextTick(callback)
9840}
9841
9842//TODO: remove from here, not a necessary primitive
9843AbstractLevelDOWN.prototype.approximateSize = function (start, end, callback) {
9844 if ( start == null
9845 || end == null
9846 || typeof start == 'function'
9847 || typeof end == 'function') {
9848 throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments')
9849 }
9850
9851 if (typeof callback != 'function')
9852 throw new Error('approximateSize() requires a callback argument')
9853
9854 if (!this._isBuffer(start))
9855 start = String(start)
9856
9857 if (!this._isBuffer(end))
9858 end = String(end)
9859
9860 if (typeof this._approximateSize == 'function')
9861 return this._approximateSize(start, end, callback)
9862
9863 process.nextTick(function () {
9864 callback(null, 0)
9865 })
9866}
9867
9868AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
9869 var self = this
9870
9871 options = xtend(options)
9872
9873 ;[ 'start', 'end', 'gt', 'gte', 'lt', 'lte' ].forEach(function (o) {
9874 if (options[o] && self._isBuffer(options[o]) && options[o].length === 0)
9875 delete options[o]
9876 })
9877
9878 options.reverse = !!options.reverse
9879 options.keys = options.keys != false
9880 options.values = options.values != false
9881 options.limit = 'limit' in options ? options.limit : -1
9882 options.keyAsBuffer = options.keyAsBuffer != false
9883 options.valueAsBuffer = options.valueAsBuffer != false
9884
9885 return options
9886}
9887
9888AbstractLevelDOWN.prototype.iterator = function (options) {
9889 if (typeof options != 'object')
9890 options = {}
9891
9892 options = this._setupIteratorOptions(options)
9893
9894 if (typeof this._iterator == 'function')
9895 return this._iterator(options)
9896
9897 return new AbstractIterator(this)
9898}
9899
9900AbstractLevelDOWN.prototype._chainedBatch = function () {
9901 return new AbstractChainedBatch(this)
9902}
9903
9904AbstractLevelDOWN.prototype._isBuffer = function (obj) {
9905 return Buffer.isBuffer(obj)
9906}
9907
9908AbstractLevelDOWN.prototype._checkKey = function (obj, type) {
9909
9910 if (obj === null || obj === undefined)
9911 return new Error(type + ' cannot be `null` or `undefined`')
9912
9913 if (this._isBuffer(obj)) {
9914 if (obj.length === 0)
9915 return new Error(type + ' cannot be an empty Buffer')
9916 } else if (String(obj) === '')
9917 return new Error(type + ' cannot be an empty String')
9918}
9919
9920module.exports = AbstractLevelDOWN
9921
9922}).call(this,{"isBuffer":_dereq_(19)},_dereq_(62))
9923},{"19":19,"48":48,"49":49,"60":60,"62":62}],51:[function(_dereq_,module,exports){
9924exports.AbstractLevelDOWN = _dereq_(50)
9925exports.AbstractIterator = _dereq_(49)
9926exports.AbstractChainedBatch = _dereq_(48)
9927exports.isLevelDOWN = _dereq_(52)
9928
9929},{"48":48,"49":49,"50":50,"52":52}],52:[function(_dereq_,module,exports){
9930var AbstractLevelDOWN = _dereq_(50)
9931
9932function isLevelDOWN (db) {
9933 if (!db || typeof db !== 'object')
9934 return false
9935 return Object.keys(AbstractLevelDOWN.prototype).filter(function (name) {
9936 // TODO remove approximateSize check when method is gone
9937 return name[0] != '_' && name != 'approximateSize'
9938 }).every(function (name) {
9939 return typeof db[name] == 'function'
9940 })
9941}
9942
9943module.exports = isLevelDOWN
9944
9945},{"50":50}],53:[function(_dereq_,module,exports){
9946'use strict';
9947var types = [
9948 _dereq_(56),
9949 _dereq_(55),
9950 _dereq_(54),
9951 _dereq_(57),
9952 _dereq_(58)
9953];
9954var draining;
9955var currentQueue;
9956var queueIndex = -1;
9957var queue = [];
9958var scheduled = false;
9959function cleanUpNextTick() {
9960 if (!draining || !currentQueue) {
9961 return;
9962 }
9963 draining = false;
9964 if (currentQueue.length) {
9965 queue = currentQueue.concat(queue);
9966 } else {
9967 queueIndex = -1;
9968 }
9969 if (queue.length) {
9970 nextTick();
9971 }
9972}
9973
9974//named nextTick for less confusing stack traces
9975function nextTick() {
9976 if (draining) {
9977 return;
9978 }
9979 scheduled = false;
9980 draining = true;
9981 var len = queue.length;
9982 var timeout = setTimeout(cleanUpNextTick);
9983 while (len) {
9984 currentQueue = queue;
9985 queue = [];
9986 while (currentQueue && ++queueIndex < len) {
9987 currentQueue[queueIndex].run();
9988 }
9989 queueIndex = -1;
9990 len = queue.length;
9991 }
9992 currentQueue = null;
9993 queueIndex = -1;
9994 draining = false;
9995 clearTimeout(timeout);
9996}
9997var scheduleDrain;
9998var i = -1;
9999var len = types.length;
10000while (++i < len) {
10001 if (types[i] && types[i].test && types[i].test()) {
10002 scheduleDrain = types[i].install(nextTick);
10003 break;
10004 }
10005}
10006// v8 likes predictible objects
10007function Item(fun, array) {
10008 this.fun = fun;
10009 this.array = array;
10010}
10011Item.prototype.run = function () {
10012 var fun = this.fun;
10013 var array = this.array;
10014 switch (array.length) {
10015 case 0:
10016 return fun();
10017 case 1:
10018 return fun(array[0]);
10019 case 2:
10020 return fun(array[0], array[1]);
10021 case 3:
10022 return fun(array[0], array[1], array[2]);
10023 default:
10024 return fun.apply(null, array);
10025 }
10026
10027};
10028module.exports = immediate;
10029function immediate(task) {
10030 var args = new Array(arguments.length - 1);
10031 if (arguments.length > 1) {
10032 for (var i = 1; i < arguments.length; i++) {
10033 args[i - 1] = arguments[i];
10034 }
10035 }
10036 queue.push(new Item(task, args));
10037 if (!scheduled && !draining) {
10038 scheduled = true;
10039 scheduleDrain();
10040 }
10041}
10042
10043},{"54":54,"55":55,"56":56,"57":57,"58":58}],54:[function(_dereq_,module,exports){
10044(function (global){
10045'use strict';
10046
10047exports.test = function () {
10048 if (global.setImmediate) {
10049 // we can only get here in IE10
10050 // which doesn't handel postMessage well
10051 return false;
10052 }
10053 return typeof global.MessageChannel !== 'undefined';
10054};
10055
10056exports.install = function (func) {
10057 var channel = new global.MessageChannel();
10058 channel.port1.onmessage = func;
10059 return function () {
10060 channel.port2.postMessage(0);
10061 };
10062};
10063}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10064},{}],55:[function(_dereq_,module,exports){
10065(function (global){
10066'use strict';
10067//based off rsvp https://github.com/tildeio/rsvp.js
10068//license https://github.com/tildeio/rsvp.js/blob/master/LICENSE
10069//https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/asap.js
10070
10071var Mutation = global.MutationObserver || global.WebKitMutationObserver;
10072
10073exports.test = function () {
10074 return Mutation;
10075};
10076
10077exports.install = function (handle) {
10078 var called = 0;
10079 var observer = new Mutation(handle);
10080 var element = global.document.createTextNode('');
10081 observer.observe(element, {
10082 characterData: true
10083 });
10084 return function () {
10085 element.data = (called = ++called % 2);
10086 };
10087};
10088}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10089},{}],56:[function(_dereq_,module,exports){
10090(function (process){
10091'use strict';
10092exports.test = function () {
10093 // Don't get fooled by e.g. browserify environments.
10094 return (typeof process !== 'undefined') && !process.browser;
10095};
10096
10097exports.install = function (func) {
10098 return function () {
10099 process.nextTick(func);
10100 };
10101};
10102
10103}).call(this,_dereq_(62))
10104},{"62":62}],57:[function(_dereq_,module,exports){
10105(function (global){
10106'use strict';
10107
10108exports.test = function () {
10109 return 'document' in global && 'onreadystatechange' in global.document.createElement('script');
10110};
10111
10112exports.install = function (handle) {
10113 return function () {
10114
10115 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
10116 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
10117 var scriptEl = global.document.createElement('script');
10118 scriptEl.onreadystatechange = function () {
10119 handle();
10120
10121 scriptEl.onreadystatechange = null;
10122 scriptEl.parentNode.removeChild(scriptEl);
10123 scriptEl = null;
10124 };
10125 global.document.documentElement.appendChild(scriptEl);
10126
10127 return handle;
10128 };
10129};
10130}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10131},{}],58:[function(_dereq_,module,exports){
10132'use strict';
10133exports.test = function () {
10134 return true;
10135};
10136
10137exports.install = function (t) {
10138 return function () {
10139 setTimeout(t, 0);
10140 };
10141};
10142},{}],59:[function(_dereq_,module,exports){
10143(function (Buffer){
10144
10145exports.compare = function (a, b) {
10146
10147 if(Buffer.isBuffer(a)) {
10148 var l = Math.min(a.length, b.length)
10149 for(var i = 0; i < l; i++) {
10150 var cmp = a[i] - b[i]
10151 if(cmp) return cmp
10152 }
10153 return a.length - b.length
10154 }
10155
10156 return a < b ? -1 : a > b ? 1 : 0
10157}
10158
10159function has(obj, key) {
10160 return Object.hasOwnProperty.call(obj, key)
10161}
10162
10163// to be compatible with the current abstract-leveldown tests
10164// nullish or empty strings.
10165// I could use !!val but I want to permit numbers and booleans,
10166// if possible.
10167
10168function isDef (val) {
10169 return val !== undefined && val !== ''
10170}
10171
10172function has (range, name) {
10173 return Object.hasOwnProperty.call(range, name)
10174}
10175
10176function hasKey(range, name) {
10177 return Object.hasOwnProperty.call(range, name) && name
10178}
10179
10180var lowerBoundKey = exports.lowerBoundKey = function (range) {
10181 return (
10182 hasKey(range, 'gt')
10183 || hasKey(range, 'gte')
10184 || hasKey(range, 'min')
10185 || (range.reverse ? hasKey(range, 'end') : hasKey(range, 'start'))
10186 || undefined
10187 )
10188}
10189
10190var lowerBound = exports.lowerBound = function (range) {
10191 var k = lowerBoundKey(range)
10192 return k && range[k]
10193}
10194
10195var lowerBoundInclusive = exports.lowerBoundInclusive = function (range) {
10196 return has(range, 'gt') ? false : true
10197}
10198
10199var upperBoundInclusive = exports.upperBoundInclusive =
10200 function (range) {
10201 return (has(range, 'lt') /*&& !range.maxEx*/) ? false : true
10202 }
10203
10204var lowerBoundExclusive = exports.lowerBoundExclusive =
10205 function (range) {
10206 return !lowerBoundInclusive(range)
10207 }
10208
10209var upperBoundExclusive = exports.upperBoundExclusive =
10210 function (range) {
10211 return !upperBoundInclusive(range)
10212 }
10213
10214var upperBoundKey = exports.upperBoundKey = function (range) {
10215 return (
10216 hasKey(range, 'lt')
10217 || hasKey(range, 'lte')
10218 || hasKey(range, 'max')
10219 || (range.reverse ? hasKey(range, 'start') : hasKey(range, 'end'))
10220 || undefined
10221 )
10222}
10223
10224var upperBound = exports.upperBound = function (range) {
10225 var k = upperBoundKey(range)
10226 return k && range[k]
10227}
10228
10229function id (e) { return e }
10230
10231exports.toLtgt = function (range, _range, map, lower, upper) {
10232 _range = _range || {}
10233 map = map || id
10234 var defaults = arguments.length > 3
10235 var lb = exports.lowerBoundKey(range)
10236 var ub = exports.upperBoundKey(range)
10237 if(lb) {
10238 if(lb === 'gt') _range.gt = map(range.gt, false)
10239 else _range.gte = map(range[lb], false)
10240 }
10241 else if(defaults)
10242 _range.gte = map(lower, false)
10243
10244 if(ub) {
10245 if(ub === 'lt') _range.lt = map(range.lt, true)
10246 else _range.lte = map(range[ub], true)
10247 }
10248 else if(defaults)
10249 _range.lte = map(upper, true)
10250
10251 if(range.reverse != null)
10252 _range.reverse = !!range.reverse
10253
10254 //if range was used mutably
10255 //(in level-sublevel it's part of an options object
10256 //that has more properties on it.)
10257 if(has(_range, 'max')) delete _range.max
10258 if(has(_range, 'min')) delete _range.min
10259 if(has(_range, 'start')) delete _range.start
10260 if(has(_range, 'end')) delete _range.end
10261
10262 return _range
10263}
10264
10265exports.contains = function (range, key, compare) {
10266 compare = compare || exports.compare
10267
10268 var lb = lowerBound(range)
10269 if(isDef(lb)) {
10270 var cmp = compare(key, lb)
10271 if(cmp < 0 || (cmp === 0 && lowerBoundExclusive(range)))
10272 return false
10273 }
10274
10275 var ub = upperBound(range)
10276 if(isDef(ub)) {
10277 var cmp = compare(key, ub)
10278 if(cmp > 0 || (cmp === 0) && upperBoundExclusive(range))
10279 return false
10280 }
10281
10282 return true
10283}
10284
10285exports.filter = function (range, compare) {
10286 return function (key) {
10287 return exports.contains(range, key, compare)
10288 }
10289}
10290
10291
10292
10293
10294
10295
10296}).call(this,{"isBuffer":_dereq_(19)})
10297},{"19":19}],60:[function(_dereq_,module,exports){
10298arguments[4][33][0].apply(exports,arguments)
10299},{"33":33}],61:[function(_dereq_,module,exports){
10300(function (process){
10301'use strict';
10302
10303if (!process.version ||
10304 process.version.indexOf('v0.') === 0 ||
10305 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
10306 module.exports = { nextTick: nextTick };
10307} else {
10308 module.exports = process
10309}
10310
10311function nextTick(fn, arg1, arg2, arg3) {
10312 if (typeof fn !== 'function') {
10313 throw new TypeError('"callback" argument must be a function');
10314 }
10315 var len = arguments.length;
10316 var args, i;
10317 switch (len) {
10318 case 0:
10319 case 1:
10320 return process.nextTick(fn);
10321 case 2:
10322 return process.nextTick(function afterTickOne() {
10323 fn.call(null, arg1);
10324 });
10325 case 3:
10326 return process.nextTick(function afterTickTwo() {
10327 fn.call(null, arg1, arg2);
10328 });
10329 case 4:
10330 return process.nextTick(function afterTickThree() {
10331 fn.call(null, arg1, arg2, arg3);
10332 });
10333 default:
10334 args = new Array(len - 1);
10335 i = 0;
10336 while (i < args.length) {
10337 args[i++] = arguments[i];
10338 }
10339 return process.nextTick(function afterTick() {
10340 fn.apply(null, args);
10341 });
10342 }
10343}
10344
10345
10346}).call(this,_dereq_(62))
10347},{"62":62}],62:[function(_dereq_,module,exports){
10348// shim for using process in browser
10349var process = module.exports = {};
10350
10351// cached from whatever global is present so that test runners that stub it
10352// don't break things. But we need to wrap it in a try catch in case it is
10353// wrapped in strict mode code which doesn't define any globals. It's inside a
10354// function because try/catches deoptimize in certain engines.
10355
10356var cachedSetTimeout;
10357var cachedClearTimeout;
10358
10359function defaultSetTimout() {
10360 throw new Error('setTimeout has not been defined');
10361}
10362function defaultClearTimeout () {
10363 throw new Error('clearTimeout has not been defined');
10364}
10365(function () {
10366 try {
10367 if (typeof setTimeout === 'function') {
10368 cachedSetTimeout = setTimeout;
10369 } else {
10370 cachedSetTimeout = defaultSetTimout;
10371 }
10372 } catch (e) {
10373 cachedSetTimeout = defaultSetTimout;
10374 }
10375 try {
10376 if (typeof clearTimeout === 'function') {
10377 cachedClearTimeout = clearTimeout;
10378 } else {
10379 cachedClearTimeout = defaultClearTimeout;
10380 }
10381 } catch (e) {
10382 cachedClearTimeout = defaultClearTimeout;
10383 }
10384} ())
10385function runTimeout(fun) {
10386 if (cachedSetTimeout === setTimeout) {
10387 //normal enviroments in sane situations
10388 return setTimeout(fun, 0);
10389 }
10390 // if setTimeout wasn't available but was latter defined
10391 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
10392 cachedSetTimeout = setTimeout;
10393 return setTimeout(fun, 0);
10394 }
10395 try {
10396 // when when somebody has screwed with setTimeout but no I.E. maddness
10397 return cachedSetTimeout(fun, 0);
10398 } catch(e){
10399 try {
10400 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
10401 return cachedSetTimeout.call(null, fun, 0);
10402 } catch(e){
10403 // 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
10404 return cachedSetTimeout.call(this, fun, 0);
10405 }
10406 }
10407
10408
10409}
10410function runClearTimeout(marker) {
10411 if (cachedClearTimeout === clearTimeout) {
10412 //normal enviroments in sane situations
10413 return clearTimeout(marker);
10414 }
10415 // if clearTimeout wasn't available but was latter defined
10416 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
10417 cachedClearTimeout = clearTimeout;
10418 return clearTimeout(marker);
10419 }
10420 try {
10421 // when when somebody has screwed with setTimeout but no I.E. maddness
10422 return cachedClearTimeout(marker);
10423 } catch (e){
10424 try {
10425 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
10426 return cachedClearTimeout.call(null, marker);
10427 } catch (e){
10428 // 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.
10429 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
10430 return cachedClearTimeout.call(this, marker);
10431 }
10432 }
10433
10434
10435
10436}
10437var queue = [];
10438var draining = false;
10439var currentQueue;
10440var queueIndex = -1;
10441
10442function cleanUpNextTick() {
10443 if (!draining || !currentQueue) {
10444 return;
10445 }
10446 draining = false;
10447 if (currentQueue.length) {
10448 queue = currentQueue.concat(queue);
10449 } else {
10450 queueIndex = -1;
10451 }
10452 if (queue.length) {
10453 drainQueue();
10454 }
10455}
10456
10457function drainQueue() {
10458 if (draining) {
10459 return;
10460 }
10461 var timeout = runTimeout(cleanUpNextTick);
10462 draining = true;
10463
10464 var len = queue.length;
10465 while(len) {
10466 currentQueue = queue;
10467 queue = [];
10468 while (++queueIndex < len) {
10469 if (currentQueue) {
10470 currentQueue[queueIndex].run();
10471 }
10472 }
10473 queueIndex = -1;
10474 len = queue.length;
10475 }
10476 currentQueue = null;
10477 draining = false;
10478 runClearTimeout(timeout);
10479}
10480
10481process.nextTick = function (fun) {
10482 var args = new Array(arguments.length - 1);
10483 if (arguments.length > 1) {
10484 for (var i = 1; i < arguments.length; i++) {
10485 args[i - 1] = arguments[i];
10486 }
10487 }
10488 queue.push(new Item(fun, args));
10489 if (queue.length === 1 && !draining) {
10490 runTimeout(drainQueue);
10491 }
10492};
10493
10494// v8 likes predictible objects
10495function Item(fun, array) {
10496 this.fun = fun;
10497 this.array = array;
10498}
10499Item.prototype.run = function () {
10500 this.fun.apply(null, this.array);
10501};
10502process.title = 'browser';
10503process.browser = true;
10504process.env = {};
10505process.argv = [];
10506process.version = ''; // empty string to avoid regexp issues
10507process.versions = {};
10508
10509function noop() {}
10510
10511process.on = noop;
10512process.addListener = noop;
10513process.once = noop;
10514process.off = noop;
10515process.removeListener = noop;
10516process.removeAllListeners = noop;
10517process.emit = noop;
10518process.prependListener = noop;
10519process.prependOnceListener = noop;
10520
10521process.listeners = function (name) { return [] }
10522
10523process.binding = function (name) {
10524 throw new Error('process.binding is not supported');
10525};
10526
10527process.cwd = function () { return '/' };
10528process.chdir = function (dir) {
10529 throw new Error('process.chdir is not supported');
10530};
10531process.umask = function() { return 0; };
10532
10533},{}],63:[function(_dereq_,module,exports){
10534/*!
10535 * prr
10536 * (c) 2013 Rod Vagg <rod@vagg.org>
10537 * https://github.com/rvagg/prr
10538 * License: MIT
10539 */
10540
10541(function (name, context, definition) {
10542 if (typeof module != 'undefined' && module.exports)
10543 module.exports = definition()
10544 else
10545 context[name] = definition()
10546})('prr', this, function() {
10547
10548 var setProperty = typeof Object.defineProperty == 'function'
10549 ? function (obj, key, options) {
10550 Object.defineProperty(obj, key, options)
10551 return obj
10552 }
10553 : function (obj, key, options) { // < es5
10554 obj[key] = options.value
10555 return obj
10556 }
10557
10558 , makeOptions = function (value, options) {
10559 var oo = typeof options == 'object'
10560 , os = !oo && typeof options == 'string'
10561 , op = function (p) {
10562 return oo
10563 ? !!options[p]
10564 : os
10565 ? options.indexOf(p[0]) > -1
10566 : false
10567 }
10568
10569 return {
10570 enumerable : op('enumerable')
10571 , configurable : op('configurable')
10572 , writable : op('writable')
10573 , value : value
10574 }
10575 }
10576
10577 , prr = function (obj, key, value, options) {
10578 var k
10579
10580 options = makeOptions(value, options)
10581
10582 if (typeof key == 'object') {
10583 for (k in key) {
10584 if (Object.hasOwnProperty.call(key, k)) {
10585 options.value = key[k]
10586 setProperty(obj, k, options)
10587 }
10588 }
10589 return obj
10590 }
10591
10592 return setProperty(obj, key, options)
10593 }
10594
10595 return prr
10596})
10597},{}],64:[function(_dereq_,module,exports){
10598(function (process){
10599// Copyright Joyent, Inc. and other Node contributors.
10600//
10601// Permission is hereby granted, free of charge, to any person obtaining a
10602// copy of this software and associated documentation files (the
10603// "Software"), to deal in the Software without restriction, including
10604// without limitation the rights to use, copy, modify, merge, publish,
10605// distribute, sublicense, and/or sell copies of the Software, and to permit
10606// persons to whom the Software is furnished to do so, subject to the
10607// following conditions:
10608//
10609// The above copyright notice and this permission notice shall be included
10610// in all copies or substantial portions of the Software.
10611//
10612// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
10613// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
10614// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
10615// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
10616// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
10617// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
10618// USE OR OTHER DEALINGS IN THE SOFTWARE.
10619
10620// a duplex stream is just a stream that is both readable and writable.
10621// Since JS doesn't have multiple prototypal inheritance, this class
10622// prototypally inherits from Readable, and then parasitically from
10623// Writable.
10624
10625module.exports = Duplex;
10626
10627/*<replacement>*/
10628var objectKeys = Object.keys || function (obj) {
10629 var keys = [];
10630 for (var key in obj) keys.push(key);
10631 return keys;
10632}
10633/*</replacement>*/
10634
10635
10636/*<replacement>*/
10637var util = _dereq_(10);
10638util.inherits = _dereq_(18);
10639/*</replacement>*/
10640
10641var Readable = _dereq_(66);
10642var Writable = _dereq_(68);
10643
10644util.inherits(Duplex, Readable);
10645
10646forEach(objectKeys(Writable.prototype), function(method) {
10647 if (!Duplex.prototype[method])
10648 Duplex.prototype[method] = Writable.prototype[method];
10649});
10650
10651function Duplex(options) {
10652 if (!(this instanceof Duplex))
10653 return new Duplex(options);
10654
10655 Readable.call(this, options);
10656 Writable.call(this, options);
10657
10658 if (options && options.readable === false)
10659 this.readable = false;
10660
10661 if (options && options.writable === false)
10662 this.writable = false;
10663
10664 this.allowHalfOpen = true;
10665 if (options && options.allowHalfOpen === false)
10666 this.allowHalfOpen = false;
10667
10668 this.once('end', onend);
10669}
10670
10671// the no-half-open enforcer
10672function onend() {
10673 // if we allow half-open state, or if the writable side ended,
10674 // then we're ok.
10675 if (this.allowHalfOpen || this._writableState.ended)
10676 return;
10677
10678 // no more data can be written.
10679 // But allow more writes to happen in this tick.
10680 process.nextTick(this.end.bind(this));
10681}
10682
10683function forEach (xs, f) {
10684 for (var i = 0, l = xs.length; i < l; i++) {
10685 f(xs[i], i);
10686 }
10687}
10688
10689}).call(this,_dereq_(62))
10690},{"10":10,"18":18,"62":62,"66":66,"68":68}],65:[function(_dereq_,module,exports){
10691// Copyright Joyent, Inc. and other Node contributors.
10692//
10693// Permission is hereby granted, free of charge, to any person obtaining a
10694// copy of this software and associated documentation files (the
10695// "Software"), to deal in the Software without restriction, including
10696// without limitation the rights to use, copy, modify, merge, publish,
10697// distribute, sublicense, and/or sell copies of the Software, and to permit
10698// persons to whom the Software is furnished to do so, subject to the
10699// following conditions:
10700//
10701// The above copyright notice and this permission notice shall be included
10702// in all copies or substantial portions of the Software.
10703//
10704// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
10705// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
10706// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
10707// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
10708// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
10709// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
10710// USE OR OTHER DEALINGS IN THE SOFTWARE.
10711
10712// a passthrough stream.
10713// basically just the most minimal sort of Transform stream.
10714// Every written chunk gets output as-is.
10715
10716module.exports = PassThrough;
10717
10718var Transform = _dereq_(67);
10719
10720/*<replacement>*/
10721var util = _dereq_(10);
10722util.inherits = _dereq_(18);
10723/*</replacement>*/
10724
10725util.inherits(PassThrough, Transform);
10726
10727function PassThrough(options) {
10728 if (!(this instanceof PassThrough))
10729 return new PassThrough(options);
10730
10731 Transform.call(this, options);
10732}
10733
10734PassThrough.prototype._transform = function(chunk, encoding, cb) {
10735 cb(null, chunk);
10736};
10737
10738},{"10":10,"18":18,"67":67}],66:[function(_dereq_,module,exports){
10739(function (process){
10740// Copyright Joyent, Inc. and other Node contributors.
10741//
10742// Permission is hereby granted, free of charge, to any person obtaining a
10743// copy of this software and associated documentation files (the
10744// "Software"), to deal in the Software without restriction, including
10745// without limitation the rights to use, copy, modify, merge, publish,
10746// distribute, sublicense, and/or sell copies of the Software, and to permit
10747// persons to whom the Software is furnished to do so, subject to the
10748// following conditions:
10749//
10750// The above copyright notice and this permission notice shall be included
10751// in all copies or substantial portions of the Software.
10752//
10753// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
10754// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
10755// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
10756// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
10757// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
10758// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
10759// USE OR OTHER DEALINGS IN THE SOFTWARE.
10760
10761module.exports = Readable;
10762
10763/*<replacement>*/
10764var isArray = _dereq_(69);
10765/*</replacement>*/
10766
10767
10768/*<replacement>*/
10769var Buffer = _dereq_(9).Buffer;
10770/*</replacement>*/
10771
10772Readable.ReadableState = ReadableState;
10773
10774var EE = _dereq_(14).EventEmitter;
10775
10776/*<replacement>*/
10777if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
10778 return emitter.listeners(type).length;
10779};
10780/*</replacement>*/
10781
10782var Stream = _dereq_(74);
10783
10784/*<replacement>*/
10785var util = _dereq_(10);
10786util.inherits = _dereq_(18);
10787/*</replacement>*/
10788
10789var StringDecoder;
10790
10791util.inherits(Readable, Stream);
10792
10793function ReadableState(options, stream) {
10794 options = options || {};
10795
10796 // the point at which it stops calling _read() to fill the buffer
10797 // Note: 0 is a valid value, means "don't call _read preemptively ever"
10798 var hwm = options.highWaterMark;
10799 this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
10800
10801 // cast to ints.
10802 this.highWaterMark = ~~this.highWaterMark;
10803
10804 this.buffer = [];
10805 this.length = 0;
10806 this.pipes = null;
10807 this.pipesCount = 0;
10808 this.flowing = false;
10809 this.ended = false;
10810 this.endEmitted = false;
10811 this.reading = false;
10812
10813 // In streams that never have any data, and do push(null) right away,
10814 // the consumer can miss the 'end' event if they do some I/O before
10815 // consuming the stream. So, we don't emit('end') until some reading
10816 // happens.
10817 this.calledRead = false;
10818
10819 // a flag to be able to tell if the onwrite cb is called immediately,
10820 // or on a later tick. We set this to true at first, becuase any
10821 // actions that shouldn't happen until "later" should generally also
10822 // not happen before the first write call.
10823 this.sync = true;
10824
10825 // whenever we return null, then we set a flag to say
10826 // that we're awaiting a 'readable' event emission.
10827 this.needReadable = false;
10828 this.emittedReadable = false;
10829 this.readableListening = false;
10830
10831
10832 // object stream flag. Used to make read(n) ignore n and to
10833 // make all the buffer merging and length checks go away
10834 this.objectMode = !!options.objectMode;
10835
10836 // Crypto is kind of old and crusty. Historically, its default string
10837 // encoding is 'binary' so we have to make this configurable.
10838 // Everything else in the universe uses 'utf8', though.
10839 this.defaultEncoding = options.defaultEncoding || 'utf8';
10840
10841 // when piping, we only care about 'readable' events that happen
10842 // after read()ing all the bytes and not getting any pushback.
10843 this.ranOut = false;
10844
10845 // the number of writers that are awaiting a drain event in .pipe()s
10846 this.awaitDrain = 0;
10847
10848 // if true, a maybeReadMore has been scheduled
10849 this.readingMore = false;
10850
10851 this.decoder = null;
10852 this.encoding = null;
10853 if (options.encoding) {
10854 if (!StringDecoder)
10855 StringDecoder = _dereq_(70).StringDecoder;
10856 this.decoder = new StringDecoder(options.encoding);
10857 this.encoding = options.encoding;
10858 }
10859}
10860
10861function Readable(options) {
10862 if (!(this instanceof Readable))
10863 return new Readable(options);
10864
10865 this._readableState = new ReadableState(options, this);
10866
10867 // legacy
10868 this.readable = true;
10869
10870 Stream.call(this);
10871}
10872
10873// Manually shove something into the read() buffer.
10874// This returns true if the highWaterMark has not been hit yet,
10875// similar to how Writable.write() returns true if you should
10876// write() some more.
10877Readable.prototype.push = function(chunk, encoding) {
10878 var state = this._readableState;
10879
10880 if (typeof chunk === 'string' && !state.objectMode) {
10881 encoding = encoding || state.defaultEncoding;
10882 if (encoding !== state.encoding) {
10883 chunk = new Buffer(chunk, encoding);
10884 encoding = '';
10885 }
10886 }
10887
10888 return readableAddChunk(this, state, chunk, encoding, false);
10889};
10890
10891// Unshift should *always* be something directly out of read()
10892Readable.prototype.unshift = function(chunk) {
10893 var state = this._readableState;
10894 return readableAddChunk(this, state, chunk, '', true);
10895};
10896
10897function readableAddChunk(stream, state, chunk, encoding, addToFront) {
10898 var er = chunkInvalid(state, chunk);
10899 if (er) {
10900 stream.emit('error', er);
10901 } else if (chunk === null || chunk === undefined) {
10902 state.reading = false;
10903 if (!state.ended)
10904 onEofChunk(stream, state);
10905 } else if (state.objectMode || chunk && chunk.length > 0) {
10906 if (state.ended && !addToFront) {
10907 var e = new Error('stream.push() after EOF');
10908 stream.emit('error', e);
10909 } else if (state.endEmitted && addToFront) {
10910 var e = new Error('stream.unshift() after end event');
10911 stream.emit('error', e);
10912 } else {
10913 if (state.decoder && !addToFront && !encoding)
10914 chunk = state.decoder.write(chunk);
10915
10916 // update the buffer info.
10917 state.length += state.objectMode ? 1 : chunk.length;
10918 if (addToFront) {
10919 state.buffer.unshift(chunk);
10920 } else {
10921 state.reading = false;
10922 state.buffer.push(chunk);
10923 }
10924
10925 if (state.needReadable)
10926 emitReadable(stream);
10927
10928 maybeReadMore(stream, state);
10929 }
10930 } else if (!addToFront) {
10931 state.reading = false;
10932 }
10933
10934 return needMoreData(state);
10935}
10936
10937
10938
10939// if it's past the high water mark, we can push in some more.
10940// Also, if we have no data yet, we can stand some
10941// more bytes. This is to work around cases where hwm=0,
10942// such as the repl. Also, if the push() triggered a
10943// readable event, and the user called read(largeNumber) such that
10944// needReadable was set, then we ought to push more, so that another
10945// 'readable' event will be triggered.
10946function needMoreData(state) {
10947 return !state.ended &&
10948 (state.needReadable ||
10949 state.length < state.highWaterMark ||
10950 state.length === 0);
10951}
10952
10953// backwards compatibility.
10954Readable.prototype.setEncoding = function(enc) {
10955 if (!StringDecoder)
10956 StringDecoder = _dereq_(70).StringDecoder;
10957 this._readableState.decoder = new StringDecoder(enc);
10958 this._readableState.encoding = enc;
10959};
10960
10961// Don't raise the hwm > 128MB
10962var MAX_HWM = 0x800000;
10963function roundUpToNextPowerOf2(n) {
10964 if (n >= MAX_HWM) {
10965 n = MAX_HWM;
10966 } else {
10967 // Get the next highest power of 2
10968 n--;
10969 for (var p = 1; p < 32; p <<= 1) n |= n >> p;
10970 n++;
10971 }
10972 return n;
10973}
10974
10975function howMuchToRead(n, state) {
10976 if (state.length === 0 && state.ended)
10977 return 0;
10978
10979 if (state.objectMode)
10980 return n === 0 ? 0 : 1;
10981
10982 if (n === null || isNaN(n)) {
10983 // only flow one buffer at a time
10984 if (state.flowing && state.buffer.length)
10985 return state.buffer[0].length;
10986 else
10987 return state.length;
10988 }
10989
10990 if (n <= 0)
10991 return 0;
10992
10993 // If we're asking for more than the target buffer level,
10994 // then raise the water mark. Bump up to the next highest
10995 // power of 2, to prevent increasing it excessively in tiny
10996 // amounts.
10997 if (n > state.highWaterMark)
10998 state.highWaterMark = roundUpToNextPowerOf2(n);
10999
11000 // don't have that much. return null, unless we've ended.
11001 if (n > state.length) {
11002 if (!state.ended) {
11003 state.needReadable = true;
11004 return 0;
11005 } else
11006 return state.length;
11007 }
11008
11009 return n;
11010}
11011
11012// you can override either this method, or the async _read(n) below.
11013Readable.prototype.read = function(n) {
11014 var state = this._readableState;
11015 state.calledRead = true;
11016 var nOrig = n;
11017 var ret;
11018
11019 if (typeof n !== 'number' || n > 0)
11020 state.emittedReadable = false;
11021
11022 // if we're doing read(0) to trigger a readable event, but we
11023 // already have a bunch of data in the buffer, then just trigger
11024 // the 'readable' event and move on.
11025 if (n === 0 &&
11026 state.needReadable &&
11027 (state.length >= state.highWaterMark || state.ended)) {
11028 emitReadable(this);
11029 return null;
11030 }
11031
11032 n = howMuchToRead(n, state);
11033
11034 // if we've ended, and we're now clear, then finish it up.
11035 if (n === 0 && state.ended) {
11036 ret = null;
11037
11038 // In cases where the decoder did not receive enough data
11039 // to produce a full chunk, then immediately received an
11040 // EOF, state.buffer will contain [<Buffer >, <Buffer 00 ...>].
11041 // howMuchToRead will see this and coerce the amount to
11042 // read to zero (because it's looking at the length of the
11043 // first <Buffer > in state.buffer), and we'll end up here.
11044 //
11045 // This can only happen via state.decoder -- no other venue
11046 // exists for pushing a zero-length chunk into state.buffer
11047 // and triggering this behavior. In this case, we return our
11048 // remaining data and end the stream, if appropriate.
11049 if (state.length > 0 && state.decoder) {
11050 ret = fromList(n, state);
11051 state.length -= ret.length;
11052 }
11053
11054 if (state.length === 0)
11055 endReadable(this);
11056
11057 return ret;
11058 }
11059
11060 // All the actual chunk generation logic needs to be
11061 // *below* the call to _read. The reason is that in certain
11062 // synthetic stream cases, such as passthrough streams, _read
11063 // may be a completely synchronous operation which may change
11064 // the state of the read buffer, providing enough data when
11065 // before there was *not* enough.
11066 //
11067 // So, the steps are:
11068 // 1. Figure out what the state of things will be after we do
11069 // a read from the buffer.
11070 //
11071 // 2. If that resulting state will trigger a _read, then call _read.
11072 // Note that this may be asynchronous, or synchronous. Yes, it is
11073 // deeply ugly to write APIs this way, but that still doesn't mean
11074 // that the Readable class should behave improperly, as streams are
11075 // designed to be sync/async agnostic.
11076 // Take note if the _read call is sync or async (ie, if the read call
11077 // has returned yet), so that we know whether or not it's safe to emit
11078 // 'readable' etc.
11079 //
11080 // 3. Actually pull the requested chunks out of the buffer and return.
11081
11082 // if we need a readable event, then we need to do some reading.
11083 var doRead = state.needReadable;
11084
11085 // if we currently have less than the highWaterMark, then also read some
11086 if (state.length - n <= state.highWaterMark)
11087 doRead = true;
11088
11089 // however, if we've ended, then there's no point, and if we're already
11090 // reading, then it's unnecessary.
11091 if (state.ended || state.reading)
11092 doRead = false;
11093
11094 if (doRead) {
11095 state.reading = true;
11096 state.sync = true;
11097 // if the length is currently zero, then we *need* a readable event.
11098 if (state.length === 0)
11099 state.needReadable = true;
11100 // call internal read method
11101 this._read(state.highWaterMark);
11102 state.sync = false;
11103 }
11104
11105 // If _read called its callback synchronously, then `reading`
11106 // will be false, and we need to re-evaluate how much data we
11107 // can return to the user.
11108 if (doRead && !state.reading)
11109 n = howMuchToRead(nOrig, state);
11110
11111 if (n > 0)
11112 ret = fromList(n, state);
11113 else
11114 ret = null;
11115
11116 if (ret === null) {
11117 state.needReadable = true;
11118 n = 0;
11119 }
11120
11121 state.length -= n;
11122
11123 // If we have nothing in the buffer, then we want to know
11124 // as soon as we *do* get something into the buffer.
11125 if (state.length === 0 && !state.ended)
11126 state.needReadable = true;
11127
11128 // If we happened to read() exactly the remaining amount in the
11129 // buffer, and the EOF has been seen at this point, then make sure
11130 // that we emit 'end' on the very next tick.
11131 if (state.ended && !state.endEmitted && state.length === 0)
11132 endReadable(this);
11133
11134 return ret;
11135};
11136
11137function chunkInvalid(state, chunk) {
11138 var er = null;
11139 if (!Buffer.isBuffer(chunk) &&
11140 'string' !== typeof chunk &&
11141 chunk !== null &&
11142 chunk !== undefined &&
11143 !state.objectMode) {
11144 er = new TypeError('Invalid non-string/buffer chunk');
11145 }
11146 return er;
11147}
11148
11149
11150function onEofChunk(stream, state) {
11151 if (state.decoder && !state.ended) {
11152 var chunk = state.decoder.end();
11153 if (chunk && chunk.length) {
11154 state.buffer.push(chunk);
11155 state.length += state.objectMode ? 1 : chunk.length;
11156 }
11157 }
11158 state.ended = true;
11159
11160 // if we've ended and we have some data left, then emit
11161 // 'readable' now to make sure it gets picked up.
11162 if (state.length > 0)
11163 emitReadable(stream);
11164 else
11165 endReadable(stream);
11166}
11167
11168// Don't emit readable right away in sync mode, because this can trigger
11169// another read() call => stack overflow. This way, it might trigger
11170// a nextTick recursion warning, but that's not so bad.
11171function emitReadable(stream) {
11172 var state = stream._readableState;
11173 state.needReadable = false;
11174 if (state.emittedReadable)
11175 return;
11176
11177 state.emittedReadable = true;
11178 if (state.sync)
11179 process.nextTick(function() {
11180 emitReadable_(stream);
11181 });
11182 else
11183 emitReadable_(stream);
11184}
11185
11186function emitReadable_(stream) {
11187 stream.emit('readable');
11188}
11189
11190
11191// at this point, the user has presumably seen the 'readable' event,
11192// and called read() to consume some data. that may have triggered
11193// in turn another _read(n) call, in which case reading = true if
11194// it's in progress.
11195// However, if we're not ended, or reading, and the length < hwm,
11196// then go ahead and try to read some more preemptively.
11197function maybeReadMore(stream, state) {
11198 if (!state.readingMore) {
11199 state.readingMore = true;
11200 process.nextTick(function() {
11201 maybeReadMore_(stream, state);
11202 });
11203 }
11204}
11205
11206function maybeReadMore_(stream, state) {
11207 var len = state.length;
11208 while (!state.reading && !state.flowing && !state.ended &&
11209 state.length < state.highWaterMark) {
11210 stream.read(0);
11211 if (len === state.length)
11212 // didn't get any data, stop spinning.
11213 break;
11214 else
11215 len = state.length;
11216 }
11217 state.readingMore = false;
11218}
11219
11220// abstract method. to be overridden in specific implementation classes.
11221// call cb(er, data) where data is <= n in length.
11222// for virtual (non-string, non-buffer) streams, "length" is somewhat
11223// arbitrary, and perhaps not very meaningful.
11224Readable.prototype._read = function(n) {
11225 this.emit('error', new Error('not implemented'));
11226};
11227
11228Readable.prototype.pipe = function(dest, pipeOpts) {
11229 var src = this;
11230 var state = this._readableState;
11231
11232 switch (state.pipesCount) {
11233 case 0:
11234 state.pipes = dest;
11235 break;
11236 case 1:
11237 state.pipes = [state.pipes, dest];
11238 break;
11239 default:
11240 state.pipes.push(dest);
11241 break;
11242 }
11243 state.pipesCount += 1;
11244
11245 var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
11246 dest !== process.stdout &&
11247 dest !== process.stderr;
11248
11249 var endFn = doEnd ? onend : cleanup;
11250 if (state.endEmitted)
11251 process.nextTick(endFn);
11252 else
11253 src.once('end', endFn);
11254
11255 dest.on('unpipe', onunpipe);
11256 function onunpipe(readable) {
11257 if (readable !== src) return;
11258 cleanup();
11259 }
11260
11261 function onend() {
11262 dest.end();
11263 }
11264
11265 // when the dest drains, it reduces the awaitDrain counter
11266 // on the source. This would be more elegant with a .once()
11267 // handler in flow(), but adding and removing repeatedly is
11268 // too slow.
11269 var ondrain = pipeOnDrain(src);
11270 dest.on('drain', ondrain);
11271
11272 function cleanup() {
11273 // cleanup event handlers once the pipe is broken
11274 dest.removeListener('close', onclose);
11275 dest.removeListener('finish', onfinish);
11276 dest.removeListener('drain', ondrain);
11277 dest.removeListener('error', onerror);
11278 dest.removeListener('unpipe', onunpipe);
11279 src.removeListener('end', onend);
11280 src.removeListener('end', cleanup);
11281
11282 // if the reader is waiting for a drain event from this
11283 // specific writer, then it would cause it to never start
11284 // flowing again.
11285 // So, if this is awaiting a drain, then we just call it now.
11286 // If we don't know, then assume that we are waiting for one.
11287 if (!dest._writableState || dest._writableState.needDrain)
11288 ondrain();
11289 }
11290
11291 // if the dest has an error, then stop piping into it.
11292 // however, don't suppress the throwing behavior for this.
11293 function onerror(er) {
11294 unpipe();
11295 dest.removeListener('error', onerror);
11296 if (EE.listenerCount(dest, 'error') === 0)
11297 dest.emit('error', er);
11298 }
11299 // This is a brutally ugly hack to make sure that our error handler
11300 // is attached before any userland ones. NEVER DO THIS.
11301 if (!dest._events || !dest._events.error)
11302 dest.on('error', onerror);
11303 else if (isArray(dest._events.error))
11304 dest._events.error.unshift(onerror);
11305 else
11306 dest._events.error = [onerror, dest._events.error];
11307
11308
11309
11310 // Both close and finish should trigger unpipe, but only once.
11311 function onclose() {
11312 dest.removeListener('finish', onfinish);
11313 unpipe();
11314 }
11315 dest.once('close', onclose);
11316 function onfinish() {
11317 dest.removeListener('close', onclose);
11318 unpipe();
11319 }
11320 dest.once('finish', onfinish);
11321
11322 function unpipe() {
11323 src.unpipe(dest);
11324 }
11325
11326 // tell the dest that it's being piped to
11327 dest.emit('pipe', src);
11328
11329 // start the flow if it hasn't been started already.
11330 if (!state.flowing) {
11331 // the handler that waits for readable events after all
11332 // the data gets sucked out in flow.
11333 // This would be easier to follow with a .once() handler
11334 // in flow(), but that is too slow.
11335 this.on('readable', pipeOnReadable);
11336
11337 state.flowing = true;
11338 process.nextTick(function() {
11339 flow(src);
11340 });
11341 }
11342
11343 return dest;
11344};
11345
11346function pipeOnDrain(src) {
11347 return function() {
11348 var dest = this;
11349 var state = src._readableState;
11350 state.awaitDrain--;
11351 if (state.awaitDrain === 0)
11352 flow(src);
11353 };
11354}
11355
11356function flow(src) {
11357 var state = src._readableState;
11358 var chunk;
11359 state.awaitDrain = 0;
11360
11361 function write(dest, i, list) {
11362 var written = dest.write(chunk);
11363 if (false === written) {
11364 state.awaitDrain++;
11365 }
11366 }
11367
11368 while (state.pipesCount && null !== (chunk = src.read())) {
11369
11370 if (state.pipesCount === 1)
11371 write(state.pipes, 0, null);
11372 else
11373 forEach(state.pipes, write);
11374
11375 src.emit('data', chunk);
11376
11377 // if anyone needs a drain, then we have to wait for that.
11378 if (state.awaitDrain > 0)
11379 return;
11380 }
11381
11382 // if every destination was unpiped, either before entering this
11383 // function, or in the while loop, then stop flowing.
11384 //
11385 // NB: This is a pretty rare edge case.
11386 if (state.pipesCount === 0) {
11387 state.flowing = false;
11388
11389 // if there were data event listeners added, then switch to old mode.
11390 if (EE.listenerCount(src, 'data') > 0)
11391 emitDataEvents(src);
11392 return;
11393 }
11394
11395 // at this point, no one needed a drain, so we just ran out of data
11396 // on the next readable event, start it over again.
11397 state.ranOut = true;
11398}
11399
11400function pipeOnReadable() {
11401 if (this._readableState.ranOut) {
11402 this._readableState.ranOut = false;
11403 flow(this);
11404 }
11405}
11406
11407
11408Readable.prototype.unpipe = function(dest) {
11409 var state = this._readableState;
11410
11411 // if we're not piping anywhere, then do nothing.
11412 if (state.pipesCount === 0)
11413 return this;
11414
11415 // just one destination. most common case.
11416 if (state.pipesCount === 1) {
11417 // passed in one, but it's not the right one.
11418 if (dest && dest !== state.pipes)
11419 return this;
11420
11421 if (!dest)
11422 dest = state.pipes;
11423
11424 // got a match.
11425 state.pipes = null;
11426 state.pipesCount = 0;
11427 this.removeListener('readable', pipeOnReadable);
11428 state.flowing = false;
11429 if (dest)
11430 dest.emit('unpipe', this);
11431 return this;
11432 }
11433
11434 // slow case. multiple pipe destinations.
11435
11436 if (!dest) {
11437 // remove all.
11438 var dests = state.pipes;
11439 var len = state.pipesCount;
11440 state.pipes = null;
11441 state.pipesCount = 0;
11442 this.removeListener('readable', pipeOnReadable);
11443 state.flowing = false;
11444
11445 for (var i = 0; i < len; i++)
11446 dests[i].emit('unpipe', this);
11447 return this;
11448 }
11449
11450 // try to find the right one.
11451 var i = indexOf(state.pipes, dest);
11452 if (i === -1)
11453 return this;
11454
11455 state.pipes.splice(i, 1);
11456 state.pipesCount -= 1;
11457 if (state.pipesCount === 1)
11458 state.pipes = state.pipes[0];
11459
11460 dest.emit('unpipe', this);
11461
11462 return this;
11463};
11464
11465// set up data events if they are asked for
11466// Ensure readable listeners eventually get something
11467Readable.prototype.on = function(ev, fn) {
11468 var res = Stream.prototype.on.call(this, ev, fn);
11469
11470 if (ev === 'data' && !this._readableState.flowing)
11471 emitDataEvents(this);
11472
11473 if (ev === 'readable' && this.readable) {
11474 var state = this._readableState;
11475 if (!state.readableListening) {
11476 state.readableListening = true;
11477 state.emittedReadable = false;
11478 state.needReadable = true;
11479 if (!state.reading) {
11480 this.read(0);
11481 } else if (state.length) {
11482 emitReadable(this, state);
11483 }
11484 }
11485 }
11486
11487 return res;
11488};
11489Readable.prototype.addListener = Readable.prototype.on;
11490
11491// pause() and resume() are remnants of the legacy readable stream API
11492// If the user uses them, then switch into old mode.
11493Readable.prototype.resume = function() {
11494 emitDataEvents(this);
11495 this.read(0);
11496 this.emit('resume');
11497};
11498
11499Readable.prototype.pause = function() {
11500 emitDataEvents(this, true);
11501 this.emit('pause');
11502};
11503
11504function emitDataEvents(stream, startPaused) {
11505 var state = stream._readableState;
11506
11507 if (state.flowing) {
11508 // https://github.com/isaacs/readable-stream/issues/16
11509 throw new Error('Cannot switch to old mode now.');
11510 }
11511
11512 var paused = startPaused || false;
11513 var readable = false;
11514
11515 // convert to an old-style stream.
11516 stream.readable = true;
11517 stream.pipe = Stream.prototype.pipe;
11518 stream.on = stream.addListener = Stream.prototype.on;
11519
11520 stream.on('readable', function() {
11521 readable = true;
11522
11523 var c;
11524 while (!paused && (null !== (c = stream.read())))
11525 stream.emit('data', c);
11526
11527 if (c === null) {
11528 readable = false;
11529 stream._readableState.needReadable = true;
11530 }
11531 });
11532
11533 stream.pause = function() {
11534 paused = true;
11535 this.emit('pause');
11536 };
11537
11538 stream.resume = function() {
11539 paused = false;
11540 if (readable)
11541 process.nextTick(function() {
11542 stream.emit('readable');
11543 });
11544 else
11545 this.read(0);
11546 this.emit('resume');
11547 };
11548
11549 // now make it start, just in case it hadn't already.
11550 stream.emit('readable');
11551}
11552
11553// wrap an old-style stream as the async data source.
11554// This is *not* part of the readable stream interface.
11555// It is an ugly unfortunate mess of history.
11556Readable.prototype.wrap = function(stream) {
11557 var state = this._readableState;
11558 var paused = false;
11559
11560 var self = this;
11561 stream.on('end', function() {
11562 if (state.decoder && !state.ended) {
11563 var chunk = state.decoder.end();
11564 if (chunk && chunk.length)
11565 self.push(chunk);
11566 }
11567
11568 self.push(null);
11569 });
11570
11571 stream.on('data', function(chunk) {
11572 if (state.decoder)
11573 chunk = state.decoder.write(chunk);
11574
11575 // don't skip over falsy values in objectMode
11576 //if (state.objectMode && util.isNullOrUndefined(chunk))
11577 if (state.objectMode && (chunk === null || chunk === undefined))
11578 return;
11579 else if (!state.objectMode && (!chunk || !chunk.length))
11580 return;
11581
11582 var ret = self.push(chunk);
11583 if (!ret) {
11584 paused = true;
11585 stream.pause();
11586 }
11587 });
11588
11589 // proxy all the other methods.
11590 // important when wrapping filters and duplexes.
11591 for (var i in stream) {
11592 if (typeof stream[i] === 'function' &&
11593 typeof this[i] === 'undefined') {
11594 this[i] = function(method) { return function() {
11595 return stream[method].apply(stream, arguments);
11596 }}(i);
11597 }
11598 }
11599
11600 // proxy certain important events.
11601 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
11602 forEach(events, function(ev) {
11603 stream.on(ev, self.emit.bind(self, ev));
11604 });
11605
11606 // when we try to consume some more bytes, simply unpause the
11607 // underlying stream.
11608 self._read = function(n) {
11609 if (paused) {
11610 paused = false;
11611 stream.resume();
11612 }
11613 };
11614
11615 return self;
11616};
11617
11618
11619
11620// exposed for testing purposes only.
11621Readable._fromList = fromList;
11622
11623// Pluck off n bytes from an array of buffers.
11624// Length is the combined lengths of all the buffers in the list.
11625function fromList(n, state) {
11626 var list = state.buffer;
11627 var length = state.length;
11628 var stringMode = !!state.decoder;
11629 var objectMode = !!state.objectMode;
11630 var ret;
11631
11632 // nothing in the list, definitely empty.
11633 if (list.length === 0)
11634 return null;
11635
11636 if (length === 0)
11637 ret = null;
11638 else if (objectMode)
11639 ret = list.shift();
11640 else if (!n || n >= length) {
11641 // read it all, truncate the array.
11642 if (stringMode)
11643 ret = list.join('');
11644 else
11645 ret = Buffer.concat(list, length);
11646 list.length = 0;
11647 } else {
11648 // read just some of it.
11649 if (n < list[0].length) {
11650 // just take a part of the first list item.
11651 // slice is the same for buffers and strings.
11652 var buf = list[0];
11653 ret = buf.slice(0, n);
11654 list[0] = buf.slice(n);
11655 } else if (n === list[0].length) {
11656 // first list is a perfect match
11657 ret = list.shift();
11658 } else {
11659 // complex case.
11660 // we have enough to cover it, but it spans past the first buffer.
11661 if (stringMode)
11662 ret = '';
11663 else
11664 ret = new Buffer(n);
11665
11666 var c = 0;
11667 for (var i = 0, l = list.length; i < l && c < n; i++) {
11668 var buf = list[0];
11669 var cpy = Math.min(n - c, buf.length);
11670
11671 if (stringMode)
11672 ret += buf.slice(0, cpy);
11673 else
11674 buf.copy(ret, c, 0, cpy);
11675
11676 if (cpy < buf.length)
11677 list[0] = buf.slice(cpy);
11678 else
11679 list.shift();
11680
11681 c += cpy;
11682 }
11683 }
11684 }
11685
11686 return ret;
11687}
11688
11689function endReadable(stream) {
11690 var state = stream._readableState;
11691
11692 // If we get here before consuming all the bytes, then that is a
11693 // bug in node. Should never happen.
11694 if (state.length > 0)
11695 throw new Error('endReadable called on non-empty stream');
11696
11697 if (!state.endEmitted && state.calledRead) {
11698 state.ended = true;
11699 process.nextTick(function() {
11700 // Check that we didn't get one last unshift.
11701 if (!state.endEmitted && state.length === 0) {
11702 state.endEmitted = true;
11703 stream.readable = false;
11704 stream.emit('end');
11705 }
11706 });
11707 }
11708}
11709
11710function forEach (xs, f) {
11711 for (var i = 0, l = xs.length; i < l; i++) {
11712 f(xs[i], i);
11713 }
11714}
11715
11716function indexOf (xs, x) {
11717 for (var i = 0, l = xs.length; i < l; i++) {
11718 if (xs[i] === x) return i;
11719 }
11720 return -1;
11721}
11722
11723}).call(this,_dereq_(62))
11724},{"10":10,"14":14,"18":18,"62":62,"69":69,"70":70,"74":74,"9":9}],67:[function(_dereq_,module,exports){
11725// Copyright Joyent, Inc. and other Node contributors.
11726//
11727// Permission is hereby granted, free of charge, to any person obtaining a
11728// copy of this software and associated documentation files (the
11729// "Software"), to deal in the Software without restriction, including
11730// without limitation the rights to use, copy, modify, merge, publish,
11731// distribute, sublicense, and/or sell copies of the Software, and to permit
11732// persons to whom the Software is furnished to do so, subject to the
11733// following conditions:
11734//
11735// The above copyright notice and this permission notice shall be included
11736// in all copies or substantial portions of the Software.
11737//
11738// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11739// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11740// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11741// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11742// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11743// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11744// USE OR OTHER DEALINGS IN THE SOFTWARE.
11745
11746
11747// a transform stream is a readable/writable stream where you do
11748// something with the data. Sometimes it's called a "filter",
11749// but that's not a great name for it, since that implies a thing where
11750// some bits pass through, and others are simply ignored. (That would
11751// be a valid example of a transform, of course.)
11752//
11753// While the output is causally related to the input, it's not a
11754// necessarily symmetric or synchronous transformation. For example,
11755// a zlib stream might take multiple plain-text writes(), and then
11756// emit a single compressed chunk some time in the future.
11757//
11758// Here's how this works:
11759//
11760// The Transform stream has all the aspects of the readable and writable
11761// stream classes. When you write(chunk), that calls _write(chunk,cb)
11762// internally, and returns false if there's a lot of pending writes
11763// buffered up. When you call read(), that calls _read(n) until
11764// there's enough pending readable data buffered up.
11765//
11766// In a transform stream, the written data is placed in a buffer. When
11767// _read(n) is called, it transforms the queued up data, calling the
11768// buffered _write cb's as it consumes chunks. If consuming a single
11769// written chunk would result in multiple output chunks, then the first
11770// outputted bit calls the readcb, and subsequent chunks just go into
11771// the read buffer, and will cause it to emit 'readable' if necessary.
11772//
11773// This way, back-pressure is actually determined by the reading side,
11774// since _read has to be called to start processing a new chunk. However,
11775// a pathological inflate type of transform can cause excessive buffering
11776// here. For example, imagine a stream where every byte of input is
11777// interpreted as an integer from 0-255, and then results in that many
11778// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
11779// 1kb of data being output. In this case, you could write a very small
11780// amount of input, and end up with a very large amount of output. In
11781// such a pathological inflating mechanism, there'd be no way to tell
11782// the system to stop doing the transform. A single 4MB write could
11783// cause the system to run out of memory.
11784//
11785// However, even in such a pathological case, only a single written chunk
11786// would be consumed, and then the rest would wait (un-transformed) until
11787// the results of the previous transformed chunk were consumed.
11788
11789module.exports = Transform;
11790
11791var Duplex = _dereq_(64);
11792
11793/*<replacement>*/
11794var util = _dereq_(10);
11795util.inherits = _dereq_(18);
11796/*</replacement>*/
11797
11798util.inherits(Transform, Duplex);
11799
11800
11801function TransformState(options, stream) {
11802 this.afterTransform = function(er, data) {
11803 return afterTransform(stream, er, data);
11804 };
11805
11806 this.needTransform = false;
11807 this.transforming = false;
11808 this.writecb = null;
11809 this.writechunk = null;
11810}
11811
11812function afterTransform(stream, er, data) {
11813 var ts = stream._transformState;
11814 ts.transforming = false;
11815
11816 var cb = ts.writecb;
11817
11818 if (!cb)
11819 return stream.emit('error', new Error('no writecb in Transform class'));
11820
11821 ts.writechunk = null;
11822 ts.writecb = null;
11823
11824 if (data !== null && data !== undefined)
11825 stream.push(data);
11826
11827 if (cb)
11828 cb(er);
11829
11830 var rs = stream._readableState;
11831 rs.reading = false;
11832 if (rs.needReadable || rs.length < rs.highWaterMark) {
11833 stream._read(rs.highWaterMark);
11834 }
11835}
11836
11837
11838function Transform(options) {
11839 if (!(this instanceof Transform))
11840 return new Transform(options);
11841
11842 Duplex.call(this, options);
11843
11844 var ts = this._transformState = new TransformState(options, this);
11845
11846 // when the writable side finishes, then flush out anything remaining.
11847 var stream = this;
11848
11849 // start out asking for a readable event once data is transformed.
11850 this._readableState.needReadable = true;
11851
11852 // we have implemented the _read method, and done the other things
11853 // that Readable wants before the first _read call, so unset the
11854 // sync guard flag.
11855 this._readableState.sync = false;
11856
11857 this.once('finish', function() {
11858 if ('function' === typeof this._flush)
11859 this._flush(function(er) {
11860 done(stream, er);
11861 });
11862 else
11863 done(stream);
11864 });
11865}
11866
11867Transform.prototype.push = function(chunk, encoding) {
11868 this._transformState.needTransform = false;
11869 return Duplex.prototype.push.call(this, chunk, encoding);
11870};
11871
11872// This is the part where you do stuff!
11873// override this function in implementation classes.
11874// 'chunk' is an input chunk.
11875//
11876// Call `push(newChunk)` to pass along transformed output
11877// to the readable side. You may call 'push' zero or more times.
11878//
11879// Call `cb(err)` when you are done with this chunk. If you pass
11880// an error, then that'll put the hurt on the whole operation. If you
11881// never call cb(), then you'll never get another chunk.
11882Transform.prototype._transform = function(chunk, encoding, cb) {
11883 throw new Error('not implemented');
11884};
11885
11886Transform.prototype._write = function(chunk, encoding, cb) {
11887 var ts = this._transformState;
11888 ts.writecb = cb;
11889 ts.writechunk = chunk;
11890 ts.writeencoding = encoding;
11891 if (!ts.transforming) {
11892 var rs = this._readableState;
11893 if (ts.needTransform ||
11894 rs.needReadable ||
11895 rs.length < rs.highWaterMark)
11896 this._read(rs.highWaterMark);
11897 }
11898};
11899
11900// Doesn't matter what the args are here.
11901// _transform does all the work.
11902// That we got here means that the readable side wants more data.
11903Transform.prototype._read = function(n) {
11904 var ts = this._transformState;
11905
11906 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
11907 ts.transforming = true;
11908 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
11909 } else {
11910 // mark that we need a transform, so that any data that comes in
11911 // will get processed, now that we've asked for it.
11912 ts.needTransform = true;
11913 }
11914};
11915
11916
11917function done(stream, er) {
11918 if (er)
11919 return stream.emit('error', er);
11920
11921 // if there's nothing in the write buffer, then that means
11922 // that nothing more will ever be provided
11923 var ws = stream._writableState;
11924 var rs = stream._readableState;
11925 var ts = stream._transformState;
11926
11927 if (ws.length)
11928 throw new Error('calling transform done when ws.length != 0');
11929
11930 if (ts.transforming)
11931 throw new Error('calling transform done when still transforming');
11932
11933 return stream.push(null);
11934}
11935
11936},{"10":10,"18":18,"64":64}],68:[function(_dereq_,module,exports){
11937(function (process){
11938// Copyright Joyent, Inc. and other Node contributors.
11939//
11940// Permission is hereby granted, free of charge, to any person obtaining a
11941// copy of this software and associated documentation files (the
11942// "Software"), to deal in the Software without restriction, including
11943// without limitation the rights to use, copy, modify, merge, publish,
11944// distribute, sublicense, and/or sell copies of the Software, and to permit
11945// persons to whom the Software is furnished to do so, subject to the
11946// following conditions:
11947//
11948// The above copyright notice and this permission notice shall be included
11949// in all copies or substantial portions of the Software.
11950//
11951// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11952// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11953// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11954// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11955// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11956// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11957// USE OR OTHER DEALINGS IN THE SOFTWARE.
11958
11959// A bit simpler than readable streams.
11960// Implement an async ._write(chunk, cb), and it'll handle all
11961// the drain event emission and buffering.
11962
11963module.exports = Writable;
11964
11965/*<replacement>*/
11966var Buffer = _dereq_(9).Buffer;
11967/*</replacement>*/
11968
11969Writable.WritableState = WritableState;
11970
11971
11972/*<replacement>*/
11973var util = _dereq_(10);
11974util.inherits = _dereq_(18);
11975/*</replacement>*/
11976
11977var Stream = _dereq_(74);
11978
11979util.inherits(Writable, Stream);
11980
11981function WriteReq(chunk, encoding, cb) {
11982 this.chunk = chunk;
11983 this.encoding = encoding;
11984 this.callback = cb;
11985}
11986
11987function WritableState(options, stream) {
11988 options = options || {};
11989
11990 // the point at which write() starts returning false
11991 // Note: 0 is a valid value, means that we always return false if
11992 // the entire buffer is not flushed immediately on write()
11993 var hwm = options.highWaterMark;
11994 this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
11995
11996 // object stream flag to indicate whether or not this stream
11997 // contains buffers or objects.
11998 this.objectMode = !!options.objectMode;
11999
12000 // cast to ints.
12001 this.highWaterMark = ~~this.highWaterMark;
12002
12003 this.needDrain = false;
12004 // at the start of calling end()
12005 this.ending = false;
12006 // when end() has been called, and returned
12007 this.ended = false;
12008 // when 'finish' is emitted
12009 this.finished = false;
12010
12011 // should we decode strings into buffers before passing to _write?
12012 // this is here so that some node-core streams can optimize string
12013 // handling at a lower level.
12014 var noDecode = options.decodeStrings === false;
12015 this.decodeStrings = !noDecode;
12016
12017 // Crypto is kind of old and crusty. Historically, its default string
12018 // encoding is 'binary' so we have to make this configurable.
12019 // Everything else in the universe uses 'utf8', though.
12020 this.defaultEncoding = options.defaultEncoding || 'utf8';
12021
12022 // not an actual buffer we keep track of, but a measurement
12023 // of how much we're waiting to get pushed to some underlying
12024 // socket or file.
12025 this.length = 0;
12026
12027 // a flag to see when we're in the middle of a write.
12028 this.writing = false;
12029
12030 // a flag to be able to tell if the onwrite cb is called immediately,
12031 // or on a later tick. We set this to true at first, becuase any
12032 // actions that shouldn't happen until "later" should generally also
12033 // not happen before the first write call.
12034 this.sync = true;
12035
12036 // a flag to know if we're processing previously buffered items, which
12037 // may call the _write() callback in the same tick, so that we don't
12038 // end up in an overlapped onwrite situation.
12039 this.bufferProcessing = false;
12040
12041 // the callback that's passed to _write(chunk,cb)
12042 this.onwrite = function(er) {
12043 onwrite(stream, er);
12044 };
12045
12046 // the callback that the user supplies to write(chunk,encoding,cb)
12047 this.writecb = null;
12048
12049 // the amount that is being written when _write is called.
12050 this.writelen = 0;
12051
12052 this.buffer = [];
12053
12054 // True if the error was already emitted and should not be thrown again
12055 this.errorEmitted = false;
12056}
12057
12058function Writable(options) {
12059 var Duplex = _dereq_(64);
12060
12061 // Writable ctor is applied to Duplexes, though they're not
12062 // instanceof Writable, they're instanceof Readable.
12063 if (!(this instanceof Writable) && !(this instanceof Duplex))
12064 return new Writable(options);
12065
12066 this._writableState = new WritableState(options, this);
12067
12068 // legacy.
12069 this.writable = true;
12070
12071 Stream.call(this);
12072}
12073
12074// Otherwise people can pipe Writable streams, which is just wrong.
12075Writable.prototype.pipe = function() {
12076 this.emit('error', new Error('Cannot pipe. Not readable.'));
12077};
12078
12079
12080function writeAfterEnd(stream, state, cb) {
12081 var er = new Error('write after end');
12082 // TODO: defer error events consistently everywhere, not just the cb
12083 stream.emit('error', er);
12084 process.nextTick(function() {
12085 cb(er);
12086 });
12087}
12088
12089// If we get something that is not a buffer, string, null, or undefined,
12090// and we're not in objectMode, then that's an error.
12091// Otherwise stream chunks are all considered to be of length=1, and the
12092// watermarks determine how many objects to keep in the buffer, rather than
12093// how many bytes or characters.
12094function validChunk(stream, state, chunk, cb) {
12095 var valid = true;
12096 if (!Buffer.isBuffer(chunk) &&
12097 'string' !== typeof chunk &&
12098 chunk !== null &&
12099 chunk !== undefined &&
12100 !state.objectMode) {
12101 var er = new TypeError('Invalid non-string/buffer chunk');
12102 stream.emit('error', er);
12103 process.nextTick(function() {
12104 cb(er);
12105 });
12106 valid = false;
12107 }
12108 return valid;
12109}
12110
12111Writable.prototype.write = function(chunk, encoding, cb) {
12112 var state = this._writableState;
12113 var ret = false;
12114
12115 if (typeof encoding === 'function') {
12116 cb = encoding;
12117 encoding = null;
12118 }
12119
12120 if (Buffer.isBuffer(chunk))
12121 encoding = 'buffer';
12122 else if (!encoding)
12123 encoding = state.defaultEncoding;
12124
12125 if (typeof cb !== 'function')
12126 cb = function() {};
12127
12128 if (state.ended)
12129 writeAfterEnd(this, state, cb);
12130 else if (validChunk(this, state, chunk, cb))
12131 ret = writeOrBuffer(this, state, chunk, encoding, cb);
12132
12133 return ret;
12134};
12135
12136function decodeChunk(state, chunk, encoding) {
12137 if (!state.objectMode &&
12138 state.decodeStrings !== false &&
12139 typeof chunk === 'string') {
12140 chunk = new Buffer(chunk, encoding);
12141 }
12142 return chunk;
12143}
12144
12145// if we're already writing something, then just put this
12146// in the queue, and wait our turn. Otherwise, call _write
12147// If we return false, then we need a drain event, so set that flag.
12148function writeOrBuffer(stream, state, chunk, encoding, cb) {
12149 chunk = decodeChunk(state, chunk, encoding);
12150 if (Buffer.isBuffer(chunk))
12151 encoding = 'buffer';
12152 var len = state.objectMode ? 1 : chunk.length;
12153
12154 state.length += len;
12155
12156 var ret = state.length < state.highWaterMark;
12157 // we must ensure that previous needDrain will not be reset to false.
12158 if (!ret)
12159 state.needDrain = true;
12160
12161 if (state.writing)
12162 state.buffer.push(new WriteReq(chunk, encoding, cb));
12163 else
12164 doWrite(stream, state, len, chunk, encoding, cb);
12165
12166 return ret;
12167}
12168
12169function doWrite(stream, state, len, chunk, encoding, cb) {
12170 state.writelen = len;
12171 state.writecb = cb;
12172 state.writing = true;
12173 state.sync = true;
12174 stream._write(chunk, encoding, state.onwrite);
12175 state.sync = false;
12176}
12177
12178function onwriteError(stream, state, sync, er, cb) {
12179 if (sync)
12180 process.nextTick(function() {
12181 cb(er);
12182 });
12183 else
12184 cb(er);
12185
12186 stream._writableState.errorEmitted = true;
12187 stream.emit('error', er);
12188}
12189
12190function onwriteStateUpdate(state) {
12191 state.writing = false;
12192 state.writecb = null;
12193 state.length -= state.writelen;
12194 state.writelen = 0;
12195}
12196
12197function onwrite(stream, er) {
12198 var state = stream._writableState;
12199 var sync = state.sync;
12200 var cb = state.writecb;
12201
12202 onwriteStateUpdate(state);
12203
12204 if (er)
12205 onwriteError(stream, state, sync, er, cb);
12206 else {
12207 // Check if we're actually ready to finish, but don't emit yet
12208 var finished = needFinish(stream, state);
12209
12210 if (!finished && !state.bufferProcessing && state.buffer.length)
12211 clearBuffer(stream, state);
12212
12213 if (sync) {
12214 process.nextTick(function() {
12215 afterWrite(stream, state, finished, cb);
12216 });
12217 } else {
12218 afterWrite(stream, state, finished, cb);
12219 }
12220 }
12221}
12222
12223function afterWrite(stream, state, finished, cb) {
12224 if (!finished)
12225 onwriteDrain(stream, state);
12226 cb();
12227 if (finished)
12228 finishMaybe(stream, state);
12229}
12230
12231// Must force callback to be called on nextTick, so that we don't
12232// emit 'drain' before the write() consumer gets the 'false' return
12233// value, and has a chance to attach a 'drain' listener.
12234function onwriteDrain(stream, state) {
12235 if (state.length === 0 && state.needDrain) {
12236 state.needDrain = false;
12237 stream.emit('drain');
12238 }
12239}
12240
12241
12242// if there's something in the buffer waiting, then process it
12243function clearBuffer(stream, state) {
12244 state.bufferProcessing = true;
12245
12246 for (var c = 0; c < state.buffer.length; c++) {
12247 var entry = state.buffer[c];
12248 var chunk = entry.chunk;
12249 var encoding = entry.encoding;
12250 var cb = entry.callback;
12251 var len = state.objectMode ? 1 : chunk.length;
12252
12253 doWrite(stream, state, len, chunk, encoding, cb);
12254
12255 // if we didn't call the onwrite immediately, then
12256 // it means that we need to wait until it does.
12257 // also, that means that the chunk and cb are currently
12258 // being processed, so move the buffer counter past them.
12259 if (state.writing) {
12260 c++;
12261 break;
12262 }
12263 }
12264
12265 state.bufferProcessing = false;
12266 if (c < state.buffer.length)
12267 state.buffer = state.buffer.slice(c);
12268 else
12269 state.buffer.length = 0;
12270}
12271
12272Writable.prototype._write = function(chunk, encoding, cb) {
12273 cb(new Error('not implemented'));
12274};
12275
12276Writable.prototype.end = function(chunk, encoding, cb) {
12277 var state = this._writableState;
12278
12279 if (typeof chunk === 'function') {
12280 cb = chunk;
12281 chunk = null;
12282 encoding = null;
12283 } else if (typeof encoding === 'function') {
12284 cb = encoding;
12285 encoding = null;
12286 }
12287
12288 if (typeof chunk !== 'undefined' && chunk !== null)
12289 this.write(chunk, encoding);
12290
12291 // ignore unnecessary end() calls.
12292 if (!state.ending && !state.finished)
12293 endWritable(this, state, cb);
12294};
12295
12296
12297function needFinish(stream, state) {
12298 return (state.ending &&
12299 state.length === 0 &&
12300 !state.finished &&
12301 !state.writing);
12302}
12303
12304function finishMaybe(stream, state) {
12305 var need = needFinish(stream, state);
12306 if (need) {
12307 state.finished = true;
12308 stream.emit('finish');
12309 }
12310 return need;
12311}
12312
12313function endWritable(stream, state, cb) {
12314 state.ending = true;
12315 finishMaybe(stream, state);
12316 if (cb) {
12317 if (state.finished)
12318 process.nextTick(cb);
12319 else
12320 stream.once('finish', cb);
12321 }
12322 state.ended = true;
12323}
12324
12325}).call(this,_dereq_(62))
12326},{"10":10,"18":18,"62":62,"64":64,"74":74,"9":9}],69:[function(_dereq_,module,exports){
12327module.exports = Array.isArray || function (arr) {
12328 return Object.prototype.toString.call(arr) == '[object Array]';
12329};
12330
12331},{}],70:[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
12353var Buffer = _dereq_(9).Buffer;
12354
12355var isBufferEncoding = Buffer.isEncoding
12356 || function(encoding) {
12357 switch (encoding && encoding.toLowerCase()) {
12358 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;
12359 default: return false;
12360 }
12361 }
12362
12363
12364function assertEncoding(encoding) {
12365 if (encoding && !isBufferEncoding(encoding)) {
12366 throw new Error('Unknown encoding: ' + encoding);
12367 }
12368}
12369
12370// StringDecoder provides an interface for efficiently splitting a series of
12371// buffers into a series of JS strings without breaking apart multi-byte
12372// characters. CESU-8 is handled as part of the UTF-8 encoding.
12373//
12374// @TODO Handling all encodings inside a single object makes it very difficult
12375// to reason about this code, so it should be split up in the future.
12376// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
12377// points as used by CESU-8.
12378var StringDecoder = exports.StringDecoder = function(encoding) {
12379 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
12380 assertEncoding(encoding);
12381 switch (this.encoding) {
12382 case 'utf8':
12383 // CESU-8 represents each of Surrogate Pair by 3-bytes
12384 this.surrogateSize = 3;
12385 break;
12386 case 'ucs2':
12387 case 'utf16le':
12388 // UTF-16 represents each of Surrogate Pair by 2-bytes
12389 this.surrogateSize = 2;
12390 this.detectIncompleteChar = utf16DetectIncompleteChar;
12391 break;
12392 case 'base64':
12393 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
12394 this.surrogateSize = 3;
12395 this.detectIncompleteChar = base64DetectIncompleteChar;
12396 break;
12397 default:
12398 this.write = passThroughWrite;
12399 return;
12400 }
12401
12402 // Enough space to store all bytes of a single character. UTF-8 needs 4
12403 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
12404 this.charBuffer = new Buffer(6);
12405 // Number of bytes received for the current incomplete multi-byte character.
12406 this.charReceived = 0;
12407 // Number of bytes expected for the current incomplete multi-byte character.
12408 this.charLength = 0;
12409};
12410
12411
12412// write decodes the given buffer and returns it as JS string that is
12413// guaranteed to not contain any partial multi-byte characters. Any partial
12414// character found at the end of the buffer is buffered up, and will be
12415// returned when calling write again with the remaining bytes.
12416//
12417// Note: Converting a Buffer containing an orphan surrogate to a String
12418// currently works, but converting a String to a Buffer (via `new Buffer`, or
12419// Buffer#write) will replace incomplete surrogates with the unicode
12420// replacement character. See https://codereview.chromium.org/121173009/ .
12421StringDecoder.prototype.write = function(buffer) {
12422 var charStr = '';
12423 // if our last write ended with an incomplete multibyte character
12424 while (this.charLength) {
12425 // determine how many remaining bytes this buffer has to offer for this char
12426 var available = (buffer.length >= this.charLength - this.charReceived) ?
12427 this.charLength - this.charReceived :
12428 buffer.length;
12429
12430 // add the new bytes to the char buffer
12431 buffer.copy(this.charBuffer, this.charReceived, 0, available);
12432 this.charReceived += available;
12433
12434 if (this.charReceived < this.charLength) {
12435 // still not enough chars in this buffer? wait for more ...
12436 return '';
12437 }
12438
12439 // remove bytes belonging to the current character from the buffer
12440 buffer = buffer.slice(available, buffer.length);
12441
12442 // get the character that was split
12443 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
12444
12445 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
12446 var charCode = charStr.charCodeAt(charStr.length - 1);
12447 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
12448 this.charLength += this.surrogateSize;
12449 charStr = '';
12450 continue;
12451 }
12452 this.charReceived = this.charLength = 0;
12453
12454 // if there are no more bytes in this buffer, just emit our char
12455 if (buffer.length === 0) {
12456 return charStr;
12457 }
12458 break;
12459 }
12460
12461 // determine and set charLength / charReceived
12462 this.detectIncompleteChar(buffer);
12463
12464 var end = buffer.length;
12465 if (this.charLength) {
12466 // buffer the incomplete character bytes we got
12467 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
12468 end -= this.charReceived;
12469 }
12470
12471 charStr += buffer.toString(this.encoding, 0, end);
12472
12473 var end = charStr.length - 1;
12474 var charCode = charStr.charCodeAt(end);
12475 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
12476 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
12477 var size = this.surrogateSize;
12478 this.charLength += size;
12479 this.charReceived += size;
12480 this.charBuffer.copy(this.charBuffer, size, 0, size);
12481 buffer.copy(this.charBuffer, 0, 0, size);
12482 return charStr.substring(0, end);
12483 }
12484
12485 // or just emit the charStr
12486 return charStr;
12487};
12488
12489// detectIncompleteChar determines if there is an incomplete UTF-8 character at
12490// the end of the given buffer. If so, it sets this.charLength to the byte
12491// length that character, and sets this.charReceived to the number of bytes
12492// that are available for this character.
12493StringDecoder.prototype.detectIncompleteChar = function(buffer) {
12494 // determine how many bytes we have to check at the end of this buffer
12495 var i = (buffer.length >= 3) ? 3 : buffer.length;
12496
12497 // Figure out if one of the last i bytes of our buffer announces an
12498 // incomplete char.
12499 for (; i > 0; i--) {
12500 var c = buffer[buffer.length - i];
12501
12502 // See http://en.wikipedia.org/wiki/UTF-8#Description
12503
12504 // 110XXXXX
12505 if (i == 1 && c >> 5 == 0x06) {
12506 this.charLength = 2;
12507 break;
12508 }
12509
12510 // 1110XXXX
12511 if (i <= 2 && c >> 4 == 0x0E) {
12512 this.charLength = 3;
12513 break;
12514 }
12515
12516 // 11110XXX
12517 if (i <= 3 && c >> 3 == 0x1E) {
12518 this.charLength = 4;
12519 break;
12520 }
12521 }
12522 this.charReceived = i;
12523};
12524
12525StringDecoder.prototype.end = function(buffer) {
12526 var res = '';
12527 if (buffer && buffer.length)
12528 res = this.write(buffer);
12529
12530 if (this.charReceived) {
12531 var cr = this.charReceived;
12532 var buf = this.charBuffer;
12533 var enc = this.encoding;
12534 res += buf.slice(0, cr).toString(enc);
12535 }
12536
12537 return res;
12538};
12539
12540function passThroughWrite(buffer) {
12541 return buffer.toString(this.encoding);
12542}
12543
12544function utf16DetectIncompleteChar(buffer) {
12545 this.charReceived = buffer.length % 2;
12546 this.charLength = this.charReceived ? 2 : 0;
12547}
12548
12549function base64DetectIncompleteChar(buffer) {
12550 this.charReceived = buffer.length % 3;
12551 this.charLength = this.charReceived ? 3 : 0;
12552}
12553
12554},{"9":9}],71:[function(_dereq_,module,exports){
12555var Stream = _dereq_(74); // hack to fix a circular dependency issue when used with browserify
12556exports = module.exports = _dereq_(66);
12557exports.Stream = Stream;
12558exports.Readable = exports;
12559exports.Writable = _dereq_(68);
12560exports.Duplex = _dereq_(64);
12561exports.Transform = _dereq_(67);
12562exports.PassThrough = _dereq_(65);
12563
12564},{"64":64,"65":65,"66":66,"67":67,"68":68,"74":74}],72:[function(_dereq_,module,exports){
12565/* eslint-disable node/no-deprecated-api */
12566var buffer = _dereq_(9)
12567var Buffer = buffer.Buffer
12568
12569// alternative to using Object.keys for old browsers
12570function copyProps (src, dst) {
12571 for (var key in src) {
12572 dst[key] = src[key]
12573 }
12574}
12575if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
12576 module.exports = buffer
12577} else {
12578 // Copy properties from require('buffer')
12579 copyProps(buffer, exports)
12580 exports.Buffer = SafeBuffer
12581}
12582
12583function SafeBuffer (arg, encodingOrOffset, length) {
12584 return Buffer(arg, encodingOrOffset, length)
12585}
12586
12587// Copy static methods from Buffer
12588copyProps(Buffer, SafeBuffer)
12589
12590SafeBuffer.from = function (arg, encodingOrOffset, length) {
12591 if (typeof arg === 'number') {
12592 throw new TypeError('Argument must not be a number')
12593 }
12594 return Buffer(arg, encodingOrOffset, length)
12595}
12596
12597SafeBuffer.alloc = function (size, fill, encoding) {
12598 if (typeof size !== 'number') {
12599 throw new TypeError('Argument must be a number')
12600 }
12601 var buf = Buffer(size)
12602 if (fill !== undefined) {
12603 if (typeof encoding === 'string') {
12604 buf.fill(fill, encoding)
12605 } else {
12606 buf.fill(fill)
12607 }
12608 } else {
12609 buf.fill(0)
12610 }
12611 return buf
12612}
12613
12614SafeBuffer.allocUnsafe = function (size) {
12615 if (typeof size !== 'number') {
12616 throw new TypeError('Argument must be a number')
12617 }
12618 return Buffer(size)
12619}
12620
12621SafeBuffer.allocUnsafeSlow = function (size) {
12622 if (typeof size !== 'number') {
12623 throw new TypeError('Argument must be a number')
12624 }
12625 return buffer.SlowBuffer(size)
12626}
12627
12628},{"9":9}],73:[function(_dereq_,module,exports){
12629(function (factory) {
12630 if (typeof exports === 'object') {
12631 // Node/CommonJS
12632 module.exports = factory();
12633 } else if (typeof define === 'function' && define.amd) {
12634 // AMD
12635 define(factory);
12636 } else {
12637 // Browser globals (with support for web workers)
12638 var glob;
12639
12640 try {
12641 glob = window;
12642 } catch (e) {
12643 glob = self;
12644 }
12645
12646 glob.SparkMD5 = factory();
12647 }
12648}(function (undefined) {
12649
12650 'use strict';
12651
12652 /*
12653 * Fastest md5 implementation around (JKM md5).
12654 * Credits: Joseph Myers
12655 *
12656 * @see http://www.myersdaily.org/joseph/javascript/md5-text.html
12657 * @see http://jsperf.com/md5-shootout/7
12658 */
12659
12660 /* this function is much faster,
12661 so if possible we use it. Some IEs
12662 are the only ones I know of that
12663 need the idiotic second function,
12664 generated by an if clause. */
12665 var add32 = function (a, b) {
12666 return (a + b) & 0xFFFFFFFF;
12667 },
12668 hex_chr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
12669
12670
12671 function cmn(q, a, b, x, s, t) {
12672 a = add32(add32(a, q), add32(x, t));
12673 return add32((a << s) | (a >>> (32 - s)), b);
12674 }
12675
12676 function md5cycle(x, k) {
12677 var a = x[0],
12678 b = x[1],
12679 c = x[2],
12680 d = x[3];
12681
12682 a += (b & c | ~b & d) + k[0] - 680876936 | 0;
12683 a = (a << 7 | a >>> 25) + b | 0;
12684 d += (a & b | ~a & c) + k[1] - 389564586 | 0;
12685 d = (d << 12 | d >>> 20) + a | 0;
12686 c += (d & a | ~d & b) + k[2] + 606105819 | 0;
12687 c = (c << 17 | c >>> 15) + d | 0;
12688 b += (c & d | ~c & a) + k[3] - 1044525330 | 0;
12689 b = (b << 22 | b >>> 10) + c | 0;
12690 a += (b & c | ~b & d) + k[4] - 176418897 | 0;
12691 a = (a << 7 | a >>> 25) + b | 0;
12692 d += (a & b | ~a & c) + k[5] + 1200080426 | 0;
12693 d = (d << 12 | d >>> 20) + a | 0;
12694 c += (d & a | ~d & b) + k[6] - 1473231341 | 0;
12695 c = (c << 17 | c >>> 15) + d | 0;
12696 b += (c & d | ~c & a) + k[7] - 45705983 | 0;
12697 b = (b << 22 | b >>> 10) + c | 0;
12698 a += (b & c | ~b & d) + k[8] + 1770035416 | 0;
12699 a = (a << 7 | a >>> 25) + b | 0;
12700 d += (a & b | ~a & c) + k[9] - 1958414417 | 0;
12701 d = (d << 12 | d >>> 20) + a | 0;
12702 c += (d & a | ~d & b) + k[10] - 42063 | 0;
12703 c = (c << 17 | c >>> 15) + d | 0;
12704 b += (c & d | ~c & a) + k[11] - 1990404162 | 0;
12705 b = (b << 22 | b >>> 10) + c | 0;
12706 a += (b & c | ~b & d) + k[12] + 1804603682 | 0;
12707 a = (a << 7 | a >>> 25) + b | 0;
12708 d += (a & b | ~a & c) + k[13] - 40341101 | 0;
12709 d = (d << 12 | d >>> 20) + a | 0;
12710 c += (d & a | ~d & b) + k[14] - 1502002290 | 0;
12711 c = (c << 17 | c >>> 15) + d | 0;
12712 b += (c & d | ~c & a) + k[15] + 1236535329 | 0;
12713 b = (b << 22 | b >>> 10) + c | 0;
12714
12715 a += (b & d | c & ~d) + k[1] - 165796510 | 0;
12716 a = (a << 5 | a >>> 27) + b | 0;
12717 d += (a & c | b & ~c) + k[6] - 1069501632 | 0;
12718 d = (d << 9 | d >>> 23) + a | 0;
12719 c += (d & b | a & ~b) + k[11] + 643717713 | 0;
12720 c = (c << 14 | c >>> 18) + d | 0;
12721 b += (c & a | d & ~a) + k[0] - 373897302 | 0;
12722 b = (b << 20 | b >>> 12) + c | 0;
12723 a += (b & d | c & ~d) + k[5] - 701558691 | 0;
12724 a = (a << 5 | a >>> 27) + b | 0;
12725 d += (a & c | b & ~c) + k[10] + 38016083 | 0;
12726 d = (d << 9 | d >>> 23) + a | 0;
12727 c += (d & b | a & ~b) + k[15] - 660478335 | 0;
12728 c = (c << 14 | c >>> 18) + d | 0;
12729 b += (c & a | d & ~a) + k[4] - 405537848 | 0;
12730 b = (b << 20 | b >>> 12) + c | 0;
12731 a += (b & d | c & ~d) + k[9] + 568446438 | 0;
12732 a = (a << 5 | a >>> 27) + b | 0;
12733 d += (a & c | b & ~c) + k[14] - 1019803690 | 0;
12734 d = (d << 9 | d >>> 23) + a | 0;
12735 c += (d & b | a & ~b) + k[3] - 187363961 | 0;
12736 c = (c << 14 | c >>> 18) + d | 0;
12737 b += (c & a | d & ~a) + k[8] + 1163531501 | 0;
12738 b = (b << 20 | b >>> 12) + c | 0;
12739 a += (b & d | c & ~d) + k[13] - 1444681467 | 0;
12740 a = (a << 5 | a >>> 27) + b | 0;
12741 d += (a & c | b & ~c) + k[2] - 51403784 | 0;
12742 d = (d << 9 | d >>> 23) + a | 0;
12743 c += (d & b | a & ~b) + k[7] + 1735328473 | 0;
12744 c = (c << 14 | c >>> 18) + d | 0;
12745 b += (c & a | d & ~a) + k[12] - 1926607734 | 0;
12746 b = (b << 20 | b >>> 12) + c | 0;
12747
12748 a += (b ^ c ^ d) + k[5] - 378558 | 0;
12749 a = (a << 4 | a >>> 28) + b | 0;
12750 d += (a ^ b ^ c) + k[8] - 2022574463 | 0;
12751 d = (d << 11 | d >>> 21) + a | 0;
12752 c += (d ^ a ^ b) + k[11] + 1839030562 | 0;
12753 c = (c << 16 | c >>> 16) + d | 0;
12754 b += (c ^ d ^ a) + k[14] - 35309556 | 0;
12755 b = (b << 23 | b >>> 9) + c | 0;
12756 a += (b ^ c ^ d) + k[1] - 1530992060 | 0;
12757 a = (a << 4 | a >>> 28) + b | 0;
12758 d += (a ^ b ^ c) + k[4] + 1272893353 | 0;
12759 d = (d << 11 | d >>> 21) + a | 0;
12760 c += (d ^ a ^ b) + k[7] - 155497632 | 0;
12761 c = (c << 16 | c >>> 16) + d | 0;
12762 b += (c ^ d ^ a) + k[10] - 1094730640 | 0;
12763 b = (b << 23 | b >>> 9) + c | 0;
12764 a += (b ^ c ^ d) + k[13] + 681279174 | 0;
12765 a = (a << 4 | a >>> 28) + b | 0;
12766 d += (a ^ b ^ c) + k[0] - 358537222 | 0;
12767 d = (d << 11 | d >>> 21) + a | 0;
12768 c += (d ^ a ^ b) + k[3] - 722521979 | 0;
12769 c = (c << 16 | c >>> 16) + d | 0;
12770 b += (c ^ d ^ a) + k[6] + 76029189 | 0;
12771 b = (b << 23 | b >>> 9) + c | 0;
12772 a += (b ^ c ^ d) + k[9] - 640364487 | 0;
12773 a = (a << 4 | a >>> 28) + b | 0;
12774 d += (a ^ b ^ c) + k[12] - 421815835 | 0;
12775 d = (d << 11 | d >>> 21) + a | 0;
12776 c += (d ^ a ^ b) + k[15] + 530742520 | 0;
12777 c = (c << 16 | c >>> 16) + d | 0;
12778 b += (c ^ d ^ a) + k[2] - 995338651 | 0;
12779 b = (b << 23 | b >>> 9) + c | 0;
12780
12781 a += (c ^ (b | ~d)) + k[0] - 198630844 | 0;
12782 a = (a << 6 | a >>> 26) + b | 0;
12783 d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0;
12784 d = (d << 10 | d >>> 22) + a | 0;
12785 c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0;
12786 c = (c << 15 | c >>> 17) + d | 0;
12787 b += (d ^ (c | ~a)) + k[5] - 57434055 | 0;
12788 b = (b << 21 |b >>> 11) + c | 0;
12789 a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0;
12790 a = (a << 6 | a >>> 26) + b | 0;
12791 d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0;
12792 d = (d << 10 | d >>> 22) + a | 0;
12793 c += (a ^ (d | ~b)) + k[10] - 1051523 | 0;
12794 c = (c << 15 | c >>> 17) + d | 0;
12795 b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0;
12796 b = (b << 21 |b >>> 11) + c | 0;
12797 a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0;
12798 a = (a << 6 | a >>> 26) + b | 0;
12799 d += (b ^ (a | ~c)) + k[15] - 30611744 | 0;
12800 d = (d << 10 | d >>> 22) + a | 0;
12801 c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0;
12802 c = (c << 15 | c >>> 17) + d | 0;
12803 b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0;
12804 b = (b << 21 |b >>> 11) + c | 0;
12805 a += (c ^ (b | ~d)) + k[4] - 145523070 | 0;
12806 a = (a << 6 | a >>> 26) + b | 0;
12807 d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0;
12808 d = (d << 10 | d >>> 22) + a | 0;
12809 c += (a ^ (d | ~b)) + k[2] + 718787259 | 0;
12810 c = (c << 15 | c >>> 17) + d | 0;
12811 b += (d ^ (c | ~a)) + k[9] - 343485551 | 0;
12812 b = (b << 21 | b >>> 11) + c | 0;
12813
12814 x[0] = a + x[0] | 0;
12815 x[1] = b + x[1] | 0;
12816 x[2] = c + x[2] | 0;
12817 x[3] = d + x[3] | 0;
12818 }
12819
12820 function md5blk(s) {
12821 var md5blks = [],
12822 i; /* Andy King said do it this way. */
12823
12824 for (i = 0; i < 64; i += 4) {
12825 md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
12826 }
12827 return md5blks;
12828 }
12829
12830 function md5blk_array(a) {
12831 var md5blks = [],
12832 i; /* Andy King said do it this way. */
12833
12834 for (i = 0; i < 64; i += 4) {
12835 md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);
12836 }
12837 return md5blks;
12838 }
12839
12840 function md51(s) {
12841 var n = s.length,
12842 state = [1732584193, -271733879, -1732584194, 271733878],
12843 i,
12844 length,
12845 tail,
12846 tmp,
12847 lo,
12848 hi;
12849
12850 for (i = 64; i <= n; i += 64) {
12851 md5cycle(state, md5blk(s.substring(i - 64, i)));
12852 }
12853 s = s.substring(i - 64);
12854 length = s.length;
12855 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
12856 for (i = 0; i < length; i += 1) {
12857 tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
12858 }
12859 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
12860 if (i > 55) {
12861 md5cycle(state, tail);
12862 for (i = 0; i < 16; i += 1) {
12863 tail[i] = 0;
12864 }
12865 }
12866
12867 // Beware that the final length might not fit in 32 bits so we take care of that
12868 tmp = n * 8;
12869 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
12870 lo = parseInt(tmp[2], 16);
12871 hi = parseInt(tmp[1], 16) || 0;
12872
12873 tail[14] = lo;
12874 tail[15] = hi;
12875
12876 md5cycle(state, tail);
12877 return state;
12878 }
12879
12880 function md51_array(a) {
12881 var n = a.length,
12882 state = [1732584193, -271733879, -1732584194, 271733878],
12883 i,
12884 length,
12885 tail,
12886 tmp,
12887 lo,
12888 hi;
12889
12890 for (i = 64; i <= n; i += 64) {
12891 md5cycle(state, md5blk_array(a.subarray(i - 64, i)));
12892 }
12893
12894 // Not sure if it is a bug, however IE10 will always produce a sub array of length 1
12895 // containing the last element of the parent array if the sub array specified starts
12896 // beyond the length of the parent array - weird.
12897 // https://connect.microsoft.com/IE/feedback/details/771452/typed-array-subarray-issue
12898 a = (i - 64) < n ? a.subarray(i - 64) : new Uint8Array(0);
12899
12900 length = a.length;
12901 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
12902 for (i = 0; i < length; i += 1) {
12903 tail[i >> 2] |= a[i] << ((i % 4) << 3);
12904 }
12905
12906 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
12907 if (i > 55) {
12908 md5cycle(state, tail);
12909 for (i = 0; i < 16; i += 1) {
12910 tail[i] = 0;
12911 }
12912 }
12913
12914 // Beware that the final length might not fit in 32 bits so we take care of that
12915 tmp = n * 8;
12916 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
12917 lo = parseInt(tmp[2], 16);
12918 hi = parseInt(tmp[1], 16) || 0;
12919
12920 tail[14] = lo;
12921 tail[15] = hi;
12922
12923 md5cycle(state, tail);
12924
12925 return state;
12926 }
12927
12928 function rhex(n) {
12929 var s = '',
12930 j;
12931 for (j = 0; j < 4; j += 1) {
12932 s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
12933 }
12934 return s;
12935 }
12936
12937 function hex(x) {
12938 var i;
12939 for (i = 0; i < x.length; i += 1) {
12940 x[i] = rhex(x[i]);
12941 }
12942 return x.join('');
12943 }
12944
12945 // In some cases the fast add32 function cannot be used..
12946 if (hex(md51('hello')) !== '5d41402abc4b2a76b9719d911017c592') {
12947 add32 = function (x, y) {
12948 var lsw = (x & 0xFFFF) + (y & 0xFFFF),
12949 msw = (x >> 16) + (y >> 16) + (lsw >> 16);
12950 return (msw << 16) | (lsw & 0xFFFF);
12951 };
12952 }
12953
12954 // ---------------------------------------------------
12955
12956 /**
12957 * ArrayBuffer slice polyfill.
12958 *
12959 * @see https://github.com/ttaubert/node-arraybuffer-slice
12960 */
12961
12962 if (typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.prototype.slice) {
12963 (function () {
12964 function clamp(val, length) {
12965 val = (val | 0) || 0;
12966
12967 if (val < 0) {
12968 return Math.max(val + length, 0);
12969 }
12970
12971 return Math.min(val, length);
12972 }
12973
12974 ArrayBuffer.prototype.slice = function (from, to) {
12975 var length = this.byteLength,
12976 begin = clamp(from, length),
12977 end = length,
12978 num,
12979 target,
12980 targetArray,
12981 sourceArray;
12982
12983 if (to !== undefined) {
12984 end = clamp(to, length);
12985 }
12986
12987 if (begin > end) {
12988 return new ArrayBuffer(0);
12989 }
12990
12991 num = end - begin;
12992 target = new ArrayBuffer(num);
12993 targetArray = new Uint8Array(target);
12994
12995 sourceArray = new Uint8Array(this, begin, num);
12996 targetArray.set(sourceArray);
12997
12998 return target;
12999 };
13000 })();
13001 }
13002
13003 // ---------------------------------------------------
13004
13005 /**
13006 * Helpers.
13007 */
13008
13009 function toUtf8(str) {
13010 if (/[\u0080-\uFFFF]/.test(str)) {
13011 str = unescape(encodeURIComponent(str));
13012 }
13013
13014 return str;
13015 }
13016
13017 function utf8Str2ArrayBuffer(str, returnUInt8Array) {
13018 var length = str.length,
13019 buff = new ArrayBuffer(length),
13020 arr = new Uint8Array(buff),
13021 i;
13022
13023 for (i = 0; i < length; i += 1) {
13024 arr[i] = str.charCodeAt(i);
13025 }
13026
13027 return returnUInt8Array ? arr : buff;
13028 }
13029
13030 function arrayBuffer2Utf8Str(buff) {
13031 return String.fromCharCode.apply(null, new Uint8Array(buff));
13032 }
13033
13034 function concatenateArrayBuffers(first, second, returnUInt8Array) {
13035 var result = new Uint8Array(first.byteLength + second.byteLength);
13036
13037 result.set(new Uint8Array(first));
13038 result.set(new Uint8Array(second), first.byteLength);
13039
13040 return returnUInt8Array ? result : result.buffer;
13041 }
13042
13043 function hexToBinaryString(hex) {
13044 var bytes = [],
13045 length = hex.length,
13046 x;
13047
13048 for (x = 0; x < length - 1; x += 2) {
13049 bytes.push(parseInt(hex.substr(x, 2), 16));
13050 }
13051
13052 return String.fromCharCode.apply(String, bytes);
13053 }
13054
13055 // ---------------------------------------------------
13056
13057 /**
13058 * SparkMD5 OOP implementation.
13059 *
13060 * Use this class to perform an incremental md5, otherwise use the
13061 * static methods instead.
13062 */
13063
13064 function SparkMD5() {
13065 // call reset to init the instance
13066 this.reset();
13067 }
13068
13069 /**
13070 * Appends a string.
13071 * A conversion will be applied if an utf8 string is detected.
13072 *
13073 * @param {String} str The string to be appended
13074 *
13075 * @return {SparkMD5} The instance itself
13076 */
13077 SparkMD5.prototype.append = function (str) {
13078 // Converts the string to utf8 bytes if necessary
13079 // Then append as binary
13080 this.appendBinary(toUtf8(str));
13081
13082 return this;
13083 };
13084
13085 /**
13086 * Appends a binary string.
13087 *
13088 * @param {String} contents The binary string to be appended
13089 *
13090 * @return {SparkMD5} The instance itself
13091 */
13092 SparkMD5.prototype.appendBinary = function (contents) {
13093 this._buff += contents;
13094 this._length += contents.length;
13095
13096 var length = this._buff.length,
13097 i;
13098
13099 for (i = 64; i <= length; i += 64) {
13100 md5cycle(this._hash, md5blk(this._buff.substring(i - 64, i)));
13101 }
13102
13103 this._buff = this._buff.substring(i - 64);
13104
13105 return this;
13106 };
13107
13108 /**
13109 * Finishes the incremental computation, reseting the internal state and
13110 * returning the result.
13111 *
13112 * @param {Boolean} raw True to get the raw string, false to get the hex string
13113 *
13114 * @return {String} The result
13115 */
13116 SparkMD5.prototype.end = function (raw) {
13117 var buff = this._buff,
13118 length = buff.length,
13119 i,
13120 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
13121 ret;
13122
13123 for (i = 0; i < length; i += 1) {
13124 tail[i >> 2] |= buff.charCodeAt(i) << ((i % 4) << 3);
13125 }
13126
13127 this._finish(tail, length);
13128 ret = hex(this._hash);
13129
13130 if (raw) {
13131 ret = hexToBinaryString(ret);
13132 }
13133
13134 this.reset();
13135
13136 return ret;
13137 };
13138
13139 /**
13140 * Resets the internal state of the computation.
13141 *
13142 * @return {SparkMD5} The instance itself
13143 */
13144 SparkMD5.prototype.reset = function () {
13145 this._buff = '';
13146 this._length = 0;
13147 this._hash = [1732584193, -271733879, -1732584194, 271733878];
13148
13149 return this;
13150 };
13151
13152 /**
13153 * Gets the internal state of the computation.
13154 *
13155 * @return {Object} The state
13156 */
13157 SparkMD5.prototype.getState = function () {
13158 return {
13159 buff: this._buff,
13160 length: this._length,
13161 hash: this._hash
13162 };
13163 };
13164
13165 /**
13166 * Gets the internal state of the computation.
13167 *
13168 * @param {Object} state The state
13169 *
13170 * @return {SparkMD5} The instance itself
13171 */
13172 SparkMD5.prototype.setState = function (state) {
13173 this._buff = state.buff;
13174 this._length = state.length;
13175 this._hash = state.hash;
13176
13177 return this;
13178 };
13179
13180 /**
13181 * Releases memory used by the incremental buffer and other additional
13182 * resources. If you plan to use the instance again, use reset instead.
13183 */
13184 SparkMD5.prototype.destroy = function () {
13185 delete this._hash;
13186 delete this._buff;
13187 delete this._length;
13188 };
13189
13190 /**
13191 * Finish the final calculation based on the tail.
13192 *
13193 * @param {Array} tail The tail (will be modified)
13194 * @param {Number} length The length of the remaining buffer
13195 */
13196 SparkMD5.prototype._finish = function (tail, length) {
13197 var i = length,
13198 tmp,
13199 lo,
13200 hi;
13201
13202 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13203 if (i > 55) {
13204 md5cycle(this._hash, tail);
13205 for (i = 0; i < 16; i += 1) {
13206 tail[i] = 0;
13207 }
13208 }
13209
13210 // Do the final computation based on the tail and length
13211 // Beware that the final length may not fit in 32 bits so we take care of that
13212 tmp = this._length * 8;
13213 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
13214 lo = parseInt(tmp[2], 16);
13215 hi = parseInt(tmp[1], 16) || 0;
13216
13217 tail[14] = lo;
13218 tail[15] = hi;
13219 md5cycle(this._hash, tail);
13220 };
13221
13222 /**
13223 * Performs the md5 hash on a string.
13224 * A conversion will be applied if utf8 string is detected.
13225 *
13226 * @param {String} str The string
13227 * @param {Boolean} raw True to get the raw string, false to get the hex string
13228 *
13229 * @return {String} The result
13230 */
13231 SparkMD5.hash = function (str, raw) {
13232 // Converts the string to utf8 bytes if necessary
13233 // Then compute it using the binary function
13234 return SparkMD5.hashBinary(toUtf8(str), raw);
13235 };
13236
13237 /**
13238 * Performs the md5 hash on a binary string.
13239 *
13240 * @param {String} content The binary string
13241 * @param {Boolean} raw True to get the raw string, false to get the hex string
13242 *
13243 * @return {String} The result
13244 */
13245 SparkMD5.hashBinary = function (content, raw) {
13246 var hash = md51(content),
13247 ret = hex(hash);
13248
13249 return raw ? hexToBinaryString(ret) : ret;
13250 };
13251
13252 // ---------------------------------------------------
13253
13254 /**
13255 * SparkMD5 OOP implementation for array buffers.
13256 *
13257 * Use this class to perform an incremental md5 ONLY for array buffers.
13258 */
13259 SparkMD5.ArrayBuffer = function () {
13260 // call reset to init the instance
13261 this.reset();
13262 };
13263
13264 /**
13265 * Appends an array buffer.
13266 *
13267 * @param {ArrayBuffer} arr The array to be appended
13268 *
13269 * @return {SparkMD5.ArrayBuffer} The instance itself
13270 */
13271 SparkMD5.ArrayBuffer.prototype.append = function (arr) {
13272 var buff = concatenateArrayBuffers(this._buff.buffer, arr, true),
13273 length = buff.length,
13274 i;
13275
13276 this._length += arr.byteLength;
13277
13278 for (i = 64; i <= length; i += 64) {
13279 md5cycle(this._hash, md5blk_array(buff.subarray(i - 64, i)));
13280 }
13281
13282 this._buff = (i - 64) < length ? new Uint8Array(buff.buffer.slice(i - 64)) : new Uint8Array(0);
13283
13284 return this;
13285 };
13286
13287 /**
13288 * Finishes the incremental computation, reseting the internal state and
13289 * returning the result.
13290 *
13291 * @param {Boolean} raw True to get the raw string, false to get the hex string
13292 *
13293 * @return {String} The result
13294 */
13295 SparkMD5.ArrayBuffer.prototype.end = function (raw) {
13296 var buff = this._buff,
13297 length = buff.length,
13298 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
13299 i,
13300 ret;
13301
13302 for (i = 0; i < length; i += 1) {
13303 tail[i >> 2] |= buff[i] << ((i % 4) << 3);
13304 }
13305
13306 this._finish(tail, length);
13307 ret = hex(this._hash);
13308
13309 if (raw) {
13310 ret = hexToBinaryString(ret);
13311 }
13312
13313 this.reset();
13314
13315 return ret;
13316 };
13317
13318 /**
13319 * Resets the internal state of the computation.
13320 *
13321 * @return {SparkMD5.ArrayBuffer} The instance itself
13322 */
13323 SparkMD5.ArrayBuffer.prototype.reset = function () {
13324 this._buff = new Uint8Array(0);
13325 this._length = 0;
13326 this._hash = [1732584193, -271733879, -1732584194, 271733878];
13327
13328 return this;
13329 };
13330
13331 /**
13332 * Gets the internal state of the computation.
13333 *
13334 * @return {Object} The state
13335 */
13336 SparkMD5.ArrayBuffer.prototype.getState = function () {
13337 var state = SparkMD5.prototype.getState.call(this);
13338
13339 // Convert buffer to a string
13340 state.buff = arrayBuffer2Utf8Str(state.buff);
13341
13342 return state;
13343 };
13344
13345 /**
13346 * Gets the internal state of the computation.
13347 *
13348 * @param {Object} state The state
13349 *
13350 * @return {SparkMD5.ArrayBuffer} The instance itself
13351 */
13352 SparkMD5.ArrayBuffer.prototype.setState = function (state) {
13353 // Convert string to buffer
13354 state.buff = utf8Str2ArrayBuffer(state.buff, true);
13355
13356 return SparkMD5.prototype.setState.call(this, state);
13357 };
13358
13359 SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
13360
13361 SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
13362
13363 /**
13364 * Performs the md5 hash on an array buffer.
13365 *
13366 * @param {ArrayBuffer} arr The array buffer
13367 * @param {Boolean} raw True to get the raw string, false to get the hex one
13368 *
13369 * @return {String} The result
13370 */
13371 SparkMD5.ArrayBuffer.hash = function (arr, raw) {
13372 var hash = md51_array(new Uint8Array(arr)),
13373 ret = hex(hash);
13374
13375 return raw ? hexToBinaryString(ret) : ret;
13376 };
13377
13378 return SparkMD5;
13379}));
13380
13381},{}],74:[function(_dereq_,module,exports){
13382// Copyright Joyent, Inc. and other Node contributors.
13383//
13384// Permission is hereby granted, free of charge, to any person obtaining a
13385// copy of this software and associated documentation files (the
13386// "Software"), to deal in the Software without restriction, including
13387// without limitation the rights to use, copy, modify, merge, publish,
13388// distribute, sublicense, and/or sell copies of the Software, and to permit
13389// persons to whom the Software is furnished to do so, subject to the
13390// following conditions:
13391//
13392// The above copyright notice and this permission notice shall be included
13393// in all copies or substantial portions of the Software.
13394//
13395// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13396// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13397// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13398// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13399// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13400// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13401// USE OR OTHER DEALINGS IN THE SOFTWARE.
13402
13403module.exports = Stream;
13404
13405var EE = _dereq_(14).EventEmitter;
13406var inherits = _dereq_(18);
13407
13408inherits(Stream, EE);
13409Stream.Readable = _dereq_(85);
13410Stream.Writable = _dereq_(87);
13411Stream.Duplex = _dereq_(75);
13412Stream.Transform = _dereq_(86);
13413Stream.PassThrough = _dereq_(84);
13414
13415// Backwards-compat with node 0.4.x
13416Stream.Stream = Stream;
13417
13418
13419
13420// old-style streams. Note that the pipe method (the only relevant
13421// part of this class) is overridden in the Readable class.
13422
13423function Stream() {
13424 EE.call(this);
13425}
13426
13427Stream.prototype.pipe = function(dest, options) {
13428 var source = this;
13429
13430 function ondata(chunk) {
13431 if (dest.writable) {
13432 if (false === dest.write(chunk) && source.pause) {
13433 source.pause();
13434 }
13435 }
13436 }
13437
13438 source.on('data', ondata);
13439
13440 function ondrain() {
13441 if (source.readable && source.resume) {
13442 source.resume();
13443 }
13444 }
13445
13446 dest.on('drain', ondrain);
13447
13448 // If the 'end' option is not supplied, dest.end() will be called when
13449 // source gets the 'end' or 'close' events. Only dest.end() once.
13450 if (!dest._isStdio && (!options || options.end !== false)) {
13451 source.on('end', onend);
13452 source.on('close', onclose);
13453 }
13454
13455 var didOnEnd = false;
13456 function onend() {
13457 if (didOnEnd) return;
13458 didOnEnd = true;
13459
13460 dest.end();
13461 }
13462
13463
13464 function onclose() {
13465 if (didOnEnd) return;
13466 didOnEnd = true;
13467
13468 if (typeof dest.destroy === 'function') dest.destroy();
13469 }
13470
13471 // don't leave dangling pipes when there are errors.
13472 function onerror(er) {
13473 cleanup();
13474 if (EE.listenerCount(this, 'error') === 0) {
13475 throw er; // Unhandled stream error in pipe.
13476 }
13477 }
13478
13479 source.on('error', onerror);
13480 dest.on('error', onerror);
13481
13482 // remove all the event listeners that were added.
13483 function cleanup() {
13484 source.removeListener('data', ondata);
13485 dest.removeListener('drain', ondrain);
13486
13487 source.removeListener('end', onend);
13488 source.removeListener('close', onclose);
13489
13490 source.removeListener('error', onerror);
13491 dest.removeListener('error', onerror);
13492
13493 source.removeListener('end', cleanup);
13494 source.removeListener('close', cleanup);
13495
13496 dest.removeListener('close', cleanup);
13497 }
13498
13499 source.on('end', cleanup);
13500 source.on('close', cleanup);
13501
13502 dest.on('close', cleanup);
13503
13504 dest.emit('pipe', source);
13505
13506 // Allow for unix-like usage: A.pipe(B).pipe(C)
13507 return dest;
13508};
13509
13510},{"14":14,"18":18,"75":75,"84":84,"85":85,"86":86,"87":87}],75:[function(_dereq_,module,exports){
13511module.exports = _dereq_(76);
13512
13513},{"76":76}],76:[function(_dereq_,module,exports){
13514arguments[4][24][0].apply(exports,arguments)
13515},{"10":10,"18":18,"24":24,"61":61,"78":78,"80":80}],77:[function(_dereq_,module,exports){
13516arguments[4][25][0].apply(exports,arguments)
13517},{"10":10,"18":18,"25":25,"79":79}],78:[function(_dereq_,module,exports){
13518arguments[4][26][0].apply(exports,arguments)
13519},{"10":10,"14":14,"18":18,"20":20,"26":26,"61":61,"62":62,"7":7,"72":72,"76":76,"81":81,"82":82,"83":83,"88":88}],79:[function(_dereq_,module,exports){
13520arguments[4][27][0].apply(exports,arguments)
13521},{"10":10,"18":18,"27":27,"76":76}],80:[function(_dereq_,module,exports){
13522arguments[4][28][0].apply(exports,arguments)
13523},{"10":10,"101":101,"102":102,"18":18,"28":28,"61":61,"62":62,"72":72,"76":76,"82":82,"83":83}],81:[function(_dereq_,module,exports){
13524arguments[4][29][0].apply(exports,arguments)
13525},{"29":29,"7":7,"72":72}],82:[function(_dereq_,module,exports){
13526arguments[4][30][0].apply(exports,arguments)
13527},{"30":30,"61":61}],83:[function(_dereq_,module,exports){
13528arguments[4][31][0].apply(exports,arguments)
13529},{"14":14,"31":31}],84:[function(_dereq_,module,exports){
13530module.exports = _dereq_(85).PassThrough
13531
13532},{"85":85}],85:[function(_dereq_,module,exports){
13533arguments[4][32][0].apply(exports,arguments)
13534},{"32":32,"76":76,"77":77,"78":78,"79":79,"80":80}],86:[function(_dereq_,module,exports){
13535module.exports = _dereq_(85).Transform
13536
13537},{"85":85}],87:[function(_dereq_,module,exports){
13538module.exports = _dereq_(80);
13539
13540},{"80":80}],88:[function(_dereq_,module,exports){
13541// Copyright Joyent, Inc. and other Node contributors.
13542//
13543// Permission is hereby granted, free of charge, to any person obtaining a
13544// copy of this software and associated documentation files (the
13545// "Software"), to deal in the Software without restriction, including
13546// without limitation the rights to use, copy, modify, merge, publish,
13547// distribute, sublicense, and/or sell copies of the Software, and to permit
13548// persons to whom the Software is furnished to do so, subject to the
13549// following conditions:
13550//
13551// The above copyright notice and this permission notice shall be included
13552// in all copies or substantial portions of the Software.
13553//
13554// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13555// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13556// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13557// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13558// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13559// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13560// USE OR OTHER DEALINGS IN THE SOFTWARE.
13561
13562'use strict';
13563
13564/*<replacement>*/
13565
13566var Buffer = _dereq_(72).Buffer;
13567/*</replacement>*/
13568
13569var isEncoding = Buffer.isEncoding || function (encoding) {
13570 encoding = '' + encoding;
13571 switch (encoding && encoding.toLowerCase()) {
13572 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':
13573 return true;
13574 default:
13575 return false;
13576 }
13577};
13578
13579function _normalizeEncoding(enc) {
13580 if (!enc) return 'utf8';
13581 var retried;
13582 while (true) {
13583 switch (enc) {
13584 case 'utf8':
13585 case 'utf-8':
13586 return 'utf8';
13587 case 'ucs2':
13588 case 'ucs-2':
13589 case 'utf16le':
13590 case 'utf-16le':
13591 return 'utf16le';
13592 case 'latin1':
13593 case 'binary':
13594 return 'latin1';
13595 case 'base64':
13596 case 'ascii':
13597 case 'hex':
13598 return enc;
13599 default:
13600 if (retried) return; // undefined
13601 enc = ('' + enc).toLowerCase();
13602 retried = true;
13603 }
13604 }
13605};
13606
13607// Do not cache `Buffer.isEncoding` when checking encoding names as some
13608// modules monkey-patch it to support additional encodings
13609function normalizeEncoding(enc) {
13610 var nenc = _normalizeEncoding(enc);
13611 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
13612 return nenc || enc;
13613}
13614
13615// StringDecoder provides an interface for efficiently splitting a series of
13616// buffers into a series of JS strings without breaking apart multi-byte
13617// characters.
13618exports.StringDecoder = StringDecoder;
13619function StringDecoder(encoding) {
13620 this.encoding = normalizeEncoding(encoding);
13621 var nb;
13622 switch (this.encoding) {
13623 case 'utf16le':
13624 this.text = utf16Text;
13625 this.end = utf16End;
13626 nb = 4;
13627 break;
13628 case 'utf8':
13629 this.fillLast = utf8FillLast;
13630 nb = 4;
13631 break;
13632 case 'base64':
13633 this.text = base64Text;
13634 this.end = base64End;
13635 nb = 3;
13636 break;
13637 default:
13638 this.write = simpleWrite;
13639 this.end = simpleEnd;
13640 return;
13641 }
13642 this.lastNeed = 0;
13643 this.lastTotal = 0;
13644 this.lastChar = Buffer.allocUnsafe(nb);
13645}
13646
13647StringDecoder.prototype.write = function (buf) {
13648 if (buf.length === 0) return '';
13649 var r;
13650 var i;
13651 if (this.lastNeed) {
13652 r = this.fillLast(buf);
13653 if (r === undefined) return '';
13654 i = this.lastNeed;
13655 this.lastNeed = 0;
13656 } else {
13657 i = 0;
13658 }
13659 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
13660 return r || '';
13661};
13662
13663StringDecoder.prototype.end = utf8End;
13664
13665// Returns only complete characters in a Buffer
13666StringDecoder.prototype.text = utf8Text;
13667
13668// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
13669StringDecoder.prototype.fillLast = function (buf) {
13670 if (this.lastNeed <= buf.length) {
13671 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
13672 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
13673 }
13674 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
13675 this.lastNeed -= buf.length;
13676};
13677
13678// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
13679// continuation byte. If an invalid byte is detected, -2 is returned.
13680function utf8CheckByte(byte) {
13681 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;
13682 return byte >> 6 === 0x02 ? -1 : -2;
13683}
13684
13685// Checks at most 3 bytes at the end of a Buffer in order to detect an
13686// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
13687// needed to complete the UTF-8 character (if applicable) are returned.
13688function utf8CheckIncomplete(self, buf, i) {
13689 var j = buf.length - 1;
13690 if (j < i) return 0;
13691 var nb = utf8CheckByte(buf[j]);
13692 if (nb >= 0) {
13693 if (nb > 0) self.lastNeed = nb - 1;
13694 return nb;
13695 }
13696 if (--j < i || nb === -2) return 0;
13697 nb = utf8CheckByte(buf[j]);
13698 if (nb >= 0) {
13699 if (nb > 0) self.lastNeed = nb - 2;
13700 return nb;
13701 }
13702 if (--j < i || nb === -2) return 0;
13703 nb = utf8CheckByte(buf[j]);
13704 if (nb >= 0) {
13705 if (nb > 0) {
13706 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
13707 }
13708 return nb;
13709 }
13710 return 0;
13711}
13712
13713// Validates as many continuation bytes for a multi-byte UTF-8 character as
13714// needed or are available. If we see a non-continuation byte where we expect
13715// one, we "replace" the validated continuation bytes we've seen so far with
13716// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
13717// behavior. The continuation byte check is included three times in the case
13718// where all of the continuation bytes for a character exist in the same buffer.
13719// It is also done this way as a slight performance increase instead of using a
13720// loop.
13721function utf8CheckExtraBytes(self, buf, p) {
13722 if ((buf[0] & 0xC0) !== 0x80) {
13723 self.lastNeed = 0;
13724 return '\ufffd';
13725 }
13726 if (self.lastNeed > 1 && buf.length > 1) {
13727 if ((buf[1] & 0xC0) !== 0x80) {
13728 self.lastNeed = 1;
13729 return '\ufffd';
13730 }
13731 if (self.lastNeed > 2 && buf.length > 2) {
13732 if ((buf[2] & 0xC0) !== 0x80) {
13733 self.lastNeed = 2;
13734 return '\ufffd';
13735 }
13736 }
13737 }
13738}
13739
13740// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
13741function utf8FillLast(buf) {
13742 var p = this.lastTotal - this.lastNeed;
13743 var r = utf8CheckExtraBytes(this, buf, p);
13744 if (r !== undefined) return r;
13745 if (this.lastNeed <= buf.length) {
13746 buf.copy(this.lastChar, p, 0, this.lastNeed);
13747 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
13748 }
13749 buf.copy(this.lastChar, p, 0, buf.length);
13750 this.lastNeed -= buf.length;
13751}
13752
13753// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
13754// partial character, the character's bytes are buffered until the required
13755// number of bytes are available.
13756function utf8Text(buf, i) {
13757 var total = utf8CheckIncomplete(this, buf, i);
13758 if (!this.lastNeed) return buf.toString('utf8', i);
13759 this.lastTotal = total;
13760 var end = buf.length - (total - this.lastNeed);
13761 buf.copy(this.lastChar, 0, end);
13762 return buf.toString('utf8', i, end);
13763}
13764
13765// For UTF-8, a replacement character is added when ending on a partial
13766// character.
13767function utf8End(buf) {
13768 var r = buf && buf.length ? this.write(buf) : '';
13769 if (this.lastNeed) return r + '\ufffd';
13770 return r;
13771}
13772
13773// UTF-16LE typically needs two bytes per character, but even if we have an even
13774// number of bytes available, we need to check if we end on a leading/high
13775// surrogate. In that case, we need to wait for the next two bytes in order to
13776// decode the last character properly.
13777function utf16Text(buf, i) {
13778 if ((buf.length - i) % 2 === 0) {
13779 var r = buf.toString('utf16le', i);
13780 if (r) {
13781 var c = r.charCodeAt(r.length - 1);
13782 if (c >= 0xD800 && c <= 0xDBFF) {
13783 this.lastNeed = 2;
13784 this.lastTotal = 4;
13785 this.lastChar[0] = buf[buf.length - 2];
13786 this.lastChar[1] = buf[buf.length - 1];
13787 return r.slice(0, -1);
13788 }
13789 }
13790 return r;
13791 }
13792 this.lastNeed = 1;
13793 this.lastTotal = 2;
13794 this.lastChar[0] = buf[buf.length - 1];
13795 return buf.toString('utf16le', i, buf.length - 1);
13796}
13797
13798// For UTF-16LE we do not explicitly append special replacement characters if we
13799// end on a partial character, we simply let v8 handle that.
13800function utf16End(buf) {
13801 var r = buf && buf.length ? this.write(buf) : '';
13802 if (this.lastNeed) {
13803 var end = this.lastTotal - this.lastNeed;
13804 return r + this.lastChar.toString('utf16le', 0, end);
13805 }
13806 return r;
13807}
13808
13809function base64Text(buf, i) {
13810 var n = (buf.length - i) % 3;
13811 if (n === 0) return buf.toString('base64', i);
13812 this.lastNeed = 3 - n;
13813 this.lastTotal = 3;
13814 if (n === 1) {
13815 this.lastChar[0] = buf[buf.length - 1];
13816 } else {
13817 this.lastChar[0] = buf[buf.length - 2];
13818 this.lastChar[1] = buf[buf.length - 1];
13819 }
13820 return buf.toString('base64', i, buf.length - n);
13821}
13822
13823function base64End(buf) {
13824 var r = buf && buf.length ? this.write(buf) : '';
13825 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
13826 return r;
13827}
13828
13829// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
13830function simpleWrite(buf) {
13831 return buf.toString(this.encoding);
13832}
13833
13834function simpleEnd(buf) {
13835 return buf && buf.length ? this.write(buf) : '';
13836}
13837},{"72":72}],89:[function(_dereq_,module,exports){
13838arguments[4][24][0].apply(exports,arguments)
13839},{"10":10,"18":18,"24":24,"61":61,"91":91,"93":93}],90:[function(_dereq_,module,exports){
13840arguments[4][25][0].apply(exports,arguments)
13841},{"10":10,"18":18,"25":25,"92":92}],91:[function(_dereq_,module,exports){
13842arguments[4][26][0].apply(exports,arguments)
13843},{"10":10,"14":14,"18":18,"20":20,"26":26,"61":61,"62":62,"7":7,"72":72,"88":88,"89":89,"94":94,"95":95,"96":96}],92:[function(_dereq_,module,exports){
13844arguments[4][27][0].apply(exports,arguments)
13845},{"10":10,"18":18,"27":27,"89":89}],93:[function(_dereq_,module,exports){
13846arguments[4][28][0].apply(exports,arguments)
13847},{"10":10,"101":101,"102":102,"18":18,"28":28,"61":61,"62":62,"72":72,"89":89,"95":95,"96":96}],94:[function(_dereq_,module,exports){
13848arguments[4][29][0].apply(exports,arguments)
13849},{"29":29,"7":7,"72":72}],95:[function(_dereq_,module,exports){
13850arguments[4][30][0].apply(exports,arguments)
13851},{"30":30,"61":61}],96:[function(_dereq_,module,exports){
13852arguments[4][31][0].apply(exports,arguments)
13853},{"14":14,"31":31}],97:[function(_dereq_,module,exports){
13854arguments[4][32][0].apply(exports,arguments)
13855},{"32":32,"89":89,"90":90,"91":91,"92":92,"93":93}],98:[function(_dereq_,module,exports){
13856arguments[4][86][0].apply(exports,arguments)
13857},{"86":86,"97":97}],99:[function(_dereq_,module,exports){
13858arguments[4][33][0].apply(exports,arguments)
13859},{"33":33}],100:[function(_dereq_,module,exports){
13860(function (process){
13861var Transform = _dereq_(98)
13862 , inherits = _dereq_(104).inherits
13863 , xtend = _dereq_(99)
13864
13865function DestroyableTransform(opts) {
13866 Transform.call(this, opts)
13867 this._destroyed = false
13868}
13869
13870inherits(DestroyableTransform, Transform)
13871
13872DestroyableTransform.prototype.destroy = function(err) {
13873 if (this._destroyed) return
13874 this._destroyed = true
13875
13876 var self = this
13877 process.nextTick(function() {
13878 if (err)
13879 self.emit('error', err)
13880 self.emit('close')
13881 })
13882}
13883
13884// a noop _transform function
13885function noop (chunk, enc, callback) {
13886 callback(null, chunk)
13887}
13888
13889
13890// create a new export function, used by both the main export and
13891// the .ctor export, contains common logic for dealing with arguments
13892function through2 (construct) {
13893 return function (options, transform, flush) {
13894 if (typeof options == 'function') {
13895 flush = transform
13896 transform = options
13897 options = {}
13898 }
13899
13900 if (typeof transform != 'function')
13901 transform = noop
13902
13903 if (typeof flush != 'function')
13904 flush = null
13905
13906 return construct(options, transform, flush)
13907 }
13908}
13909
13910
13911// main export, just make me a transform stream!
13912module.exports = through2(function (options, transform, flush) {
13913 var t2 = new DestroyableTransform(options)
13914
13915 t2._transform = transform
13916
13917 if (flush)
13918 t2._flush = flush
13919
13920 return t2
13921})
13922
13923
13924// make me a reusable prototype that I can `new`, or implicitly `new`
13925// with a constructor call
13926module.exports.ctor = through2(function (options, transform, flush) {
13927 function Through2 (override) {
13928 if (!(this instanceof Through2))
13929 return new Through2(override)
13930
13931 this.options = xtend(options, override)
13932
13933 DestroyableTransform.call(this, this.options)
13934 }
13935
13936 inherits(Through2, DestroyableTransform)
13937
13938 Through2.prototype._transform = transform
13939
13940 if (flush)
13941 Through2.prototype._flush = flush
13942
13943 return Through2
13944})
13945
13946
13947module.exports.obj = through2(function (options, transform, flush) {
13948 var t2 = new DestroyableTransform(xtend({ objectMode: true, highWaterMark: 16 }, options))
13949
13950 t2._transform = transform
13951
13952 if (flush)
13953 t2._flush = flush
13954
13955 return t2
13956})
13957
13958}).call(this,_dereq_(62))
13959},{"104":104,"62":62,"98":98,"99":99}],101:[function(_dereq_,module,exports){
13960(function (setImmediate,clearImmediate){
13961var nextTick = _dereq_(62).nextTick;
13962var apply = Function.prototype.apply;
13963var slice = Array.prototype.slice;
13964var immediateIds = {};
13965var nextImmediateId = 0;
13966
13967// DOM APIs, for completeness
13968
13969exports.setTimeout = function() {
13970 return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
13971};
13972exports.setInterval = function() {
13973 return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
13974};
13975exports.clearTimeout =
13976exports.clearInterval = function(timeout) { timeout.close(); };
13977
13978function Timeout(id, clearFn) {
13979 this._id = id;
13980 this._clearFn = clearFn;
13981}
13982Timeout.prototype.unref = Timeout.prototype.ref = function() {};
13983Timeout.prototype.close = function() {
13984 this._clearFn.call(window, this._id);
13985};
13986
13987// Does not start the time, just sets up the members needed.
13988exports.enroll = function(item, msecs) {
13989 clearTimeout(item._idleTimeoutId);
13990 item._idleTimeout = msecs;
13991};
13992
13993exports.unenroll = function(item) {
13994 clearTimeout(item._idleTimeoutId);
13995 item._idleTimeout = -1;
13996};
13997
13998exports._unrefActive = exports.active = function(item) {
13999 clearTimeout(item._idleTimeoutId);
14000
14001 var msecs = item._idleTimeout;
14002 if (msecs >= 0) {
14003 item._idleTimeoutId = setTimeout(function onTimeout() {
14004 if (item._onTimeout)
14005 item._onTimeout();
14006 }, msecs);
14007 }
14008};
14009
14010// That's not how node.js implements it but the exposed api is the same.
14011exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
14012 var id = nextImmediateId++;
14013 var args = arguments.length < 2 ? false : slice.call(arguments, 1);
14014
14015 immediateIds[id] = true;
14016
14017 nextTick(function onNextTick() {
14018 if (immediateIds[id]) {
14019 // fn.call() is faster so we optimize for the common use-case
14020 // @see http://jsperf.com/call-apply-segu
14021 if (args) {
14022 fn.apply(null, args);
14023 } else {
14024 fn.call(null);
14025 }
14026 // Prevent ids from leaking
14027 exports.clearImmediate(id);
14028 }
14029 });
14030
14031 return id;
14032};
14033
14034exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
14035 delete immediateIds[id];
14036};
14037}).call(this,_dereq_(101).setImmediate,_dereq_(101).clearImmediate)
14038},{"101":101,"62":62}],102:[function(_dereq_,module,exports){
14039(function (global){
14040
14041/**
14042 * Module exports.
14043 */
14044
14045module.exports = deprecate;
14046
14047/**
14048 * Mark that a method should not be used.
14049 * Returns a modified function which warns once by default.
14050 *
14051 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
14052 *
14053 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
14054 * will throw an Error when invoked.
14055 *
14056 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
14057 * will invoke `console.trace()` instead of `console.error()`.
14058 *
14059 * @param {Function} fn - the function to deprecate
14060 * @param {String} msg - the string to print to the console when `fn` is invoked
14061 * @returns {Function} a new "deprecated" version of `fn`
14062 * @api public
14063 */
14064
14065function deprecate (fn, msg) {
14066 if (config('noDeprecation')) {
14067 return fn;
14068 }
14069
14070 var warned = false;
14071 function deprecated() {
14072 if (!warned) {
14073 if (config('throwDeprecation')) {
14074 throw new Error(msg);
14075 } else if (config('traceDeprecation')) {
14076 console.trace(msg);
14077 } else {
14078 console.warn(msg);
14079 }
14080 warned = true;
14081 }
14082 return fn.apply(this, arguments);
14083 }
14084
14085 return deprecated;
14086}
14087
14088/**
14089 * Checks `localStorage` for boolean values for the given `name`.
14090 *
14091 * @param {String} name
14092 * @returns {Boolean}
14093 * @api private
14094 */
14095
14096function config (name) {
14097 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
14098 try {
14099 if (!global.localStorage) return false;
14100 } catch (_) {
14101 return false;
14102 }
14103 var val = global.localStorage[name];
14104 if (null == val) return false;
14105 return String(val).toLowerCase() === 'true';
14106}
14107
14108}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
14109},{}],103:[function(_dereq_,module,exports){
14110arguments[4][4][0].apply(exports,arguments)
14111},{"4":4}],104:[function(_dereq_,module,exports){
14112arguments[4][5][0].apply(exports,arguments)
14113},{"103":103,"18":18,"5":5,"62":62}],105:[function(_dereq_,module,exports){
14114var v1 = _dereq_(108);
14115var v4 = _dereq_(109);
14116
14117var uuid = v4;
14118uuid.v1 = v1;
14119uuid.v4 = v4;
14120
14121module.exports = uuid;
14122
14123},{"108":108,"109":109}],106:[function(_dereq_,module,exports){
14124/**
14125 * Convert array of 16 byte values to UUID string format of the form:
14126 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
14127 */
14128var byteToHex = [];
14129for (var i = 0; i < 256; ++i) {
14130 byteToHex[i] = (i + 0x100).toString(16).substr(1);
14131}
14132
14133function bytesToUuid(buf, offset) {
14134 var i = offset || 0;
14135 var bth = byteToHex;
14136 return bth[buf[i++]] + bth[buf[i++]] +
14137 bth[buf[i++]] + bth[buf[i++]] + '-' +
14138 bth[buf[i++]] + bth[buf[i++]] + '-' +
14139 bth[buf[i++]] + bth[buf[i++]] + '-' +
14140 bth[buf[i++]] + bth[buf[i++]] + '-' +
14141 bth[buf[i++]] + bth[buf[i++]] +
14142 bth[buf[i++]] + bth[buf[i++]] +
14143 bth[buf[i++]] + bth[buf[i++]];
14144}
14145
14146module.exports = bytesToUuid;
14147
14148},{}],107:[function(_dereq_,module,exports){
14149// Unique ID creation requires a high quality random # generator. In the
14150// browser this is a little complicated due to unknown quality of Math.random()
14151// and inconsistent support for the `crypto` API. We do the best we can via
14152// feature-detection
14153
14154// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
14155var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues.bind(crypto)) ||
14156 (typeof(msCrypto) != 'undefined' && msCrypto.getRandomValues.bind(msCrypto));
14157if (getRandomValues) {
14158 // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
14159 var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
14160
14161 module.exports = function whatwgRNG() {
14162 getRandomValues(rnds8);
14163 return rnds8;
14164 };
14165} else {
14166 // Math.random()-based (RNG)
14167 //
14168 // If all else fails, use Math.random(). It's fast, but is of unspecified
14169 // quality.
14170 var rnds = new Array(16);
14171
14172 module.exports = function mathRNG() {
14173 for (var i = 0, r; i < 16; i++) {
14174 if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
14175 rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
14176 }
14177
14178 return rnds;
14179 };
14180}
14181
14182},{}],108:[function(_dereq_,module,exports){
14183var rng = _dereq_(107);
14184var bytesToUuid = _dereq_(106);
14185
14186// **`v1()` - Generate time-based UUID**
14187//
14188// Inspired by https://github.com/LiosK/UUID.js
14189// and http://docs.python.org/library/uuid.html
14190
14191var _nodeId;
14192var _clockseq;
14193
14194// Previous uuid creation time
14195var _lastMSecs = 0;
14196var _lastNSecs = 0;
14197
14198// See https://github.com/broofa/node-uuid for API details
14199function v1(options, buf, offset) {
14200 var i = buf && offset || 0;
14201 var b = buf || [];
14202
14203 options = options || {};
14204 var node = options.node || _nodeId;
14205 var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
14206
14207 // node and clockseq need to be initialized to random values if they're not
14208 // specified. We do this lazily to minimize issues related to insufficient
14209 // system entropy. See #189
14210 if (node == null || clockseq == null) {
14211 var seedBytes = rng();
14212 if (node == null) {
14213 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
14214 node = _nodeId = [
14215 seedBytes[0] | 0x01,
14216 seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]
14217 ];
14218 }
14219 if (clockseq == null) {
14220 // Per 4.2.2, randomize (14 bit) clockseq
14221 clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
14222 }
14223 }
14224
14225 // UUID timestamps are 100 nano-second units since the Gregorian epoch,
14226 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
14227 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
14228 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
14229 var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
14230
14231 // Per 4.2.1.2, use count of uuid's generated during the current clock
14232 // cycle to simulate higher resolution clock
14233 var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
14234
14235 // Time since last uuid creation (in msecs)
14236 var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
14237
14238 // Per 4.2.1.2, Bump clockseq on clock regression
14239 if (dt < 0 && options.clockseq === undefined) {
14240 clockseq = clockseq + 1 & 0x3fff;
14241 }
14242
14243 // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
14244 // time interval
14245 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
14246 nsecs = 0;
14247 }
14248
14249 // Per 4.2.1.2 Throw error if too many uuids are requested
14250 if (nsecs >= 10000) {
14251 throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
14252 }
14253
14254 _lastMSecs = msecs;
14255 _lastNSecs = nsecs;
14256 _clockseq = clockseq;
14257
14258 // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
14259 msecs += 12219292800000;
14260
14261 // `time_low`
14262 var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
14263 b[i++] = tl >>> 24 & 0xff;
14264 b[i++] = tl >>> 16 & 0xff;
14265 b[i++] = tl >>> 8 & 0xff;
14266 b[i++] = tl & 0xff;
14267
14268 // `time_mid`
14269 var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
14270 b[i++] = tmh >>> 8 & 0xff;
14271 b[i++] = tmh & 0xff;
14272
14273 // `time_high_and_version`
14274 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
14275 b[i++] = tmh >>> 16 & 0xff;
14276
14277 // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
14278 b[i++] = clockseq >>> 8 | 0x80;
14279
14280 // `clock_seq_low`
14281 b[i++] = clockseq & 0xff;
14282
14283 // `node`
14284 for (var n = 0; n < 6; ++n) {
14285 b[i + n] = node[n];
14286 }
14287
14288 return buf ? buf : bytesToUuid(b);
14289}
14290
14291module.exports = v1;
14292
14293},{"106":106,"107":107}],109:[function(_dereq_,module,exports){
14294var rng = _dereq_(107);
14295var bytesToUuid = _dereq_(106);
14296
14297function v4(options, buf, offset) {
14298 var i = buf && offset || 0;
14299
14300 if (typeof(options) == 'string') {
14301 buf = options === 'binary' ? new Array(16) : null;
14302 options = null;
14303 }
14304 options = options || {};
14305
14306 var rnds = options.random || (options.rng || rng)();
14307
14308 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
14309 rnds[6] = (rnds[6] & 0x0f) | 0x40;
14310 rnds[8] = (rnds[8] & 0x3f) | 0x80;
14311
14312 // Copy bytes to buffer, if provided
14313 if (buf) {
14314 for (var ii = 0; ii < 16; ++ii) {
14315 buf[i + ii] = rnds[ii];
14316 }
14317 }
14318
14319 return buf || bytesToUuid(rnds);
14320}
14321
14322module.exports = v4;
14323
14324},{"106":106,"107":107}],110:[function(_dereq_,module,exports){
14325'use strict';
14326
14327/**
14328 * Stringify/parse functions that don't operate
14329 * recursively, so they avoid call stack exceeded
14330 * errors.
14331 */
14332exports.stringify = function stringify(input) {
14333 var queue = [];
14334 queue.push({obj: input});
14335
14336 var res = '';
14337 var next, obj, prefix, val, i, arrayPrefix, keys, k, key, value, objPrefix;
14338 while ((next = queue.pop())) {
14339 obj = next.obj;
14340 prefix = next.prefix || '';
14341 val = next.val || '';
14342 res += prefix;
14343 if (val) {
14344 res += val;
14345 } else if (typeof obj !== 'object') {
14346 res += typeof obj === 'undefined' ? null : JSON.stringify(obj);
14347 } else if (obj === null) {
14348 res += 'null';
14349 } else if (Array.isArray(obj)) {
14350 queue.push({val: ']'});
14351 for (i = obj.length - 1; i >= 0; i--) {
14352 arrayPrefix = i === 0 ? '' : ',';
14353 queue.push({obj: obj[i], prefix: arrayPrefix});
14354 }
14355 queue.push({val: '['});
14356 } else { // object
14357 keys = [];
14358 for (k in obj) {
14359 if (obj.hasOwnProperty(k)) {
14360 keys.push(k);
14361 }
14362 }
14363 queue.push({val: '}'});
14364 for (i = keys.length - 1; i >= 0; i--) {
14365 key = keys[i];
14366 value = obj[key];
14367 objPrefix = (i > 0 ? ',' : '');
14368 objPrefix += JSON.stringify(key) + ':';
14369 queue.push({obj: value, prefix: objPrefix});
14370 }
14371 queue.push({val: '{'});
14372 }
14373 }
14374 return res;
14375};
14376
14377// Convenience function for the parse function.
14378// This pop function is basically copied from
14379// pouchCollate.parseIndexableString
14380function pop(obj, stack, metaStack) {
14381 var lastMetaElement = metaStack[metaStack.length - 1];
14382 if (obj === lastMetaElement.element) {
14383 // popping a meta-element, e.g. an object whose value is another object
14384 metaStack.pop();
14385 lastMetaElement = metaStack[metaStack.length - 1];
14386 }
14387 var element = lastMetaElement.element;
14388 var lastElementIndex = lastMetaElement.index;
14389 if (Array.isArray(element)) {
14390 element.push(obj);
14391 } else if (lastElementIndex === stack.length - 2) { // obj with key+value
14392 var key = stack.pop();
14393 element[key] = obj;
14394 } else {
14395 stack.push(obj); // obj with key only
14396 }
14397}
14398
14399exports.parse = function (str) {
14400 var stack = [];
14401 var metaStack = []; // stack for arrays and objects
14402 var i = 0;
14403 var collationIndex,parsedNum,numChar;
14404 var parsedString,lastCh,numConsecutiveSlashes,ch;
14405 var arrayElement, objElement;
14406 while (true) {
14407 collationIndex = str[i++];
14408 if (collationIndex === '}' ||
14409 collationIndex === ']' ||
14410 typeof collationIndex === 'undefined') {
14411 if (stack.length === 1) {
14412 return stack.pop();
14413 } else {
14414 pop(stack.pop(), stack, metaStack);
14415 continue;
14416 }
14417 }
14418 switch (collationIndex) {
14419 case ' ':
14420 case '\t':
14421 case '\n':
14422 case ':':
14423 case ',':
14424 break;
14425 case 'n':
14426 i += 3; // 'ull'
14427 pop(null, stack, metaStack);
14428 break;
14429 case 't':
14430 i += 3; // 'rue'
14431 pop(true, stack, metaStack);
14432 break;
14433 case 'f':
14434 i += 4; // 'alse'
14435 pop(false, stack, metaStack);
14436 break;
14437 case '0':
14438 case '1':
14439 case '2':
14440 case '3':
14441 case '4':
14442 case '5':
14443 case '6':
14444 case '7':
14445 case '8':
14446 case '9':
14447 case '-':
14448 parsedNum = '';
14449 i--;
14450 while (true) {
14451 numChar = str[i++];
14452 if (/[\d\.\-e\+]/.test(numChar)) {
14453 parsedNum += numChar;
14454 } else {
14455 i--;
14456 break;
14457 }
14458 }
14459 pop(parseFloat(parsedNum), stack, metaStack);
14460 break;
14461 case '"':
14462 parsedString = '';
14463 lastCh = void 0;
14464 numConsecutiveSlashes = 0;
14465 while (true) {
14466 ch = str[i++];
14467 if (ch !== '"' || (lastCh === '\\' &&
14468 numConsecutiveSlashes % 2 === 1)) {
14469 parsedString += ch;
14470 lastCh = ch;
14471 if (lastCh === '\\') {
14472 numConsecutiveSlashes++;
14473 } else {
14474 numConsecutiveSlashes = 0;
14475 }
14476 } else {
14477 break;
14478 }
14479 }
14480 pop(JSON.parse('"' + parsedString + '"'), stack, metaStack);
14481 break;
14482 case '[':
14483 arrayElement = { element: [], index: stack.length };
14484 stack.push(arrayElement.element);
14485 metaStack.push(arrayElement);
14486 break;
14487 case '{':
14488 objElement = { element: {}, index: stack.length };
14489 stack.push(objElement.element);
14490 metaStack.push(objElement);
14491 break;
14492 default:
14493 throw new Error(
14494 'unexpectedly reached end of input: ' + collationIndex);
14495 }
14496 }
14497};
14498
14499},{}],111:[function(_dereq_,module,exports){
14500(function (global){
14501'use strict';
14502
14503function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
14504
14505var getArguments = _interopDefault(_dereq_(1));
14506var nextTick = _interopDefault(_dereq_(17));
14507var events = _dereq_(14);
14508var events__default = _interopDefault(events);
14509var inherits = _interopDefault(_dereq_(18));
14510var Md5 = _interopDefault(_dereq_(73));
14511var uuidV4 = _interopDefault(_dereq_(105));
14512var ltgt = _interopDefault(_dereq_(45));
14513var ReadableStreamCore = _interopDefault(_dereq_(71));
14514var Codec = _interopDefault(_dereq_(21));
14515var vuvuzela = _interopDefault(_dereq_(110));
14516var levelup = _interopDefault(_dereq_(35));
14517var through2 = _dereq_(100);
14518var Deque = _interopDefault(_dereq_(11));
14519var bufferFrom = _interopDefault(_dereq_(8));
14520var memdown = _interopDefault(_dereq_(47));
14521
14522function isBinaryObject(object) {
14523 return (typeof ArrayBuffer !== 'undefined' && object instanceof ArrayBuffer) ||
14524 (typeof Blob !== 'undefined' && object instanceof Blob);
14525}
14526
14527function cloneArrayBuffer(buff) {
14528 if (typeof buff.slice === 'function') {
14529 return buff.slice(0);
14530 }
14531 // IE10-11 slice() polyfill
14532 var target = new ArrayBuffer(buff.byteLength);
14533 var targetArray = new Uint8Array(target);
14534 var sourceArray = new Uint8Array(buff);
14535 targetArray.set(sourceArray);
14536 return target;
14537}
14538
14539function cloneBinaryObject(object) {
14540 if (object instanceof ArrayBuffer) {
14541 return cloneArrayBuffer(object);
14542 }
14543 var size = object.size;
14544 var type = object.type;
14545 // Blob
14546 if (typeof object.slice === 'function') {
14547 return object.slice(0, size, type);
14548 }
14549 // PhantomJS slice() replacement
14550 return object.webkitSlice(0, size, type);
14551}
14552
14553// most of this is borrowed from lodash.isPlainObject:
14554// https://github.com/fis-components/lodash.isplainobject/
14555// blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js
14556
14557var funcToString = Function.prototype.toString;
14558var objectCtorString = funcToString.call(Object);
14559
14560function isPlainObject(value) {
14561 var proto = Object.getPrototypeOf(value);
14562 /* istanbul ignore if */
14563 if (proto === null) { // not sure when this happens, but I guess it can
14564 return true;
14565 }
14566 var Ctor = proto.constructor;
14567 return (typeof Ctor == 'function' &&
14568 Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
14569}
14570
14571function clone(object) {
14572 var newObject;
14573 var i;
14574 var len;
14575
14576 if (!object || typeof object !== 'object') {
14577 return object;
14578 }
14579
14580 if (Array.isArray(object)) {
14581 newObject = [];
14582 for (i = 0, len = object.length; i < len; i++) {
14583 newObject[i] = clone(object[i]);
14584 }
14585 return newObject;
14586 }
14587
14588 // special case: to avoid inconsistencies between IndexedDB
14589 // and other backends, we automatically stringify Dates
14590 if (object instanceof Date) {
14591 return object.toISOString();
14592 }
14593
14594 if (isBinaryObject(object)) {
14595 return cloneBinaryObject(object);
14596 }
14597
14598 if (!isPlainObject(object)) {
14599 return object; // don't clone objects like Workers
14600 }
14601
14602 newObject = {};
14603 for (i in object) {
14604 /* istanbul ignore else */
14605 if (Object.prototype.hasOwnProperty.call(object, i)) {
14606 var value = clone(object[i]);
14607 if (typeof value !== 'undefined') {
14608 newObject[i] = value;
14609 }
14610 }
14611 }
14612 return newObject;
14613}
14614
14615function mangle(key) {
14616 return '$' + key;
14617}
14618function unmangle(key) {
14619 return key.substring(1);
14620}
14621function Map$1() {
14622 this._store = {};
14623}
14624Map$1.prototype.get = function (key) {
14625 var mangled = mangle(key);
14626 return this._store[mangled];
14627};
14628Map$1.prototype.set = function (key, value) {
14629 var mangled = mangle(key);
14630 this._store[mangled] = value;
14631 return true;
14632};
14633Map$1.prototype.has = function (key) {
14634 var mangled = mangle(key);
14635 return mangled in this._store;
14636};
14637Map$1.prototype["delete"] = function (key) {
14638 var mangled = mangle(key);
14639 var res = mangled in this._store;
14640 delete this._store[mangled];
14641 return res;
14642};
14643Map$1.prototype.forEach = function (cb) {
14644 var keys = Object.keys(this._store);
14645 for (var i = 0, len = keys.length; i < len; i++) {
14646 var key = keys[i];
14647 var value = this._store[key];
14648 key = unmangle(key);
14649 cb(value, key);
14650 }
14651};
14652Object.defineProperty(Map$1.prototype, 'size', {
14653 get: function () {
14654 return Object.keys(this._store).length;
14655 }
14656});
14657
14658function Set$1(array) {
14659 this._store = new Map$1();
14660
14661 // init with an array
14662 if (array && Array.isArray(array)) {
14663 for (var i = 0, len = array.length; i < len; i++) {
14664 this.add(array[i]);
14665 }
14666 }
14667}
14668Set$1.prototype.add = function (key) {
14669 return this._store.set(key, true);
14670};
14671Set$1.prototype.has = function (key) {
14672 return this._store.has(key);
14673};
14674Set$1.prototype.forEach = function (cb) {
14675 this._store.forEach(function (value, key) {
14676 cb(key);
14677 });
14678};
14679Object.defineProperty(Set$1.prototype, 'size', {
14680 get: function () {
14681 return this._store.size;
14682 }
14683});
14684
14685/* global Map,Set,Symbol */
14686// Based on https://kangax.github.io/compat-table/es6/ we can sniff out
14687// incomplete Map/Set implementations which would otherwise cause our tests to fail.
14688// Notably they fail in IE11 and iOS 8.4, which this prevents.
14689function supportsMapAndSet() {
14690 if (typeof Symbol === 'undefined' || typeof Map === 'undefined' || typeof Set === 'undefined') {
14691 return false;
14692 }
14693 var prop = Object.getOwnPropertyDescriptor(Map, Symbol.species);
14694 return prop && 'get' in prop && Map[Symbol.species] === Map;
14695}
14696
14697// based on https://github.com/montagejs/collections
14698
14699var ExportedSet;
14700var ExportedMap;
14701
14702{
14703 if (supportsMapAndSet()) { // prefer built-in Map/Set
14704 ExportedSet = Set;
14705 ExportedMap = Map;
14706 } else { // fall back to our polyfill
14707 ExportedSet = Set$1;
14708 ExportedMap = Map$1;
14709 }
14710}
14711
14712// like underscore/lodash _.pick()
14713function pick(obj, arr) {
14714 var res = {};
14715 for (var i = 0, len = arr.length; i < len; i++) {
14716 var prop = arr[i];
14717 if (prop in obj) {
14718 res[prop] = obj[prop];
14719 }
14720 }
14721 return res;
14722}
14723
14724var hasLocal;
14725
14726try {
14727 localStorage.setItem('_pouch_check_localstorage', 1);
14728 hasLocal = !!localStorage.getItem('_pouch_check_localstorage');
14729} catch (e) {
14730 hasLocal = false;
14731}
14732
14733function hasLocalStorage() {
14734 return hasLocal;
14735}
14736
14737// Custom nextTick() shim for browsers. In node, this will just be process.nextTick(). We
14738
14739inherits(Changes, events.EventEmitter);
14740
14741/* istanbul ignore next */
14742function attachBrowserEvents(self) {
14743 if (hasLocalStorage()) {
14744 addEventListener("storage", function (e) {
14745 self.emit(e.key);
14746 });
14747 }
14748}
14749
14750function Changes() {
14751 events.EventEmitter.call(this);
14752 this._listeners = {};
14753
14754 attachBrowserEvents(this);
14755}
14756Changes.prototype.addListener = function (dbName, id, db, opts) {
14757 /* istanbul ignore if */
14758 if (this._listeners[id]) {
14759 return;
14760 }
14761 var self = this;
14762 var inprogress = false;
14763 function eventFunction() {
14764 /* istanbul ignore if */
14765 if (!self._listeners[id]) {
14766 return;
14767 }
14768 if (inprogress) {
14769 inprogress = 'waiting';
14770 return;
14771 }
14772 inprogress = true;
14773 var changesOpts = pick(opts, [
14774 'style', 'include_docs', 'attachments', 'conflicts', 'filter',
14775 'doc_ids', 'view', 'since', 'query_params', 'binary', 'return_docs'
14776 ]);
14777
14778 /* istanbul ignore next */
14779 function onError() {
14780 inprogress = false;
14781 }
14782
14783 db.changes(changesOpts).on('change', function (c) {
14784 if (c.seq > opts.since && !opts.cancelled) {
14785 opts.since = c.seq;
14786 opts.onChange(c);
14787 }
14788 }).on('complete', function () {
14789 if (inprogress === 'waiting') {
14790 nextTick(eventFunction);
14791 }
14792 inprogress = false;
14793 }).on('error', onError);
14794 }
14795 this._listeners[id] = eventFunction;
14796 this.on(dbName, eventFunction);
14797};
14798
14799Changes.prototype.removeListener = function (dbName, id) {
14800 /* istanbul ignore if */
14801 if (!(id in this._listeners)) {
14802 return;
14803 }
14804 events.EventEmitter.prototype.removeListener.call(this, dbName,
14805 this._listeners[id]);
14806 delete this._listeners[id];
14807};
14808
14809
14810/* istanbul ignore next */
14811Changes.prototype.notifyLocalWindows = function (dbName) {
14812 //do a useless change on a storage thing
14813 //in order to get other windows's listeners to activate
14814 if (hasLocalStorage()) {
14815 localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a";
14816 }
14817};
14818
14819Changes.prototype.notify = function (dbName) {
14820 this.emit(dbName);
14821 this.notifyLocalWindows(dbName);
14822};
14823
14824function guardedConsole(method) {
14825 /* istanbul ignore else */
14826 if (typeof console !== 'undefined' && typeof console[method] === 'function') {
14827 var args = Array.prototype.slice.call(arguments, 1);
14828 console[method].apply(console, args);
14829 }
14830}
14831
14832var assign;
14833{
14834 if (typeof Object.assign === 'function') {
14835 assign = Object.assign;
14836 } else {
14837 // lite Object.assign polyfill based on
14838 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
14839 assign = function (target) {
14840 var to = Object(target);
14841
14842 for (var index = 1; index < arguments.length; index++) {
14843 var nextSource = arguments[index];
14844
14845 if (nextSource != null) { // Skip over if undefined or null
14846 for (var nextKey in nextSource) {
14847 // Avoid bugs when hasOwnProperty is shadowed
14848 if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
14849 to[nextKey] = nextSource[nextKey];
14850 }
14851 }
14852 }
14853 }
14854 return to;
14855 };
14856 }
14857}
14858
14859var $inject_Object_assign = assign;
14860
14861inherits(PouchError, Error);
14862
14863function PouchError(status, error, reason) {
14864 Error.call(this, reason);
14865 this.status = status;
14866 this.name = error;
14867 this.message = reason;
14868 this.error = true;
14869}
14870
14871PouchError.prototype.toString = function () {
14872 return JSON.stringify({
14873 status: this.status,
14874 name: this.name,
14875 message: this.message,
14876 reason: this.reason
14877 });
14878};
14879
14880var UNAUTHORIZED = new PouchError(401, 'unauthorized', "Name or password is incorrect.");
14881var MISSING_BULK_DOCS = new PouchError(400, 'bad_request', "Missing JSON list of 'docs'");
14882var MISSING_DOC = new PouchError(404, 'not_found', 'missing');
14883var REV_CONFLICT = new PouchError(409, 'conflict', 'Document update conflict');
14884var INVALID_ID = new PouchError(400, 'bad_request', '_id field must contain a string');
14885var MISSING_ID = new PouchError(412, 'missing_id', '_id is required for puts');
14886var RESERVED_ID = new PouchError(400, 'bad_request', 'Only reserved document ids may start with underscore.');
14887var NOT_OPEN = new PouchError(412, 'precondition_failed', 'Database not open');
14888var UNKNOWN_ERROR = new PouchError(500, 'unknown_error', 'Database encountered an unknown error');
14889var BAD_ARG = new PouchError(500, 'badarg', 'Some query argument is invalid');
14890var INVALID_REQUEST = new PouchError(400, 'invalid_request', 'Request was invalid');
14891var QUERY_PARSE_ERROR = new PouchError(400, 'query_parse_error', 'Some query parameter is invalid');
14892var DOC_VALIDATION = new PouchError(500, 'doc_validation', 'Bad special document member');
14893var BAD_REQUEST = new PouchError(400, 'bad_request', 'Something wrong with the request');
14894var NOT_AN_OBJECT = new PouchError(400, 'bad_request', 'Document must be a JSON object');
14895var DB_MISSING = new PouchError(404, 'not_found', 'Database not found');
14896var IDB_ERROR = new PouchError(500, 'indexed_db_went_bad', 'unknown');
14897var WSQ_ERROR = new PouchError(500, 'web_sql_went_bad', 'unknown');
14898var LDB_ERROR = new PouchError(500, 'levelDB_went_went_bad', 'unknown');
14899var FORBIDDEN = new PouchError(403, 'forbidden', 'Forbidden by design doc validate_doc_update function');
14900var INVALID_REV = new PouchError(400, 'bad_request', 'Invalid rev format');
14901var FILE_EXISTS = new PouchError(412, 'file_exists', 'The database could not be created, the file already exists.');
14902var MISSING_STUB = new PouchError(412, 'missing_stub', 'A pre-existing attachment stub wasn\'t found');
14903var INVALID_URL = new PouchError(413, 'invalid_url', 'Provided URL is invalid');
14904
14905function createError(error, reason) {
14906 function CustomPouchError(reason) {
14907 // inherit error properties from our parent error manually
14908 // so as to allow proper JSON parsing.
14909 /* jshint ignore:start */
14910 for (var p in error) {
14911 if (typeof error[p] !== 'function') {
14912 this[p] = error[p];
14913 }
14914 }
14915 /* jshint ignore:end */
14916 if (reason !== undefined) {
14917 this.reason = reason;
14918 }
14919 }
14920 CustomPouchError.prototype = PouchError.prototype;
14921 return new CustomPouchError(reason);
14922}
14923
14924function tryFilter(filter, doc, req) {
14925 try {
14926 return !filter(doc, req);
14927 } catch (err) {
14928 var msg = 'Filter function threw: ' + err.toString();
14929 return createError(BAD_REQUEST, msg);
14930 }
14931}
14932
14933function filterChange(opts) {
14934 var req = {};
14935 var hasFilter = opts.filter && typeof opts.filter === 'function';
14936 req.query = opts.query_params;
14937
14938 return function filter(change) {
14939 if (!change.doc) {
14940 // CSG sends events on the changes feed that don't have documents,
14941 // this hack makes a whole lot of existing code robust.
14942 change.doc = {};
14943 }
14944
14945 var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req);
14946
14947 if (typeof filterReturn === 'object') {
14948 return filterReturn;
14949 }
14950
14951 if (filterReturn) {
14952 return false;
14953 }
14954
14955 if (!opts.include_docs) {
14956 delete change.doc;
14957 } else if (!opts.attachments) {
14958 for (var att in change.doc._attachments) {
14959 /* istanbul ignore else */
14960 if (change.doc._attachments.hasOwnProperty(att)) {
14961 change.doc._attachments[att].stub = true;
14962 }
14963 }
14964 }
14965 return true;
14966 };
14967}
14968
14969// shim for Function.prototype.name,
14970// for browsers that don't support it like IE
14971
14972/* istanbul ignore next */
14973function f() {}
14974
14975var hasName = f.name;
14976var res;
14977
14978// We dont run coverage in IE
14979/* istanbul ignore else */
14980if (hasName) {
14981 res = function (fun) {
14982 return fun.name;
14983 };
14984} else {
14985 res = function (fun) {
14986 var match = fun.toString().match(/^\s*function\s*(?:(\S+)\s*)?\(/);
14987 if (match && match[1]) {
14988 return match[1];
14989 }
14990 else {
14991 return '';
14992 }
14993 };
14994}
14995
14996var functionName = res;
14997
14998// Determine id an ID is valid
14999// - invalid IDs begin with an underescore that does not begin '_design' or
15000// '_local'
15001// - any other string value is a valid id
15002// Returns the specific error object for each case
15003function invalidIdError(id) {
15004 var err;
15005 if (!id) {
15006 err = createError(MISSING_ID);
15007 } else if (typeof id !== 'string') {
15008 err = createError(INVALID_ID);
15009 } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {
15010 err = createError(RESERVED_ID);
15011 }
15012 if (err) {
15013 throw err;
15014 }
15015}
15016
15017// Checks if a PouchDB object is "remote" or not. This is
15018
15019// originally parseUri 1.2.2, now patched by us
15020
15021// Based on https://github.com/alexdavid/scope-eval v0.0.3
15022
15023var thisAtob = function (str) {
15024 return atob(str);
15025};
15026
15027var thisBtoa = function (str) {
15028 return btoa(str);
15029};
15030
15031// Abstracts constructing a Blob object, so it also works in older
15032// browsers that don't support the native Blob constructor (e.g.
15033// old QtWebKit versions, Android < 4.4).
15034function createBlob(parts, properties) {
15035 /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
15036 parts = parts || [];
15037 properties = properties || {};
15038 try {
15039 return new Blob(parts, properties);
15040 } catch (e) {
15041 if (e.name !== "TypeError") {
15042 throw e;
15043 }
15044 var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
15045 typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
15046 typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
15047 WebKitBlobBuilder;
15048 var builder = new Builder();
15049 for (var i = 0; i < parts.length; i += 1) {
15050 builder.append(parts[i]);
15051 }
15052 return builder.getBlob(properties.type);
15053 }
15054}
15055
15056// From http://stackoverflow.com/questions/14967647/ (continues on next line)
15057// encode-decode-image-with-base64-breaks-image (2013-04-21)
15058function binaryStringToArrayBuffer(bin) {
15059 var length = bin.length;
15060 var buf = new ArrayBuffer(length);
15061 var arr = new Uint8Array(buf);
15062 for (var i = 0; i < length; i++) {
15063 arr[i] = bin.charCodeAt(i);
15064 }
15065 return buf;
15066}
15067
15068function binStringToBluffer(binString, type) {
15069 return createBlob([binaryStringToArrayBuffer(binString)], {type: type});
15070}
15071
15072//Can't find original post, but this is close
15073//http://stackoverflow.com/questions/6965107/ (continues on next line)
15074//converting-between-strings-and-arraybuffers
15075function arrayBufferToBinaryString(buffer) {
15076 var binary = '';
15077 var bytes = new Uint8Array(buffer);
15078 var length = bytes.byteLength;
15079 for (var i = 0; i < length; i++) {
15080 binary += String.fromCharCode(bytes[i]);
15081 }
15082 return binary;
15083}
15084
15085// shim for browsers that don't support it
15086function readAsBinaryString(blob, callback) {
15087 var reader = new FileReader();
15088 var hasBinaryString = typeof reader.readAsBinaryString === 'function';
15089 reader.onloadend = function (e) {
15090 var result = e.target.result || '';
15091 if (hasBinaryString) {
15092 return callback(result);
15093 }
15094 callback(arrayBufferToBinaryString(result));
15095 };
15096 if (hasBinaryString) {
15097 reader.readAsBinaryString(blob);
15098 } else {
15099 reader.readAsArrayBuffer(blob);
15100 }
15101}
15102
15103// simplified API. universal browser support is assumed
15104function readAsArrayBuffer(blob, callback) {
15105 var reader = new FileReader();
15106 reader.onloadend = function (e) {
15107 var result = e.target.result || new ArrayBuffer(0);
15108 callback(result);
15109 };
15110 reader.readAsArrayBuffer(blob);
15111}
15112
15113// this is not used in the browser
15114
15115var setImmediateShim = global.setImmediate || global.setTimeout;
15116var MD5_CHUNK_SIZE = 32768;
15117
15118function rawToBase64(raw) {
15119 return thisBtoa(raw);
15120}
15121
15122function sliceBlob(blob, start, end) {
15123 if (blob.webkitSlice) {
15124 return blob.webkitSlice(start, end);
15125 }
15126 return blob.slice(start, end);
15127}
15128
15129function appendBlob(buffer, blob, start, end, callback) {
15130 if (start > 0 || end < blob.size) {
15131 // only slice blob if we really need to
15132 blob = sliceBlob(blob, start, end);
15133 }
15134 readAsArrayBuffer(blob, function (arrayBuffer) {
15135 buffer.append(arrayBuffer);
15136 callback();
15137 });
15138}
15139
15140function appendString(buffer, string, start, end, callback) {
15141 if (start > 0 || end < string.length) {
15142 // only create a substring if we really need to
15143 string = string.substring(start, end);
15144 }
15145 buffer.appendBinary(string);
15146 callback();
15147}
15148
15149function binaryMd5(data, callback) {
15150 var inputIsString = typeof data === 'string';
15151 var len = inputIsString ? data.length : data.size;
15152 var chunkSize = Math.min(MD5_CHUNK_SIZE, len);
15153 var chunks = Math.ceil(len / chunkSize);
15154 var currentChunk = 0;
15155 var buffer = inputIsString ? new Md5() : new Md5.ArrayBuffer();
15156
15157 var append = inputIsString ? appendString : appendBlob;
15158
15159 function next() {
15160 setImmediateShim(loadNextChunk);
15161 }
15162
15163 function done() {
15164 var raw = buffer.end(true);
15165 var base64 = rawToBase64(raw);
15166 callback(base64);
15167 buffer.destroy();
15168 }
15169
15170 function loadNextChunk() {
15171 var start = currentChunk * chunkSize;
15172 var end = start + chunkSize;
15173 currentChunk++;
15174 if (currentChunk < chunks) {
15175 append(buffer, data, start, end, next);
15176 } else {
15177 append(buffer, data, start, end, done);
15178 }
15179 }
15180 loadNextChunk();
15181}
15182
15183function stringMd5(string) {
15184 return Md5.hash(string);
15185}
15186
15187function rev$$1(doc, deterministic_revs) {
15188 var clonedDoc = clone(doc);
15189 if (!deterministic_revs) {
15190 return uuidV4.v4().replace(/-/g, '').toLowerCase();
15191 }
15192
15193 delete clonedDoc._rev_tree;
15194 return stringMd5(JSON.stringify(clonedDoc));
15195}
15196
15197var uuid = uuidV4.v4;
15198
15199function isFunction(f) {
15200 return 'function' === typeof f;
15201}
15202
15203function getPrefix(db) {
15204 if (isFunction(db.prefix)) {
15205 return db.prefix();
15206 }
15207 return db;
15208}
15209
15210function clone$1(_obj) {
15211 var obj = {};
15212 for (var k in _obj) {
15213 obj[k] = _obj[k];
15214 }
15215 return obj;
15216}
15217
15218function nut(db, precodec, codec) {
15219 function encodePrefix(prefix, key, opts1, opts2) {
15220 return precodec.encode([ prefix, codec.encodeKey(key, opts1, opts2 ) ]);
15221 }
15222
15223 function addEncodings(op, prefix) {
15224 if (prefix && prefix.options) {
15225 op.keyEncoding =
15226 op.keyEncoding || prefix.options.keyEncoding;
15227 op.valueEncoding =
15228 op.valueEncoding || prefix.options.valueEncoding;
15229 }
15230 return op;
15231 }
15232
15233 db.open(function () { /* no-op */});
15234
15235 return {
15236 apply: function (ops, opts, cb) {
15237 opts = opts || {};
15238
15239 var batch = [];
15240 var i = -1;
15241 var len = ops.length;
15242
15243 while (++i < len) {
15244 var op = ops[i];
15245 addEncodings(op, op.prefix);
15246 op.prefix = getPrefix(op.prefix);
15247 batch.push({
15248 key: encodePrefix(op.prefix, op.key, opts, op),
15249 value: op.type !== 'del' && codec.encodeValue(op.value, opts, op),
15250 type: op.type
15251 });
15252 }
15253 db.db.batch(batch, opts, cb);
15254 },
15255 get: function (key, prefix, opts, cb) {
15256 opts.asBuffer = codec.valueAsBuffer(opts);
15257 return db.db.get(
15258 encodePrefix(prefix, key, opts),
15259 opts,
15260 function (err, value) {
15261 if (err) {
15262 cb(err);
15263 } else {
15264 cb(null, codec.decodeValue(value, opts));
15265 }
15266 }
15267 );
15268 },
15269 createDecoder: function (opts) {
15270 return function (key, value) {
15271 return {
15272 key: codec.decodeKey(precodec.decode(key)[1], opts),
15273 value: codec.decodeValue(value, opts)
15274 };
15275 };
15276 },
15277 isClosed: function isClosed() {
15278 return db.isClosed();
15279 },
15280 close: function close(cb) {
15281 return db.close(cb);
15282 },
15283 iterator: function (_opts) {
15284 var opts = clone$1(_opts || {});
15285 var prefix = _opts.prefix || [];
15286
15287 function encodeKey(key) {
15288 return encodePrefix(prefix, key, opts, {});
15289 }
15290
15291 ltgt.toLtgt(_opts, opts, encodeKey, precodec.lowerBound, precodec.upperBound);
15292
15293 // if these legacy values are in the options, remove them
15294
15295 opts.prefix = null;
15296
15297 //************************************************
15298 //hard coded defaults, for now...
15299 //TODO: pull defaults and encoding out of levelup.
15300 opts.keyAsBuffer = opts.valueAsBuffer = false;
15301 //************************************************
15302
15303
15304 //this is vital, otherwise limit: undefined will
15305 //create an empty stream.
15306 /* istanbul ignore next */
15307 if ('number' !== typeof opts.limit) {
15308 opts.limit = -1;
15309 }
15310
15311 opts.keyAsBuffer = precodec.buffer;
15312 opts.valueAsBuffer = codec.valueAsBuffer(opts);
15313
15314 function wrapIterator(iterator) {
15315 return {
15316 next: function (cb) {
15317 return iterator.next(cb);
15318 },
15319 end: function (cb) {
15320 iterator.end(cb);
15321 }
15322 };
15323 }
15324
15325 return wrapIterator(db.db.iterator(opts));
15326 }
15327 };
15328}
15329
15330function NotFoundError() {
15331 Error.call(this);
15332}
15333
15334inherits(NotFoundError, Error);
15335
15336NotFoundError.prototype.name = 'NotFoundError';
15337
15338var EventEmitter = events__default.EventEmitter;
15339var version = "6.5.4";
15340
15341var NOT_FOUND_ERROR = new NotFoundError();
15342
15343var sublevel = function (nut, prefix, createStream, options) {
15344 var emitter = new EventEmitter();
15345 emitter.sublevels = {};
15346 emitter.options = options;
15347
15348 emitter.version = version;
15349
15350 emitter.methods = {};
15351 prefix = prefix || [];
15352
15353 function mergeOpts(opts) {
15354 var o = {};
15355 var k;
15356 if (options) {
15357 for (k in options) {
15358 if (typeof options[k] !== 'undefined') {
15359 o[k] = options[k];
15360 }
15361 }
15362 }
15363 if (opts) {
15364 for (k in opts) {
15365 if (typeof opts[k] !== 'undefined') {
15366 o[k] = opts[k];
15367 }
15368 }
15369 }
15370 return o;
15371 }
15372
15373 emitter.put = function (key, value, opts, cb) {
15374 if ('function' === typeof opts) {
15375 cb = opts;
15376 opts = {};
15377 }
15378
15379 nut.apply([{
15380 key: key, value: value,
15381 prefix: prefix.slice(), type: 'put'
15382 }], mergeOpts(opts), function (err) {
15383 /* istanbul ignore next */
15384 if (err) {
15385 return cb(err);
15386 }
15387 emitter.emit('put', key, value);
15388 cb(null);
15389 });
15390 };
15391
15392 emitter.prefix = function () {
15393 return prefix.slice();
15394 };
15395
15396 emitter.batch = function (ops, opts, cb) {
15397 if ('function' === typeof opts) {
15398 cb = opts;
15399 opts = {};
15400 }
15401
15402 ops = ops.map(function (op) {
15403 return {
15404 key: op.key,
15405 value: op.value,
15406 prefix: op.prefix || prefix,
15407 keyEncoding: op.keyEncoding, // *
15408 valueEncoding: op.valueEncoding, // * (TODO: encodings on sublevel)
15409 type: op.type
15410 };
15411 });
15412
15413 nut.apply(ops, mergeOpts(opts), function (err) {
15414 /* istanbul ignore next */
15415 if (err) {
15416 return cb(err);
15417 }
15418 emitter.emit('batch', ops);
15419 cb(null);
15420 });
15421 };
15422
15423 emitter.get = function (key, opts, cb) {
15424 /* istanbul ignore else */
15425 if ('function' === typeof opts) {
15426 cb = opts;
15427 opts = {};
15428 }
15429 nut.get(key, prefix, mergeOpts(opts), function (err, value) {
15430 if (err) {
15431 cb(NOT_FOUND_ERROR);
15432 } else {
15433 cb(null, value);
15434 }
15435 });
15436 };
15437
15438 emitter.sublevel = function (name, opts) {
15439 return emitter.sublevels[name] =
15440 emitter.sublevels[name] || sublevel(nut, prefix.concat(name), createStream, mergeOpts(opts));
15441 };
15442
15443 emitter.readStream = emitter.createReadStream = function (opts) {
15444 opts = mergeOpts(opts);
15445 opts.prefix = prefix;
15446 var stream;
15447 var it = nut.iterator(opts);
15448
15449 stream = createStream(opts, nut.createDecoder(opts));
15450 stream.setIterator(it);
15451
15452 return stream;
15453 };
15454
15455 emitter.close = function (cb) {
15456 nut.close(cb);
15457 };
15458
15459 emitter.isOpen = nut.isOpen;
15460 emitter.isClosed = nut.isClosed;
15461
15462 return emitter;
15463};
15464
15465/* Copyright (c) 2012-2014 LevelUP contributors
15466 * See list at <https://github.com/rvagg/node-levelup#contributing>
15467 * MIT License <https://github.com/rvagg/node-levelup/blob/master/LICENSE.md>
15468 */
15469
15470var Readable = ReadableStreamCore.Readable;
15471
15472function ReadStream(options, makeData) {
15473 if (!(this instanceof ReadStream)) {
15474 return new ReadStream(options, makeData);
15475 }
15476
15477 Readable.call(this, { objectMode: true, highWaterMark: options.highWaterMark });
15478
15479 // purely to keep `db` around until we're done so it's not GCed if the user doesn't keep a ref
15480
15481 this._waiting = false;
15482 this._options = options;
15483 this._makeData = makeData;
15484}
15485
15486inherits(ReadStream, Readable);
15487
15488ReadStream.prototype.setIterator = function (it) {
15489 this._iterator = it;
15490 /* istanbul ignore if */
15491 if (this._destroyed) {
15492 return it.end(function () {});
15493 }
15494 /* istanbul ignore if */
15495 if (this._waiting) {
15496 this._waiting = false;
15497 return this._read();
15498 }
15499 return this;
15500};
15501
15502ReadStream.prototype._read = function read() {
15503 var self = this;
15504 /* istanbul ignore if */
15505 if (self._destroyed) {
15506 return;
15507 }
15508 /* istanbul ignore if */
15509 if (!self._iterator) {
15510 return this._waiting = true;
15511 }
15512
15513 self._iterator.next(function (err, key, value) {
15514 if (err || (key === undefined && value === undefined)) {
15515 if (!err && !self._destroyed) {
15516 self.push(null);
15517 }
15518 return self._cleanup(err);
15519 }
15520
15521
15522 value = self._makeData(key, value);
15523 if (!self._destroyed) {
15524 self.push(value);
15525 }
15526 });
15527};
15528
15529ReadStream.prototype._cleanup = function (err) {
15530 if (this._destroyed) {
15531 return;
15532 }
15533
15534 this._destroyed = true;
15535
15536 var self = this;
15537 /* istanbul ignore if */
15538 if (err && err.message !== 'iterator has ended') {
15539 self.emit('error', err);
15540 }
15541
15542 /* istanbul ignore else */
15543 if (self._iterator) {
15544 self._iterator.end(function () {
15545 self._iterator = null;
15546 self.emit('close');
15547 });
15548 } else {
15549 self.emit('close');
15550 }
15551};
15552
15553ReadStream.prototype.destroy = function () {
15554 this._cleanup();
15555};
15556
15557var precodec = {
15558 encode: function (decodedKey) {
15559 return '\xff' + decodedKey[0] + '\xff' + decodedKey[1];
15560 },
15561 decode: function (encodedKeyAsBuffer) {
15562 var str = encodedKeyAsBuffer.toString();
15563 var idx = str.indexOf('\xff', 1);
15564 return [str.substring(1, idx), str.substring(idx + 1)];
15565 },
15566 lowerBound: '\x00',
15567 upperBound: '\xff'
15568};
15569
15570var codec = new Codec();
15571
15572function sublevelPouch(db) {
15573 return sublevel(nut(db, precodec, codec), [], ReadStream, db.options);
15574}
15575
15576function allDocsKeysQuery(api, opts) {
15577 var keys = opts.keys;
15578 var finalResults = {
15579 offset: opts.skip
15580 };
15581 return Promise.all(keys.map(function (key) {
15582 var subOpts = $inject_Object_assign({key: key, deleted: 'ok'}, opts);
15583 ['limit', 'skip', 'keys'].forEach(function (optKey) {
15584 delete subOpts[optKey];
15585 });
15586 return new Promise(function (resolve, reject) {
15587 api._allDocs(subOpts, function (err, res) {
15588 /* istanbul ignore if */
15589 if (err) {
15590 return reject(err);
15591 }
15592 /* istanbul ignore if */
15593 if (opts.update_seq && res.update_seq !== undefined) {
15594 finalResults.update_seq = res.update_seq;
15595 }
15596 finalResults.total_rows = res.total_rows;
15597 resolve(res.rows[0] || {key: key, error: 'not_found'});
15598 });
15599 });
15600 })).then(function (results) {
15601 finalResults.rows = results;
15602 return finalResults;
15603 });
15604}
15605
15606function toObject(array) {
15607 return array.reduce(function (obj, item) {
15608 obj[item] = true;
15609 return obj;
15610 }, {});
15611}
15612// List of top level reserved words for doc
15613var reservedWords = toObject([
15614 '_id',
15615 '_rev',
15616 '_attachments',
15617 '_deleted',
15618 '_revisions',
15619 '_revs_info',
15620 '_conflicts',
15621 '_deleted_conflicts',
15622 '_local_seq',
15623 '_rev_tree',
15624 //replication documents
15625 '_replication_id',
15626 '_replication_state',
15627 '_replication_state_time',
15628 '_replication_state_reason',
15629 '_replication_stats',
15630 // Specific to Couchbase Sync Gateway
15631 '_removed'
15632]);
15633
15634// List of reserved words that should end up the document
15635var dataWords = toObject([
15636 '_attachments',
15637 //replication documents
15638 '_replication_id',
15639 '_replication_state',
15640 '_replication_state_time',
15641 '_replication_state_reason',
15642 '_replication_stats'
15643]);
15644
15645function parseRevisionInfo(rev) {
15646 if (!/^\d+-./.test(rev)) {
15647 return createError(INVALID_REV);
15648 }
15649 var idx = rev.indexOf('-');
15650 var left = rev.substring(0, idx);
15651 var right = rev.substring(idx + 1);
15652 return {
15653 prefix: parseInt(left, 10),
15654 id: right
15655 };
15656}
15657
15658function makeRevTreeFromRevisions(revisions, opts) {
15659 var pos = revisions.start - revisions.ids.length + 1;
15660
15661 var revisionIds = revisions.ids;
15662 var ids = [revisionIds[0], opts, []];
15663
15664 for (var i = 1, len = revisionIds.length; i < len; i++) {
15665 ids = [revisionIds[i], {status: 'missing'}, [ids]];
15666 }
15667
15668 return [{
15669 pos: pos,
15670 ids: ids
15671 }];
15672}
15673
15674// Preprocess documents, parse their revisions, assign an id and a
15675// revision for new writes that are missing them, etc
15676function parseDoc(doc, newEdits, dbOpts) {
15677 if (!dbOpts) {
15678 dbOpts = {
15679 deterministic_revs: true
15680 };
15681 }
15682
15683 var nRevNum;
15684 var newRevId;
15685 var revInfo;
15686 var opts = {status: 'available'};
15687 if (doc._deleted) {
15688 opts.deleted = true;
15689 }
15690
15691 if (newEdits) {
15692 if (!doc._id) {
15693 doc._id = uuid();
15694 }
15695 newRevId = rev$$1(doc, dbOpts.deterministic_revs);
15696 if (doc._rev) {
15697 revInfo = parseRevisionInfo(doc._rev);
15698 if (revInfo.error) {
15699 return revInfo;
15700 }
15701 doc._rev_tree = [{
15702 pos: revInfo.prefix,
15703 ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]]
15704 }];
15705 nRevNum = revInfo.prefix + 1;
15706 } else {
15707 doc._rev_tree = [{
15708 pos: 1,
15709 ids : [newRevId, opts, []]
15710 }];
15711 nRevNum = 1;
15712 }
15713 } else {
15714 if (doc._revisions) {
15715 doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts);
15716 nRevNum = doc._revisions.start;
15717 newRevId = doc._revisions.ids[0];
15718 }
15719 if (!doc._rev_tree) {
15720 revInfo = parseRevisionInfo(doc._rev);
15721 if (revInfo.error) {
15722 return revInfo;
15723 }
15724 nRevNum = revInfo.prefix;
15725 newRevId = revInfo.id;
15726 doc._rev_tree = [{
15727 pos: nRevNum,
15728 ids: [newRevId, opts, []]
15729 }];
15730 }
15731 }
15732
15733 invalidIdError(doc._id);
15734
15735 doc._rev = nRevNum + '-' + newRevId;
15736
15737 var result = {metadata : {}, data : {}};
15738 for (var key in doc) {
15739 /* istanbul ignore else */
15740 if (Object.prototype.hasOwnProperty.call(doc, key)) {
15741 var specialKey = key[0] === '_';
15742 if (specialKey && !reservedWords[key]) {
15743 var error = createError(DOC_VALIDATION, key);
15744 error.message = DOC_VALIDATION.message + ': ' + key;
15745 throw error;
15746 } else if (specialKey && !dataWords[key]) {
15747 result.metadata[key.slice(1)] = doc[key];
15748 } else {
15749 result.data[key] = doc[key];
15750 }
15751 }
15752 }
15753 return result;
15754}
15755
15756// We fetch all leafs of the revision tree, and sort them based on tree length
15757// and whether they were deleted, undeleted documents with the longest revision
15758// tree (most edits) win
15759// The final sort algorithm is slightly documented in a sidebar here:
15760// http://guide.couchdb.org/draft/conflicts.html
15761function winningRev(metadata) {
15762 var winningId;
15763 var winningPos;
15764 var winningDeleted;
15765 var toVisit = metadata.rev_tree.slice();
15766 var node;
15767 while ((node = toVisit.pop())) {
15768 var tree = node.ids;
15769 var branches = tree[2];
15770 var pos = node.pos;
15771 if (branches.length) { // non-leaf
15772 for (var i = 0, len = branches.length; i < len; i++) {
15773 toVisit.push({pos: pos + 1, ids: branches[i]});
15774 }
15775 continue;
15776 }
15777 var deleted = !!tree[1].deleted;
15778 var id = tree[0];
15779 // sort by deleted, then pos, then id
15780 if (!winningId || (winningDeleted !== deleted ? winningDeleted :
15781 winningPos !== pos ? winningPos < pos : winningId < id)) {
15782 winningId = id;
15783 winningPos = pos;
15784 winningDeleted = deleted;
15785 }
15786 }
15787
15788 return winningPos + '-' + winningId;
15789}
15790
15791// Pretty much all below can be combined into a higher order function to
15792// traverse revisions
15793// The return value from the callback will be passed as context to all
15794// children of that node
15795function traverseRevTree(revs, callback) {
15796 var toVisit = revs.slice();
15797
15798 var node;
15799 while ((node = toVisit.pop())) {
15800 var pos = node.pos;
15801 var tree = node.ids;
15802 var branches = tree[2];
15803 var newCtx =
15804 callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]);
15805 for (var i = 0, len = branches.length; i < len; i++) {
15806 toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx});
15807 }
15808 }
15809}
15810
15811function sortByPos(a, b) {
15812 return a.pos - b.pos;
15813}
15814
15815function collectLeaves(revs) {
15816 var leaves = [];
15817 traverseRevTree(revs, function (isLeaf, pos, id, acc, opts) {
15818 if (isLeaf) {
15819 leaves.push({rev: pos + "-" + id, pos: pos, opts: opts});
15820 }
15821 });
15822 leaves.sort(sortByPos).reverse();
15823 for (var i = 0, len = leaves.length; i < len; i++) {
15824 delete leaves[i].pos;
15825 }
15826 return leaves;
15827}
15828
15829// returns revs of all conflicts that is leaves such that
15830// 1. are not deleted and
15831// 2. are different than winning revision
15832function collectConflicts(metadata) {
15833 var win = winningRev(metadata);
15834 var leaves = collectLeaves(metadata.rev_tree);
15835 var conflicts = [];
15836 for (var i = 0, len = leaves.length; i < len; i++) {
15837 var leaf = leaves[i];
15838 if (leaf.rev !== win && !leaf.opts.deleted) {
15839 conflicts.push(leaf.rev);
15840 }
15841 }
15842 return conflicts;
15843}
15844
15845// compact a tree by marking its non-leafs as missing,
15846// and return a list of revs to delete
15847function compactTree(metadata) {
15848 var revs = [];
15849 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
15850 revHash, ctx, opts) {
15851 if (opts.status === 'available' && !isLeaf) {
15852 revs.push(pos + '-' + revHash);
15853 opts.status = 'missing';
15854 }
15855 });
15856 return revs;
15857}
15858
15859// build up a list of all the paths to the leafs in this revision tree
15860function rootToLeaf(revs) {
15861 var paths = [];
15862 var toVisit = revs.slice();
15863 var node;
15864 while ((node = toVisit.pop())) {
15865 var pos = node.pos;
15866 var tree = node.ids;
15867 var id = tree[0];
15868 var opts = tree[1];
15869 var branches = tree[2];
15870 var isLeaf = branches.length === 0;
15871
15872 var history = node.history ? node.history.slice() : [];
15873 history.push({id: id, opts: opts});
15874 if (isLeaf) {
15875 paths.push({pos: (pos + 1 - history.length), ids: history});
15876 }
15877 for (var i = 0, len = branches.length; i < len; i++) {
15878 toVisit.push({pos: pos + 1, ids: branches[i], history: history});
15879 }
15880 }
15881 return paths.reverse();
15882}
15883
15884// for a better overview of what this is doing, read:
15885
15886function sortByPos$1(a, b) {
15887 return a.pos - b.pos;
15888}
15889
15890// classic binary search
15891function binarySearch(arr, item, comparator) {
15892 var low = 0;
15893 var high = arr.length;
15894 var mid;
15895 while (low < high) {
15896 mid = (low + high) >>> 1;
15897 if (comparator(arr[mid], item) < 0) {
15898 low = mid + 1;
15899 } else {
15900 high = mid;
15901 }
15902 }
15903 return low;
15904}
15905
15906// assuming the arr is sorted, insert the item in the proper place
15907function insertSorted(arr, item, comparator) {
15908 var idx = binarySearch(arr, item, comparator);
15909 arr.splice(idx, 0, item);
15910}
15911
15912// Turn a path as a flat array into a tree with a single branch.
15913// If any should be stemmed from the beginning of the array, that's passed
15914// in as the second argument
15915function pathToTree(path, numStemmed) {
15916 var root;
15917 var leaf;
15918 for (var i = numStemmed, len = path.length; i < len; i++) {
15919 var node = path[i];
15920 var currentLeaf = [node.id, node.opts, []];
15921 if (leaf) {
15922 leaf[2].push(currentLeaf);
15923 leaf = currentLeaf;
15924 } else {
15925 root = leaf = currentLeaf;
15926 }
15927 }
15928 return root;
15929}
15930
15931// compare the IDs of two trees
15932function compareTree(a, b) {
15933 return a[0] < b[0] ? -1 : 1;
15934}
15935
15936// Merge two trees together
15937// The roots of tree1 and tree2 must be the same revision
15938function mergeTree(in_tree1, in_tree2) {
15939 var queue = [{tree1: in_tree1, tree2: in_tree2}];
15940 var conflicts = false;
15941 while (queue.length > 0) {
15942 var item = queue.pop();
15943 var tree1 = item.tree1;
15944 var tree2 = item.tree2;
15945
15946 if (tree1[1].status || tree2[1].status) {
15947 tree1[1].status =
15948 (tree1[1].status === 'available' ||
15949 tree2[1].status === 'available') ? 'available' : 'missing';
15950 }
15951
15952 for (var i = 0; i < tree2[2].length; i++) {
15953 if (!tree1[2][0]) {
15954 conflicts = 'new_leaf';
15955 tree1[2][0] = tree2[2][i];
15956 continue;
15957 }
15958
15959 var merged = false;
15960 for (var j = 0; j < tree1[2].length; j++) {
15961 if (tree1[2][j][0] === tree2[2][i][0]) {
15962 queue.push({tree1: tree1[2][j], tree2: tree2[2][i]});
15963 merged = true;
15964 }
15965 }
15966 if (!merged) {
15967 conflicts = 'new_branch';
15968 insertSorted(tree1[2], tree2[2][i], compareTree);
15969 }
15970 }
15971 }
15972 return {conflicts: conflicts, tree: in_tree1};
15973}
15974
15975function doMerge(tree, path, dontExpand) {
15976 var restree = [];
15977 var conflicts = false;
15978 var merged = false;
15979 var res;
15980
15981 if (!tree.length) {
15982 return {tree: [path], conflicts: 'new_leaf'};
15983 }
15984
15985 for (var i = 0, len = tree.length; i < len; i++) {
15986 var branch = tree[i];
15987 if (branch.pos === path.pos && branch.ids[0] === path.ids[0]) {
15988 // Paths start at the same position and have the same root, so they need
15989 // merged
15990 res = mergeTree(branch.ids, path.ids);
15991 restree.push({pos: branch.pos, ids: res.tree});
15992 conflicts = conflicts || res.conflicts;
15993 merged = true;
15994 } else if (dontExpand !== true) {
15995 // The paths start at a different position, take the earliest path and
15996 // traverse up until it as at the same point from root as the path we
15997 // want to merge. If the keys match we return the longer path with the
15998 // other merged After stemming we dont want to expand the trees
15999
16000 var t1 = branch.pos < path.pos ? branch : path;
16001 var t2 = branch.pos < path.pos ? path : branch;
16002 var diff = t2.pos - t1.pos;
16003
16004 var candidateParents = [];
16005
16006 var trees = [];
16007 trees.push({ids: t1.ids, diff: diff, parent: null, parentIdx: null});
16008 while (trees.length > 0) {
16009 var item = trees.pop();
16010 if (item.diff === 0) {
16011 if (item.ids[0] === t2.ids[0]) {
16012 candidateParents.push(item);
16013 }
16014 continue;
16015 }
16016 var elements = item.ids[2];
16017 for (var j = 0, elementsLen = elements.length; j < elementsLen; j++) {
16018 trees.push({
16019 ids: elements[j],
16020 diff: item.diff - 1,
16021 parent: item.ids,
16022 parentIdx: j
16023 });
16024 }
16025 }
16026
16027 var el = candidateParents[0];
16028
16029 if (!el) {
16030 restree.push(branch);
16031 } else {
16032 res = mergeTree(el.ids, t2.ids);
16033 el.parent[2][el.parentIdx] = res.tree;
16034 restree.push({pos: t1.pos, ids: t1.ids});
16035 conflicts = conflicts || res.conflicts;
16036 merged = true;
16037 }
16038 } else {
16039 restree.push(branch);
16040 }
16041 }
16042
16043 // We didnt find
16044 if (!merged) {
16045 restree.push(path);
16046 }
16047
16048 restree.sort(sortByPos$1);
16049
16050 return {
16051 tree: restree,
16052 conflicts: conflicts || 'internal_node'
16053 };
16054}
16055
16056// To ensure we dont grow the revision tree infinitely, we stem old revisions
16057function stem(tree, depth) {
16058 // First we break out the tree into a complete list of root to leaf paths
16059 var paths = rootToLeaf(tree);
16060 var stemmedRevs;
16061
16062 var result;
16063 for (var i = 0, len = paths.length; i < len; i++) {
16064 // Then for each path, we cut off the start of the path based on the
16065 // `depth` to stem to, and generate a new set of flat trees
16066 var path = paths[i];
16067 var stemmed = path.ids;
16068 var node;
16069 if (stemmed.length > depth) {
16070 // only do the stemming work if we actually need to stem
16071 if (!stemmedRevs) {
16072 stemmedRevs = {}; // avoid allocating this object unnecessarily
16073 }
16074 var numStemmed = stemmed.length - depth;
16075 node = {
16076 pos: path.pos + numStemmed,
16077 ids: pathToTree(stemmed, numStemmed)
16078 };
16079
16080 for (var s = 0; s < numStemmed; s++) {
16081 var rev = (path.pos + s) + '-' + stemmed[s].id;
16082 stemmedRevs[rev] = true;
16083 }
16084 } else { // no need to actually stem
16085 node = {
16086 pos: path.pos,
16087 ids: pathToTree(stemmed, 0)
16088 };
16089 }
16090
16091 // Then we remerge all those flat trees together, ensuring that we dont
16092 // connect trees that would go beyond the depth limit
16093 if (result) {
16094 result = doMerge(result, node, true).tree;
16095 } else {
16096 result = [node];
16097 }
16098 }
16099
16100 // this is memory-heavy per Chrome profiler, avoid unless we actually stemmed
16101 if (stemmedRevs) {
16102 traverseRevTree(result, function (isLeaf, pos, revHash) {
16103 // some revisions may have been removed in a branch but not in another
16104 delete stemmedRevs[pos + '-' + revHash];
16105 });
16106 }
16107
16108 return {
16109 tree: result,
16110 revs: stemmedRevs ? Object.keys(stemmedRevs) : []
16111 };
16112}
16113
16114function merge(tree, path, depth) {
16115 var newTree = doMerge(tree, path);
16116 var stemmed = stem(newTree.tree, depth);
16117 return {
16118 tree: stemmed.tree,
16119 stemmedRevs: stemmed.revs,
16120 conflicts: newTree.conflicts
16121 };
16122}
16123
16124// return true if a rev exists in the rev tree, false otherwise
16125function revExists(revs, rev) {
16126 var toVisit = revs.slice();
16127 var splitRev = rev.split('-');
16128 var targetPos = parseInt(splitRev[0], 10);
16129 var targetId = splitRev[1];
16130
16131 var node;
16132 while ((node = toVisit.pop())) {
16133 if (node.pos === targetPos && node.ids[0] === targetId) {
16134 return true;
16135 }
16136 var branches = node.ids[2];
16137 for (var i = 0, len = branches.length; i < len; i++) {
16138 toVisit.push({pos: node.pos + 1, ids: branches[i]});
16139 }
16140 }
16141 return false;
16142}
16143
16144function getTrees(node) {
16145 return node.ids;
16146}
16147
16148// check if a specific revision of a doc has been deleted
16149// - metadata: the metadata object from the doc store
16150// - rev: (optional) the revision to check. defaults to winning revision
16151function isDeleted(metadata, rev) {
16152 if (!rev) {
16153 rev = winningRev(metadata);
16154 }
16155 var id = rev.substring(rev.indexOf('-') + 1);
16156 var toVisit = metadata.rev_tree.map(getTrees);
16157
16158 var tree;
16159 while ((tree = toVisit.pop())) {
16160 if (tree[0] === id) {
16161 return !!tree[1].deleted;
16162 }
16163 toVisit = toVisit.concat(tree[2]);
16164 }
16165}
16166
16167function isLocalId(id) {
16168 return (/^_local/).test(id);
16169}
16170
16171// returns the current leaf node for a given revision
16172function latest(rev, metadata) {
16173 var toVisit = metadata.rev_tree.slice();
16174 var node;
16175 while ((node = toVisit.pop())) {
16176 var pos = node.pos;
16177 var tree = node.ids;
16178 var id = tree[0];
16179 var opts = tree[1];
16180 var branches = tree[2];
16181 var isLeaf = branches.length === 0;
16182
16183 var history = node.history ? node.history.slice() : [];
16184 history.push({id: id, pos: pos, opts: opts});
16185
16186 if (isLeaf) {
16187 for (var i = 0, len = history.length; i < len; i++) {
16188 var historyNode = history[i];
16189 var historyRev = historyNode.pos + '-' + historyNode.id;
16190
16191 if (historyRev === rev) {
16192 // return the rev of this leaf
16193 return pos + '-' + id;
16194 }
16195 }
16196 }
16197
16198 for (var j = 0, l = branches.length; j < l; j++) {
16199 toVisit.push({pos: pos + 1, ids: branches[j], history: history});
16200 }
16201 }
16202
16203 /* istanbul ignore next */
16204 throw new Error('Unable to resolve latest revision for id ' + metadata.id + ', rev ' + rev);
16205}
16206
16207function updateDoc(revLimit, prev, docInfo, results,
16208 i, cb, writeDoc, newEdits) {
16209
16210 if (revExists(prev.rev_tree, docInfo.metadata.rev) && !newEdits) {
16211 results[i] = docInfo;
16212 return cb();
16213 }
16214
16215 // sometimes this is pre-calculated. historically not always
16216 var previousWinningRev = prev.winningRev || winningRev(prev);
16217 var previouslyDeleted = 'deleted' in prev ? prev.deleted :
16218 isDeleted(prev, previousWinningRev);
16219 var deleted = 'deleted' in docInfo.metadata ? docInfo.metadata.deleted :
16220 isDeleted(docInfo.metadata);
16221 var isRoot = /^1-/.test(docInfo.metadata.rev);
16222
16223 if (previouslyDeleted && !deleted && newEdits && isRoot) {
16224 var newDoc = docInfo.data;
16225 newDoc._rev = previousWinningRev;
16226 newDoc._id = docInfo.metadata.id;
16227 docInfo = parseDoc(newDoc, newEdits);
16228 }
16229
16230 var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit);
16231
16232 var inConflict = newEdits && ((
16233 (previouslyDeleted && deleted && merged.conflicts !== 'new_leaf') ||
16234 (!previouslyDeleted && merged.conflicts !== 'new_leaf') ||
16235 (previouslyDeleted && !deleted && merged.conflicts === 'new_branch')));
16236
16237 if (inConflict) {
16238 var err = createError(REV_CONFLICT);
16239 results[i] = err;
16240 return cb();
16241 }
16242
16243 var newRev = docInfo.metadata.rev;
16244 docInfo.metadata.rev_tree = merged.tree;
16245 docInfo.stemmedRevs = merged.stemmedRevs || [];
16246 /* istanbul ignore else */
16247 if (prev.rev_map) {
16248 docInfo.metadata.rev_map = prev.rev_map; // used only by leveldb
16249 }
16250
16251 // recalculate
16252 var winningRev$$1 = winningRev(docInfo.metadata);
16253 var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev$$1);
16254
16255 // calculate the total number of documents that were added/removed,
16256 // from the perspective of total_rows/doc_count
16257 var delta = (previouslyDeleted === winningRevIsDeleted) ? 0 :
16258 previouslyDeleted < winningRevIsDeleted ? -1 : 1;
16259
16260 var newRevIsDeleted;
16261 if (newRev === winningRev$$1) {
16262 // if the new rev is the same as the winning rev, we can reuse that value
16263 newRevIsDeleted = winningRevIsDeleted;
16264 } else {
16265 // if they're not the same, then we need to recalculate
16266 newRevIsDeleted = isDeleted(docInfo.metadata, newRev);
16267 }
16268
16269 writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
16270 true, delta, i, cb);
16271}
16272
16273function rootIsMissing(docInfo) {
16274 return docInfo.metadata.rev_tree[0].ids[1].status === 'missing';
16275}
16276
16277function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results,
16278 writeDoc, opts, overallCallback) {
16279
16280 // Default to 1000 locally
16281 revLimit = revLimit || 1000;
16282
16283 function insertDoc(docInfo, resultsIdx, callback) {
16284 // Cant insert new deleted documents
16285 var winningRev$$1 = winningRev(docInfo.metadata);
16286 var deleted = isDeleted(docInfo.metadata, winningRev$$1);
16287 if ('was_delete' in opts && deleted) {
16288 results[resultsIdx] = createError(MISSING_DOC, 'deleted');
16289 return callback();
16290 }
16291
16292 // 4712 - detect whether a new document was inserted with a _rev
16293 var inConflict = newEdits && rootIsMissing(docInfo);
16294
16295 if (inConflict) {
16296 var err = createError(REV_CONFLICT);
16297 results[resultsIdx] = err;
16298 return callback();
16299 }
16300
16301 var delta = deleted ? 0 : 1;
16302
16303 writeDoc(docInfo, winningRev$$1, deleted, deleted, false,
16304 delta, resultsIdx, callback);
16305 }
16306
16307 var newEdits = opts.new_edits;
16308 var idsToDocs = new ExportedMap();
16309
16310 var docsDone = 0;
16311 var docsToDo = docInfos.length;
16312
16313 function checkAllDocsDone() {
16314 if (++docsDone === docsToDo && overallCallback) {
16315 overallCallback();
16316 }
16317 }
16318
16319 docInfos.forEach(function (currentDoc, resultsIdx) {
16320
16321 if (currentDoc._id && isLocalId(currentDoc._id)) {
16322 var fun = currentDoc._deleted ? '_removeLocal' : '_putLocal';
16323 api[fun](currentDoc, {ctx: tx}, function (err, res) {
16324 results[resultsIdx] = err || res;
16325 checkAllDocsDone();
16326 });
16327 return;
16328 }
16329
16330 var id = currentDoc.metadata.id;
16331 if (idsToDocs.has(id)) {
16332 docsToDo--; // duplicate
16333 idsToDocs.get(id).push([currentDoc, resultsIdx]);
16334 } else {
16335 idsToDocs.set(id, [[currentDoc, resultsIdx]]);
16336 }
16337 });
16338
16339 // in the case of new_edits, the user can provide multiple docs
16340 // with the same id. these need to be processed sequentially
16341 idsToDocs.forEach(function (docs, id) {
16342 var numDone = 0;
16343
16344 function docWritten() {
16345 if (++numDone < docs.length) {
16346 nextDoc();
16347 } else {
16348 checkAllDocsDone();
16349 }
16350 }
16351 function nextDoc() {
16352 var value = docs[numDone];
16353 var currentDoc = value[0];
16354 var resultsIdx = value[1];
16355
16356 if (fetchedDocs.has(id)) {
16357 updateDoc(revLimit, fetchedDocs.get(id), currentDoc, results,
16358 resultsIdx, docWritten, writeDoc, newEdits);
16359 } else {
16360 // Ensure stemming applies to new writes as well
16361 var merged = merge([], currentDoc.metadata.rev_tree[0], revLimit);
16362 currentDoc.metadata.rev_tree = merged.tree;
16363 currentDoc.stemmedRevs = merged.stemmedRevs || [];
16364 insertDoc(currentDoc, resultsIdx, docWritten);
16365 }
16366 }
16367 nextDoc();
16368 });
16369}
16370
16371function safeJsonParse(str) {
16372 // This try/catch guards against stack overflow errors.
16373 // JSON.parse() is faster than vuvuzela.parse() but vuvuzela
16374 // cannot overflow.
16375 try {
16376 return JSON.parse(str);
16377 } catch (e) {
16378 /* istanbul ignore next */
16379 return vuvuzela.parse(str);
16380 }
16381}
16382
16383function safeJsonStringify(json) {
16384 try {
16385 return JSON.stringify(json);
16386 } catch (e) {
16387 /* istanbul ignore next */
16388 return vuvuzela.stringify(json);
16389 }
16390}
16391
16392function readAsBlobOrBuffer(storedObject, type) {
16393 // In the browser, we've stored a binary string. This now comes back as a
16394 // browserified Node-style Buffer (implemented as a typed array),
16395 // but we want a Blob instead.
16396 var byteArray = new Uint8Array(storedObject);
16397 return createBlob([byteArray], {type: type});
16398}
16399
16400// In the browser, we store a binary string
16401function prepareAttachmentForStorage(attData, cb) {
16402 readAsBinaryString(attData, cb);
16403}
16404
16405function createEmptyBlobOrBuffer(type) {
16406 return createBlob([''], {type: type});
16407}
16408
16409function getCacheFor(transaction, store) {
16410 var prefix = store.prefix()[0];
16411 var cache = transaction._cache;
16412 var subCache = cache.get(prefix);
16413 if (!subCache) {
16414 subCache = new ExportedMap();
16415 cache.set(prefix, subCache);
16416 }
16417 return subCache;
16418}
16419
16420function LevelTransaction() {
16421 this._batch = [];
16422 this._cache = new ExportedMap();
16423}
16424
16425LevelTransaction.prototype.get = function (store, key, callback) {
16426 var cache = getCacheFor(this, store);
16427 var exists = cache.get(key);
16428 if (exists) {
16429 return nextTick(function () {
16430 callback(null, exists);
16431 });
16432 } else if (exists === null) { // deleted marker
16433 /* istanbul ignore next */
16434 return nextTick(function () {
16435 callback({name: 'NotFoundError'});
16436 });
16437 }
16438 store.get(key, function (err, res) {
16439 if (err) {
16440 /* istanbul ignore else */
16441 if (err.name === 'NotFoundError') {
16442 cache.set(key, null);
16443 }
16444 return callback(err);
16445 }
16446 cache.set(key, res);
16447 callback(null, res);
16448 });
16449};
16450
16451LevelTransaction.prototype.batch = function (batch) {
16452 for (var i = 0, len = batch.length; i < len; i++) {
16453 var operation = batch[i];
16454
16455 var cache = getCacheFor(this, operation.prefix);
16456
16457 if (operation.type === 'put') {
16458 cache.set(operation.key, operation.value);
16459 } else {
16460 cache.set(operation.key, null);
16461 }
16462 }
16463 this._batch = this._batch.concat(batch);
16464};
16465
16466LevelTransaction.prototype.execute = function (db, callback) {
16467
16468 var keys = new ExportedSet();
16469 var uniqBatches = [];
16470
16471 // remove duplicates; last one wins
16472 for (var i = this._batch.length - 1; i >= 0; i--) {
16473 var operation = this._batch[i];
16474 var lookupKey = operation.prefix.prefix()[0] + '\xff' + operation.key;
16475 if (keys.has(lookupKey)) {
16476 continue;
16477 }
16478 keys.add(lookupKey);
16479 uniqBatches.push(operation);
16480 }
16481
16482 db.batch(uniqBatches, callback);
16483};
16484
16485var DOC_STORE = 'document-store';
16486var BY_SEQ_STORE = 'by-sequence';
16487var ATTACHMENT_STORE = 'attach-store';
16488var BINARY_STORE = 'attach-binary-store';
16489var LOCAL_STORE = 'local-store';
16490var META_STORE = 'meta-store';
16491
16492// leveldb barks if we try to open a db multiple times
16493// so we cache opened connections here for initstore()
16494var dbStores = new ExportedMap();
16495
16496// store the value of update_seq in the by-sequence store the key name will
16497// never conflict, since the keys in the by-sequence store are integers
16498var UPDATE_SEQ_KEY = '_local_last_update_seq';
16499var DOC_COUNT_KEY = '_local_doc_count';
16500var UUID_KEY = '_local_uuid';
16501
16502var MD5_PREFIX = 'md5-';
16503
16504var safeJsonEncoding = {
16505 encode: safeJsonStringify,
16506 decode: safeJsonParse,
16507 buffer: false,
16508 type: 'cheap-json'
16509};
16510
16511var levelChanges = new Changes();
16512
16513// winningRev and deleted are performance-killers, but
16514// in newer versions of PouchDB, they are cached on the metadata
16515function getWinningRev(metadata) {
16516 return 'winningRev' in metadata ?
16517 metadata.winningRev : winningRev(metadata);
16518}
16519
16520function getIsDeleted(metadata, winningRev$$1) {
16521 return 'deleted' in metadata ?
16522 metadata.deleted : isDeleted(metadata, winningRev$$1);
16523}
16524
16525function fetchAttachment(att, stores, opts) {
16526 var type = att.content_type;
16527 return new Promise(function (resolve, reject) {
16528 stores.binaryStore.get(att.digest, function (err, buffer) {
16529 var data;
16530 if (err) {
16531 /* istanbul ignore if */
16532 if (err.name !== 'NotFoundError') {
16533 return reject(err);
16534 } else {
16535 // empty
16536 if (!opts.binary) {
16537 data = '';
16538 } else {
16539 data = binStringToBluffer('', type);
16540 }
16541 }
16542 } else { // non-empty
16543 if (opts.binary) {
16544 data = readAsBlobOrBuffer(buffer, type);
16545 } else {
16546 data = buffer.toString('base64');
16547 }
16548 }
16549 delete att.stub;
16550 delete att.length;
16551 att.data = data;
16552 resolve();
16553 });
16554 });
16555}
16556
16557function fetchAttachments(results, stores, opts) {
16558 var atts = [];
16559 results.forEach(function (row) {
16560 if (!(row.doc && row.doc._attachments)) {
16561 return;
16562 }
16563 var attNames = Object.keys(row.doc._attachments);
16564 attNames.forEach(function (attName) {
16565 var att = row.doc._attachments[attName];
16566 if (!('data' in att)) {
16567 atts.push(att);
16568 }
16569 });
16570 });
16571
16572 return Promise.all(atts.map(function (att) {
16573 return fetchAttachment(att, stores, opts);
16574 }));
16575}
16576
16577function LevelPouch(opts, callback) {
16578 opts = clone(opts);
16579 var api = this;
16580 var instanceId;
16581 var stores = {};
16582 var revLimit = opts.revs_limit;
16583 var db;
16584 var name = opts.name;
16585 // TODO: this is undocumented and unused probably
16586 /* istanbul ignore else */
16587 if (typeof opts.createIfMissing === 'undefined') {
16588 opts.createIfMissing = true;
16589 }
16590
16591 var leveldown = opts.db;
16592
16593 var dbStore;
16594 var leveldownName = functionName(leveldown);
16595 if (dbStores.has(leveldownName)) {
16596 dbStore = dbStores.get(leveldownName);
16597 } else {
16598 dbStore = new ExportedMap();
16599 dbStores.set(leveldownName, dbStore);
16600 }
16601 if (dbStore.has(name)) {
16602 db = dbStore.get(name);
16603 afterDBCreated();
16604 } else {
16605 dbStore.set(name, sublevelPouch(levelup(leveldown(name), opts, function (err) {
16606 /* istanbul ignore if */
16607 if (err) {
16608 dbStore["delete"](name);
16609 return callback(err);
16610 }
16611 db = dbStore.get(name);
16612 db._docCount = -1;
16613 db._queue = new Deque();
16614 /* istanbul ignore else */
16615 if (typeof opts.migrate === 'object') { // migration for leveldown
16616 opts.migrate.doMigrationOne(name, db, afterDBCreated);
16617 } else {
16618 afterDBCreated();
16619 }
16620 })));
16621 }
16622
16623 function afterDBCreated() {
16624 stores.docStore = db.sublevel(DOC_STORE, {valueEncoding: safeJsonEncoding});
16625 stores.bySeqStore = db.sublevel(BY_SEQ_STORE, {valueEncoding: 'json'});
16626 stores.attachmentStore =
16627 db.sublevel(ATTACHMENT_STORE, {valueEncoding: 'json'});
16628 stores.binaryStore = db.sublevel(BINARY_STORE, {valueEncoding: 'binary'});
16629 stores.localStore = db.sublevel(LOCAL_STORE, {valueEncoding: 'json'});
16630 stores.metaStore = db.sublevel(META_STORE, {valueEncoding: 'json'});
16631 /* istanbul ignore else */
16632 if (typeof opts.migrate === 'object') { // migration for leveldown
16633 opts.migrate.doMigrationTwo(db, stores, afterLastMigration);
16634 } else {
16635 afterLastMigration();
16636 }
16637 }
16638
16639 function afterLastMigration() {
16640 stores.metaStore.get(UPDATE_SEQ_KEY, function (err, value) {
16641 if (typeof db._updateSeq === 'undefined') {
16642 db._updateSeq = value || 0;
16643 }
16644 stores.metaStore.get(DOC_COUNT_KEY, function (err, value) {
16645 db._docCount = !err ? value : 0;
16646 stores.metaStore.get(UUID_KEY, function (err, value) {
16647 instanceId = !err ? value : uuid();
16648 stores.metaStore.put(UUID_KEY, instanceId, function () {
16649 nextTick(function () {
16650 callback(null, api);
16651 });
16652 });
16653 });
16654 });
16655 });
16656 }
16657
16658 function countDocs(callback) {
16659 /* istanbul ignore if */
16660 if (db.isClosed()) {
16661 return callback(new Error('database is closed'));
16662 }
16663 return callback(null, db._docCount); // use cached value
16664 }
16665
16666 api._remote = false;
16667 /* istanbul ignore next */
16668 api.type = function () {
16669 return 'leveldb';
16670 };
16671
16672 api._id = function (callback) {
16673 callback(null, instanceId);
16674 };
16675
16676 api._info = function (callback) {
16677 var res = {
16678 doc_count: db._docCount,
16679 update_seq: db._updateSeq,
16680 backend_adapter: functionName(leveldown)
16681 };
16682 return nextTick(function () {
16683 callback(null, res);
16684 });
16685 };
16686
16687 function tryCode(fun, args) {
16688 try {
16689 fun.apply(null, args);
16690 } catch (err) {
16691 args[args.length - 1](err);
16692 }
16693 }
16694
16695 function executeNext() {
16696 var firstTask = db._queue.peekFront();
16697
16698 if (firstTask.type === 'read') {
16699 runReadOperation(firstTask);
16700 } else { // write, only do one at a time
16701 runWriteOperation(firstTask);
16702 }
16703 }
16704
16705 function runReadOperation(firstTask) {
16706 // do multiple reads at once simultaneously, because it's safe
16707
16708 var readTasks = [firstTask];
16709 var i = 1;
16710 var nextTask = db._queue.get(i);
16711 while (typeof nextTask !== 'undefined' && nextTask.type === 'read') {
16712 readTasks.push(nextTask);
16713 i++;
16714 nextTask = db._queue.get(i);
16715 }
16716
16717 var numDone = 0;
16718
16719 readTasks.forEach(function (readTask) {
16720 var args = readTask.args;
16721 var callback = args[args.length - 1];
16722 args[args.length - 1] = getArguments(function (cbArgs) {
16723 callback.apply(null, cbArgs);
16724 if (++numDone === readTasks.length) {
16725 nextTick(function () {
16726 // all read tasks have finished
16727 readTasks.forEach(function () {
16728 db._queue.shift();
16729 });
16730 if (db._queue.length) {
16731 executeNext();
16732 }
16733 });
16734 }
16735 });
16736 tryCode(readTask.fun, args);
16737 });
16738 }
16739
16740 function runWriteOperation(firstTask) {
16741 var args = firstTask.args;
16742 var callback = args[args.length - 1];
16743 args[args.length - 1] = getArguments(function (cbArgs) {
16744 callback.apply(null, cbArgs);
16745 nextTick(function () {
16746 db._queue.shift();
16747 if (db._queue.length) {
16748 executeNext();
16749 }
16750 });
16751 });
16752 tryCode(firstTask.fun, args);
16753 }
16754
16755 // all read/write operations to the database are done in a queue,
16756 // similar to how websql/idb works. this avoids problems such
16757 // as e.g. compaction needing to have a lock on the database while
16758 // it updates stuff. in the future we can revisit this.
16759 function writeLock(fun) {
16760 return getArguments(function (args) {
16761 db._queue.push({
16762 fun: fun,
16763 args: args,
16764 type: 'write'
16765 });
16766
16767 if (db._queue.length === 1) {
16768 nextTick(executeNext);
16769 }
16770 });
16771 }
16772
16773 // same as the writelock, but multiple can run at once
16774 function readLock(fun) {
16775 return getArguments(function (args) {
16776 db._queue.push({
16777 fun: fun,
16778 args: args,
16779 type: 'read'
16780 });
16781
16782 if (db._queue.length === 1) {
16783 nextTick(executeNext);
16784 }
16785 });
16786 }
16787
16788 function formatSeq(n) {
16789 return ('0000000000000000' + n).slice(-16);
16790 }
16791
16792 function parseSeq(s) {
16793 return parseInt(s, 10);
16794 }
16795
16796 api._get = readLock(function (id, opts, callback) {
16797 opts = clone(opts);
16798
16799 stores.docStore.get(id, function (err, metadata) {
16800
16801 if (err || !metadata) {
16802 return callback(createError(MISSING_DOC, 'missing'));
16803 }
16804
16805 var rev;
16806 if (!opts.rev) {
16807 rev = getWinningRev(metadata);
16808 var deleted = getIsDeleted(metadata, rev);
16809 if (deleted) {
16810 return callback(createError(MISSING_DOC, "deleted"));
16811 }
16812 } else {
16813 rev = opts.latest ? latest(opts.rev, metadata) : opts.rev;
16814 }
16815
16816 var seq = metadata.rev_map[rev];
16817
16818 stores.bySeqStore.get(formatSeq(seq), function (err, doc) {
16819 if (!doc) {
16820 return callback(createError(MISSING_DOC));
16821 }
16822 /* istanbul ignore if */
16823 if ('_id' in doc && doc._id !== metadata.id) {
16824 // this failing implies something very wrong
16825 return callback(new Error('wrong doc returned'));
16826 }
16827 doc._id = metadata.id;
16828 if ('_rev' in doc) {
16829 /* istanbul ignore if */
16830 if (doc._rev !== rev) {
16831 // this failing implies something very wrong
16832 return callback(new Error('wrong doc returned'));
16833 }
16834 } else {
16835 // we didn't always store this
16836 doc._rev = rev;
16837 }
16838 return callback(null, {doc: doc, metadata: metadata});
16839 });
16840 });
16841 });
16842
16843 // not technically part of the spec, but if putAttachment has its own
16844 // method...
16845 api._getAttachment = function (docId, attachId, attachment, opts, callback) {
16846 var digest = attachment.digest;
16847 var type = attachment.content_type;
16848
16849 stores.binaryStore.get(digest, function (err, attach) {
16850 if (err) {
16851 /* istanbul ignore if */
16852 if (err.name !== 'NotFoundError') {
16853 return callback(err);
16854 }
16855 // Empty attachment
16856 return callback(null, opts.binary ? createEmptyBlobOrBuffer(type) : '');
16857 }
16858
16859 if (opts.binary) {
16860 callback(null, readAsBlobOrBuffer(attach, type));
16861 } else {
16862 callback(null, attach.toString('base64'));
16863 }
16864 });
16865 };
16866
16867 api._bulkDocs = writeLock(function (req, opts, callback) {
16868 var newEdits = opts.new_edits;
16869 var results = new Array(req.docs.length);
16870 var fetchedDocs = new ExportedMap();
16871 var stemmedRevs = new ExportedMap();
16872
16873 var txn = new LevelTransaction();
16874 var docCountDelta = 0;
16875 var newUpdateSeq = db._updateSeq;
16876
16877 // parse the docs and give each a sequence number
16878 var userDocs = req.docs;
16879 var docInfos = userDocs.map(function (doc) {
16880 if (doc._id && isLocalId(doc._id)) {
16881 return doc;
16882 }
16883 var newDoc = parseDoc(doc, newEdits, api.__opts);
16884
16885 if (newDoc.metadata && !newDoc.metadata.rev_map) {
16886 newDoc.metadata.rev_map = {};
16887 }
16888
16889 return newDoc;
16890 });
16891 var infoErrors = docInfos.filter(function (doc) {
16892 return doc.error;
16893 });
16894
16895 if (infoErrors.length) {
16896 return callback(infoErrors[0]);
16897 }
16898
16899 // verify any stub attachments as a precondition test
16900
16901 function verifyAttachment(digest, callback) {
16902 txn.get(stores.attachmentStore, digest, function (levelErr) {
16903 if (levelErr) {
16904 var err = createError(MISSING_STUB,
16905 'unknown stub attachment with digest ' +
16906 digest);
16907 callback(err);
16908 } else {
16909 callback();
16910 }
16911 });
16912 }
16913
16914 function verifyAttachments(finish) {
16915 var digests = [];
16916 userDocs.forEach(function (doc) {
16917 if (doc && doc._attachments) {
16918 Object.keys(doc._attachments).forEach(function (filename) {
16919 var att = doc._attachments[filename];
16920 if (att.stub) {
16921 digests.push(att.digest);
16922 }
16923 });
16924 }
16925 });
16926 if (!digests.length) {
16927 return finish();
16928 }
16929 var numDone = 0;
16930 var err;
16931
16932 digests.forEach(function (digest) {
16933 verifyAttachment(digest, function (attErr) {
16934 if (attErr && !err) {
16935 err = attErr;
16936 }
16937
16938 if (++numDone === digests.length) {
16939 finish(err);
16940 }
16941 });
16942 });
16943 }
16944
16945 function fetchExistingDocs(finish) {
16946 var numDone = 0;
16947 var overallErr;
16948 function checkDone() {
16949 if (++numDone === userDocs.length) {
16950 return finish(overallErr);
16951 }
16952 }
16953
16954 userDocs.forEach(function (doc) {
16955 if (doc._id && isLocalId(doc._id)) {
16956 // skip local docs
16957 return checkDone();
16958 }
16959 txn.get(stores.docStore, doc._id, function (err, info) {
16960 if (err) {
16961 /* istanbul ignore if */
16962 if (err.name !== 'NotFoundError') {
16963 overallErr = err;
16964 }
16965 } else {
16966 fetchedDocs.set(doc._id, info);
16967 }
16968 checkDone();
16969 });
16970 });
16971 }
16972
16973 function compact(revsMap, callback) {
16974 var promise = Promise.resolve();
16975 revsMap.forEach(function (revs, docId) {
16976 // TODO: parallelize, for now need to be sequential to
16977 // pass orphaned attachment tests
16978 promise = promise.then(function () {
16979 return new Promise(function (resolve, reject) {
16980 api._doCompactionNoLock(docId, revs, {ctx: txn}, function (err) {
16981 /* istanbul ignore if */
16982 if (err) {
16983 return reject(err);
16984 }
16985 resolve();
16986 });
16987 });
16988 });
16989 });
16990
16991 promise.then(function () {
16992 callback();
16993 }, callback);
16994 }
16995
16996 function autoCompact(callback) {
16997 var revsMap = new ExportedMap();
16998 fetchedDocs.forEach(function (metadata, docId) {
16999 revsMap.set(docId, compactTree(metadata));
17000 });
17001 compact(revsMap, callback);
17002 }
17003
17004 function finish() {
17005 compact(stemmedRevs, function (error) {
17006 /* istanbul ignore if */
17007 if (error) {
17008 complete(error);
17009 }
17010 if (api.auto_compaction) {
17011 return autoCompact(complete);
17012 }
17013 complete();
17014 });
17015 }
17016
17017 function writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
17018 isUpdate, delta, resultsIdx, callback2) {
17019 docCountDelta += delta;
17020
17021 var err = null;
17022 var recv = 0;
17023
17024 docInfo.metadata.winningRev = winningRev$$1;
17025 docInfo.metadata.deleted = winningRevIsDeleted;
17026
17027 docInfo.data._id = docInfo.metadata.id;
17028 docInfo.data._rev = docInfo.metadata.rev;
17029
17030 if (newRevIsDeleted) {
17031 docInfo.data._deleted = true;
17032 }
17033
17034 if (docInfo.stemmedRevs.length) {
17035 stemmedRevs.set(docInfo.metadata.id, docInfo.stemmedRevs);
17036 }
17037
17038 var attachments = docInfo.data._attachments ?
17039 Object.keys(docInfo.data._attachments) :
17040 [];
17041
17042 function attachmentSaved(attachmentErr) {
17043 recv++;
17044 if (!err) {
17045 /* istanbul ignore if */
17046 if (attachmentErr) {
17047 err = attachmentErr;
17048 callback2(err);
17049 } else if (recv === attachments.length) {
17050 finish();
17051 }
17052 }
17053 }
17054
17055 function onMD5Load(doc, key, data, attachmentSaved) {
17056 return function (result) {
17057 saveAttachment(doc, MD5_PREFIX + result, key, data, attachmentSaved);
17058 };
17059 }
17060
17061 function doMD5(doc, key, attachmentSaved) {
17062 return function (data) {
17063 binaryMd5(data, onMD5Load(doc, key, data, attachmentSaved));
17064 };
17065 }
17066
17067 for (var i = 0; i < attachments.length; i++) {
17068 var key = attachments[i];
17069 var att = docInfo.data._attachments[key];
17070
17071 if (att.stub) {
17072 // still need to update the refs mapping
17073 var id = docInfo.data._id;
17074 var rev = docInfo.data._rev;
17075 saveAttachmentRefs(id, rev, att.digest, attachmentSaved);
17076 continue;
17077 }
17078 var data;
17079 if (typeof att.data === 'string') {
17080 // input is assumed to be a base64 string
17081 try {
17082 data = thisAtob(att.data);
17083 } catch (e) {
17084 callback(createError(BAD_ARG,
17085 'Attachment is not a valid base64 string'));
17086 return;
17087 }
17088 doMD5(docInfo, key, attachmentSaved)(data);
17089 } else {
17090 prepareAttachmentForStorage(att.data,
17091 doMD5(docInfo, key, attachmentSaved));
17092 }
17093 }
17094
17095 function finish() {
17096 var seq = docInfo.metadata.rev_map[docInfo.metadata.rev];
17097 /* istanbul ignore if */
17098 if (seq) {
17099 // check that there aren't any existing revisions with the same
17100 // revision id, else we shouldn't do anything
17101 return callback2();
17102 }
17103 seq = ++newUpdateSeq;
17104 docInfo.metadata.rev_map[docInfo.metadata.rev] =
17105 docInfo.metadata.seq = seq;
17106 var seqKey = formatSeq(seq);
17107 var batch = [{
17108 key: seqKey,
17109 value: docInfo.data,
17110 prefix: stores.bySeqStore,
17111 type: 'put'
17112 }, {
17113 key: docInfo.metadata.id,
17114 value: docInfo.metadata,
17115 prefix: stores.docStore,
17116 type: 'put'
17117 }];
17118 txn.batch(batch);
17119 results[resultsIdx] = {
17120 ok: true,
17121 id: docInfo.metadata.id,
17122 rev: docInfo.metadata.rev
17123 };
17124 fetchedDocs.set(docInfo.metadata.id, docInfo.metadata);
17125 callback2();
17126 }
17127
17128 if (!attachments.length) {
17129 finish();
17130 }
17131 }
17132
17133 // attachments are queued per-digest, otherwise the refs could be
17134 // overwritten by concurrent writes in the same bulkDocs session
17135 var attachmentQueues = {};
17136
17137 function saveAttachmentRefs(id, rev, digest, callback) {
17138
17139 function fetchAtt() {
17140 return new Promise(function (resolve, reject) {
17141 txn.get(stores.attachmentStore, digest, function (err, oldAtt) {
17142 /* istanbul ignore if */
17143 if (err && err.name !== 'NotFoundError') {
17144 return reject(err);
17145 }
17146 resolve(oldAtt);
17147 });
17148 });
17149 }
17150
17151 function saveAtt(oldAtt) {
17152 var ref = [id, rev].join('@');
17153 var newAtt = {};
17154
17155 if (oldAtt) {
17156 if (oldAtt.refs) {
17157 // only update references if this attachment already has them
17158 // since we cannot migrate old style attachments here without
17159 // doing a full db scan for references
17160 newAtt.refs = oldAtt.refs;
17161 newAtt.refs[ref] = true;
17162 }
17163 } else {
17164 newAtt.refs = {};
17165 newAtt.refs[ref] = true;
17166 }
17167
17168 return new Promise(function (resolve) {
17169 txn.batch([{
17170 type: 'put',
17171 prefix: stores.attachmentStore,
17172 key: digest,
17173 value: newAtt
17174 }]);
17175 resolve(!oldAtt);
17176 });
17177 }
17178
17179 // put attachments in a per-digest queue, to avoid two docs with the same
17180 // attachment overwriting each other
17181 var queue = attachmentQueues[digest] || Promise.resolve();
17182 attachmentQueues[digest] = queue.then(function () {
17183 return fetchAtt().then(saveAtt).then(function (isNewAttachment) {
17184 callback(null, isNewAttachment);
17185 }, callback);
17186 });
17187 }
17188
17189 function saveAttachment(docInfo, digest, key, data, callback) {
17190 var att = docInfo.data._attachments[key];
17191 delete att.data;
17192 att.digest = digest;
17193 att.length = data.length;
17194 var id = docInfo.metadata.id;
17195 var rev = docInfo.metadata.rev;
17196 att.revpos = parseInt(rev, 10);
17197
17198 saveAttachmentRefs(id, rev, digest, function (err, isNewAttachment) {
17199 /* istanbul ignore if */
17200 if (err) {
17201 return callback(err);
17202 }
17203 // do not try to store empty attachments
17204 if (data.length === 0) {
17205 return callback(err);
17206 }
17207 if (!isNewAttachment) {
17208 // small optimization - don't bother writing it again
17209 return callback(err);
17210 }
17211 txn.batch([{
17212 type: 'put',
17213 prefix: stores.binaryStore,
17214 key: digest,
17215 value: bufferFrom(data, 'binary')
17216 }]);
17217 callback();
17218 });
17219 }
17220
17221 function complete(err) {
17222 /* istanbul ignore if */
17223 if (err) {
17224 return nextTick(function () {
17225 callback(err);
17226 });
17227 }
17228 txn.batch([
17229 {
17230 prefix: stores.metaStore,
17231 type: 'put',
17232 key: UPDATE_SEQ_KEY,
17233 value: newUpdateSeq
17234 },
17235 {
17236 prefix: stores.metaStore,
17237 type: 'put',
17238 key: DOC_COUNT_KEY,
17239 value: db._docCount + docCountDelta
17240 }
17241 ]);
17242 txn.execute(db, function (err) {
17243 /* istanbul ignore if */
17244 if (err) {
17245 return callback(err);
17246 }
17247 db._docCount += docCountDelta;
17248 db._updateSeq = newUpdateSeq;
17249 levelChanges.notify(name);
17250 nextTick(function () {
17251 callback(null, results);
17252 });
17253 });
17254 }
17255
17256 if (!docInfos.length) {
17257 return callback(null, []);
17258 }
17259
17260 verifyAttachments(function (err) {
17261 if (err) {
17262 return callback(err);
17263 }
17264 fetchExistingDocs(function (err) {
17265 /* istanbul ignore if */
17266 if (err) {
17267 return callback(err);
17268 }
17269 processDocs(revLimit, docInfos, api, fetchedDocs, txn, results,
17270 writeDoc, opts, finish);
17271 });
17272 });
17273 });
17274 api._allDocs = function (opts, callback) {
17275 if ('keys' in opts) {
17276 return allDocsKeysQuery(this, opts);
17277 }
17278 return readLock(function (opts, callback) {
17279 opts = clone(opts);
17280 countDocs(function (err, docCount) {
17281 /* istanbul ignore if */
17282 if (err) {
17283 return callback(err);
17284 }
17285 var readstreamOpts = {};
17286 var skip = opts.skip || 0;
17287 if (opts.startkey) {
17288 readstreamOpts.gte = opts.startkey;
17289 }
17290 if (opts.endkey) {
17291 readstreamOpts.lte = opts.endkey;
17292 }
17293 if (opts.key) {
17294 readstreamOpts.gte = readstreamOpts.lte = opts.key;
17295 }
17296 if (opts.descending) {
17297 readstreamOpts.reverse = true;
17298 // switch start and ends
17299 var tmp = readstreamOpts.lte;
17300 readstreamOpts.lte = readstreamOpts.gte;
17301 readstreamOpts.gte = tmp;
17302 }
17303 var limit;
17304 if (typeof opts.limit === 'number') {
17305 limit = opts.limit;
17306 }
17307 if (limit === 0 ||
17308 ('gte' in readstreamOpts && 'lte' in readstreamOpts &&
17309 readstreamOpts.gte > readstreamOpts.lte)) {
17310 // should return 0 results when start is greater than end.
17311 // normally level would "fix" this for us by reversing the order,
17312 // so short-circuit instead
17313 var returnVal = {
17314 total_rows: docCount,
17315 offset: opts.skip,
17316 rows: []
17317 };
17318 /* istanbul ignore if */
17319 if (opts.update_seq) {
17320 returnVal.update_seq = db._updateSeq;
17321 }
17322 return callback(null, returnVal);
17323 }
17324 var results = [];
17325 var docstream = stores.docStore.readStream(readstreamOpts);
17326
17327 var throughStream = through2.obj(function (entry, _, next) {
17328 var metadata = entry.value;
17329 // winningRev and deleted are performance-killers, but
17330 // in newer versions of PouchDB, they are cached on the metadata
17331 var winningRev$$1 = getWinningRev(metadata);
17332 var deleted = getIsDeleted(metadata, winningRev$$1);
17333 if (!deleted) {
17334 if (skip-- > 0) {
17335 next();
17336 return;
17337 } else if (typeof limit === 'number' && limit-- <= 0) {
17338 docstream.unpipe();
17339 docstream.destroy();
17340 next();
17341 return;
17342 }
17343 } else if (opts.deleted !== 'ok') {
17344 next();
17345 return;
17346 }
17347 function allDocsInner(data) {
17348 var doc = {
17349 id: metadata.id,
17350 key: metadata.id,
17351 value: {
17352 rev: winningRev$$1
17353 }
17354 };
17355 if (opts.include_docs) {
17356 doc.doc = data;
17357 doc.doc._rev = doc.value.rev;
17358 if (opts.conflicts) {
17359 var conflicts = collectConflicts(metadata);
17360 if (conflicts.length) {
17361 doc.doc._conflicts = conflicts;
17362 }
17363 }
17364 for (var att in doc.doc._attachments) {
17365 if (doc.doc._attachments.hasOwnProperty(att)) {
17366 doc.doc._attachments[att].stub = true;
17367 }
17368 }
17369 }
17370 if (opts.inclusive_end === false && metadata.id === opts.endkey) {
17371 return next();
17372 } else if (deleted) {
17373 if (opts.deleted === 'ok') {
17374 doc.value.deleted = true;
17375 doc.doc = null;
17376 } else {
17377 /* istanbul ignore next */
17378 return next();
17379 }
17380 }
17381 results.push(doc);
17382 next();
17383 }
17384 if (opts.include_docs) {
17385 var seq = metadata.rev_map[winningRev$$1];
17386 stores.bySeqStore.get(formatSeq(seq), function (err, data) {
17387 allDocsInner(data);
17388 });
17389 }
17390 else {
17391 allDocsInner();
17392 }
17393 }, function (next) {
17394 Promise.resolve().then(function () {
17395 if (opts.include_docs && opts.attachments) {
17396 return fetchAttachments(results, stores, opts);
17397 }
17398 }).then(function () {
17399 var returnVal = {
17400 total_rows: docCount,
17401 offset: opts.skip,
17402 rows: results
17403 };
17404
17405 /* istanbul ignore if */
17406 if (opts.update_seq) {
17407 returnVal.update_seq = db._updateSeq;
17408 }
17409 callback(null, returnVal);
17410 }, callback);
17411 next();
17412 }).on('unpipe', function () {
17413 throughStream.end();
17414 });
17415
17416 docstream.on('error', callback);
17417
17418 docstream.pipe(throughStream);
17419 });
17420 })(opts, callback);
17421 };
17422
17423 api._changes = function (opts) {
17424 opts = clone(opts);
17425
17426 if (opts.continuous) {
17427 var id = name + ':' + uuid();
17428 levelChanges.addListener(name, id, api, opts);
17429 levelChanges.notify(name);
17430 return {
17431 cancel: function () {
17432 levelChanges.removeListener(name, id);
17433 }
17434 };
17435 }
17436
17437 var descending = opts.descending;
17438 var results = [];
17439 var lastSeq = opts.since || 0;
17440 var called = 0;
17441 var streamOpts = {
17442 reverse: descending
17443 };
17444 var limit;
17445 if ('limit' in opts && opts.limit > 0) {
17446 limit = opts.limit;
17447 }
17448 if (!streamOpts.reverse) {
17449 streamOpts.start = formatSeq(opts.since || 0);
17450 }
17451
17452 var docIds = opts.doc_ids && new ExportedSet(opts.doc_ids);
17453 var filter = filterChange(opts);
17454 var docIdsToMetadata = new ExportedMap();
17455
17456 function complete() {
17457 opts.done = true;
17458 if (opts.return_docs && opts.limit) {
17459 /* istanbul ignore if */
17460 if (opts.limit < results.length) {
17461 results.length = opts.limit;
17462 }
17463 }
17464 changeStream.unpipe(throughStream);
17465 changeStream.destroy();
17466 if (!opts.continuous && !opts.cancelled) {
17467 if (opts.include_docs && opts.attachments && opts.return_docs) {
17468 fetchAttachments(results, stores, opts).then(function () {
17469 opts.complete(null, {results: results, last_seq: lastSeq});
17470 });
17471 } else {
17472 opts.complete(null, {results: results, last_seq: lastSeq});
17473 }
17474 }
17475 }
17476 var changeStream = stores.bySeqStore.readStream(streamOpts);
17477 var throughStream = through2.obj(function (data, _, next) {
17478 if (limit && called >= limit) {
17479 complete();
17480 return next();
17481 }
17482 if (opts.cancelled || opts.done) {
17483 return next();
17484 }
17485
17486 var seq = parseSeq(data.key);
17487 var doc = data.value;
17488
17489 if (seq === opts.since && !descending) {
17490 // couchdb ignores `since` if descending=true
17491 return next();
17492 }
17493
17494 if (docIds && !docIds.has(doc._id)) {
17495 return next();
17496 }
17497
17498 var metadata;
17499
17500 function onGetMetadata(metadata) {
17501 var winningRev$$1 = getWinningRev(metadata);
17502
17503 function onGetWinningDoc(winningDoc) {
17504
17505 var change = opts.processChange(winningDoc, metadata, opts);
17506 change.seq = metadata.seq;
17507
17508 var filtered = filter(change);
17509 if (typeof filtered === 'object') {
17510 return opts.complete(filtered);
17511 }
17512
17513 if (filtered) {
17514 called++;
17515
17516 if (opts.attachments && opts.include_docs) {
17517 // fetch attachment immediately for the benefit
17518 // of live listeners
17519 fetchAttachments([change], stores, opts).then(function () {
17520 opts.onChange(change);
17521 });
17522 } else {
17523 opts.onChange(change);
17524 }
17525
17526 if (opts.return_docs) {
17527 results.push(change);
17528 }
17529 }
17530 next();
17531 }
17532
17533 if (metadata.seq !== seq) {
17534 // some other seq is later
17535 return next();
17536 }
17537
17538 lastSeq = seq;
17539
17540 if (winningRev$$1 === doc._rev) {
17541 return onGetWinningDoc(doc);
17542 }
17543
17544 // fetch the winner
17545
17546 var winningSeq = metadata.rev_map[winningRev$$1];
17547
17548 stores.bySeqStore.get(formatSeq(winningSeq), function (err, doc) {
17549 onGetWinningDoc(doc);
17550 });
17551 }
17552
17553 metadata = docIdsToMetadata.get(doc._id);
17554 if (metadata) { // cached
17555 return onGetMetadata(metadata);
17556 }
17557 // metadata not cached, have to go fetch it
17558 stores.docStore.get(doc._id, function (err, metadata) {
17559 /* istanbul ignore if */
17560 if (opts.cancelled || opts.done || db.isClosed() ||
17561 isLocalId(metadata.id)) {
17562 return next();
17563 }
17564 docIdsToMetadata.set(doc._id, metadata);
17565 onGetMetadata(metadata);
17566 });
17567 }, function (next) {
17568 if (opts.cancelled) {
17569 return next();
17570 }
17571 if (opts.return_docs && opts.limit) {
17572 /* istanbul ignore if */
17573 if (opts.limit < results.length) {
17574 results.length = opts.limit;
17575 }
17576 }
17577
17578 next();
17579 }).on('unpipe', function () {
17580 throughStream.end();
17581 complete();
17582 });
17583 changeStream.pipe(throughStream);
17584 return {
17585 cancel: function () {
17586 opts.cancelled = true;
17587 complete();
17588 }
17589 };
17590 };
17591
17592 api._close = function (callback) {
17593 /* istanbul ignore if */
17594 if (db.isClosed()) {
17595 return callback(createError(NOT_OPEN));
17596 }
17597 db.close(function (err) {
17598 /* istanbul ignore if */
17599 if (err) {
17600 callback(err);
17601 } else {
17602 dbStore["delete"](name);
17603 callback();
17604 }
17605 });
17606 };
17607
17608 api._getRevisionTree = function (docId, callback) {
17609 stores.docStore.get(docId, function (err, metadata) {
17610 if (err) {
17611 callback(createError(MISSING_DOC));
17612 } else {
17613 callback(null, metadata.rev_tree);
17614 }
17615 });
17616 };
17617
17618 api._doCompaction = writeLock(function (docId, revs, opts, callback) {
17619 api._doCompactionNoLock(docId, revs, opts, callback);
17620 });
17621
17622 // the NoLock version is for use by bulkDocs
17623 api._doCompactionNoLock = function (docId, revs, opts, callback) {
17624 if (typeof opts === 'function') {
17625 callback = opts;
17626 opts = {};
17627 }
17628
17629 if (!revs.length) {
17630 return callback();
17631 }
17632 var txn = opts.ctx || new LevelTransaction();
17633
17634 txn.get(stores.docStore, docId, function (err, metadata) {
17635 /* istanbul ignore if */
17636 if (err) {
17637 return callback(err);
17638 }
17639 var seqs = revs.map(function (rev) {
17640 var seq = metadata.rev_map[rev];
17641 delete metadata.rev_map[rev];
17642 return seq;
17643 });
17644 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
17645 revHash, ctx, opts) {
17646 var rev = pos + '-' + revHash;
17647 if (revs.indexOf(rev) !== -1) {
17648 opts.status = 'missing';
17649 }
17650 });
17651
17652 var batch = [];
17653 batch.push({
17654 key: metadata.id,
17655 value: metadata,
17656 type: 'put',
17657 prefix: stores.docStore
17658 });
17659
17660 var digestMap = {};
17661 var numDone = 0;
17662 var overallErr;
17663 function checkDone(err) {
17664 /* istanbul ignore if */
17665 if (err) {
17666 overallErr = err;
17667 }
17668 if (++numDone === revs.length) { // done
17669 /* istanbul ignore if */
17670 if (overallErr) {
17671 return callback(overallErr);
17672 }
17673 deleteOrphanedAttachments();
17674 }
17675 }
17676
17677 function finish(err) {
17678 /* istanbul ignore if */
17679 if (err) {
17680 return callback(err);
17681 }
17682 txn.batch(batch);
17683 if (opts.ctx) {
17684 // don't execute immediately
17685 return callback();
17686 }
17687 txn.execute(db, callback);
17688 }
17689
17690 function deleteOrphanedAttachments() {
17691 var possiblyOrphanedAttachments = Object.keys(digestMap);
17692 if (!possiblyOrphanedAttachments.length) {
17693 return finish();
17694 }
17695 var numDone = 0;
17696 var overallErr;
17697 function checkDone(err) {
17698 /* istanbul ignore if */
17699 if (err) {
17700 overallErr = err;
17701 }
17702 if (++numDone === possiblyOrphanedAttachments.length) {
17703 finish(overallErr);
17704 }
17705 }
17706 var refsToDelete = new ExportedMap();
17707 revs.forEach(function (rev) {
17708 refsToDelete.set(docId + '@' + rev, true);
17709 });
17710 possiblyOrphanedAttachments.forEach(function (digest) {
17711 txn.get(stores.attachmentStore, digest, function (err, attData) {
17712 /* istanbul ignore if */
17713 if (err) {
17714 if (err.name === 'NotFoundError') {
17715 return checkDone();
17716 } else {
17717 return checkDone(err);
17718 }
17719 }
17720 var refs = Object.keys(attData.refs || {}).filter(function (ref) {
17721 return !refsToDelete.has(ref);
17722 });
17723 var newRefs = {};
17724 refs.forEach(function (ref) {
17725 newRefs[ref] = true;
17726 });
17727 if (refs.length) { // not orphaned
17728 batch.push({
17729 key: digest,
17730 type: 'put',
17731 value: {refs: newRefs},
17732 prefix: stores.attachmentStore
17733 });
17734 } else { // orphaned, can safely delete
17735 batch = batch.concat([{
17736 key: digest,
17737 type: 'del',
17738 prefix: stores.attachmentStore
17739 }, {
17740 key: digest,
17741 type: 'del',
17742 prefix: stores.binaryStore
17743 }]);
17744 }
17745 checkDone();
17746 });
17747 });
17748 }
17749
17750 seqs.forEach(function (seq) {
17751 batch.push({
17752 key: formatSeq(seq),
17753 type: 'del',
17754 prefix: stores.bySeqStore
17755 });
17756 txn.get(stores.bySeqStore, formatSeq(seq), function (err, doc) {
17757 /* istanbul ignore if */
17758 if (err) {
17759 if (err.name === 'NotFoundError') {
17760 return checkDone();
17761 } else {
17762 return checkDone(err);
17763 }
17764 }
17765 var atts = Object.keys(doc._attachments || {});
17766 atts.forEach(function (attName) {
17767 var digest = doc._attachments[attName].digest;
17768 digestMap[digest] = true;
17769 });
17770 checkDone();
17771 });
17772 });
17773 });
17774 };
17775
17776 api._getLocal = function (id, callback) {
17777 stores.localStore.get(id, function (err, doc) {
17778 if (err) {
17779 callback(createError(MISSING_DOC));
17780 } else {
17781 callback(null, doc);
17782 }
17783 });
17784 };
17785
17786 api._putLocal = function (doc, opts, callback) {
17787 if (typeof opts === 'function') {
17788 callback = opts;
17789 opts = {};
17790 }
17791 if (opts.ctx) {
17792 api._putLocalNoLock(doc, opts, callback);
17793 } else {
17794 api._putLocalWithLock(doc, opts, callback);
17795 }
17796 };
17797
17798 api._putLocalWithLock = writeLock(function (doc, opts, callback) {
17799 api._putLocalNoLock(doc, opts, callback);
17800 });
17801
17802 // the NoLock version is for use by bulkDocs
17803 api._putLocalNoLock = function (doc, opts, callback) {
17804 delete doc._revisions; // ignore this, trust the rev
17805 var oldRev = doc._rev;
17806 var id = doc._id;
17807
17808 var txn = opts.ctx || new LevelTransaction();
17809
17810 txn.get(stores.localStore, id, function (err, resp) {
17811 if (err && oldRev) {
17812 return callback(createError(REV_CONFLICT));
17813 }
17814 if (resp && resp._rev !== oldRev) {
17815 return callback(createError(REV_CONFLICT));
17816 }
17817 doc._rev =
17818 oldRev ? '0-' + (parseInt(oldRev.split('-')[1], 10) + 1) : '0-1';
17819 var batch = [
17820 {
17821 type: 'put',
17822 prefix: stores.localStore,
17823 key: id,
17824 value: doc
17825 }
17826 ];
17827
17828 txn.batch(batch);
17829 var ret = {ok: true, id: doc._id, rev: doc._rev};
17830
17831 if (opts.ctx) {
17832 // don't execute immediately
17833 return callback(null, ret);
17834 }
17835 txn.execute(db, function (err) {
17836 /* istanbul ignore if */
17837 if (err) {
17838 return callback(err);
17839 }
17840 callback(null, ret);
17841 });
17842 });
17843 };
17844
17845 api._removeLocal = function (doc, opts, callback) {
17846 if (typeof opts === 'function') {
17847 callback = opts;
17848 opts = {};
17849 }
17850 if (opts.ctx) {
17851 api._removeLocalNoLock(doc, opts, callback);
17852 } else {
17853 api._removeLocalWithLock(doc, opts, callback);
17854 }
17855 };
17856
17857 api._removeLocalWithLock = writeLock(function (doc, opts, callback) {
17858 api._removeLocalNoLock(doc, opts, callback);
17859 });
17860
17861 // the NoLock version is for use by bulkDocs
17862 api._removeLocalNoLock = function (doc, opts, callback) {
17863 var txn = opts.ctx || new LevelTransaction();
17864 txn.get(stores.localStore, doc._id, function (err, resp) {
17865 if (err) {
17866 /* istanbul ignore if */
17867 if (err.name !== 'NotFoundError') {
17868 return callback(err);
17869 } else {
17870 return callback(createError(MISSING_DOC));
17871 }
17872 }
17873 if (resp._rev !== doc._rev) {
17874 return callback(createError(REV_CONFLICT));
17875 }
17876 txn.batch([{
17877 prefix: stores.localStore,
17878 type: 'del',
17879 key: doc._id
17880 }]);
17881 var ret = {ok: true, id: doc._id, rev: '0-0'};
17882 if (opts.ctx) {
17883 // don't execute immediately
17884 return callback(null, ret);
17885 }
17886 txn.execute(db, function (err) {
17887 /* istanbul ignore if */
17888 if (err) {
17889 return callback(err);
17890 }
17891 callback(null, ret);
17892 });
17893 });
17894 };
17895
17896 // close and delete open leveldb stores
17897 api._destroy = function (opts, callback) {
17898 var dbStore;
17899 var leveldownName = functionName(leveldown);
17900 /* istanbul ignore else */
17901 if (dbStores.has(leveldownName)) {
17902 dbStore = dbStores.get(leveldownName);
17903 } else {
17904 return callDestroy(name, callback);
17905 }
17906
17907 /* istanbul ignore else */
17908 if (dbStore.has(name)) {
17909 levelChanges.removeAllListeners(name);
17910
17911 dbStore.get(name).close(function () {
17912 dbStore["delete"](name);
17913 callDestroy(name, callback);
17914 });
17915 } else {
17916 callDestroy(name, callback);
17917 }
17918 };
17919 function callDestroy(name, cb) {
17920 // May not exist if leveldown is backed by memory adapter
17921 if ('destroy' in leveldown) {
17922 leveldown.destroy(name, cb);
17923 }
17924 }
17925}
17926
17927function MemDownPouch(opts, callback) {
17928 var _opts = $inject_Object_assign({
17929 db: memdown
17930 }, opts);
17931
17932 LevelPouch.call(this, _opts, callback);
17933}
17934
17935// overrides for normal LevelDB behavior on Node
17936MemDownPouch.valid = function () {
17937 return true;
17938};
17939MemDownPouch.use_prefix = false;
17940
17941function MemoryPouchPlugin (PouchDB) {
17942 PouchDB.adapter('memory', MemDownPouch, true);
17943}
17944
17945/* global PouchDB */
17946
17947if (typeof PouchDB === 'undefined') {
17948 guardedConsole('error', 'memory adapter plugin error: ' +
17949 'Cannot find global "PouchDB" object! ' +
17950 'Did you remember to include pouchdb.js?');
17951} else {
17952 PouchDB.plugin(MemoryPouchPlugin);
17953}
17954
17955}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
17956},{"1":1,"100":100,"105":105,"11":11,"110":110,"14":14,"17":17,"18":18,"21":21,"35":35,"45":45,"47":47,"71":71,"73":73,"8":8}]},{},[111]);
17957
\No newline at end of file