UNPKG

603 kBJavaScriptView Raw
1// PouchDB in-memory plugin 7.2.1
2// Based on MemDOWN: https://github.com/rvagg/memdown
3//
4// (c) 2012-2020 Dale Harvey and the PouchDB team
5// PouchDB may be freely distributed under the Apache license, version 2.0.
6// For all details and documentation:
7// http://pouchdb.com
8(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(_dereq_,module,exports){
9'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
32var objectAssign = _dereq_(68);
33
34// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
35// original notice:
36
37/*!
38 * The buffer module from node.js, for the browser.
39 *
40 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
41 * @license MIT
42 */
43function compare(a, b) {
44 if (a === b) {
45 return 0;
46 }
47
48 var x = a.length;
49 var y = b.length;
50
51 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
52 if (a[i] !== b[i]) {
53 x = a[i];
54 y = b[i];
55 break;
56 }
57 }
58
59 if (x < y) {
60 return -1;
61 }
62 if (y < x) {
63 return 1;
64 }
65 return 0;
66}
67function isBuffer(b) {
68 if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
69 return global.Buffer.isBuffer(b);
70 }
71 return !!(b != null && b._isBuffer);
72}
73
74// based on node assert, original notice:
75// NB: The URL to the CommonJS spec is kept just for tradition.
76// node-assert has evolved a lot since then, both in API and behavior.
77
78// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
79//
80// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
81//
82// Originally from narwhal.js (http://narwhaljs.org)
83// Copyright (c) 2009 Thomas Robinson <280north.com>
84//
85// Permission is hereby granted, free of charge, to any person obtaining a copy
86// of this software and associated documentation files (the 'Software'), to
87// deal in the Software without restriction, including without limitation the
88// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
89// sell copies of the Software, and to permit persons to whom the Software is
90// furnished to do so, subject to the following conditions:
91//
92// The above copyright notice and this permission notice shall be included in
93// all copies or substantial portions of the Software.
94//
95// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
96// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
97// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
98// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
99// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
100// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
101
102var util = _dereq_(5);
103var hasOwn = Object.prototype.hasOwnProperty;
104var pSlice = Array.prototype.slice;
105var functionsHaveNames = (function () {
106 return function foo() {}.name === 'foo';
107}());
108function pToString (obj) {
109 return Object.prototype.toString.call(obj);
110}
111function isView(arrbuf) {
112 if (isBuffer(arrbuf)) {
113 return false;
114 }
115 if (typeof global.ArrayBuffer !== 'function') {
116 return false;
117 }
118 if (typeof ArrayBuffer.isView === 'function') {
119 return ArrayBuffer.isView(arrbuf);
120 }
121 if (!arrbuf) {
122 return false;
123 }
124 if (arrbuf instanceof DataView) {
125 return true;
126 }
127 if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
128 return true;
129 }
130 return false;
131}
132// 1. The assert module provides functions that throw
133// AssertionError's when particular conditions are not met. The
134// assert module must conform to the following interface.
135
136var assert = module.exports = ok;
137
138// 2. The AssertionError is defined in assert.
139// new assert.AssertionError({ message: message,
140// actual: actual,
141// expected: expected })
142
143var regex = /\s*function\s+([^\(\s]*)\s*/;
144// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
145function getName(func) {
146 if (!util.isFunction(func)) {
147 return;
148 }
149 if (functionsHaveNames) {
150 return func.name;
151 }
152 var str = func.toString();
153 var match = str.match(regex);
154 return match && match[1];
155}
156assert.AssertionError = function AssertionError(options) {
157 this.name = 'AssertionError';
158 this.actual = options.actual;
159 this.expected = options.expected;
160 this.operator = options.operator;
161 if (options.message) {
162 this.message = options.message;
163 this.generatedMessage = false;
164 } else {
165 this.message = getMessage(this);
166 this.generatedMessage = true;
167 }
168 var stackStartFunction = options.stackStartFunction || fail;
169 if (Error.captureStackTrace) {
170 Error.captureStackTrace(this, stackStartFunction);
171 } else {
172 // non v8 browsers so we can have a stacktrace
173 var err = new Error();
174 if (err.stack) {
175 var out = err.stack;
176
177 // try to strip useless frames
178 var fn_name = getName(stackStartFunction);
179 var idx = out.indexOf('\n' + fn_name);
180 if (idx >= 0) {
181 // once we have located the function frame
182 // we need to strip out everything before it (and its line)
183 var next_line = out.indexOf('\n', idx + 1);
184 out = out.substring(next_line + 1);
185 }
186
187 this.stack = out;
188 }
189 }
190};
191
192// assert.AssertionError instanceof Error
193util.inherits(assert.AssertionError, Error);
194
195function truncate(s, n) {
196 if (typeof s === 'string') {
197 return s.length < n ? s : s.slice(0, n);
198 } else {
199 return s;
200 }
201}
202function inspect(something) {
203 if (functionsHaveNames || !util.isFunction(something)) {
204 return util.inspect(something);
205 }
206 var rawname = getName(something);
207 var name = rawname ? ': ' + rawname : '';
208 return '[Function' + name + ']';
209}
210function getMessage(self) {
211 return truncate(inspect(self.actual), 128) + ' ' +
212 self.operator + ' ' +
213 truncate(inspect(self.expected), 128);
214}
215
216// At present only the three keys mentioned above are used and
217// understood by the spec. Implementations or sub modules can pass
218// other keys to the AssertionError's constructor - they will be
219// ignored.
220
221// 3. All of the following functions must throw an AssertionError
222// when a corresponding condition is not met, with a message that
223// may be undefined if not provided. All assertion methods provide
224// both the actual and expected values to the assertion error for
225// display purposes.
226
227function fail(actual, expected, message, operator, stackStartFunction) {
228 throw new assert.AssertionError({
229 message: message,
230 actual: actual,
231 expected: expected,
232 operator: operator,
233 stackStartFunction: stackStartFunction
234 });
235}
236
237// EXTENSION! allows for well behaved errors defined elsewhere.
238assert.fail = fail;
239
240// 4. Pure assertion tests whether a value is truthy, as determined
241// by !!guard.
242// assert.ok(guard, message_opt);
243// This statement is equivalent to assert.equal(true, !!guard,
244// message_opt);. To test strictly for the value true, use
245// assert.strictEqual(true, guard, message_opt);.
246
247function ok(value, message) {
248 if (!value) fail(value, true, message, '==', assert.ok);
249}
250assert.ok = ok;
251
252// 5. The equality assertion tests shallow, coercive equality with
253// ==.
254// assert.equal(actual, expected, message_opt);
255
256assert.equal = function equal(actual, expected, message) {
257 if (actual != expected) fail(actual, expected, message, '==', assert.equal);
258};
259
260// 6. The non-equality assertion tests for whether two objects are not equal
261// with != assert.notEqual(actual, expected, message_opt);
262
263assert.notEqual = function notEqual(actual, expected, message) {
264 if (actual == expected) {
265 fail(actual, expected, message, '!=', assert.notEqual);
266 }
267};
268
269// 7. The equivalence assertion tests a deep equality relation.
270// assert.deepEqual(actual, expected, message_opt);
271
272assert.deepEqual = function deepEqual(actual, expected, message) {
273 if (!_deepEqual(actual, expected, false)) {
274 fail(actual, expected, message, 'deepEqual', assert.deepEqual);
275 }
276};
277
278assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
279 if (!_deepEqual(actual, expected, true)) {
280 fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
281 }
282};
283
284function _deepEqual(actual, expected, strict, memos) {
285 // 7.1. All identical values are equivalent, as determined by ===.
286 if (actual === expected) {
287 return true;
288 } else if (isBuffer(actual) && isBuffer(expected)) {
289 return compare(actual, expected) === 0;
290
291 // 7.2. If the expected value is a Date object, the actual value is
292 // equivalent if it is also a Date object that refers to the same time.
293 } else if (util.isDate(actual) && util.isDate(expected)) {
294 return actual.getTime() === expected.getTime();
295
296 // 7.3 If the expected value is a RegExp object, the actual value is
297 // equivalent if it is also a RegExp object with the same source and
298 // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
299 } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
300 return actual.source === expected.source &&
301 actual.global === expected.global &&
302 actual.multiline === expected.multiline &&
303 actual.lastIndex === expected.lastIndex &&
304 actual.ignoreCase === expected.ignoreCase;
305
306 // 7.4. Other pairs that do not both pass typeof value == 'object',
307 // equivalence is determined by ==.
308 } else if ((actual === null || typeof actual !== 'object') &&
309 (expected === null || typeof expected !== 'object')) {
310 return strict ? actual === expected : actual == expected;
311
312 // If both values are instances of typed arrays, wrap their underlying
313 // ArrayBuffers in a Buffer each to increase performance
314 // This optimization requires the arrays to have the same type as checked by
315 // Object.prototype.toString (aka pToString). Never perform binary
316 // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
317 // bit patterns are not identical.
318 } else if (isView(actual) && isView(expected) &&
319 pToString(actual) === pToString(expected) &&
320 !(actual instanceof Float32Array ||
321 actual instanceof Float64Array)) {
322 return compare(new Uint8Array(actual.buffer),
323 new Uint8Array(expected.buffer)) === 0;
324
325 // 7.5 For all other Object pairs, including Array objects, equivalence is
326 // determined by having the same number of owned properties (as verified
327 // with Object.prototype.hasOwnProperty.call), the same set of keys
328 // (although not necessarily the same order), equivalent values for every
329 // corresponding key, and an identical 'prototype' property. Note: this
330 // accounts for both named and indexed properties on Arrays.
331 } else if (isBuffer(actual) !== isBuffer(expected)) {
332 return false;
333 } else {
334 memos = memos || {actual: [], expected: []};
335
336 var actualIndex = memos.actual.indexOf(actual);
337 if (actualIndex !== -1) {
338 if (actualIndex === memos.expected.indexOf(expected)) {
339 return true;
340 }
341 }
342
343 memos.actual.push(actual);
344 memos.expected.push(expected);
345
346 return objEquiv(actual, expected, strict, memos);
347 }
348}
349
350function isArguments(object) {
351 return Object.prototype.toString.call(object) == '[object Arguments]';
352}
353
354function objEquiv(a, b, strict, actualVisitedObjects) {
355 if (a === null || a === undefined || b === null || b === undefined)
356 return false;
357 // if one is a primitive, the other must be same
358 if (util.isPrimitive(a) || util.isPrimitive(b))
359 return a === b;
360 if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
361 return false;
362 var aIsArgs = isArguments(a);
363 var bIsArgs = isArguments(b);
364 if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
365 return false;
366 if (aIsArgs) {
367 a = pSlice.call(a);
368 b = pSlice.call(b);
369 return _deepEqual(a, b, strict);
370 }
371 var ka = objectKeys(a);
372 var kb = objectKeys(b);
373 var key, i;
374 // having the same number of owned properties (keys incorporates
375 // hasOwnProperty)
376 if (ka.length !== kb.length)
377 return false;
378 //the same set of keys (although not necessarily the same order),
379 ka.sort();
380 kb.sort();
381 //~~~cheap key test
382 for (i = ka.length - 1; i >= 0; i--) {
383 if (ka[i] !== kb[i])
384 return false;
385 }
386 //equivalent values for every corresponding key, and
387 //~~~possibly expensive deep test
388 for (i = ka.length - 1; i >= 0; i--) {
389 key = ka[i];
390 if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
391 return false;
392 }
393 return true;
394}
395
396// 8. The non-equivalence assertion tests for any deep inequality.
397// assert.notDeepEqual(actual, expected, message_opt);
398
399assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
400 if (_deepEqual(actual, expected, false)) {
401 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
402 }
403};
404
405assert.notDeepStrictEqual = notDeepStrictEqual;
406function notDeepStrictEqual(actual, expected, message) {
407 if (_deepEqual(actual, expected, true)) {
408 fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
409 }
410}
411
412
413// 9. The strict equality assertion tests strict equality, as determined by ===.
414// assert.strictEqual(actual, expected, message_opt);
415
416assert.strictEqual = function strictEqual(actual, expected, message) {
417 if (actual !== expected) {
418 fail(actual, expected, message, '===', assert.strictEqual);
419 }
420};
421
422// 10. The strict non-equality assertion tests for strict inequality, as
423// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
424
425assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
426 if (actual === expected) {
427 fail(actual, expected, message, '!==', assert.notStrictEqual);
428 }
429};
430
431function expectedException(actual, expected) {
432 if (!actual || !expected) {
433 return false;
434 }
435
436 if (Object.prototype.toString.call(expected) == '[object RegExp]') {
437 return expected.test(actual);
438 }
439
440 try {
441 if (actual instanceof expected) {
442 return true;
443 }
444 } catch (e) {
445 // Ignore. The instanceof check doesn't work for arrow functions.
446 }
447
448 if (Error.isPrototypeOf(expected)) {
449 return false;
450 }
451
452 return expected.call({}, actual) === true;
453}
454
455function _tryBlock(block) {
456 var error;
457 try {
458 block();
459 } catch (e) {
460 error = e;
461 }
462 return error;
463}
464
465function _throws(shouldThrow, block, expected, message) {
466 var actual;
467
468 if (typeof block !== 'function') {
469 throw new TypeError('"block" argument must be a function');
470 }
471
472 if (typeof expected === 'string') {
473 message = expected;
474 expected = null;
475 }
476
477 actual = _tryBlock(block);
478
479 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
480 (message ? ' ' + message : '.');
481
482 if (shouldThrow && !actual) {
483 fail(actual, expected, 'Missing expected exception' + message);
484 }
485
486 var userProvidedMessage = typeof message === 'string';
487 var isUnwantedException = !shouldThrow && util.isError(actual);
488 var isUnexpectedException = !shouldThrow && actual && !expected;
489
490 if ((isUnwantedException &&
491 userProvidedMessage &&
492 expectedException(actual, expected)) ||
493 isUnexpectedException) {
494 fail(actual, expected, 'Got unwanted exception' + message);
495 }
496
497 if ((shouldThrow && actual && expected &&
498 !expectedException(actual, expected)) || (!shouldThrow && actual)) {
499 throw actual;
500 }
501}
502
503// 11. Expected to throw an error:
504// assert.throws(block, Error_opt, message_opt);
505
506assert.throws = function(block, /*optional*/error, /*optional*/message) {
507 _throws(true, block, error, message);
508};
509
510// EXTENSION! This is annoying to write outside this module.
511assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
512 _throws(false, block, error, message);
513};
514
515assert.ifError = function(err) { if (err) throw err; };
516
517// Expose a strict only variant of assert
518function strict(value, message) {
519 if (!value) fail(value, true, message, '==', strict);
520}
521assert.strict = objectAssign(strict, assert, {
522 equal: assert.strictEqual,
523 deepEqual: assert.deepStrictEqual,
524 notEqual: assert.notStrictEqual,
525 notDeepEqual: assert.notDeepStrictEqual
526});
527assert.strict.strict = assert.strict;
528
529var objectKeys = Object.keys || function (obj) {
530 var keys = [];
531 for (var key in obj) {
532 if (hasOwn.call(obj, key)) keys.push(key);
533 }
534 return keys;
535};
536
537}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
538},{"5":5,"68":68}],3:[function(_dereq_,module,exports){
539if (typeof Object.create === 'function') {
540 // implementation from standard node.js 'util' module
541 module.exports = function inherits(ctor, superCtor) {
542 ctor.super_ = superCtor
543 ctor.prototype = Object.create(superCtor.prototype, {
544 constructor: {
545 value: ctor,
546 enumerable: false,
547 writable: true,
548 configurable: true
549 }
550 });
551 };
552} else {
553 // old school shim for old browsers
554 module.exports = function inherits(ctor, superCtor) {
555 ctor.super_ = superCtor
556 var TempCtor = function () {}
557 TempCtor.prototype = superCtor.prototype
558 ctor.prototype = new TempCtor()
559 ctor.prototype.constructor = ctor
560 }
561}
562
563},{}],4:[function(_dereq_,module,exports){
564module.exports = function isBuffer(arg) {
565 return arg && typeof arg === 'object'
566 && typeof arg.copy === 'function'
567 && typeof arg.fill === 'function'
568 && typeof arg.readUInt8 === 'function';
569}
570},{}],5:[function(_dereq_,module,exports){
571(function (process,global){
572// Copyright Joyent, Inc. and other Node contributors.
573//
574// Permission is hereby granted, free of charge, to any person obtaining a
575// copy of this software and associated documentation files (the
576// "Software"), to deal in the Software without restriction, including
577// without limitation the rights to use, copy, modify, merge, publish,
578// distribute, sublicense, and/or sell copies of the Software, and to permit
579// persons to whom the Software is furnished to do so, subject to the
580// following conditions:
581//
582// The above copyright notice and this permission notice shall be included
583// in all copies or substantial portions of the Software.
584//
585// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
586// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
587// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
588// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
589// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
590// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
591// USE OR OTHER DEALINGS IN THE SOFTWARE.
592
593var formatRegExp = /%[sdj%]/g;
594exports.format = function(f) {
595 if (!isString(f)) {
596 var objects = [];
597 for (var i = 0; i < arguments.length; i++) {
598 objects.push(inspect(arguments[i]));
599 }
600 return objects.join(' ');
601 }
602
603 var i = 1;
604 var args = arguments;
605 var len = args.length;
606 var str = String(f).replace(formatRegExp, function(x) {
607 if (x === '%%') return '%';
608 if (i >= len) return x;
609 switch (x) {
610 case '%s': return String(args[i++]);
611 case '%d': return Number(args[i++]);
612 case '%j':
613 try {
614 return JSON.stringify(args[i++]);
615 } catch (_) {
616 return '[Circular]';
617 }
618 default:
619 return x;
620 }
621 });
622 for (var x = args[i]; i < len; x = args[++i]) {
623 if (isNull(x) || !isObject(x)) {
624 str += ' ' + x;
625 } else {
626 str += ' ' + inspect(x);
627 }
628 }
629 return str;
630};
631
632
633// Mark that a method should not be used.
634// Returns a modified function which warns once by default.
635// If --no-deprecation is set, then it is a no-op.
636exports.deprecate = function(fn, msg) {
637 // Allow for deprecating things in the process of starting up.
638 if (isUndefined(global.process)) {
639 return function() {
640 return exports.deprecate(fn, msg).apply(this, arguments);
641 };
642 }
643
644 if (process.noDeprecation === true) {
645 return fn;
646 }
647
648 var warned = false;
649 function deprecated() {
650 if (!warned) {
651 if (process.throwDeprecation) {
652 throw new Error(msg);
653 } else if (process.traceDeprecation) {
654 console.trace(msg);
655 } else {
656 console.error(msg);
657 }
658 warned = true;
659 }
660 return fn.apply(this, arguments);
661 }
662
663 return deprecated;
664};
665
666
667var debugs = {};
668var debugEnviron;
669exports.debuglog = function(set) {
670 if (isUndefined(debugEnviron))
671 debugEnviron = process.env.NODE_DEBUG || '';
672 set = set.toUpperCase();
673 if (!debugs[set]) {
674 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
675 var pid = process.pid;
676 debugs[set] = function() {
677 var msg = exports.format.apply(exports, arguments);
678 console.error('%s %d: %s', set, pid, msg);
679 };
680 } else {
681 debugs[set] = function() {};
682 }
683 }
684 return debugs[set];
685};
686
687
688/**
689 * Echos the value of a value. Trys to print the value out
690 * in the best way possible given the different types.
691 *
692 * @param {Object} obj The object to print out.
693 * @param {Object} opts Optional options object that alters the output.
694 */
695/* legacy: obj, showHidden, depth, colors*/
696function inspect(obj, opts) {
697 // default options
698 var ctx = {
699 seen: [],
700 stylize: stylizeNoColor
701 };
702 // legacy...
703 if (arguments.length >= 3) ctx.depth = arguments[2];
704 if (arguments.length >= 4) ctx.colors = arguments[3];
705 if (isBoolean(opts)) {
706 // legacy...
707 ctx.showHidden = opts;
708 } else if (opts) {
709 // got an "options" object
710 exports._extend(ctx, opts);
711 }
712 // set default options
713 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
714 if (isUndefined(ctx.depth)) ctx.depth = 2;
715 if (isUndefined(ctx.colors)) ctx.colors = false;
716 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
717 if (ctx.colors) ctx.stylize = stylizeWithColor;
718 return formatValue(ctx, obj, ctx.depth);
719}
720exports.inspect = inspect;
721
722
723// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
724inspect.colors = {
725 'bold' : [1, 22],
726 'italic' : [3, 23],
727 'underline' : [4, 24],
728 'inverse' : [7, 27],
729 'white' : [37, 39],
730 'grey' : [90, 39],
731 'black' : [30, 39],
732 'blue' : [34, 39],
733 'cyan' : [36, 39],
734 'green' : [32, 39],
735 'magenta' : [35, 39],
736 'red' : [31, 39],
737 'yellow' : [33, 39]
738};
739
740// Don't use 'blue' not visible on cmd.exe
741inspect.styles = {
742 'special': 'cyan',
743 'number': 'yellow',
744 'boolean': 'yellow',
745 'undefined': 'grey',
746 'null': 'bold',
747 'string': 'green',
748 'date': 'magenta',
749 // "name": intentionally not styling
750 'regexp': 'red'
751};
752
753
754function stylizeWithColor(str, styleType) {
755 var style = inspect.styles[styleType];
756
757 if (style) {
758 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
759 '\u001b[' + inspect.colors[style][1] + 'm';
760 } else {
761 return str;
762 }
763}
764
765
766function stylizeNoColor(str, styleType) {
767 return str;
768}
769
770
771function arrayToHash(array) {
772 var hash = {};
773
774 array.forEach(function(val, idx) {
775 hash[val] = true;
776 });
777
778 return hash;
779}
780
781
782function formatValue(ctx, value, recurseTimes) {
783 // Provide a hook for user-specified inspect functions.
784 // Check that value is an object with an inspect function on it
785 if (ctx.customInspect &&
786 value &&
787 isFunction(value.inspect) &&
788 // Filter out the util module, it's inspect function is special
789 value.inspect !== exports.inspect &&
790 // Also filter out any prototype objects using the circular check.
791 !(value.constructor && value.constructor.prototype === value)) {
792 var ret = value.inspect(recurseTimes, ctx);
793 if (!isString(ret)) {
794 ret = formatValue(ctx, ret, recurseTimes);
795 }
796 return ret;
797 }
798
799 // Primitive types cannot have properties
800 var primitive = formatPrimitive(ctx, value);
801 if (primitive) {
802 return primitive;
803 }
804
805 // Look up the keys of the object.
806 var keys = Object.keys(value);
807 var visibleKeys = arrayToHash(keys);
808
809 if (ctx.showHidden) {
810 keys = Object.getOwnPropertyNames(value);
811 }
812
813 // IE doesn't make error fields non-enumerable
814 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
815 if (isError(value)
816 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
817 return formatError(value);
818 }
819
820 // Some type of object without properties can be shortcutted.
821 if (keys.length === 0) {
822 if (isFunction(value)) {
823 var name = value.name ? ': ' + value.name : '';
824 return ctx.stylize('[Function' + name + ']', 'special');
825 }
826 if (isRegExp(value)) {
827 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
828 }
829 if (isDate(value)) {
830 return ctx.stylize(Date.prototype.toString.call(value), 'date');
831 }
832 if (isError(value)) {
833 return formatError(value);
834 }
835 }
836
837 var base = '', array = false, braces = ['{', '}'];
838
839 // Make Array say that they are Array
840 if (isArray(value)) {
841 array = true;
842 braces = ['[', ']'];
843 }
844
845 // Make functions say that they are functions
846 if (isFunction(value)) {
847 var n = value.name ? ': ' + value.name : '';
848 base = ' [Function' + n + ']';
849 }
850
851 // Make RegExps say that they are RegExps
852 if (isRegExp(value)) {
853 base = ' ' + RegExp.prototype.toString.call(value);
854 }
855
856 // Make dates with properties first say the date
857 if (isDate(value)) {
858 base = ' ' + Date.prototype.toUTCString.call(value);
859 }
860
861 // Make error with message first say the error
862 if (isError(value)) {
863 base = ' ' + formatError(value);
864 }
865
866 if (keys.length === 0 && (!array || value.length == 0)) {
867 return braces[0] + base + braces[1];
868 }
869
870 if (recurseTimes < 0) {
871 if (isRegExp(value)) {
872 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
873 } else {
874 return ctx.stylize('[Object]', 'special');
875 }
876 }
877
878 ctx.seen.push(value);
879
880 var output;
881 if (array) {
882 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
883 } else {
884 output = keys.map(function(key) {
885 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
886 });
887 }
888
889 ctx.seen.pop();
890
891 return reduceToSingleString(output, base, braces);
892}
893
894
895function formatPrimitive(ctx, value) {
896 if (isUndefined(value))
897 return ctx.stylize('undefined', 'undefined');
898 if (isString(value)) {
899 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
900 .replace(/'/g, "\\'")
901 .replace(/\\"/g, '"') + '\'';
902 return ctx.stylize(simple, 'string');
903 }
904 if (isNumber(value))
905 return ctx.stylize('' + value, 'number');
906 if (isBoolean(value))
907 return ctx.stylize('' + value, 'boolean');
908 // For some reason typeof null is "object", so special case here.
909 if (isNull(value))
910 return ctx.stylize('null', 'null');
911}
912
913
914function formatError(value) {
915 return '[' + Error.prototype.toString.call(value) + ']';
916}
917
918
919function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
920 var output = [];
921 for (var i = 0, l = value.length; i < l; ++i) {
922 if (hasOwnProperty(value, String(i))) {
923 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
924 String(i), true));
925 } else {
926 output.push('');
927 }
928 }
929 keys.forEach(function(key) {
930 if (!key.match(/^\d+$/)) {
931 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
932 key, true));
933 }
934 });
935 return output;
936}
937
938
939function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
940 var name, str, desc;
941 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
942 if (desc.get) {
943 if (desc.set) {
944 str = ctx.stylize('[Getter/Setter]', 'special');
945 } else {
946 str = ctx.stylize('[Getter]', 'special');
947 }
948 } else {
949 if (desc.set) {
950 str = ctx.stylize('[Setter]', 'special');
951 }
952 }
953 if (!hasOwnProperty(visibleKeys, key)) {
954 name = '[' + key + ']';
955 }
956 if (!str) {
957 if (ctx.seen.indexOf(desc.value) < 0) {
958 if (isNull(recurseTimes)) {
959 str = formatValue(ctx, desc.value, null);
960 } else {
961 str = formatValue(ctx, desc.value, recurseTimes - 1);
962 }
963 if (str.indexOf('\n') > -1) {
964 if (array) {
965 str = str.split('\n').map(function(line) {
966 return ' ' + line;
967 }).join('\n').substr(2);
968 } else {
969 str = '\n' + str.split('\n').map(function(line) {
970 return ' ' + line;
971 }).join('\n');
972 }
973 }
974 } else {
975 str = ctx.stylize('[Circular]', 'special');
976 }
977 }
978 if (isUndefined(name)) {
979 if (array && key.match(/^\d+$/)) {
980 return str;
981 }
982 name = JSON.stringify('' + key);
983 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
984 name = name.substr(1, name.length - 2);
985 name = ctx.stylize(name, 'name');
986 } else {
987 name = name.replace(/'/g, "\\'")
988 .replace(/\\"/g, '"')
989 .replace(/(^"|"$)/g, "'");
990 name = ctx.stylize(name, 'string');
991 }
992 }
993
994 return name + ': ' + str;
995}
996
997
998function reduceToSingleString(output, base, braces) {
999 var numLinesEst = 0;
1000 var length = output.reduce(function(prev, cur) {
1001 numLinesEst++;
1002 if (cur.indexOf('\n') >= 0) numLinesEst++;
1003 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
1004 }, 0);
1005
1006 if (length > 60) {
1007 return braces[0] +
1008 (base === '' ? '' : base + '\n ') +
1009 ' ' +
1010 output.join(',\n ') +
1011 ' ' +
1012 braces[1];
1013 }
1014
1015 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
1016}
1017
1018
1019// NOTE: These type checking functions intentionally don't use `instanceof`
1020// because it is fragile and can be easily faked with `Object.create()`.
1021function isArray(ar) {
1022 return Array.isArray(ar);
1023}
1024exports.isArray = isArray;
1025
1026function isBoolean(arg) {
1027 return typeof arg === 'boolean';
1028}
1029exports.isBoolean = isBoolean;
1030
1031function isNull(arg) {
1032 return arg === null;
1033}
1034exports.isNull = isNull;
1035
1036function isNullOrUndefined(arg) {
1037 return arg == null;
1038}
1039exports.isNullOrUndefined = isNullOrUndefined;
1040
1041function isNumber(arg) {
1042 return typeof arg === 'number';
1043}
1044exports.isNumber = isNumber;
1045
1046function isString(arg) {
1047 return typeof arg === 'string';
1048}
1049exports.isString = isString;
1050
1051function isSymbol(arg) {
1052 return typeof arg === 'symbol';
1053}
1054exports.isSymbol = isSymbol;
1055
1056function isUndefined(arg) {
1057 return arg === void 0;
1058}
1059exports.isUndefined = isUndefined;
1060
1061function isRegExp(re) {
1062 return isObject(re) && objectToString(re) === '[object RegExp]';
1063}
1064exports.isRegExp = isRegExp;
1065
1066function isObject(arg) {
1067 return typeof arg === 'object' && arg !== null;
1068}
1069exports.isObject = isObject;
1070
1071function isDate(d) {
1072 return isObject(d) && objectToString(d) === '[object Date]';
1073}
1074exports.isDate = isDate;
1075
1076function isError(e) {
1077 return isObject(e) &&
1078 (objectToString(e) === '[object Error]' || e instanceof Error);
1079}
1080exports.isError = isError;
1081
1082function isFunction(arg) {
1083 return typeof arg === 'function';
1084}
1085exports.isFunction = isFunction;
1086
1087function isPrimitive(arg) {
1088 return arg === null ||
1089 typeof arg === 'boolean' ||
1090 typeof arg === 'number' ||
1091 typeof arg === 'string' ||
1092 typeof arg === 'symbol' || // ES6 symbol
1093 typeof arg === 'undefined';
1094}
1095exports.isPrimitive = isPrimitive;
1096
1097exports.isBuffer = _dereq_(4);
1098
1099function objectToString(o) {
1100 return Object.prototype.toString.call(o);
1101}
1102
1103
1104function pad(n) {
1105 return n < 10 ? '0' + n.toString(10) : n.toString(10);
1106}
1107
1108
1109var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
1110 'Oct', 'Nov', 'Dec'];
1111
1112// 26 Feb 16:19:34
1113function timestamp() {
1114 var d = new Date();
1115 var time = [pad(d.getHours()),
1116 pad(d.getMinutes()),
1117 pad(d.getSeconds())].join(':');
1118 return [d.getDate(), months[d.getMonth()], time].join(' ');
1119}
1120
1121
1122// log is just a thin wrapper to console.log that prepends a timestamp
1123exports.log = function() {
1124 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
1125};
1126
1127
1128/**
1129 * Inherit the prototype methods from one constructor into another.
1130 *
1131 * The Function.prototype.inherits from lang.js rewritten as a standalone
1132 * function (not on Function.prototype). NOTE: If this file is to be loaded
1133 * during bootstrapping this function needs to be rewritten using some native
1134 * functions as prototype setup using normal JavaScript does not work as
1135 * expected during bootstrapping (see mirror.js in r114903).
1136 *
1137 * @param {function} ctor Constructor function which needs to inherit the
1138 * prototype.
1139 * @param {function} superCtor Constructor function to inherit prototype from.
1140 */
1141exports.inherits = _dereq_(3);
1142
1143exports._extend = function(origin, add) {
1144 // Don't do anything if add isn't an object
1145 if (!add || !isObject(add)) return origin;
1146
1147 var keys = Object.keys(add);
1148 var i = keys.length;
1149 while (i--) {
1150 origin[keys[i]] = add[keys[i]];
1151 }
1152 return origin;
1153};
1154
1155function hasOwnProperty(obj, prop) {
1156 return Object.prototype.hasOwnProperty.call(obj, prop);
1157}
1158
1159}).call(this,_dereq_(70),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
1160},{"3":3,"4":4,"70":70}],6:[function(_dereq_,module,exports){
1161'use strict'
1162
1163exports.byteLength = byteLength
1164exports.toByteArray = toByteArray
1165exports.fromByteArray = fromByteArray
1166
1167var lookup = []
1168var revLookup = []
1169var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
1170
1171var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
1172for (var i = 0, len = code.length; i < len; ++i) {
1173 lookup[i] = code[i]
1174 revLookup[code.charCodeAt(i)] = i
1175}
1176
1177// Support decoding URL-safe base64 strings, as Node.js does.
1178// See: https://en.wikipedia.org/wiki/Base64#URL_applications
1179revLookup['-'.charCodeAt(0)] = 62
1180revLookup['_'.charCodeAt(0)] = 63
1181
1182function getLens (b64) {
1183 var len = b64.length
1184
1185 if (len % 4 > 0) {
1186 throw new Error('Invalid string. Length must be a multiple of 4')
1187 }
1188
1189 // Trim off extra bytes after placeholder bytes are found
1190 // See: https://github.com/beatgammit/base64-js/issues/42
1191 var validLen = b64.indexOf('=')
1192 if (validLen === -1) validLen = len
1193
1194 var placeHoldersLen = validLen === len
1195 ? 0
1196 : 4 - (validLen % 4)
1197
1198 return [validLen, placeHoldersLen]
1199}
1200
1201// base64 is 4/3 + up to two characters of the original data
1202function byteLength (b64) {
1203 var lens = getLens(b64)
1204 var validLen = lens[0]
1205 var placeHoldersLen = lens[1]
1206 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
1207}
1208
1209function _byteLength (b64, validLen, placeHoldersLen) {
1210 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
1211}
1212
1213function toByteArray (b64) {
1214 var tmp
1215 var lens = getLens(b64)
1216 var validLen = lens[0]
1217 var placeHoldersLen = lens[1]
1218
1219 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
1220
1221 var curByte = 0
1222
1223 // if there are placeholders, only get up to the last complete 4 chars
1224 var len = placeHoldersLen > 0
1225 ? validLen - 4
1226 : validLen
1227
1228 var i
1229 for (i = 0; i < len; i += 4) {
1230 tmp =
1231 (revLookup[b64.charCodeAt(i)] << 18) |
1232 (revLookup[b64.charCodeAt(i + 1)] << 12) |
1233 (revLookup[b64.charCodeAt(i + 2)] << 6) |
1234 revLookup[b64.charCodeAt(i + 3)]
1235 arr[curByte++] = (tmp >> 16) & 0xFF
1236 arr[curByte++] = (tmp >> 8) & 0xFF
1237 arr[curByte++] = tmp & 0xFF
1238 }
1239
1240 if (placeHoldersLen === 2) {
1241 tmp =
1242 (revLookup[b64.charCodeAt(i)] << 2) |
1243 (revLookup[b64.charCodeAt(i + 1)] >> 4)
1244 arr[curByte++] = tmp & 0xFF
1245 }
1246
1247 if (placeHoldersLen === 1) {
1248 tmp =
1249 (revLookup[b64.charCodeAt(i)] << 10) |
1250 (revLookup[b64.charCodeAt(i + 1)] << 4) |
1251 (revLookup[b64.charCodeAt(i + 2)] >> 2)
1252 arr[curByte++] = (tmp >> 8) & 0xFF
1253 arr[curByte++] = tmp & 0xFF
1254 }
1255
1256 return arr
1257}
1258
1259function tripletToBase64 (num) {
1260 return lookup[num >> 18 & 0x3F] +
1261 lookup[num >> 12 & 0x3F] +
1262 lookup[num >> 6 & 0x3F] +
1263 lookup[num & 0x3F]
1264}
1265
1266function encodeChunk (uint8, start, end) {
1267 var tmp
1268 var output = []
1269 for (var i = start; i < end; i += 3) {
1270 tmp =
1271 ((uint8[i] << 16) & 0xFF0000) +
1272 ((uint8[i + 1] << 8) & 0xFF00) +
1273 (uint8[i + 2] & 0xFF)
1274 output.push(tripletToBase64(tmp))
1275 }
1276 return output.join('')
1277}
1278
1279function fromByteArray (uint8) {
1280 var tmp
1281 var len = uint8.length
1282 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
1283 var parts = []
1284 var maxChunkLength = 16383 // must be multiple of 3
1285
1286 // go through the array every three bytes, we'll deal with trailing stuff later
1287 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
1288 parts.push(encodeChunk(
1289 uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
1290 ))
1291 }
1292
1293 // pad the end with zeros, but make sure to not forget the extra bytes
1294 if (extraBytes === 1) {
1295 tmp = uint8[len - 1]
1296 parts.push(
1297 lookup[tmp >> 2] +
1298 lookup[(tmp << 4) & 0x3F] +
1299 '=='
1300 )
1301 } else if (extraBytes === 2) {
1302 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
1303 parts.push(
1304 lookup[tmp >> 10] +
1305 lookup[(tmp >> 4) & 0x3F] +
1306 lookup[(tmp << 2) & 0x3F] +
1307 '='
1308 )
1309 }
1310
1311 return parts.join('')
1312}
1313
1314},{}],7:[function(_dereq_,module,exports){
1315
1316},{}],8:[function(_dereq_,module,exports){
1317(function (Buffer){
1318var toString = Object.prototype.toString
1319
1320var isModern = (
1321 typeof Buffer.alloc === 'function' &&
1322 typeof Buffer.allocUnsafe === 'function' &&
1323 typeof Buffer.from === 'function'
1324)
1325
1326function isArrayBuffer (input) {
1327 return toString.call(input).slice(8, -1) === 'ArrayBuffer'
1328}
1329
1330function fromArrayBuffer (obj, byteOffset, length) {
1331 byteOffset >>>= 0
1332
1333 var maxLength = obj.byteLength - byteOffset
1334
1335 if (maxLength < 0) {
1336 throw new RangeError("'offset' is out of bounds")
1337 }
1338
1339 if (length === undefined) {
1340 length = maxLength
1341 } else {
1342 length >>>= 0
1343
1344 if (length > maxLength) {
1345 throw new RangeError("'length' is out of bounds")
1346 }
1347 }
1348
1349 return isModern
1350 ? Buffer.from(obj.slice(byteOffset, byteOffset + length))
1351 : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
1352}
1353
1354function fromString (string, encoding) {
1355 if (typeof encoding !== 'string' || encoding === '') {
1356 encoding = 'utf8'
1357 }
1358
1359 if (!Buffer.isEncoding(encoding)) {
1360 throw new TypeError('"encoding" must be a valid string encoding')
1361 }
1362
1363 return isModern
1364 ? Buffer.from(string, encoding)
1365 : new Buffer(string, encoding)
1366}
1367
1368function bufferFrom (value, encodingOrOffset, length) {
1369 if (typeof value === 'number') {
1370 throw new TypeError('"value" argument must not be a number')
1371 }
1372
1373 if (isArrayBuffer(value)) {
1374 return fromArrayBuffer(value, encodingOrOffset, length)
1375 }
1376
1377 if (typeof value === 'string') {
1378 return fromString(value, encodingOrOffset)
1379 }
1380
1381 return isModern
1382 ? Buffer.from(value)
1383 : new Buffer(value)
1384}
1385
1386module.exports = bufferFrom
1387
1388}).call(this,_dereq_(9).Buffer)
1389},{"9":9}],9:[function(_dereq_,module,exports){
1390(function (Buffer){
1391/*!
1392 * The buffer module from node.js, for the browser.
1393 *
1394 * @author Feross Aboukhadijeh <https://feross.org>
1395 * @license MIT
1396 */
1397/* eslint-disable no-proto */
1398
1399'use strict'
1400
1401var base64 = _dereq_(6)
1402var ieee754 = _dereq_(16)
1403var customInspectSymbol =
1404 (typeof Symbol === 'function' && typeof Symbol.for === 'function')
1405 ? Symbol.for('nodejs.util.inspect.custom')
1406 : null
1407
1408exports.Buffer = Buffer
1409exports.SlowBuffer = SlowBuffer
1410exports.INSPECT_MAX_BYTES = 50
1411
1412var K_MAX_LENGTH = 0x7fffffff
1413exports.kMaxLength = K_MAX_LENGTH
1414
1415/**
1416 * If `Buffer.TYPED_ARRAY_SUPPORT`:
1417 * === true Use Uint8Array implementation (fastest)
1418 * === false Print warning and recommend using `buffer` v4.x which has an Object
1419 * implementation (most compatible, even IE6)
1420 *
1421 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
1422 * Opera 11.6+, iOS 4.2+.
1423 *
1424 * We report that the browser does not support typed arrays if the are not subclassable
1425 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
1426 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
1427 * for __proto__ and has a buggy typed array implementation.
1428 */
1429Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
1430
1431if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
1432 typeof console.error === 'function') {
1433 console.error(
1434 'This browser lacks typed array (Uint8Array) support which is required by ' +
1435 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
1436 )
1437}
1438
1439function typedArraySupport () {
1440 // Can typed array instances can be augmented?
1441 try {
1442 var arr = new Uint8Array(1)
1443 var proto = { foo: function () { return 42 } }
1444 Object.setPrototypeOf(proto, Uint8Array.prototype)
1445 Object.setPrototypeOf(arr, proto)
1446 return arr.foo() === 42
1447 } catch (e) {
1448 return false
1449 }
1450}
1451
1452Object.defineProperty(Buffer.prototype, 'parent', {
1453 enumerable: true,
1454 get: function () {
1455 if (!Buffer.isBuffer(this)) return undefined
1456 return this.buffer
1457 }
1458})
1459
1460Object.defineProperty(Buffer.prototype, 'offset', {
1461 enumerable: true,
1462 get: function () {
1463 if (!Buffer.isBuffer(this)) return undefined
1464 return this.byteOffset
1465 }
1466})
1467
1468function createBuffer (length) {
1469 if (length > K_MAX_LENGTH) {
1470 throw new RangeError('The value "' + length + '" is invalid for option "size"')
1471 }
1472 // Return an augmented `Uint8Array` instance
1473 var buf = new Uint8Array(length)
1474 Object.setPrototypeOf(buf, Buffer.prototype)
1475 return buf
1476}
1477
1478/**
1479 * The Buffer constructor returns instances of `Uint8Array` that have their
1480 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
1481 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
1482 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
1483 * returns a single octet.
1484 *
1485 * The `Uint8Array` prototype remains unmodified.
1486 */
1487
1488function Buffer (arg, encodingOrOffset, length) {
1489 // Common case.
1490 if (typeof arg === 'number') {
1491 if (typeof encodingOrOffset === 'string') {
1492 throw new TypeError(
1493 'The "string" argument must be of type string. Received type number'
1494 )
1495 }
1496 return allocUnsafe(arg)
1497 }
1498 return from(arg, encodingOrOffset, length)
1499}
1500
1501// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
1502if (typeof Symbol !== 'undefined' && Symbol.species != null &&
1503 Buffer[Symbol.species] === Buffer) {
1504 Object.defineProperty(Buffer, Symbol.species, {
1505 value: null,
1506 configurable: true,
1507 enumerable: false,
1508 writable: false
1509 })
1510}
1511
1512Buffer.poolSize = 8192 // not used by this implementation
1513
1514function from (value, encodingOrOffset, length) {
1515 if (typeof value === 'string') {
1516 return fromString(value, encodingOrOffset)
1517 }
1518
1519 if (ArrayBuffer.isView(value)) {
1520 return fromArrayLike(value)
1521 }
1522
1523 if (value == null) {
1524 throw new TypeError(
1525 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
1526 'or Array-like Object. Received type ' + (typeof value)
1527 )
1528 }
1529
1530 if (isInstance(value, ArrayBuffer) ||
1531 (value && isInstance(value.buffer, ArrayBuffer))) {
1532 return fromArrayBuffer(value, encodingOrOffset, length)
1533 }
1534
1535 if (typeof value === 'number') {
1536 throw new TypeError(
1537 'The "value" argument must not be of type number. Received type number'
1538 )
1539 }
1540
1541 var valueOf = value.valueOf && value.valueOf()
1542 if (valueOf != null && valueOf !== value) {
1543 return Buffer.from(valueOf, encodingOrOffset, length)
1544 }
1545
1546 var b = fromObject(value)
1547 if (b) return b
1548
1549 if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
1550 typeof value[Symbol.toPrimitive] === 'function') {
1551 return Buffer.from(
1552 value[Symbol.toPrimitive]('string'), encodingOrOffset, length
1553 )
1554 }
1555
1556 throw new TypeError(
1557 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
1558 'or Array-like Object. Received type ' + (typeof value)
1559 )
1560}
1561
1562/**
1563 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
1564 * if value is a number.
1565 * Buffer.from(str[, encoding])
1566 * Buffer.from(array)
1567 * Buffer.from(buffer)
1568 * Buffer.from(arrayBuffer[, byteOffset[, length]])
1569 **/
1570Buffer.from = function (value, encodingOrOffset, length) {
1571 return from(value, encodingOrOffset, length)
1572}
1573
1574// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
1575// https://github.com/feross/buffer/pull/148
1576Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)
1577Object.setPrototypeOf(Buffer, Uint8Array)
1578
1579function assertSize (size) {
1580 if (typeof size !== 'number') {
1581 throw new TypeError('"size" argument must be of type number')
1582 } else if (size < 0) {
1583 throw new RangeError('The value "' + size + '" is invalid for option "size"')
1584 }
1585}
1586
1587function alloc (size, fill, encoding) {
1588 assertSize(size)
1589 if (size <= 0) {
1590 return createBuffer(size)
1591 }
1592 if (fill !== undefined) {
1593 // Only pay attention to encoding if it's a string. This
1594 // prevents accidentally sending in a number that would
1595 // be interpretted as a start offset.
1596 return typeof encoding === 'string'
1597 ? createBuffer(size).fill(fill, encoding)
1598 : createBuffer(size).fill(fill)
1599 }
1600 return createBuffer(size)
1601}
1602
1603/**
1604 * Creates a new filled Buffer instance.
1605 * alloc(size[, fill[, encoding]])
1606 **/
1607Buffer.alloc = function (size, fill, encoding) {
1608 return alloc(size, fill, encoding)
1609}
1610
1611function allocUnsafe (size) {
1612 assertSize(size)
1613 return createBuffer(size < 0 ? 0 : checked(size) | 0)
1614}
1615
1616/**
1617 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
1618 * */
1619Buffer.allocUnsafe = function (size) {
1620 return allocUnsafe(size)
1621}
1622/**
1623 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
1624 */
1625Buffer.allocUnsafeSlow = function (size) {
1626 return allocUnsafe(size)
1627}
1628
1629function fromString (string, encoding) {
1630 if (typeof encoding !== 'string' || encoding === '') {
1631 encoding = 'utf8'
1632 }
1633
1634 if (!Buffer.isEncoding(encoding)) {
1635 throw new TypeError('Unknown encoding: ' + encoding)
1636 }
1637
1638 var length = byteLength(string, encoding) | 0
1639 var buf = createBuffer(length)
1640
1641 var actual = buf.write(string, encoding)
1642
1643 if (actual !== length) {
1644 // Writing a hex string, for example, that contains invalid characters will
1645 // cause everything after the first invalid character to be ignored. (e.g.
1646 // 'abxxcd' will be treated as 'ab')
1647 buf = buf.slice(0, actual)
1648 }
1649
1650 return buf
1651}
1652
1653function fromArrayLike (array) {
1654 var length = array.length < 0 ? 0 : checked(array.length) | 0
1655 var buf = createBuffer(length)
1656 for (var i = 0; i < length; i += 1) {
1657 buf[i] = array[i] & 255
1658 }
1659 return buf
1660}
1661
1662function fromArrayBuffer (array, byteOffset, length) {
1663 if (byteOffset < 0 || array.byteLength < byteOffset) {
1664 throw new RangeError('"offset" is outside of buffer bounds')
1665 }
1666
1667 if (array.byteLength < byteOffset + (length || 0)) {
1668 throw new RangeError('"length" is outside of buffer bounds')
1669 }
1670
1671 var buf
1672 if (byteOffset === undefined && length === undefined) {
1673 buf = new Uint8Array(array)
1674 } else if (length === undefined) {
1675 buf = new Uint8Array(array, byteOffset)
1676 } else {
1677 buf = new Uint8Array(array, byteOffset, length)
1678 }
1679
1680 // Return an augmented `Uint8Array` instance
1681 Object.setPrototypeOf(buf, Buffer.prototype)
1682
1683 return buf
1684}
1685
1686function fromObject (obj) {
1687 if (Buffer.isBuffer(obj)) {
1688 var len = checked(obj.length) | 0
1689 var buf = createBuffer(len)
1690
1691 if (buf.length === 0) {
1692 return buf
1693 }
1694
1695 obj.copy(buf, 0, 0, len)
1696 return buf
1697 }
1698
1699 if (obj.length !== undefined) {
1700 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
1701 return createBuffer(0)
1702 }
1703 return fromArrayLike(obj)
1704 }
1705
1706 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
1707 return fromArrayLike(obj.data)
1708 }
1709}
1710
1711function checked (length) {
1712 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
1713 // length is NaN (which is otherwise coerced to zero.)
1714 if (length >= K_MAX_LENGTH) {
1715 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
1716 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
1717 }
1718 return length | 0
1719}
1720
1721function SlowBuffer (length) {
1722 if (+length != length) { // eslint-disable-line eqeqeq
1723 length = 0
1724 }
1725 return Buffer.alloc(+length)
1726}
1727
1728Buffer.isBuffer = function isBuffer (b) {
1729 return b != null && b._isBuffer === true &&
1730 b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
1731}
1732
1733Buffer.compare = function compare (a, b) {
1734 if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
1735 if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
1736 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
1737 throw new TypeError(
1738 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
1739 )
1740 }
1741
1742 if (a === b) return 0
1743
1744 var x = a.length
1745 var y = b.length
1746
1747 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
1748 if (a[i] !== b[i]) {
1749 x = a[i]
1750 y = b[i]
1751 break
1752 }
1753 }
1754
1755 if (x < y) return -1
1756 if (y < x) return 1
1757 return 0
1758}
1759
1760Buffer.isEncoding = function isEncoding (encoding) {
1761 switch (String(encoding).toLowerCase()) {
1762 case 'hex':
1763 case 'utf8':
1764 case 'utf-8':
1765 case 'ascii':
1766 case 'latin1':
1767 case 'binary':
1768 case 'base64':
1769 case 'ucs2':
1770 case 'ucs-2':
1771 case 'utf16le':
1772 case 'utf-16le':
1773 return true
1774 default:
1775 return false
1776 }
1777}
1778
1779Buffer.concat = function concat (list, length) {
1780 if (!Array.isArray(list)) {
1781 throw new TypeError('"list" argument must be an Array of Buffers')
1782 }
1783
1784 if (list.length === 0) {
1785 return Buffer.alloc(0)
1786 }
1787
1788 var i
1789 if (length === undefined) {
1790 length = 0
1791 for (i = 0; i < list.length; ++i) {
1792 length += list[i].length
1793 }
1794 }
1795
1796 var buffer = Buffer.allocUnsafe(length)
1797 var pos = 0
1798 for (i = 0; i < list.length; ++i) {
1799 var buf = list[i]
1800 if (isInstance(buf, Uint8Array)) {
1801 buf = Buffer.from(buf)
1802 }
1803 if (!Buffer.isBuffer(buf)) {
1804 throw new TypeError('"list" argument must be an Array of Buffers')
1805 }
1806 buf.copy(buffer, pos)
1807 pos += buf.length
1808 }
1809 return buffer
1810}
1811
1812function byteLength (string, encoding) {
1813 if (Buffer.isBuffer(string)) {
1814 return string.length
1815 }
1816 if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
1817 return string.byteLength
1818 }
1819 if (typeof string !== 'string') {
1820 throw new TypeError(
1821 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
1822 'Received type ' + typeof string
1823 )
1824 }
1825
1826 var len = string.length
1827 var mustMatch = (arguments.length > 2 && arguments[2] === true)
1828 if (!mustMatch && len === 0) return 0
1829
1830 // Use a for loop to avoid recursion
1831 var loweredCase = false
1832 for (;;) {
1833 switch (encoding) {
1834 case 'ascii':
1835 case 'latin1':
1836 case 'binary':
1837 return len
1838 case 'utf8':
1839 case 'utf-8':
1840 return utf8ToBytes(string).length
1841 case 'ucs2':
1842 case 'ucs-2':
1843 case 'utf16le':
1844 case 'utf-16le':
1845 return len * 2
1846 case 'hex':
1847 return len >>> 1
1848 case 'base64':
1849 return base64ToBytes(string).length
1850 default:
1851 if (loweredCase) {
1852 return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
1853 }
1854 encoding = ('' + encoding).toLowerCase()
1855 loweredCase = true
1856 }
1857 }
1858}
1859Buffer.byteLength = byteLength
1860
1861function slowToString (encoding, start, end) {
1862 var loweredCase = false
1863
1864 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
1865 // property of a typed array.
1866
1867 // This behaves neither like String nor Uint8Array in that we set start/end
1868 // to their upper/lower bounds if the value passed is out of range.
1869 // undefined is handled specially as per ECMA-262 6th Edition,
1870 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
1871 if (start === undefined || start < 0) {
1872 start = 0
1873 }
1874 // Return early if start > this.length. Done here to prevent potential uint32
1875 // coercion fail below.
1876 if (start > this.length) {
1877 return ''
1878 }
1879
1880 if (end === undefined || end > this.length) {
1881 end = this.length
1882 }
1883
1884 if (end <= 0) {
1885 return ''
1886 }
1887
1888 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
1889 end >>>= 0
1890 start >>>= 0
1891
1892 if (end <= start) {
1893 return ''
1894 }
1895
1896 if (!encoding) encoding = 'utf8'
1897
1898 while (true) {
1899 switch (encoding) {
1900 case 'hex':
1901 return hexSlice(this, start, end)
1902
1903 case 'utf8':
1904 case 'utf-8':
1905 return utf8Slice(this, start, end)
1906
1907 case 'ascii':
1908 return asciiSlice(this, start, end)
1909
1910 case 'latin1':
1911 case 'binary':
1912 return latin1Slice(this, start, end)
1913
1914 case 'base64':
1915 return base64Slice(this, start, end)
1916
1917 case 'ucs2':
1918 case 'ucs-2':
1919 case 'utf16le':
1920 case 'utf-16le':
1921 return utf16leSlice(this, start, end)
1922
1923 default:
1924 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1925 encoding = (encoding + '').toLowerCase()
1926 loweredCase = true
1927 }
1928 }
1929}
1930
1931// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
1932// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
1933// reliably in a browserify context because there could be multiple different
1934// copies of the 'buffer' package in use. This method works even for Buffer
1935// instances that were created from another copy of the `buffer` package.
1936// See: https://github.com/feross/buffer/issues/154
1937Buffer.prototype._isBuffer = true
1938
1939function swap (b, n, m) {
1940 var i = b[n]
1941 b[n] = b[m]
1942 b[m] = i
1943}
1944
1945Buffer.prototype.swap16 = function swap16 () {
1946 var len = this.length
1947 if (len % 2 !== 0) {
1948 throw new RangeError('Buffer size must be a multiple of 16-bits')
1949 }
1950 for (var i = 0; i < len; i += 2) {
1951 swap(this, i, i + 1)
1952 }
1953 return this
1954}
1955
1956Buffer.prototype.swap32 = function swap32 () {
1957 var len = this.length
1958 if (len % 4 !== 0) {
1959 throw new RangeError('Buffer size must be a multiple of 32-bits')
1960 }
1961 for (var i = 0; i < len; i += 4) {
1962 swap(this, i, i + 3)
1963 swap(this, i + 1, i + 2)
1964 }
1965 return this
1966}
1967
1968Buffer.prototype.swap64 = function swap64 () {
1969 var len = this.length
1970 if (len % 8 !== 0) {
1971 throw new RangeError('Buffer size must be a multiple of 64-bits')
1972 }
1973 for (var i = 0; i < len; i += 8) {
1974 swap(this, i, i + 7)
1975 swap(this, i + 1, i + 6)
1976 swap(this, i + 2, i + 5)
1977 swap(this, i + 3, i + 4)
1978 }
1979 return this
1980}
1981
1982Buffer.prototype.toString = function toString () {
1983 var length = this.length
1984 if (length === 0) return ''
1985 if (arguments.length === 0) return utf8Slice(this, 0, length)
1986 return slowToString.apply(this, arguments)
1987}
1988
1989Buffer.prototype.toLocaleString = Buffer.prototype.toString
1990
1991Buffer.prototype.equals = function equals (b) {
1992 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
1993 if (this === b) return true
1994 return Buffer.compare(this, b) === 0
1995}
1996
1997Buffer.prototype.inspect = function inspect () {
1998 var str = ''
1999 var max = exports.INSPECT_MAX_BYTES
2000 str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
2001 if (this.length > max) str += ' ... '
2002 return '<Buffer ' + str + '>'
2003}
2004if (customInspectSymbol) {
2005 Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect
2006}
2007
2008Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
2009 if (isInstance(target, Uint8Array)) {
2010 target = Buffer.from(target, target.offset, target.byteLength)
2011 }
2012 if (!Buffer.isBuffer(target)) {
2013 throw new TypeError(
2014 'The "target" argument must be one of type Buffer or Uint8Array. ' +
2015 'Received type ' + (typeof target)
2016 )
2017 }
2018
2019 if (start === undefined) {
2020 start = 0
2021 }
2022 if (end === undefined) {
2023 end = target ? target.length : 0
2024 }
2025 if (thisStart === undefined) {
2026 thisStart = 0
2027 }
2028 if (thisEnd === undefined) {
2029 thisEnd = this.length
2030 }
2031
2032 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
2033 throw new RangeError('out of range index')
2034 }
2035
2036 if (thisStart >= thisEnd && start >= end) {
2037 return 0
2038 }
2039 if (thisStart >= thisEnd) {
2040 return -1
2041 }
2042 if (start >= end) {
2043 return 1
2044 }
2045
2046 start >>>= 0
2047 end >>>= 0
2048 thisStart >>>= 0
2049 thisEnd >>>= 0
2050
2051 if (this === target) return 0
2052
2053 var x = thisEnd - thisStart
2054 var y = end - start
2055 var len = Math.min(x, y)
2056
2057 var thisCopy = this.slice(thisStart, thisEnd)
2058 var targetCopy = target.slice(start, end)
2059
2060 for (var i = 0; i < len; ++i) {
2061 if (thisCopy[i] !== targetCopy[i]) {
2062 x = thisCopy[i]
2063 y = targetCopy[i]
2064 break
2065 }
2066 }
2067
2068 if (x < y) return -1
2069 if (y < x) return 1
2070 return 0
2071}
2072
2073// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
2074// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
2075//
2076// Arguments:
2077// - buffer - a Buffer to search
2078// - val - a string, Buffer, or number
2079// - byteOffset - an index into `buffer`; will be clamped to an int32
2080// - encoding - an optional encoding, relevant is val is a string
2081// - dir - true for indexOf, false for lastIndexOf
2082function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
2083 // Empty buffer means no match
2084 if (buffer.length === 0) return -1
2085
2086 // Normalize byteOffset
2087 if (typeof byteOffset === 'string') {
2088 encoding = byteOffset
2089 byteOffset = 0
2090 } else if (byteOffset > 0x7fffffff) {
2091 byteOffset = 0x7fffffff
2092 } else if (byteOffset < -0x80000000) {
2093 byteOffset = -0x80000000
2094 }
2095 byteOffset = +byteOffset // Coerce to Number.
2096 if (numberIsNaN(byteOffset)) {
2097 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
2098 byteOffset = dir ? 0 : (buffer.length - 1)
2099 }
2100
2101 // Normalize byteOffset: negative offsets start from the end of the buffer
2102 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
2103 if (byteOffset >= buffer.length) {
2104 if (dir) return -1
2105 else byteOffset = buffer.length - 1
2106 } else if (byteOffset < 0) {
2107 if (dir) byteOffset = 0
2108 else return -1
2109 }
2110
2111 // Normalize val
2112 if (typeof val === 'string') {
2113 val = Buffer.from(val, encoding)
2114 }
2115
2116 // Finally, search either indexOf (if dir is true) or lastIndexOf
2117 if (Buffer.isBuffer(val)) {
2118 // Special case: looking for empty string/buffer always fails
2119 if (val.length === 0) {
2120 return -1
2121 }
2122 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
2123 } else if (typeof val === 'number') {
2124 val = val & 0xFF // Search for a byte value [0-255]
2125 if (typeof Uint8Array.prototype.indexOf === 'function') {
2126 if (dir) {
2127 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
2128 } else {
2129 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
2130 }
2131 }
2132 return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
2133 }
2134
2135 throw new TypeError('val must be string, number or Buffer')
2136}
2137
2138function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
2139 var indexSize = 1
2140 var arrLength = arr.length
2141 var valLength = val.length
2142
2143 if (encoding !== undefined) {
2144 encoding = String(encoding).toLowerCase()
2145 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
2146 encoding === 'utf16le' || encoding === 'utf-16le') {
2147 if (arr.length < 2 || val.length < 2) {
2148 return -1
2149 }
2150 indexSize = 2
2151 arrLength /= 2
2152 valLength /= 2
2153 byteOffset /= 2
2154 }
2155 }
2156
2157 function read (buf, i) {
2158 if (indexSize === 1) {
2159 return buf[i]
2160 } else {
2161 return buf.readUInt16BE(i * indexSize)
2162 }
2163 }
2164
2165 var i
2166 if (dir) {
2167 var foundIndex = -1
2168 for (i = byteOffset; i < arrLength; i++) {
2169 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
2170 if (foundIndex === -1) foundIndex = i
2171 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
2172 } else {
2173 if (foundIndex !== -1) i -= i - foundIndex
2174 foundIndex = -1
2175 }
2176 }
2177 } else {
2178 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
2179 for (i = byteOffset; i >= 0; i--) {
2180 var found = true
2181 for (var j = 0; j < valLength; j++) {
2182 if (read(arr, i + j) !== read(val, j)) {
2183 found = false
2184 break
2185 }
2186 }
2187 if (found) return i
2188 }
2189 }
2190
2191 return -1
2192}
2193
2194Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
2195 return this.indexOf(val, byteOffset, encoding) !== -1
2196}
2197
2198Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
2199 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
2200}
2201
2202Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
2203 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
2204}
2205
2206function hexWrite (buf, string, offset, length) {
2207 offset = Number(offset) || 0
2208 var remaining = buf.length - offset
2209 if (!length) {
2210 length = remaining
2211 } else {
2212 length = Number(length)
2213 if (length > remaining) {
2214 length = remaining
2215 }
2216 }
2217
2218 var strLen = string.length
2219
2220 if (length > strLen / 2) {
2221 length = strLen / 2
2222 }
2223 for (var i = 0; i < length; ++i) {
2224 var parsed = parseInt(string.substr(i * 2, 2), 16)
2225 if (numberIsNaN(parsed)) return i
2226 buf[offset + i] = parsed
2227 }
2228 return i
2229}
2230
2231function utf8Write (buf, string, offset, length) {
2232 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
2233}
2234
2235function asciiWrite (buf, string, offset, length) {
2236 return blitBuffer(asciiToBytes(string), buf, offset, length)
2237}
2238
2239function latin1Write (buf, string, offset, length) {
2240 return asciiWrite(buf, string, offset, length)
2241}
2242
2243function base64Write (buf, string, offset, length) {
2244 return blitBuffer(base64ToBytes(string), buf, offset, length)
2245}
2246
2247function ucs2Write (buf, string, offset, length) {
2248 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
2249}
2250
2251Buffer.prototype.write = function write (string, offset, length, encoding) {
2252 // Buffer#write(string)
2253 if (offset === undefined) {
2254 encoding = 'utf8'
2255 length = this.length
2256 offset = 0
2257 // Buffer#write(string, encoding)
2258 } else if (length === undefined && typeof offset === 'string') {
2259 encoding = offset
2260 length = this.length
2261 offset = 0
2262 // Buffer#write(string, offset[, length][, encoding])
2263 } else if (isFinite(offset)) {
2264 offset = offset >>> 0
2265 if (isFinite(length)) {
2266 length = length >>> 0
2267 if (encoding === undefined) encoding = 'utf8'
2268 } else {
2269 encoding = length
2270 length = undefined
2271 }
2272 } else {
2273 throw new Error(
2274 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
2275 )
2276 }
2277
2278 var remaining = this.length - offset
2279 if (length === undefined || length > remaining) length = remaining
2280
2281 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
2282 throw new RangeError('Attempt to write outside buffer bounds')
2283 }
2284
2285 if (!encoding) encoding = 'utf8'
2286
2287 var loweredCase = false
2288 for (;;) {
2289 switch (encoding) {
2290 case 'hex':
2291 return hexWrite(this, string, offset, length)
2292
2293 case 'utf8':
2294 case 'utf-8':
2295 return utf8Write(this, string, offset, length)
2296
2297 case 'ascii':
2298 return asciiWrite(this, string, offset, length)
2299
2300 case 'latin1':
2301 case 'binary':
2302 return latin1Write(this, string, offset, length)
2303
2304 case 'base64':
2305 // Warning: maxLength not taken into account in base64Write
2306 return base64Write(this, string, offset, length)
2307
2308 case 'ucs2':
2309 case 'ucs-2':
2310 case 'utf16le':
2311 case 'utf-16le':
2312 return ucs2Write(this, string, offset, length)
2313
2314 default:
2315 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
2316 encoding = ('' + encoding).toLowerCase()
2317 loweredCase = true
2318 }
2319 }
2320}
2321
2322Buffer.prototype.toJSON = function toJSON () {
2323 return {
2324 type: 'Buffer',
2325 data: Array.prototype.slice.call(this._arr || this, 0)
2326 }
2327}
2328
2329function base64Slice (buf, start, end) {
2330 if (start === 0 && end === buf.length) {
2331 return base64.fromByteArray(buf)
2332 } else {
2333 return base64.fromByteArray(buf.slice(start, end))
2334 }
2335}
2336
2337function utf8Slice (buf, start, end) {
2338 end = Math.min(buf.length, end)
2339 var res = []
2340
2341 var i = start
2342 while (i < end) {
2343 var firstByte = buf[i]
2344 var codePoint = null
2345 var bytesPerSequence = (firstByte > 0xEF) ? 4
2346 : (firstByte > 0xDF) ? 3
2347 : (firstByte > 0xBF) ? 2
2348 : 1
2349
2350 if (i + bytesPerSequence <= end) {
2351 var secondByte, thirdByte, fourthByte, tempCodePoint
2352
2353 switch (bytesPerSequence) {
2354 case 1:
2355 if (firstByte < 0x80) {
2356 codePoint = firstByte
2357 }
2358 break
2359 case 2:
2360 secondByte = buf[i + 1]
2361 if ((secondByte & 0xC0) === 0x80) {
2362 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
2363 if (tempCodePoint > 0x7F) {
2364 codePoint = tempCodePoint
2365 }
2366 }
2367 break
2368 case 3:
2369 secondByte = buf[i + 1]
2370 thirdByte = buf[i + 2]
2371 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
2372 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
2373 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
2374 codePoint = tempCodePoint
2375 }
2376 }
2377 break
2378 case 4:
2379 secondByte = buf[i + 1]
2380 thirdByte = buf[i + 2]
2381 fourthByte = buf[i + 3]
2382 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
2383 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
2384 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
2385 codePoint = tempCodePoint
2386 }
2387 }
2388 }
2389 }
2390
2391 if (codePoint === null) {
2392 // we did not generate a valid codePoint so insert a
2393 // replacement char (U+FFFD) and advance only 1 byte
2394 codePoint = 0xFFFD
2395 bytesPerSequence = 1
2396 } else if (codePoint > 0xFFFF) {
2397 // encode to utf16 (surrogate pair dance)
2398 codePoint -= 0x10000
2399 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
2400 codePoint = 0xDC00 | codePoint & 0x3FF
2401 }
2402
2403 res.push(codePoint)
2404 i += bytesPerSequence
2405 }
2406
2407 return decodeCodePointsArray(res)
2408}
2409
2410// Based on http://stackoverflow.com/a/22747272/680742, the browser with
2411// the lowest limit is Chrome, with 0x10000 args.
2412// We go 1 magnitude less, for safety
2413var MAX_ARGUMENTS_LENGTH = 0x1000
2414
2415function decodeCodePointsArray (codePoints) {
2416 var len = codePoints.length
2417 if (len <= MAX_ARGUMENTS_LENGTH) {
2418 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
2419 }
2420
2421 // Decode in chunks to avoid "call stack size exceeded".
2422 var res = ''
2423 var i = 0
2424 while (i < len) {
2425 res += String.fromCharCode.apply(
2426 String,
2427 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
2428 )
2429 }
2430 return res
2431}
2432
2433function asciiSlice (buf, start, end) {
2434 var ret = ''
2435 end = Math.min(buf.length, end)
2436
2437 for (var i = start; i < end; ++i) {
2438 ret += String.fromCharCode(buf[i] & 0x7F)
2439 }
2440 return ret
2441}
2442
2443function latin1Slice (buf, start, end) {
2444 var ret = ''
2445 end = Math.min(buf.length, end)
2446
2447 for (var i = start; i < end; ++i) {
2448 ret += String.fromCharCode(buf[i])
2449 }
2450 return ret
2451}
2452
2453function hexSlice (buf, start, end) {
2454 var len = buf.length
2455
2456 if (!start || start < 0) start = 0
2457 if (!end || end < 0 || end > len) end = len
2458
2459 var out = ''
2460 for (var i = start; i < end; ++i) {
2461 out += hexSliceLookupTable[buf[i]]
2462 }
2463 return out
2464}
2465
2466function utf16leSlice (buf, start, end) {
2467 var bytes = buf.slice(start, end)
2468 var res = ''
2469 for (var i = 0; i < bytes.length; i += 2) {
2470 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
2471 }
2472 return res
2473}
2474
2475Buffer.prototype.slice = function slice (start, end) {
2476 var len = this.length
2477 start = ~~start
2478 end = end === undefined ? len : ~~end
2479
2480 if (start < 0) {
2481 start += len
2482 if (start < 0) start = 0
2483 } else if (start > len) {
2484 start = len
2485 }
2486
2487 if (end < 0) {
2488 end += len
2489 if (end < 0) end = 0
2490 } else if (end > len) {
2491 end = len
2492 }
2493
2494 if (end < start) end = start
2495
2496 var newBuf = this.subarray(start, end)
2497 // Return an augmented `Uint8Array` instance
2498 Object.setPrototypeOf(newBuf, Buffer.prototype)
2499
2500 return newBuf
2501}
2502
2503/*
2504 * Need to make sure that buffer isn't trying to write out of bounds.
2505 */
2506function checkOffset (offset, ext, length) {
2507 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
2508 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
2509}
2510
2511Buffer.prototype.readUIntLE = function readUIntLE (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
2523 return val
2524}
2525
2526Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
2527 offset = offset >>> 0
2528 byteLength = byteLength >>> 0
2529 if (!noAssert) {
2530 checkOffset(offset, byteLength, this.length)
2531 }
2532
2533 var val = this[offset + --byteLength]
2534 var mul = 1
2535 while (byteLength > 0 && (mul *= 0x100)) {
2536 val += this[offset + --byteLength] * mul
2537 }
2538
2539 return val
2540}
2541
2542Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
2543 offset = offset >>> 0
2544 if (!noAssert) checkOffset(offset, 1, this.length)
2545 return this[offset]
2546}
2547
2548Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
2549 offset = offset >>> 0
2550 if (!noAssert) checkOffset(offset, 2, this.length)
2551 return this[offset] | (this[offset + 1] << 8)
2552}
2553
2554Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
2555 offset = offset >>> 0
2556 if (!noAssert) checkOffset(offset, 2, this.length)
2557 return (this[offset] << 8) | this[offset + 1]
2558}
2559
2560Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
2561 offset = offset >>> 0
2562 if (!noAssert) checkOffset(offset, 4, this.length)
2563
2564 return ((this[offset]) |
2565 (this[offset + 1] << 8) |
2566 (this[offset + 2] << 16)) +
2567 (this[offset + 3] * 0x1000000)
2568}
2569
2570Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
2571 offset = offset >>> 0
2572 if (!noAssert) checkOffset(offset, 4, this.length)
2573
2574 return (this[offset] * 0x1000000) +
2575 ((this[offset + 1] << 16) |
2576 (this[offset + 2] << 8) |
2577 this[offset + 3])
2578}
2579
2580Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
2581 offset = offset >>> 0
2582 byteLength = byteLength >>> 0
2583 if (!noAssert) checkOffset(offset, byteLength, this.length)
2584
2585 var val = this[offset]
2586 var mul = 1
2587 var i = 0
2588 while (++i < byteLength && (mul *= 0x100)) {
2589 val += this[offset + i] * mul
2590 }
2591 mul *= 0x80
2592
2593 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
2594
2595 return val
2596}
2597
2598Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
2599 offset = offset >>> 0
2600 byteLength = byteLength >>> 0
2601 if (!noAssert) checkOffset(offset, byteLength, this.length)
2602
2603 var i = byteLength
2604 var mul = 1
2605 var val = this[offset + --i]
2606 while (i > 0 && (mul *= 0x100)) {
2607 val += this[offset + --i] * mul
2608 }
2609 mul *= 0x80
2610
2611 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
2612
2613 return val
2614}
2615
2616Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
2617 offset = offset >>> 0
2618 if (!noAssert) checkOffset(offset, 1, this.length)
2619 if (!(this[offset] & 0x80)) return (this[offset])
2620 return ((0xff - this[offset] + 1) * -1)
2621}
2622
2623Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
2624 offset = offset >>> 0
2625 if (!noAssert) checkOffset(offset, 2, this.length)
2626 var val = this[offset] | (this[offset + 1] << 8)
2627 return (val & 0x8000) ? val | 0xFFFF0000 : val
2628}
2629
2630Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
2631 offset = offset >>> 0
2632 if (!noAssert) checkOffset(offset, 2, this.length)
2633 var val = this[offset + 1] | (this[offset] << 8)
2634 return (val & 0x8000) ? val | 0xFFFF0000 : val
2635}
2636
2637Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
2638 offset = offset >>> 0
2639 if (!noAssert) checkOffset(offset, 4, this.length)
2640
2641 return (this[offset]) |
2642 (this[offset + 1] << 8) |
2643 (this[offset + 2] << 16) |
2644 (this[offset + 3] << 24)
2645}
2646
2647Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
2648 offset = offset >>> 0
2649 if (!noAssert) checkOffset(offset, 4, this.length)
2650
2651 return (this[offset] << 24) |
2652 (this[offset + 1] << 16) |
2653 (this[offset + 2] << 8) |
2654 (this[offset + 3])
2655}
2656
2657Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
2658 offset = offset >>> 0
2659 if (!noAssert) checkOffset(offset, 4, this.length)
2660 return ieee754.read(this, offset, true, 23, 4)
2661}
2662
2663Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
2664 offset = offset >>> 0
2665 if (!noAssert) checkOffset(offset, 4, this.length)
2666 return ieee754.read(this, offset, false, 23, 4)
2667}
2668
2669Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
2670 offset = offset >>> 0
2671 if (!noAssert) checkOffset(offset, 8, this.length)
2672 return ieee754.read(this, offset, true, 52, 8)
2673}
2674
2675Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
2676 offset = offset >>> 0
2677 if (!noAssert) checkOffset(offset, 8, this.length)
2678 return ieee754.read(this, offset, false, 52, 8)
2679}
2680
2681function checkInt (buf, value, offset, ext, max, min) {
2682 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
2683 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
2684 if (offset + ext > buf.length) throw new RangeError('Index out of range')
2685}
2686
2687Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
2688 value = +value
2689 offset = offset >>> 0
2690 byteLength = byteLength >>> 0
2691 if (!noAssert) {
2692 var maxBytes = Math.pow(2, 8 * byteLength) - 1
2693 checkInt(this, value, offset, byteLength, maxBytes, 0)
2694 }
2695
2696 var mul = 1
2697 var i = 0
2698 this[offset] = value & 0xFF
2699 while (++i < byteLength && (mul *= 0x100)) {
2700 this[offset + i] = (value / mul) & 0xFF
2701 }
2702
2703 return offset + byteLength
2704}
2705
2706Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
2707 value = +value
2708 offset = offset >>> 0
2709 byteLength = byteLength >>> 0
2710 if (!noAssert) {
2711 var maxBytes = Math.pow(2, 8 * byteLength) - 1
2712 checkInt(this, value, offset, byteLength, maxBytes, 0)
2713 }
2714
2715 var i = byteLength - 1
2716 var mul = 1
2717 this[offset + i] = value & 0xFF
2718 while (--i >= 0 && (mul *= 0x100)) {
2719 this[offset + i] = (value / mul) & 0xFF
2720 }
2721
2722 return offset + byteLength
2723}
2724
2725Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
2726 value = +value
2727 offset = offset >>> 0
2728 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
2729 this[offset] = (value & 0xff)
2730 return offset + 1
2731}
2732
2733Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
2734 value = +value
2735 offset = offset >>> 0
2736 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
2737 this[offset] = (value & 0xff)
2738 this[offset + 1] = (value >>> 8)
2739 return offset + 2
2740}
2741
2742Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
2743 value = +value
2744 offset = offset >>> 0
2745 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
2746 this[offset] = (value >>> 8)
2747 this[offset + 1] = (value & 0xff)
2748 return offset + 2
2749}
2750
2751Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
2752 value = +value
2753 offset = offset >>> 0
2754 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
2755 this[offset + 3] = (value >>> 24)
2756 this[offset + 2] = (value >>> 16)
2757 this[offset + 1] = (value >>> 8)
2758 this[offset] = (value & 0xff)
2759 return offset + 4
2760}
2761
2762Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
2763 value = +value
2764 offset = offset >>> 0
2765 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
2766 this[offset] = (value >>> 24)
2767 this[offset + 1] = (value >>> 16)
2768 this[offset + 2] = (value >>> 8)
2769 this[offset + 3] = (value & 0xff)
2770 return offset + 4
2771}
2772
2773Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
2774 value = +value
2775 offset = offset >>> 0
2776 if (!noAssert) {
2777 var limit = Math.pow(2, (8 * byteLength) - 1)
2778
2779 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2780 }
2781
2782 var i = 0
2783 var mul = 1
2784 var sub = 0
2785 this[offset] = value & 0xFF
2786 while (++i < byteLength && (mul *= 0x100)) {
2787 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
2788 sub = 1
2789 }
2790 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2791 }
2792
2793 return offset + byteLength
2794}
2795
2796Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
2797 value = +value
2798 offset = offset >>> 0
2799 if (!noAssert) {
2800 var limit = Math.pow(2, (8 * byteLength) - 1)
2801
2802 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2803 }
2804
2805 var i = byteLength - 1
2806 var mul = 1
2807 var sub = 0
2808 this[offset + i] = value & 0xFF
2809 while (--i >= 0 && (mul *= 0x100)) {
2810 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
2811 sub = 1
2812 }
2813 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2814 }
2815
2816 return offset + byteLength
2817}
2818
2819Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
2820 value = +value
2821 offset = offset >>> 0
2822 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
2823 if (value < 0) value = 0xff + value + 1
2824 this[offset] = (value & 0xff)
2825 return offset + 1
2826}
2827
2828Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
2829 value = +value
2830 offset = offset >>> 0
2831 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2832 this[offset] = (value & 0xff)
2833 this[offset + 1] = (value >>> 8)
2834 return offset + 2
2835}
2836
2837Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
2838 value = +value
2839 offset = offset >>> 0
2840 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2841 this[offset] = (value >>> 8)
2842 this[offset + 1] = (value & 0xff)
2843 return offset + 2
2844}
2845
2846Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
2847 value = +value
2848 offset = offset >>> 0
2849 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2850 this[offset] = (value & 0xff)
2851 this[offset + 1] = (value >>> 8)
2852 this[offset + 2] = (value >>> 16)
2853 this[offset + 3] = (value >>> 24)
2854 return offset + 4
2855}
2856
2857Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
2858 value = +value
2859 offset = offset >>> 0
2860 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2861 if (value < 0) value = 0xffffffff + value + 1
2862 this[offset] = (value >>> 24)
2863 this[offset + 1] = (value >>> 16)
2864 this[offset + 2] = (value >>> 8)
2865 this[offset + 3] = (value & 0xff)
2866 return offset + 4
2867}
2868
2869function checkIEEE754 (buf, value, offset, ext, max, min) {
2870 if (offset + ext > buf.length) throw new RangeError('Index out of range')
2871 if (offset < 0) throw new RangeError('Index out of range')
2872}
2873
2874function writeFloat (buf, value, offset, littleEndian, noAssert) {
2875 value = +value
2876 offset = offset >>> 0
2877 if (!noAssert) {
2878 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
2879 }
2880 ieee754.write(buf, value, offset, littleEndian, 23, 4)
2881 return offset + 4
2882}
2883
2884Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
2885 return writeFloat(this, value, offset, true, noAssert)
2886}
2887
2888Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
2889 return writeFloat(this, value, offset, false, noAssert)
2890}
2891
2892function writeDouble (buf, value, offset, littleEndian, noAssert) {
2893 value = +value
2894 offset = offset >>> 0
2895 if (!noAssert) {
2896 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
2897 }
2898 ieee754.write(buf, value, offset, littleEndian, 52, 8)
2899 return offset + 8
2900}
2901
2902Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
2903 return writeDouble(this, value, offset, true, noAssert)
2904}
2905
2906Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
2907 return writeDouble(this, value, offset, false, noAssert)
2908}
2909
2910// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
2911Buffer.prototype.copy = function copy (target, targetStart, start, end) {
2912 if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
2913 if (!start) start = 0
2914 if (!end && end !== 0) end = this.length
2915 if (targetStart >= target.length) targetStart = target.length
2916 if (!targetStart) targetStart = 0
2917 if (end > 0 && end < start) end = start
2918
2919 // Copy 0 bytes; we're done
2920 if (end === start) return 0
2921 if (target.length === 0 || this.length === 0) return 0
2922
2923 // Fatal error conditions
2924 if (targetStart < 0) {
2925 throw new RangeError('targetStart out of bounds')
2926 }
2927 if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
2928 if (end < 0) throw new RangeError('sourceEnd out of bounds')
2929
2930 // Are we oob?
2931 if (end > this.length) end = this.length
2932 if (target.length - targetStart < end - start) {
2933 end = target.length - targetStart + start
2934 }
2935
2936 var len = end - start
2937
2938 if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
2939 // Use built-in when available, missing from IE11
2940 this.copyWithin(targetStart, start, end)
2941 } else if (this === target && start < targetStart && targetStart < end) {
2942 // descending copy from end
2943 for (var i = len - 1; i >= 0; --i) {
2944 target[i + targetStart] = this[i + start]
2945 }
2946 } else {
2947 Uint8Array.prototype.set.call(
2948 target,
2949 this.subarray(start, end),
2950 targetStart
2951 )
2952 }
2953
2954 return len
2955}
2956
2957// Usage:
2958// buffer.fill(number[, offset[, end]])
2959// buffer.fill(buffer[, offset[, end]])
2960// buffer.fill(string[, offset[, end]][, encoding])
2961Buffer.prototype.fill = function fill (val, start, end, encoding) {
2962 // Handle string cases:
2963 if (typeof val === 'string') {
2964 if (typeof start === 'string') {
2965 encoding = start
2966 start = 0
2967 end = this.length
2968 } else if (typeof end === 'string') {
2969 encoding = end
2970 end = this.length
2971 }
2972 if (encoding !== undefined && typeof encoding !== 'string') {
2973 throw new TypeError('encoding must be a string')
2974 }
2975 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
2976 throw new TypeError('Unknown encoding: ' + encoding)
2977 }
2978 if (val.length === 1) {
2979 var code = val.charCodeAt(0)
2980 if ((encoding === 'utf8' && code < 128) ||
2981 encoding === 'latin1') {
2982 // Fast path: If `val` fits into a single byte, use that numeric value.
2983 val = code
2984 }
2985 }
2986 } else if (typeof val === 'number') {
2987 val = val & 255
2988 } else if (typeof val === 'boolean') {
2989 val = Number(val)
2990 }
2991
2992 // Invalid ranges are not set to a default, so can range check early.
2993 if (start < 0 || this.length < start || this.length < end) {
2994 throw new RangeError('Out of range index')
2995 }
2996
2997 if (end <= start) {
2998 return this
2999 }
3000
3001 start = start >>> 0
3002 end = end === undefined ? this.length : end >>> 0
3003
3004 if (!val) val = 0
3005
3006 var i
3007 if (typeof val === 'number') {
3008 for (i = start; i < end; ++i) {
3009 this[i] = val
3010 }
3011 } else {
3012 var bytes = Buffer.isBuffer(val)
3013 ? val
3014 : Buffer.from(val, encoding)
3015 var len = bytes.length
3016 if (len === 0) {
3017 throw new TypeError('The value "' + val +
3018 '" is invalid for argument "value"')
3019 }
3020 for (i = 0; i < end - start; ++i) {
3021 this[i + start] = bytes[i % len]
3022 }
3023 }
3024
3025 return this
3026}
3027
3028// HELPER FUNCTIONS
3029// ================
3030
3031var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
3032
3033function base64clean (str) {
3034 // Node takes equal signs as end of the Base64 encoding
3035 str = str.split('=')[0]
3036 // Node strips out invalid characters like \n and \t from the string, base64-js does not
3037 str = str.trim().replace(INVALID_BASE64_RE, '')
3038 // Node converts strings with length < 2 to ''
3039 if (str.length < 2) return ''
3040 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
3041 while (str.length % 4 !== 0) {
3042 str = str + '='
3043 }
3044 return str
3045}
3046
3047function utf8ToBytes (string, units) {
3048 units = units || Infinity
3049 var codePoint
3050 var length = string.length
3051 var leadSurrogate = null
3052 var bytes = []
3053
3054 for (var i = 0; i < length; ++i) {
3055 codePoint = string.charCodeAt(i)
3056
3057 // is surrogate component
3058 if (codePoint > 0xD7FF && codePoint < 0xE000) {
3059 // last char was a lead
3060 if (!leadSurrogate) {
3061 // no lead yet
3062 if (codePoint > 0xDBFF) {
3063 // unexpected trail
3064 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3065 continue
3066 } else if (i + 1 === length) {
3067 // unpaired lead
3068 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3069 continue
3070 }
3071
3072 // valid lead
3073 leadSurrogate = codePoint
3074
3075 continue
3076 }
3077
3078 // 2 leads in a row
3079 if (codePoint < 0xDC00) {
3080 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3081 leadSurrogate = codePoint
3082 continue
3083 }
3084
3085 // valid surrogate pair
3086 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
3087 } else if (leadSurrogate) {
3088 // valid bmp char, but last char was a lead
3089 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3090 }
3091
3092 leadSurrogate = null
3093
3094 // encode utf8
3095 if (codePoint < 0x80) {
3096 if ((units -= 1) < 0) break
3097 bytes.push(codePoint)
3098 } else if (codePoint < 0x800) {
3099 if ((units -= 2) < 0) break
3100 bytes.push(
3101 codePoint >> 0x6 | 0xC0,
3102 codePoint & 0x3F | 0x80
3103 )
3104 } else if (codePoint < 0x10000) {
3105 if ((units -= 3) < 0) break
3106 bytes.push(
3107 codePoint >> 0xC | 0xE0,
3108 codePoint >> 0x6 & 0x3F | 0x80,
3109 codePoint & 0x3F | 0x80
3110 )
3111 } else if (codePoint < 0x110000) {
3112 if ((units -= 4) < 0) break
3113 bytes.push(
3114 codePoint >> 0x12 | 0xF0,
3115 codePoint >> 0xC & 0x3F | 0x80,
3116 codePoint >> 0x6 & 0x3F | 0x80,
3117 codePoint & 0x3F | 0x80
3118 )
3119 } else {
3120 throw new Error('Invalid code point')
3121 }
3122 }
3123
3124 return bytes
3125}
3126
3127function asciiToBytes (str) {
3128 var byteArray = []
3129 for (var i = 0; i < str.length; ++i) {
3130 // Node's code seems to be doing this and not & 0x7F..
3131 byteArray.push(str.charCodeAt(i) & 0xFF)
3132 }
3133 return byteArray
3134}
3135
3136function utf16leToBytes (str, units) {
3137 var c, hi, lo
3138 var byteArray = []
3139 for (var i = 0; i < str.length; ++i) {
3140 if ((units -= 2) < 0) break
3141
3142 c = str.charCodeAt(i)
3143 hi = c >> 8
3144 lo = c % 256
3145 byteArray.push(lo)
3146 byteArray.push(hi)
3147 }
3148
3149 return byteArray
3150}
3151
3152function base64ToBytes (str) {
3153 return base64.toByteArray(base64clean(str))
3154}
3155
3156function blitBuffer (src, dst, offset, length) {
3157 for (var i = 0; i < length; ++i) {
3158 if ((i + offset >= dst.length) || (i >= src.length)) break
3159 dst[i + offset] = src[i]
3160 }
3161 return i
3162}
3163
3164// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
3165// the `instanceof` check but they should be treated as of that type.
3166// See: https://github.com/feross/buffer/issues/166
3167function isInstance (obj, type) {
3168 return obj instanceof type ||
3169 (obj != null && obj.constructor != null && obj.constructor.name != null &&
3170 obj.constructor.name === type.name)
3171}
3172function numberIsNaN (obj) {
3173 // For IE11 support
3174 return obj !== obj // eslint-disable-line no-self-compare
3175}
3176
3177// Create lookup table for `toString('hex')`
3178// See: https://github.com/feross/buffer/issues/219
3179var hexSliceLookupTable = (function () {
3180 var alphabet = '0123456789abcdef'
3181 var table = new Array(256)
3182 for (var i = 0; i < 16; ++i) {
3183 var i16 = i * 16
3184 for (var j = 0; j < 16; ++j) {
3185 table[i16 + j] = alphabet[i] + alphabet[j]
3186 }
3187 }
3188 return table
3189})()
3190
3191}).call(this,_dereq_(9).Buffer)
3192},{"16":16,"6":6,"9":9}],10:[function(_dereq_,module,exports){
3193(function (Buffer){
3194// Copyright Joyent, Inc. and other Node contributors.
3195//
3196// Permission is hereby granted, free of charge, to any person obtaining a
3197// copy of this software and associated documentation files (the
3198// "Software"), to deal in the Software without restriction, including
3199// without limitation the rights to use, copy, modify, merge, publish,
3200// distribute, sublicense, and/or sell copies of the Software, and to permit
3201// persons to whom the Software is furnished to do so, subject to the
3202// following conditions:
3203//
3204// The above copyright notice and this permission notice shall be included
3205// in all copies or substantial portions of the Software.
3206//
3207// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3208// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3209// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3210// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3211// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3212// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3213// USE OR OTHER DEALINGS IN THE SOFTWARE.
3214
3215// NOTE: These type checking functions intentionally don't use `instanceof`
3216// because it is fragile and can be easily faked with `Object.create()`.
3217
3218function isArray(arg) {
3219 if (Array.isArray) {
3220 return Array.isArray(arg);
3221 }
3222 return objectToString(arg) === '[object Array]';
3223}
3224exports.isArray = isArray;
3225
3226function isBoolean(arg) {
3227 return typeof arg === 'boolean';
3228}
3229exports.isBoolean = isBoolean;
3230
3231function isNull(arg) {
3232 return arg === null;
3233}
3234exports.isNull = isNull;
3235
3236function isNullOrUndefined(arg) {
3237 return arg == null;
3238}
3239exports.isNullOrUndefined = isNullOrUndefined;
3240
3241function isNumber(arg) {
3242 return typeof arg === 'number';
3243}
3244exports.isNumber = isNumber;
3245
3246function isString(arg) {
3247 return typeof arg === 'string';
3248}
3249exports.isString = isString;
3250
3251function isSymbol(arg) {
3252 return typeof arg === 'symbol';
3253}
3254exports.isSymbol = isSymbol;
3255
3256function isUndefined(arg) {
3257 return arg === void 0;
3258}
3259exports.isUndefined = isUndefined;
3260
3261function isRegExp(re) {
3262 return objectToString(re) === '[object RegExp]';
3263}
3264exports.isRegExp = isRegExp;
3265
3266function isObject(arg) {
3267 return typeof arg === 'object' && arg !== null;
3268}
3269exports.isObject = isObject;
3270
3271function isDate(d) {
3272 return objectToString(d) === '[object Date]';
3273}
3274exports.isDate = isDate;
3275
3276function isError(e) {
3277 return (objectToString(e) === '[object Error]' || e instanceof Error);
3278}
3279exports.isError = isError;
3280
3281function isFunction(arg) {
3282 return typeof arg === 'function';
3283}
3284exports.isFunction = isFunction;
3285
3286function isPrimitive(arg) {
3287 return arg === null ||
3288 typeof arg === 'boolean' ||
3289 typeof arg === 'number' ||
3290 typeof arg === 'string' ||
3291 typeof arg === 'symbol' || // ES6 symbol
3292 typeof arg === 'undefined';
3293}
3294exports.isPrimitive = isPrimitive;
3295
3296exports.isBuffer = Buffer.isBuffer;
3297
3298function objectToString(o) {
3299 return Object.prototype.toString.call(o);
3300}
3301
3302}).call(this,{"isBuffer":_dereq_(19)})
3303},{"19":19}],11:[function(_dereq_,module,exports){
3304/**
3305 * Copyright (c) 2013 Petka Antonov
3306 *
3307 * Permission is hereby granted, free of charge, to any person obtaining a copy
3308 * of this software and associated documentation files (the "Software"), to deal
3309 * in the Software without restriction, including without limitation the rights
3310 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
3311 * copies of the Software, and to permit persons to whom the Software is
3312 * furnished to do so, subject to the following conditions:</p>
3313 *
3314 * The above copyright notice and this permission notice shall be included in
3315 * all copies or substantial portions of the Software.
3316 *
3317 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
3318 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
3319 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
3320 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
3321 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
3322 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
3323 * THE SOFTWARE.
3324 */
3325"use strict";
3326function Deque(capacity) {
3327 this._capacity = getCapacity(capacity);
3328 this._length = 0;
3329 this._front = 0;
3330 if (isArray(capacity)) {
3331 var len = capacity.length;
3332 for (var i = 0; i < len; ++i) {
3333 this[i] = capacity[i];
3334 }
3335 this._length = len;
3336 }
3337}
3338
3339Deque.prototype.toArray = function Deque$toArray() {
3340 var len = this._length;
3341 var ret = new Array(len);
3342 var front = this._front;
3343 var capacity = this._capacity;
3344 for (var j = 0; j < len; ++j) {
3345 ret[j] = this[(front + j) & (capacity - 1)];
3346 }
3347 return ret;
3348};
3349
3350Deque.prototype.push = function Deque$push(item) {
3351 var argsLength = arguments.length;
3352 var length = this._length;
3353 if (argsLength > 1) {
3354 var capacity = this._capacity;
3355 if (length + argsLength > capacity) {
3356 for (var i = 0; i < argsLength; ++i) {
3357 this._checkCapacity(length + 1);
3358 var j = (this._front + length) & (this._capacity - 1);
3359 this[j] = arguments[i];
3360 length++;
3361 this._length = length;
3362 }
3363 return length;
3364 }
3365 else {
3366 var j = this._front;
3367 for (var i = 0; i < argsLength; ++i) {
3368 this[(j + length) & (capacity - 1)] = arguments[i];
3369 j++;
3370 }
3371 this._length = length + argsLength;
3372 return length + argsLength;
3373 }
3374
3375 }
3376
3377 if (argsLength === 0) return length;
3378
3379 this._checkCapacity(length + 1);
3380 var i = (this._front + length) & (this._capacity - 1);
3381 this[i] = item;
3382 this._length = length + 1;
3383 return length + 1;
3384};
3385
3386Deque.prototype.pop = function Deque$pop() {
3387 var length = this._length;
3388 if (length === 0) {
3389 return void 0;
3390 }
3391 var i = (this._front + length - 1) & (this._capacity - 1);
3392 var ret = this[i];
3393 this[i] = void 0;
3394 this._length = length - 1;
3395 return ret;
3396};
3397
3398Deque.prototype.shift = function Deque$shift() {
3399 var length = this._length;
3400 if (length === 0) {
3401 return void 0;
3402 }
3403 var front = this._front;
3404 var ret = this[front];
3405 this[front] = void 0;
3406 this._front = (front + 1) & (this._capacity - 1);
3407 this._length = length - 1;
3408 return ret;
3409};
3410
3411Deque.prototype.unshift = function Deque$unshift(item) {
3412 var length = this._length;
3413 var argsLength = arguments.length;
3414
3415
3416 if (argsLength > 1) {
3417 var capacity = this._capacity;
3418 if (length + argsLength > capacity) {
3419 for (var i = argsLength - 1; i >= 0; i--) {
3420 this._checkCapacity(length + 1);
3421 var capacity = this._capacity;
3422 var j = (((( this._front - 1 ) &
3423 ( capacity - 1) ) ^ capacity ) - capacity );
3424 this[j] = arguments[i];
3425 length++;
3426 this._length = length;
3427 this._front = j;
3428 }
3429 return length;
3430 }
3431 else {
3432 var front = this._front;
3433 for (var i = argsLength - 1; i >= 0; i--) {
3434 var j = (((( front - 1 ) &
3435 ( capacity - 1) ) ^ capacity ) - capacity );
3436 this[j] = arguments[i];
3437 front = j;
3438 }
3439 this._front = front;
3440 this._length = length + argsLength;
3441 return length + argsLength;
3442 }
3443 }
3444
3445 if (argsLength === 0) return length;
3446
3447 this._checkCapacity(length + 1);
3448 var capacity = this._capacity;
3449 var i = (((( this._front - 1 ) &
3450 ( capacity - 1) ) ^ capacity ) - capacity );
3451 this[i] = item;
3452 this._length = length + 1;
3453 this._front = i;
3454 return length + 1;
3455};
3456
3457Deque.prototype.peekBack = function Deque$peekBack() {
3458 var length = this._length;
3459 if (length === 0) {
3460 return void 0;
3461 }
3462 var index = (this._front + length - 1) & (this._capacity - 1);
3463 return this[index];
3464};
3465
3466Deque.prototype.peekFront = function Deque$peekFront() {
3467 if (this._length === 0) {
3468 return void 0;
3469 }
3470 return this[this._front];
3471};
3472
3473Deque.prototype.get = function Deque$get(index) {
3474 var i = index;
3475 if ((i !== (i | 0))) {
3476 return void 0;
3477 }
3478 var len = this._length;
3479 if (i < 0) {
3480 i = i + len;
3481 }
3482 if (i < 0 || i >= len) {
3483 return void 0;
3484 }
3485 return this[(this._front + i) & (this._capacity - 1)];
3486};
3487
3488Deque.prototype.isEmpty = function Deque$isEmpty() {
3489 return this._length === 0;
3490};
3491
3492Deque.prototype.clear = function Deque$clear() {
3493 var len = this._length;
3494 var front = this._front;
3495 var capacity = this._capacity;
3496 for (var j = 0; j < len; ++j) {
3497 this[(front + j) & (capacity - 1)] = void 0;
3498 }
3499 this._length = 0;
3500 this._front = 0;
3501};
3502
3503Deque.prototype.toString = function Deque$toString() {
3504 return this.toArray().toString();
3505};
3506
3507Deque.prototype.valueOf = Deque.prototype.toString;
3508Deque.prototype.removeFront = Deque.prototype.shift;
3509Deque.prototype.removeBack = Deque.prototype.pop;
3510Deque.prototype.insertFront = Deque.prototype.unshift;
3511Deque.prototype.insertBack = Deque.prototype.push;
3512Deque.prototype.enqueue = Deque.prototype.push;
3513Deque.prototype.dequeue = Deque.prototype.shift;
3514Deque.prototype.toJSON = Deque.prototype.toArray;
3515
3516Object.defineProperty(Deque.prototype, "length", {
3517 get: function() {
3518 return this._length;
3519 },
3520 set: function() {
3521 throw new RangeError("");
3522 }
3523});
3524
3525Deque.prototype._checkCapacity = function Deque$_checkCapacity(size) {
3526 if (this._capacity < size) {
3527 this._resizeTo(getCapacity(this._capacity * 1.5 + 16));
3528 }
3529};
3530
3531Deque.prototype._resizeTo = function Deque$_resizeTo(capacity) {
3532 var oldCapacity = this._capacity;
3533 this._capacity = capacity;
3534 var front = this._front;
3535 var length = this._length;
3536 if (front + length > oldCapacity) {
3537 var moveItemsCount = (front + length) & (oldCapacity - 1);
3538 arrayMove(this, 0, this, oldCapacity, moveItemsCount);
3539 }
3540};
3541
3542
3543var isArray = Array.isArray;
3544
3545function arrayMove(src, srcIndex, dst, dstIndex, len) {
3546 for (var j = 0; j < len; ++j) {
3547 dst[j + dstIndex] = src[j + srcIndex];
3548 src[j + srcIndex] = void 0;
3549 }
3550}
3551
3552function pow2AtLeast(n) {
3553 n = n >>> 0;
3554 n = n - 1;
3555 n = n | (n >> 1);
3556 n = n | (n >> 2);
3557 n = n | (n >> 4);
3558 n = n | (n >> 8);
3559 n = n | (n >> 16);
3560 return n + 1;
3561}
3562
3563function getCapacity(capacity) {
3564 if (typeof capacity !== "number") {
3565 if (isArray(capacity)) {
3566 capacity = capacity.length;
3567 }
3568 else {
3569 return 16;
3570 }
3571 }
3572 return pow2AtLeast(
3573 Math.min(
3574 Math.max(16, capacity), 1073741824)
3575 );
3576}
3577
3578module.exports = Deque;
3579
3580},{}],12:[function(_dereq_,module,exports){
3581var prr = _dereq_(71)
3582
3583function init (type, message, cause) {
3584 if (!!message && typeof message != 'string') {
3585 message = message.message || message.name
3586 }
3587 prr(this, {
3588 type : type
3589 , name : type
3590 // can be passed just a 'cause'
3591 , cause : typeof message != 'string' ? message : cause
3592 , message : message
3593 }, 'ewr')
3594}
3595
3596// generic prototype, not intended to be actually used - helpful for `instanceof`
3597function CustomError (message, cause) {
3598 Error.call(this)
3599 if (Error.captureStackTrace)
3600 Error.captureStackTrace(this, this.constructor)
3601 init.call(this, 'CustomError', message, cause)
3602}
3603
3604CustomError.prototype = new Error()
3605
3606function createError (errno, type, proto) {
3607 var err = function (message, cause) {
3608 init.call(this, type, message, cause)
3609 //TODO: the specificity here is stupid, errno should be available everywhere
3610 if (type == 'FilesystemError') {
3611 this.code = this.cause.code
3612 this.path = this.cause.path
3613 this.errno = this.cause.errno
3614 this.message =
3615 (errno.errno[this.cause.errno]
3616 ? errno.errno[this.cause.errno].description
3617 : this.cause.message)
3618 + (this.cause.path ? ' [' + this.cause.path + ']' : '')
3619 }
3620 Error.call(this)
3621 if (Error.captureStackTrace)
3622 Error.captureStackTrace(this, err)
3623 }
3624 err.prototype = !!proto ? new proto() : new CustomError()
3625 return err
3626}
3627
3628module.exports = function (errno) {
3629 var ce = function (type, proto) {
3630 return createError(errno, type, proto)
3631 }
3632 return {
3633 CustomError : CustomError
3634 , FilesystemError : ce('FilesystemError')
3635 , createError : ce
3636 }
3637}
3638
3639},{"71":71}],13:[function(_dereq_,module,exports){
3640var all = module.exports.all = [
3641 {
3642 errno: -2,
3643 code: 'ENOENT',
3644 description: 'no such file or directory'
3645 },
3646 {
3647 errno: -1,
3648 code: 'UNKNOWN',
3649 description: 'unknown error'
3650 },
3651 {
3652 errno: 0,
3653 code: 'OK',
3654 description: 'success'
3655 },
3656 {
3657 errno: 1,
3658 code: 'EOF',
3659 description: 'end of file'
3660 },
3661 {
3662 errno: 2,
3663 code: 'EADDRINFO',
3664 description: 'getaddrinfo error'
3665 },
3666 {
3667 errno: 3,
3668 code: 'EACCES',
3669 description: 'permission denied'
3670 },
3671 {
3672 errno: 4,
3673 code: 'EAGAIN',
3674 description: 'resource temporarily unavailable'
3675 },
3676 {
3677 errno: 5,
3678 code: 'EADDRINUSE',
3679 description: 'address already in use'
3680 },
3681 {
3682 errno: 6,
3683 code: 'EADDRNOTAVAIL',
3684 description: 'address not available'
3685 },
3686 {
3687 errno: 7,
3688 code: 'EAFNOSUPPORT',
3689 description: 'address family not supported'
3690 },
3691 {
3692 errno: 8,
3693 code: 'EALREADY',
3694 description: 'connection already in progress'
3695 },
3696 {
3697 errno: 9,
3698 code: 'EBADF',
3699 description: 'bad file descriptor'
3700 },
3701 {
3702 errno: 10,
3703 code: 'EBUSY',
3704 description: 'resource busy or locked'
3705 },
3706 {
3707 errno: 11,
3708 code: 'ECONNABORTED',
3709 description: 'software caused connection abort'
3710 },
3711 {
3712 errno: 12,
3713 code: 'ECONNREFUSED',
3714 description: 'connection refused'
3715 },
3716 {
3717 errno: 13,
3718 code: 'ECONNRESET',
3719 description: 'connection reset by peer'
3720 },
3721 {
3722 errno: 14,
3723 code: 'EDESTADDRREQ',
3724 description: 'destination address required'
3725 },
3726 {
3727 errno: 15,
3728 code: 'EFAULT',
3729 description: 'bad address in system call argument'
3730 },
3731 {
3732 errno: 16,
3733 code: 'EHOSTUNREACH',
3734 description: 'host is unreachable'
3735 },
3736 {
3737 errno: 17,
3738 code: 'EINTR',
3739 description: 'interrupted system call'
3740 },
3741 {
3742 errno: 18,
3743 code: 'EINVAL',
3744 description: 'invalid argument'
3745 },
3746 {
3747 errno: 19,
3748 code: 'EISCONN',
3749 description: 'socket is already connected'
3750 },
3751 {
3752 errno: 20,
3753 code: 'EMFILE',
3754 description: 'too many open files'
3755 },
3756 {
3757 errno: 21,
3758 code: 'EMSGSIZE',
3759 description: 'message too long'
3760 },
3761 {
3762 errno: 22,
3763 code: 'ENETDOWN',
3764 description: 'network is down'
3765 },
3766 {
3767 errno: 23,
3768 code: 'ENETUNREACH',
3769 description: 'network is unreachable'
3770 },
3771 {
3772 errno: 24,
3773 code: 'ENFILE',
3774 description: 'file table overflow'
3775 },
3776 {
3777 errno: 25,
3778 code: 'ENOBUFS',
3779 description: 'no buffer space available'
3780 },
3781 {
3782 errno: 26,
3783 code: 'ENOMEM',
3784 description: 'not enough memory'
3785 },
3786 {
3787 errno: 27,
3788 code: 'ENOTDIR',
3789 description: 'not a directory'
3790 },
3791 {
3792 errno: 28,
3793 code: 'EISDIR',
3794 description: 'illegal operation on a directory'
3795 },
3796 {
3797 errno: 29,
3798 code: 'ENONET',
3799 description: 'machine is not on the network'
3800 },
3801 {
3802 errno: 31,
3803 code: 'ENOTCONN',
3804 description: 'socket is not connected'
3805 },
3806 {
3807 errno: 32,
3808 code: 'ENOTSOCK',
3809 description: 'socket operation on non-socket'
3810 },
3811 {
3812 errno: 33,
3813 code: 'ENOTSUP',
3814 description: 'operation not supported on socket'
3815 },
3816 {
3817 errno: 34,
3818 code: 'ENOENT',
3819 description: 'no such file or directory'
3820 },
3821 {
3822 errno: 35,
3823 code: 'ENOSYS',
3824 description: 'function not implemented'
3825 },
3826 {
3827 errno: 36,
3828 code: 'EPIPE',
3829 description: 'broken pipe'
3830 },
3831 {
3832 errno: 37,
3833 code: 'EPROTO',
3834 description: 'protocol error'
3835 },
3836 {
3837 errno: 38,
3838 code: 'EPROTONOSUPPORT',
3839 description: 'protocol not supported'
3840 },
3841 {
3842 errno: 39,
3843 code: 'EPROTOTYPE',
3844 description: 'protocol wrong type for socket'
3845 },
3846 {
3847 errno: 40,
3848 code: 'ETIMEDOUT',
3849 description: 'connection timed out'
3850 },
3851 {
3852 errno: 41,
3853 code: 'ECHARSET',
3854 description: 'invalid Unicode character'
3855 },
3856 {
3857 errno: 42,
3858 code: 'EAIFAMNOSUPPORT',
3859 description: 'address family for hostname not supported'
3860 },
3861 {
3862 errno: 44,
3863 code: 'EAISERVICE',
3864 description: 'servname not supported for ai_socktype'
3865 },
3866 {
3867 errno: 45,
3868 code: 'EAISOCKTYPE',
3869 description: 'ai_socktype not supported'
3870 },
3871 {
3872 errno: 46,
3873 code: 'ESHUTDOWN',
3874 description: 'cannot send after transport endpoint shutdown'
3875 },
3876 {
3877 errno: 47,
3878 code: 'EEXIST',
3879 description: 'file already exists'
3880 },
3881 {
3882 errno: 48,
3883 code: 'ESRCH',
3884 description: 'no such process'
3885 },
3886 {
3887 errno: 49,
3888 code: 'ENAMETOOLONG',
3889 description: 'name too long'
3890 },
3891 {
3892 errno: 50,
3893 code: 'EPERM',
3894 description: 'operation not permitted'
3895 },
3896 {
3897 errno: 51,
3898 code: 'ELOOP',
3899 description: 'too many symbolic links encountered'
3900 },
3901 {
3902 errno: 52,
3903 code: 'EXDEV',
3904 description: 'cross-device link not permitted'
3905 },
3906 {
3907 errno: 53,
3908 code: 'ENOTEMPTY',
3909 description: 'directory not empty'
3910 },
3911 {
3912 errno: 54,
3913 code: 'ENOSPC',
3914 description: 'no space left on device'
3915 },
3916 {
3917 errno: 55,
3918 code: 'EIO',
3919 description: 'i/o error'
3920 },
3921 {
3922 errno: 56,
3923 code: 'EROFS',
3924 description: 'read-only file system'
3925 },
3926 {
3927 errno: 57,
3928 code: 'ENODEV',
3929 description: 'no such device'
3930 },
3931 {
3932 errno: 58,
3933 code: 'ESPIPE',
3934 description: 'invalid seek'
3935 },
3936 {
3937 errno: 59,
3938 code: 'ECANCELED',
3939 description: 'operation canceled'
3940 }
3941]
3942
3943module.exports.errno = {}
3944module.exports.code = {}
3945
3946all.forEach(function (error) {
3947 module.exports.errno[error.errno] = error
3948 module.exports.code[error.code] = error
3949})
3950
3951module.exports.custom = _dereq_(12)(module.exports)
3952module.exports.create = module.exports.custom.createError
3953
3954},{"12":12}],14:[function(_dereq_,module,exports){
3955// Copyright Joyent, Inc. and other Node contributors.
3956//
3957// Permission is hereby granted, free of charge, to any person obtaining a
3958// copy of this software and associated documentation files (the
3959// "Software"), to deal in the Software without restriction, including
3960// without limitation the rights to use, copy, modify, merge, publish,
3961// distribute, sublicense, and/or sell copies of the Software, and to permit
3962// persons to whom the Software is furnished to do so, subject to the
3963// following conditions:
3964//
3965// The above copyright notice and this permission notice shall be included
3966// in all copies or substantial portions of the Software.
3967//
3968// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3969// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3970// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3971// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3972// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3973// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3974// USE OR OTHER DEALINGS IN THE SOFTWARE.
3975
3976var objectCreate = Object.create || objectCreatePolyfill
3977var objectKeys = Object.keys || objectKeysPolyfill
3978var bind = Function.prototype.bind || functionBindPolyfill
3979
3980function EventEmitter() {
3981 if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
3982 this._events = objectCreate(null);
3983 this._eventsCount = 0;
3984 }
3985
3986 this._maxListeners = this._maxListeners || undefined;
3987}
3988module.exports = EventEmitter;
3989
3990// Backwards-compat with node 0.10.x
3991EventEmitter.EventEmitter = EventEmitter;
3992
3993EventEmitter.prototype._events = undefined;
3994EventEmitter.prototype._maxListeners = undefined;
3995
3996// By default EventEmitters will print a warning if more than 10 listeners are
3997// added to it. This is a useful default which helps finding memory leaks.
3998var defaultMaxListeners = 10;
3999
4000var hasDefineProperty;
4001try {
4002 var o = {};
4003 if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
4004 hasDefineProperty = o.x === 0;
4005} catch (err) { hasDefineProperty = false }
4006if (hasDefineProperty) {
4007 Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
4008 enumerable: true,
4009 get: function() {
4010 return defaultMaxListeners;
4011 },
4012 set: function(arg) {
4013 // check whether the input is a positive number (whose value is zero or
4014 // greater and not a NaN).
4015 if (typeof arg !== 'number' || arg < 0 || arg !== arg)
4016 throw new TypeError('"defaultMaxListeners" must be a positive number');
4017 defaultMaxListeners = arg;
4018 }
4019 });
4020} else {
4021 EventEmitter.defaultMaxListeners = defaultMaxListeners;
4022}
4023
4024// Obviously not all Emitters should be limited to 10. This function allows
4025// that to be increased. Set to zero for unlimited.
4026EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
4027 if (typeof n !== 'number' || n < 0 || isNaN(n))
4028 throw new TypeError('"n" argument must be a positive number');
4029 this._maxListeners = n;
4030 return this;
4031};
4032
4033function $getMaxListeners(that) {
4034 if (that._maxListeners === undefined)
4035 return EventEmitter.defaultMaxListeners;
4036 return that._maxListeners;
4037}
4038
4039EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
4040 return $getMaxListeners(this);
4041};
4042
4043// These standalone emit* functions are used to optimize calling of event
4044// handlers for fast cases because emit() itself often has a variable number of
4045// arguments and can be deoptimized because of that. These functions always have
4046// the same number of arguments and thus do not get deoptimized, so the code
4047// inside them can execute faster.
4048function emitNone(handler, isFn, self) {
4049 if (isFn)
4050 handler.call(self);
4051 else {
4052 var len = handler.length;
4053 var listeners = arrayClone(handler, len);
4054 for (var i = 0; i < len; ++i)
4055 listeners[i].call(self);
4056 }
4057}
4058function emitOne(handler, isFn, self, arg1) {
4059 if (isFn)
4060 handler.call(self, arg1);
4061 else {
4062 var len = handler.length;
4063 var listeners = arrayClone(handler, len);
4064 for (var i = 0; i < len; ++i)
4065 listeners[i].call(self, arg1);
4066 }
4067}
4068function emitTwo(handler, isFn, self, arg1, arg2) {
4069 if (isFn)
4070 handler.call(self, arg1, arg2);
4071 else {
4072 var len = handler.length;
4073 var listeners = arrayClone(handler, len);
4074 for (var i = 0; i < len; ++i)
4075 listeners[i].call(self, arg1, arg2);
4076 }
4077}
4078function emitThree(handler, isFn, self, arg1, arg2, arg3) {
4079 if (isFn)
4080 handler.call(self, arg1, arg2, arg3);
4081 else {
4082 var len = handler.length;
4083 var listeners = arrayClone(handler, len);
4084 for (var i = 0; i < len; ++i)
4085 listeners[i].call(self, arg1, arg2, arg3);
4086 }
4087}
4088
4089function emitMany(handler, isFn, self, args) {
4090 if (isFn)
4091 handler.apply(self, args);
4092 else {
4093 var len = handler.length;
4094 var listeners = arrayClone(handler, len);
4095 for (var i = 0; i < len; ++i)
4096 listeners[i].apply(self, args);
4097 }
4098}
4099
4100EventEmitter.prototype.emit = function emit(type) {
4101 var er, handler, len, args, i, events;
4102 var doError = (type === 'error');
4103
4104 events = this._events;
4105 if (events)
4106 doError = (doError && events.error == null);
4107 else if (!doError)
4108 return false;
4109
4110 // If there is no 'error' event listener then throw.
4111 if (doError) {
4112 if (arguments.length > 1)
4113 er = arguments[1];
4114 if (er instanceof Error) {
4115 throw er; // Unhandled 'error' event
4116 } else {
4117 // At least give some kind of context to the user
4118 var err = new Error('Unhandled "error" event. (' + er + ')');
4119 err.context = er;
4120 throw err;
4121 }
4122 return false;
4123 }
4124
4125 handler = events[type];
4126
4127 if (!handler)
4128 return false;
4129
4130 var isFn = typeof handler === 'function';
4131 len = arguments.length;
4132 switch (len) {
4133 // fast cases
4134 case 1:
4135 emitNone(handler, isFn, this);
4136 break;
4137 case 2:
4138 emitOne(handler, isFn, this, arguments[1]);
4139 break;
4140 case 3:
4141 emitTwo(handler, isFn, this, arguments[1], arguments[2]);
4142 break;
4143 case 4:
4144 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
4145 break;
4146 // slower
4147 default:
4148 args = new Array(len - 1);
4149 for (i = 1; i < len; i++)
4150 args[i - 1] = arguments[i];
4151 emitMany(handler, isFn, this, args);
4152 }
4153
4154 return true;
4155};
4156
4157function _addListener(target, type, listener, prepend) {
4158 var m;
4159 var events;
4160 var existing;
4161
4162 if (typeof listener !== 'function')
4163 throw new TypeError('"listener" argument must be a function');
4164
4165 events = target._events;
4166 if (!events) {
4167 events = target._events = objectCreate(null);
4168 target._eventsCount = 0;
4169 } else {
4170 // To avoid recursion in the case that type === "newListener"! Before
4171 // adding it to the listeners, first emit "newListener".
4172 if (events.newListener) {
4173 target.emit('newListener', type,
4174 listener.listener ? listener.listener : listener);
4175
4176 // Re-assign `events` because a newListener handler could have caused the
4177 // this._events to be assigned to a new object
4178 events = target._events;
4179 }
4180 existing = events[type];
4181 }
4182
4183 if (!existing) {
4184 // Optimize the case of one listener. Don't need the extra array object.
4185 existing = events[type] = listener;
4186 ++target._eventsCount;
4187 } else {
4188 if (typeof existing === 'function') {
4189 // Adding the second element, need to change to array.
4190 existing = events[type] =
4191 prepend ? [listener, existing] : [existing, listener];
4192 } else {
4193 // If we've already got an array, just append.
4194 if (prepend) {
4195 existing.unshift(listener);
4196 } else {
4197 existing.push(listener);
4198 }
4199 }
4200
4201 // Check for listener leak
4202 if (!existing.warned) {
4203 m = $getMaxListeners(target);
4204 if (m && m > 0 && existing.length > m) {
4205 existing.warned = true;
4206 var w = new Error('Possible EventEmitter memory leak detected. ' +
4207 existing.length + ' "' + String(type) + '" listeners ' +
4208 'added. Use emitter.setMaxListeners() to ' +
4209 'increase limit.');
4210 w.name = 'MaxListenersExceededWarning';
4211 w.emitter = target;
4212 w.type = type;
4213 w.count = existing.length;
4214 if (typeof console === 'object' && console.warn) {
4215 console.warn('%s: %s', w.name, w.message);
4216 }
4217 }
4218 }
4219 }
4220
4221 return target;
4222}
4223
4224EventEmitter.prototype.addListener = function addListener(type, listener) {
4225 return _addListener(this, type, listener, false);
4226};
4227
4228EventEmitter.prototype.on = EventEmitter.prototype.addListener;
4229
4230EventEmitter.prototype.prependListener =
4231 function prependListener(type, listener) {
4232 return _addListener(this, type, listener, true);
4233 };
4234
4235function onceWrapper() {
4236 if (!this.fired) {
4237 this.target.removeListener(this.type, this.wrapFn);
4238 this.fired = true;
4239 switch (arguments.length) {
4240 case 0:
4241 return this.listener.call(this.target);
4242 case 1:
4243 return this.listener.call(this.target, arguments[0]);
4244 case 2:
4245 return this.listener.call(this.target, arguments[0], arguments[1]);
4246 case 3:
4247 return this.listener.call(this.target, arguments[0], arguments[1],
4248 arguments[2]);
4249 default:
4250 var args = new Array(arguments.length);
4251 for (var i = 0; i < args.length; ++i)
4252 args[i] = arguments[i];
4253 this.listener.apply(this.target, args);
4254 }
4255 }
4256}
4257
4258function _onceWrap(target, type, listener) {
4259 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
4260 var wrapped = bind.call(onceWrapper, state);
4261 wrapped.listener = listener;
4262 state.wrapFn = wrapped;
4263 return wrapped;
4264}
4265
4266EventEmitter.prototype.once = function once(type, listener) {
4267 if (typeof listener !== 'function')
4268 throw new TypeError('"listener" argument must be a function');
4269 this.on(type, _onceWrap(this, type, listener));
4270 return this;
4271};
4272
4273EventEmitter.prototype.prependOnceListener =
4274 function prependOnceListener(type, listener) {
4275 if (typeof listener !== 'function')
4276 throw new TypeError('"listener" argument must be a function');
4277 this.prependListener(type, _onceWrap(this, type, listener));
4278 return this;
4279 };
4280
4281// Emits a 'removeListener' event if and only if the listener was removed.
4282EventEmitter.prototype.removeListener =
4283 function removeListener(type, listener) {
4284 var list, events, position, i, originalListener;
4285
4286 if (typeof listener !== 'function')
4287 throw new TypeError('"listener" argument must be a function');
4288
4289 events = this._events;
4290 if (!events)
4291 return this;
4292
4293 list = events[type];
4294 if (!list)
4295 return this;
4296
4297 if (list === listener || list.listener === listener) {
4298 if (--this._eventsCount === 0)
4299 this._events = objectCreate(null);
4300 else {
4301 delete events[type];
4302 if (events.removeListener)
4303 this.emit('removeListener', type, list.listener || listener);
4304 }
4305 } else if (typeof list !== 'function') {
4306 position = -1;
4307
4308 for (i = list.length - 1; i >= 0; i--) {
4309 if (list[i] === listener || list[i].listener === listener) {
4310 originalListener = list[i].listener;
4311 position = i;
4312 break;
4313 }
4314 }
4315
4316 if (position < 0)
4317 return this;
4318
4319 if (position === 0)
4320 list.shift();
4321 else
4322 spliceOne(list, position);
4323
4324 if (list.length === 1)
4325 events[type] = list[0];
4326
4327 if (events.removeListener)
4328 this.emit('removeListener', type, originalListener || listener);
4329 }
4330
4331 return this;
4332 };
4333
4334EventEmitter.prototype.removeAllListeners =
4335 function removeAllListeners(type) {
4336 var listeners, events, i;
4337
4338 events = this._events;
4339 if (!events)
4340 return this;
4341
4342 // not listening for removeListener, no need to emit
4343 if (!events.removeListener) {
4344 if (arguments.length === 0) {
4345 this._events = objectCreate(null);
4346 this._eventsCount = 0;
4347 } else if (events[type]) {
4348 if (--this._eventsCount === 0)
4349 this._events = objectCreate(null);
4350 else
4351 delete events[type];
4352 }
4353 return this;
4354 }
4355
4356 // emit removeListener for all listeners on all events
4357 if (arguments.length === 0) {
4358 var keys = objectKeys(events);
4359 var key;
4360 for (i = 0; i < keys.length; ++i) {
4361 key = keys[i];
4362 if (key === 'removeListener') continue;
4363 this.removeAllListeners(key);
4364 }
4365 this.removeAllListeners('removeListener');
4366 this._events = objectCreate(null);
4367 this._eventsCount = 0;
4368 return this;
4369 }
4370
4371 listeners = events[type];
4372
4373 if (typeof listeners === 'function') {
4374 this.removeListener(type, listeners);
4375 } else if (listeners) {
4376 // LIFO order
4377 for (i = listeners.length - 1; i >= 0; i--) {
4378 this.removeListener(type, listeners[i]);
4379 }
4380 }
4381
4382 return this;
4383 };
4384
4385function _listeners(target, type, unwrap) {
4386 var events = target._events;
4387
4388 if (!events)
4389 return [];
4390
4391 var evlistener = events[type];
4392 if (!evlistener)
4393 return [];
4394
4395 if (typeof evlistener === 'function')
4396 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
4397
4398 return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
4399}
4400
4401EventEmitter.prototype.listeners = function listeners(type) {
4402 return _listeners(this, type, true);
4403};
4404
4405EventEmitter.prototype.rawListeners = function rawListeners(type) {
4406 return _listeners(this, type, false);
4407};
4408
4409EventEmitter.listenerCount = function(emitter, type) {
4410 if (typeof emitter.listenerCount === 'function') {
4411 return emitter.listenerCount(type);
4412 } else {
4413 return listenerCount.call(emitter, type);
4414 }
4415};
4416
4417EventEmitter.prototype.listenerCount = listenerCount;
4418function listenerCount(type) {
4419 var events = this._events;
4420
4421 if (events) {
4422 var evlistener = events[type];
4423
4424 if (typeof evlistener === 'function') {
4425 return 1;
4426 } else if (evlistener) {
4427 return evlistener.length;
4428 }
4429 }
4430
4431 return 0;
4432}
4433
4434EventEmitter.prototype.eventNames = function eventNames() {
4435 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
4436};
4437
4438// About 1.5x faster than the two-arg version of Array#splice().
4439function spliceOne(list, index) {
4440 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
4441 list[i] = list[k];
4442 list.pop();
4443}
4444
4445function arrayClone(arr, n) {
4446 var copy = new Array(n);
4447 for (var i = 0; i < n; ++i)
4448 copy[i] = arr[i];
4449 return copy;
4450}
4451
4452function unwrapListeners(arr) {
4453 var ret = new Array(arr.length);
4454 for (var i = 0; i < ret.length; ++i) {
4455 ret[i] = arr[i].listener || arr[i];
4456 }
4457 return ret;
4458}
4459
4460function objectCreatePolyfill(proto) {
4461 var F = function() {};
4462 F.prototype = proto;
4463 return new F;
4464}
4465function objectKeysPolyfill(obj) {
4466 var keys = [];
4467 for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
4468 keys.push(k);
4469 }
4470 return k;
4471}
4472function functionBindPolyfill(context) {
4473 var fn = this;
4474 return function () {
4475 return fn.apply(context, arguments);
4476 };
4477}
4478
4479},{}],15:[function(_dereq_,module,exports){
4480"use strict"
4481
4482module.exports = createRBTree
4483
4484var RED = 0
4485var BLACK = 1
4486
4487function RBNode(color, key, value, left, right, count) {
4488 this._color = color
4489 this.key = key
4490 this.value = value
4491 this.left = left
4492 this.right = right
4493 this._count = count
4494}
4495
4496function cloneNode(node) {
4497 return new RBNode(node._color, node.key, node.value, node.left, node.right, node._count)
4498}
4499
4500function repaint(color, node) {
4501 return new RBNode(color, node.key, node.value, node.left, node.right, node._count)
4502}
4503
4504function recount(node) {
4505 node._count = 1 + (node.left ? node.left._count : 0) + (node.right ? node.right._count : 0)
4506}
4507
4508function RedBlackTree(compare, root) {
4509 this._compare = compare
4510 this.root = root
4511}
4512
4513var proto = RedBlackTree.prototype
4514
4515Object.defineProperty(proto, "keys", {
4516 get: function() {
4517 var result = []
4518 this.forEach(function(k,v) {
4519 result.push(k)
4520 })
4521 return result
4522 }
4523})
4524
4525Object.defineProperty(proto, "values", {
4526 get: function() {
4527 var result = []
4528 this.forEach(function(k,v) {
4529 result.push(v)
4530 })
4531 return result
4532 }
4533})
4534
4535//Returns the number of nodes in the tree
4536Object.defineProperty(proto, "length", {
4537 get: function() {
4538 if(this.root) {
4539 return this.root._count
4540 }
4541 return 0
4542 }
4543})
4544
4545//Insert a new item into the tree
4546proto.insert = function(key, value) {
4547 var cmp = this._compare
4548 //Find point to insert new node at
4549 var n = this.root
4550 var n_stack = []
4551 var d_stack = []
4552 while(n) {
4553 var d = cmp(key, n.key)
4554 n_stack.push(n)
4555 d_stack.push(d)
4556 if(d <= 0) {
4557 n = n.left
4558 } else {
4559 n = n.right
4560 }
4561 }
4562 //Rebuild path to leaf node
4563 n_stack.push(new RBNode(RED, key, value, null, null, 1))
4564 for(var s=n_stack.length-2; s>=0; --s) {
4565 var n = n_stack[s]
4566 if(d_stack[s] <= 0) {
4567 n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s+1], n.right, n._count+1)
4568 } else {
4569 n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s+1], n._count+1)
4570 }
4571 }
4572 //Rebalance tree using rotations
4573 //console.log("start insert", key, d_stack)
4574 for(var s=n_stack.length-1; s>1; --s) {
4575 var p = n_stack[s-1]
4576 var n = n_stack[s]
4577 if(p._color === BLACK || n._color === BLACK) {
4578 break
4579 }
4580 var pp = n_stack[s-2]
4581 if(pp.left === p) {
4582 if(p.left === n) {
4583 var y = pp.right
4584 if(y && y._color === RED) {
4585 //console.log("LLr")
4586 p._color = BLACK
4587 pp.right = repaint(BLACK, y)
4588 pp._color = RED
4589 s -= 1
4590 } else {
4591 //console.log("LLb")
4592 pp._color = RED
4593 pp.left = p.right
4594 p._color = BLACK
4595 p.right = pp
4596 n_stack[s-2] = p
4597 n_stack[s-1] = n
4598 recount(pp)
4599 recount(p)
4600 if(s >= 3) {
4601 var ppp = n_stack[s-3]
4602 if(ppp.left === pp) {
4603 ppp.left = p
4604 } else {
4605 ppp.right = p
4606 }
4607 }
4608 break
4609 }
4610 } else {
4611 var y = pp.right
4612 if(y && y._color === RED) {
4613 //console.log("LRr")
4614 p._color = BLACK
4615 pp.right = repaint(BLACK, y)
4616 pp._color = RED
4617 s -= 1
4618 } else {
4619 //console.log("LRb")
4620 p.right = n.left
4621 pp._color = RED
4622 pp.left = n.right
4623 n._color = BLACK
4624 n.left = p
4625 n.right = pp
4626 n_stack[s-2] = n
4627 n_stack[s-1] = p
4628 recount(pp)
4629 recount(p)
4630 recount(n)
4631 if(s >= 3) {
4632 var ppp = n_stack[s-3]
4633 if(ppp.left === pp) {
4634 ppp.left = n
4635 } else {
4636 ppp.right = n
4637 }
4638 }
4639 break
4640 }
4641 }
4642 } else {
4643 if(p.right === n) {
4644 var y = pp.left
4645 if(y && y._color === RED) {
4646 //console.log("RRr", y.key)
4647 p._color = BLACK
4648 pp.left = repaint(BLACK, y)
4649 pp._color = RED
4650 s -= 1
4651 } else {
4652 //console.log("RRb")
4653 pp._color = RED
4654 pp.right = p.left
4655 p._color = BLACK
4656 p.left = pp
4657 n_stack[s-2] = p
4658 n_stack[s-1] = n
4659 recount(pp)
4660 recount(p)
4661 if(s >= 3) {
4662 var ppp = n_stack[s-3]
4663 if(ppp.right === pp) {
4664 ppp.right = p
4665 } else {
4666 ppp.left = p
4667 }
4668 }
4669 break
4670 }
4671 } else {
4672 var y = pp.left
4673 if(y && y._color === RED) {
4674 //console.log("RLr")
4675 p._color = BLACK
4676 pp.left = repaint(BLACK, y)
4677 pp._color = RED
4678 s -= 1
4679 } else {
4680 //console.log("RLb")
4681 p.left = n.right
4682 pp._color = RED
4683 pp.right = n.left
4684 n._color = BLACK
4685 n.right = p
4686 n.left = pp
4687 n_stack[s-2] = n
4688 n_stack[s-1] = p
4689 recount(pp)
4690 recount(p)
4691 recount(n)
4692 if(s >= 3) {
4693 var ppp = n_stack[s-3]
4694 if(ppp.right === pp) {
4695 ppp.right = n
4696 } else {
4697 ppp.left = n
4698 }
4699 }
4700 break
4701 }
4702 }
4703 }
4704 }
4705 //Return new tree
4706 n_stack[0]._color = BLACK
4707 return new RedBlackTree(cmp, n_stack[0])
4708}
4709
4710
4711//Visit all nodes inorder
4712function doVisitFull(visit, node) {
4713 if(node.left) {
4714 var v = doVisitFull(visit, node.left)
4715 if(v) { return v }
4716 }
4717 var v = visit(node.key, node.value)
4718 if(v) { return v }
4719 if(node.right) {
4720 return doVisitFull(visit, node.right)
4721 }
4722}
4723
4724//Visit half nodes in order
4725function doVisitHalf(lo, compare, visit, node) {
4726 var l = compare(lo, node.key)
4727 if(l <= 0) {
4728 if(node.left) {
4729 var v = doVisitHalf(lo, compare, visit, node.left)
4730 if(v) { return v }
4731 }
4732 var v = visit(node.key, node.value)
4733 if(v) { return v }
4734 }
4735 if(node.right) {
4736 return doVisitHalf(lo, compare, visit, node.right)
4737 }
4738}
4739
4740//Visit all nodes within a range
4741function doVisit(lo, hi, compare, visit, node) {
4742 var l = compare(lo, node.key)
4743 var h = compare(hi, node.key)
4744 var v
4745 if(l <= 0) {
4746 if(node.left) {
4747 v = doVisit(lo, hi, compare, visit, node.left)
4748 if(v) { return v }
4749 }
4750 if(h > 0) {
4751 v = visit(node.key, node.value)
4752 if(v) { return v }
4753 }
4754 }
4755 if(h > 0 && node.right) {
4756 return doVisit(lo, hi, compare, visit, node.right)
4757 }
4758}
4759
4760
4761proto.forEach = function rbTreeForEach(visit, lo, hi) {
4762 if(!this.root) {
4763 return
4764 }
4765 switch(arguments.length) {
4766 case 1:
4767 return doVisitFull(visit, this.root)
4768 break
4769
4770 case 2:
4771 return doVisitHalf(lo, this._compare, visit, this.root)
4772 break
4773
4774 case 3:
4775 if(this._compare(lo, hi) >= 0) {
4776 return
4777 }
4778 return doVisit(lo, hi, this._compare, visit, this.root)
4779 break
4780 }
4781}
4782
4783//First item in list
4784Object.defineProperty(proto, "begin", {
4785 get: function() {
4786 var stack = []
4787 var n = this.root
4788 while(n) {
4789 stack.push(n)
4790 n = n.left
4791 }
4792 return new RedBlackTreeIterator(this, stack)
4793 }
4794})
4795
4796//Last item in list
4797Object.defineProperty(proto, "end", {
4798 get: function() {
4799 var stack = []
4800 var n = this.root
4801 while(n) {
4802 stack.push(n)
4803 n = n.right
4804 }
4805 return new RedBlackTreeIterator(this, stack)
4806 }
4807})
4808
4809//Find the ith item in the tree
4810proto.at = function(idx) {
4811 if(idx < 0) {
4812 return new RedBlackTreeIterator(this, [])
4813 }
4814 var n = this.root
4815 var stack = []
4816 while(true) {
4817 stack.push(n)
4818 if(n.left) {
4819 if(idx < n.left._count) {
4820 n = n.left
4821 continue
4822 }
4823 idx -= n.left._count
4824 }
4825 if(!idx) {
4826 return new RedBlackTreeIterator(this, stack)
4827 }
4828 idx -= 1
4829 if(n.right) {
4830 if(idx >= n.right._count) {
4831 break
4832 }
4833 n = n.right
4834 } else {
4835 break
4836 }
4837 }
4838 return new RedBlackTreeIterator(this, [])
4839}
4840
4841proto.ge = function(key) {
4842 var cmp = this._compare
4843 var n = this.root
4844 var stack = []
4845 var last_ptr = 0
4846 while(n) {
4847 var d = cmp(key, n.key)
4848 stack.push(n)
4849 if(d <= 0) {
4850 last_ptr = stack.length
4851 }
4852 if(d <= 0) {
4853 n = n.left
4854 } else {
4855 n = n.right
4856 }
4857 }
4858 stack.length = last_ptr
4859 return new RedBlackTreeIterator(this, stack)
4860}
4861
4862proto.gt = function(key) {
4863 var cmp = this._compare
4864 var n = this.root
4865 var stack = []
4866 var last_ptr = 0
4867 while(n) {
4868 var d = cmp(key, n.key)
4869 stack.push(n)
4870 if(d < 0) {
4871 last_ptr = stack.length
4872 }
4873 if(d < 0) {
4874 n = n.left
4875 } else {
4876 n = n.right
4877 }
4878 }
4879 stack.length = last_ptr
4880 return new RedBlackTreeIterator(this, stack)
4881}
4882
4883proto.lt = function(key) {
4884 var cmp = this._compare
4885 var n = this.root
4886 var stack = []
4887 var last_ptr = 0
4888 while(n) {
4889 var d = cmp(key, n.key)
4890 stack.push(n)
4891 if(d > 0) {
4892 last_ptr = stack.length
4893 }
4894 if(d <= 0) {
4895 n = n.left
4896 } else {
4897 n = n.right
4898 }
4899 }
4900 stack.length = last_ptr
4901 return new RedBlackTreeIterator(this, stack)
4902}
4903
4904proto.le = function(key) {
4905 var cmp = this._compare
4906 var n = this.root
4907 var stack = []
4908 var last_ptr = 0
4909 while(n) {
4910 var d = cmp(key, n.key)
4911 stack.push(n)
4912 if(d >= 0) {
4913 last_ptr = stack.length
4914 }
4915 if(d < 0) {
4916 n = n.left
4917 } else {
4918 n = n.right
4919 }
4920 }
4921 stack.length = last_ptr
4922 return new RedBlackTreeIterator(this, stack)
4923}
4924
4925//Finds the item with key if it exists
4926proto.find = function(key) {
4927 var cmp = this._compare
4928 var n = this.root
4929 var stack = []
4930 while(n) {
4931 var d = cmp(key, n.key)
4932 stack.push(n)
4933 if(d === 0) {
4934 return new RedBlackTreeIterator(this, stack)
4935 }
4936 if(d <= 0) {
4937 n = n.left
4938 } else {
4939 n = n.right
4940 }
4941 }
4942 return new RedBlackTreeIterator(this, [])
4943}
4944
4945//Removes item with key from tree
4946proto.remove = function(key) {
4947 var iter = this.find(key)
4948 if(iter) {
4949 return iter.remove()
4950 }
4951 return this
4952}
4953
4954//Returns the item at `key`
4955proto.get = function(key) {
4956 var cmp = this._compare
4957 var n = this.root
4958 while(n) {
4959 var d = cmp(key, n.key)
4960 if(d === 0) {
4961 return n.value
4962 }
4963 if(d <= 0) {
4964 n = n.left
4965 } else {
4966 n = n.right
4967 }
4968 }
4969 return
4970}
4971
4972//Iterator for red black tree
4973function RedBlackTreeIterator(tree, stack) {
4974 this.tree = tree
4975 this._stack = stack
4976}
4977
4978var iproto = RedBlackTreeIterator.prototype
4979
4980//Test if iterator is valid
4981Object.defineProperty(iproto, "valid", {
4982 get: function() {
4983 return this._stack.length > 0
4984 }
4985})
4986
4987//Node of the iterator
4988Object.defineProperty(iproto, "node", {
4989 get: function() {
4990 if(this._stack.length > 0) {
4991 return this._stack[this._stack.length-1]
4992 }
4993 return null
4994 },
4995 enumerable: true
4996})
4997
4998//Makes a copy of an iterator
4999iproto.clone = function() {
5000 return new RedBlackTreeIterator(this.tree, this._stack.slice())
5001}
5002
5003//Swaps two nodes
5004function swapNode(n, v) {
5005 n.key = v.key
5006 n.value = v.value
5007 n.left = v.left
5008 n.right = v.right
5009 n._color = v._color
5010 n._count = v._count
5011}
5012
5013//Fix up a double black node in a tree
5014function fixDoubleBlack(stack) {
5015 var n, p, s, z
5016 for(var i=stack.length-1; i>=0; --i) {
5017 n = stack[i]
5018 if(i === 0) {
5019 n._color = BLACK
5020 return
5021 }
5022 //console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key)
5023 p = stack[i-1]
5024 if(p.left === n) {
5025 //console.log("left child")
5026 s = p.right
5027 if(s.right && s.right._color === RED) {
5028 //console.log("case 1: right sibling child red")
5029 s = p.right = cloneNode(s)
5030 z = s.right = cloneNode(s.right)
5031 p.right = s.left
5032 s.left = p
5033 s.right = z
5034 s._color = p._color
5035 n._color = BLACK
5036 p._color = BLACK
5037 z._color = BLACK
5038 recount(p)
5039 recount(s)
5040 if(i > 1) {
5041 var pp = stack[i-2]
5042 if(pp.left === p) {
5043 pp.left = s
5044 } else {
5045 pp.right = s
5046 }
5047 }
5048 stack[i-1] = s
5049 return
5050 } else if(s.left && s.left._color === RED) {
5051 //console.log("case 1: left sibling child red")
5052 s = p.right = cloneNode(s)
5053 z = s.left = cloneNode(s.left)
5054 p.right = z.left
5055 s.left = z.right
5056 z.left = p
5057 z.right = s
5058 z._color = p._color
5059 p._color = BLACK
5060 s._color = BLACK
5061 n._color = BLACK
5062 recount(p)
5063 recount(s)
5064 recount(z)
5065 if(i > 1) {
5066 var pp = stack[i-2]
5067 if(pp.left === p) {
5068 pp.left = z
5069 } else {
5070 pp.right = z
5071 }
5072 }
5073 stack[i-1] = z
5074 return
5075 }
5076 if(s._color === BLACK) {
5077 if(p._color === RED) {
5078 //console.log("case 2: black sibling, red parent", p.right.value)
5079 p._color = BLACK
5080 p.right = repaint(RED, s)
5081 return
5082 } else {
5083 //console.log("case 2: black sibling, black parent", p.right.value)
5084 p.right = repaint(RED, s)
5085 continue
5086 }
5087 } else {
5088 //console.log("case 3: red sibling")
5089 s = cloneNode(s)
5090 p.right = s.left
5091 s.left = p
5092 s._color = p._color
5093 p._color = RED
5094 recount(p)
5095 recount(s)
5096 if(i > 1) {
5097 var pp = stack[i-2]
5098 if(pp.left === p) {
5099 pp.left = s
5100 } else {
5101 pp.right = s
5102 }
5103 }
5104 stack[i-1] = s
5105 stack[i] = p
5106 if(i+1 < stack.length) {
5107 stack[i+1] = n
5108 } else {
5109 stack.push(n)
5110 }
5111 i = i+2
5112 }
5113 } else {
5114 //console.log("right child")
5115 s = p.left
5116 if(s.left && s.left._color === RED) {
5117 //console.log("case 1: left sibling child red", p.value, p._color)
5118 s = p.left = cloneNode(s)
5119 z = s.left = cloneNode(s.left)
5120 p.left = s.right
5121 s.right = p
5122 s.left = z
5123 s._color = p._color
5124 n._color = BLACK
5125 p._color = BLACK
5126 z._color = BLACK
5127 recount(p)
5128 recount(s)
5129 if(i > 1) {
5130 var pp = stack[i-2]
5131 if(pp.right === p) {
5132 pp.right = s
5133 } else {
5134 pp.left = s
5135 }
5136 }
5137 stack[i-1] = s
5138 return
5139 } else if(s.right && s.right._color === RED) {
5140 //console.log("case 1: right sibling child red")
5141 s = p.left = cloneNode(s)
5142 z = s.right = cloneNode(s.right)
5143 p.left = z.right
5144 s.right = z.left
5145 z.right = p
5146 z.left = s
5147 z._color = p._color
5148 p._color = BLACK
5149 s._color = BLACK
5150 n._color = BLACK
5151 recount(p)
5152 recount(s)
5153 recount(z)
5154 if(i > 1) {
5155 var pp = stack[i-2]
5156 if(pp.right === p) {
5157 pp.right = z
5158 } else {
5159 pp.left = z
5160 }
5161 }
5162 stack[i-1] = z
5163 return
5164 }
5165 if(s._color === BLACK) {
5166 if(p._color === RED) {
5167 //console.log("case 2: black sibling, red parent")
5168 p._color = BLACK
5169 p.left = repaint(RED, s)
5170 return
5171 } else {
5172 //console.log("case 2: black sibling, black parent")
5173 p.left = repaint(RED, s)
5174 continue
5175 }
5176 } else {
5177 //console.log("case 3: red sibling")
5178 s = cloneNode(s)
5179 p.left = s.right
5180 s.right = p
5181 s._color = p._color
5182 p._color = RED
5183 recount(p)
5184 recount(s)
5185 if(i > 1) {
5186 var pp = stack[i-2]
5187 if(pp.right === p) {
5188 pp.right = s
5189 } else {
5190 pp.left = s
5191 }
5192 }
5193 stack[i-1] = s
5194 stack[i] = p
5195 if(i+1 < stack.length) {
5196 stack[i+1] = n
5197 } else {
5198 stack.push(n)
5199 }
5200 i = i+2
5201 }
5202 }
5203 }
5204}
5205
5206//Removes item at iterator from tree
5207iproto.remove = function() {
5208 var stack = this._stack
5209 if(stack.length === 0) {
5210 return this.tree
5211 }
5212 //First copy path to node
5213 var cstack = new Array(stack.length)
5214 var n = stack[stack.length-1]
5215 cstack[cstack.length-1] = new RBNode(n._color, n.key, n.value, n.left, n.right, n._count)
5216 for(var i=stack.length-2; i>=0; --i) {
5217 var n = stack[i]
5218 if(n.left === stack[i+1]) {
5219 cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count)
5220 } else {
5221 cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
5222 }
5223 }
5224
5225 //Get node
5226 n = cstack[cstack.length-1]
5227 //console.log("start remove: ", n.value)
5228
5229 //If not leaf, then swap with previous node
5230 if(n.left && n.right) {
5231 //console.log("moving to leaf")
5232
5233 //First walk to previous leaf
5234 var split = cstack.length
5235 n = n.left
5236 while(n.right) {
5237 cstack.push(n)
5238 n = n.right
5239 }
5240 //Copy path to leaf
5241 var v = cstack[split-1]
5242 cstack.push(new RBNode(n._color, v.key, v.value, n.left, n.right, n._count))
5243 cstack[split-1].key = n.key
5244 cstack[split-1].value = n.value
5245
5246 //Fix up stack
5247 for(var i=cstack.length-2; i>=split; --i) {
5248 n = cstack[i]
5249 cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
5250 }
5251 cstack[split-1].left = cstack[split]
5252 }
5253 //console.log("stack=", cstack.map(function(v) { return v.value }))
5254
5255 //Remove leaf node
5256 n = cstack[cstack.length-1]
5257 if(n._color === RED) {
5258 //Easy case: removing red leaf
5259 //console.log("RED leaf")
5260 var p = cstack[cstack.length-2]
5261 if(p.left === n) {
5262 p.left = null
5263 } else if(p.right === n) {
5264 p.right = null
5265 }
5266 cstack.pop()
5267 for(var i=0; i<cstack.length; ++i) {
5268 cstack[i]._count--
5269 }
5270 return new RedBlackTree(this.tree._compare, cstack[0])
5271 } else {
5272 if(n.left || n.right) {
5273 //Second easy case: Single child black parent
5274 //console.log("BLACK single child")
5275 if(n.left) {
5276 swapNode(n, n.left)
5277 } else if(n.right) {
5278 swapNode(n, n.right)
5279 }
5280 //Child must be red, so repaint it black to balance color
5281 n._color = BLACK
5282 for(var i=0; i<cstack.length-1; ++i) {
5283 cstack[i]._count--
5284 }
5285 return new RedBlackTree(this.tree._compare, cstack[0])
5286 } else if(cstack.length === 1) {
5287 //Third easy case: root
5288 //console.log("ROOT")
5289 return new RedBlackTree(this.tree._compare, null)
5290 } else {
5291 //Hard case: Repaint n, and then do some nasty stuff
5292 //console.log("BLACK leaf no children")
5293 for(var i=0; i<cstack.length; ++i) {
5294 cstack[i]._count--
5295 }
5296 var parent = cstack[cstack.length-2]
5297 fixDoubleBlack(cstack)
5298 //Fix up links
5299 if(parent.left === n) {
5300 parent.left = null
5301 } else {
5302 parent.right = null
5303 }
5304 }
5305 }
5306 return new RedBlackTree(this.tree._compare, cstack[0])
5307}
5308
5309//Returns key
5310Object.defineProperty(iproto, "key", {
5311 get: function() {
5312 if(this._stack.length > 0) {
5313 return this._stack[this._stack.length-1].key
5314 }
5315 return
5316 },
5317 enumerable: true
5318})
5319
5320//Returns value
5321Object.defineProperty(iproto, "value", {
5322 get: function() {
5323 if(this._stack.length > 0) {
5324 return this._stack[this._stack.length-1].value
5325 }
5326 return
5327 },
5328 enumerable: true
5329})
5330
5331
5332//Returns the position of this iterator in the sorted list
5333Object.defineProperty(iproto, "index", {
5334 get: function() {
5335 var idx = 0
5336 var stack = this._stack
5337 if(stack.length === 0) {
5338 var r = this.tree.root
5339 if(r) {
5340 return r._count
5341 }
5342 return 0
5343 } else if(stack[stack.length-1].left) {
5344 idx = stack[stack.length-1].left._count
5345 }
5346 for(var s=stack.length-2; s>=0; --s) {
5347 if(stack[s+1] === stack[s].right) {
5348 ++idx
5349 if(stack[s].left) {
5350 idx += stack[s].left._count
5351 }
5352 }
5353 }
5354 return idx
5355 },
5356 enumerable: true
5357})
5358
5359//Advances iterator to next element in list
5360iproto.next = function() {
5361 var stack = this._stack
5362 if(stack.length === 0) {
5363 return
5364 }
5365 var n = stack[stack.length-1]
5366 if(n.right) {
5367 n = n.right
5368 while(n) {
5369 stack.push(n)
5370 n = n.left
5371 }
5372 } else {
5373 stack.pop()
5374 while(stack.length > 0 && stack[stack.length-1].right === n) {
5375 n = stack[stack.length-1]
5376 stack.pop()
5377 }
5378 }
5379}
5380
5381//Checks if iterator is at end of tree
5382Object.defineProperty(iproto, "hasNext", {
5383 get: function() {
5384 var stack = this._stack
5385 if(stack.length === 0) {
5386 return false
5387 }
5388 if(stack[stack.length-1].right) {
5389 return true
5390 }
5391 for(var s=stack.length-1; s>0; --s) {
5392 if(stack[s-1].left === stack[s]) {
5393 return true
5394 }
5395 }
5396 return false
5397 }
5398})
5399
5400//Update value
5401iproto.update = function(value) {
5402 var stack = this._stack
5403 if(stack.length === 0) {
5404 throw new Error("Can't update empty node!")
5405 }
5406 var cstack = new Array(stack.length)
5407 var n = stack[stack.length-1]
5408 cstack[cstack.length-1] = new RBNode(n._color, n.key, value, n.left, n.right, n._count)
5409 for(var i=stack.length-2; i>=0; --i) {
5410 n = stack[i]
5411 if(n.left === stack[i+1]) {
5412 cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count)
5413 } else {
5414 cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
5415 }
5416 }
5417 return new RedBlackTree(this.tree._compare, cstack[0])
5418}
5419
5420//Moves iterator backward one element
5421iproto.prev = function() {
5422 var stack = this._stack
5423 if(stack.length === 0) {
5424 return
5425 }
5426 var n = stack[stack.length-1]
5427 if(n.left) {
5428 n = n.left
5429 while(n) {
5430 stack.push(n)
5431 n = n.right
5432 }
5433 } else {
5434 stack.pop()
5435 while(stack.length > 0 && stack[stack.length-1].left === n) {
5436 n = stack[stack.length-1]
5437 stack.pop()
5438 }
5439 }
5440}
5441
5442//Checks if iterator is at start of tree
5443Object.defineProperty(iproto, "hasPrev", {
5444 get: function() {
5445 var stack = this._stack
5446 if(stack.length === 0) {
5447 return false
5448 }
5449 if(stack[stack.length-1].left) {
5450 return true
5451 }
5452 for(var s=stack.length-1; s>0; --s) {
5453 if(stack[s-1].right === stack[s]) {
5454 return true
5455 }
5456 }
5457 return false
5458 }
5459})
5460
5461//Default comparison function
5462function defaultCompare(a, b) {
5463 if(a < b) {
5464 return -1
5465 }
5466 if(a > b) {
5467 return 1
5468 }
5469 return 0
5470}
5471
5472//Build a tree
5473function createRBTree(compare) {
5474 return new RedBlackTree(compare || defaultCompare, null)
5475}
5476},{}],16:[function(_dereq_,module,exports){
5477exports.read = function (buffer, offset, isLE, mLen, nBytes) {
5478 var e, m
5479 var eLen = (nBytes * 8) - mLen - 1
5480 var eMax = (1 << eLen) - 1
5481 var eBias = eMax >> 1
5482 var nBits = -7
5483 var i = isLE ? (nBytes - 1) : 0
5484 var d = isLE ? -1 : 1
5485 var s = buffer[offset + i]
5486
5487 i += d
5488
5489 e = s & ((1 << (-nBits)) - 1)
5490 s >>= (-nBits)
5491 nBits += eLen
5492 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
5493
5494 m = e & ((1 << (-nBits)) - 1)
5495 e >>= (-nBits)
5496 nBits += mLen
5497 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
5498
5499 if (e === 0) {
5500 e = 1 - eBias
5501 } else if (e === eMax) {
5502 return m ? NaN : ((s ? -1 : 1) * Infinity)
5503 } else {
5504 m = m + Math.pow(2, mLen)
5505 e = e - eBias
5506 }
5507 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
5508}
5509
5510exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
5511 var e, m, c
5512 var eLen = (nBytes * 8) - mLen - 1
5513 var eMax = (1 << eLen) - 1
5514 var eBias = eMax >> 1
5515 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
5516 var i = isLE ? 0 : (nBytes - 1)
5517 var d = isLE ? 1 : -1
5518 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
5519
5520 value = Math.abs(value)
5521
5522 if (isNaN(value) || value === Infinity) {
5523 m = isNaN(value) ? 1 : 0
5524 e = eMax
5525 } else {
5526 e = Math.floor(Math.log(value) / Math.LN2)
5527 if (value * (c = Math.pow(2, -e)) < 1) {
5528 e--
5529 c *= 2
5530 }
5531 if (e + eBias >= 1) {
5532 value += rt / c
5533 } else {
5534 value += rt * Math.pow(2, 1 - eBias)
5535 }
5536 if (value * c >= 2) {
5537 e++
5538 c /= 2
5539 }
5540
5541 if (e + eBias >= eMax) {
5542 m = 0
5543 e = eMax
5544 } else if (e + eBias >= 1) {
5545 m = ((value * c) - 1) * Math.pow(2, mLen)
5546 e = e + eBias
5547 } else {
5548 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
5549 e = 0
5550 }
5551 }
5552
5553 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
5554
5555 e = (e << mLen) | m
5556 eLen += mLen
5557 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
5558
5559 buffer[offset + i - d] |= s * 128
5560}
5561
5562},{}],17:[function(_dereq_,module,exports){
5563(function (global){
5564'use strict';
5565var Mutation = global.MutationObserver || global.WebKitMutationObserver;
5566
5567var scheduleDrain;
5568
5569{
5570 if (Mutation) {
5571 var called = 0;
5572 var observer = new Mutation(nextTick);
5573 var element = global.document.createTextNode('');
5574 observer.observe(element, {
5575 characterData: true
5576 });
5577 scheduleDrain = function () {
5578 element.data = (called = ++called % 2);
5579 };
5580 } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
5581 var channel = new global.MessageChannel();
5582 channel.port1.onmessage = nextTick;
5583 scheduleDrain = function () {
5584 channel.port2.postMessage(0);
5585 };
5586 } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
5587 scheduleDrain = function () {
5588
5589 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
5590 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
5591 var scriptEl = global.document.createElement('script');
5592 scriptEl.onreadystatechange = function () {
5593 nextTick();
5594
5595 scriptEl.onreadystatechange = null;
5596 scriptEl.parentNode.removeChild(scriptEl);
5597 scriptEl = null;
5598 };
5599 global.document.documentElement.appendChild(scriptEl);
5600 };
5601 } else {
5602 scheduleDrain = function () {
5603 setTimeout(nextTick, 0);
5604 };
5605 }
5606}
5607
5608var draining;
5609var queue = [];
5610//named nextTick for less confusing stack traces
5611function nextTick() {
5612 draining = true;
5613 var i, oldQueue;
5614 var len = queue.length;
5615 while (len) {
5616 oldQueue = queue;
5617 queue = [];
5618 i = -1;
5619 while (++i < len) {
5620 oldQueue[i]();
5621 }
5622 len = queue.length;
5623 }
5624 draining = false;
5625}
5626
5627module.exports = immediate;
5628function immediate(task) {
5629 if (queue.push(task) === 1 && !draining) {
5630 scheduleDrain();
5631 }
5632}
5633
5634}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5635},{}],18:[function(_dereq_,module,exports){
5636if (typeof Object.create === 'function') {
5637 // implementation from standard node.js 'util' module
5638 module.exports = function inherits(ctor, superCtor) {
5639 if (superCtor) {
5640 ctor.super_ = superCtor
5641 ctor.prototype = Object.create(superCtor.prototype, {
5642 constructor: {
5643 value: ctor,
5644 enumerable: false,
5645 writable: true,
5646 configurable: true
5647 }
5648 })
5649 }
5650 };
5651} else {
5652 // old school shim for old browsers
5653 module.exports = function inherits(ctor, superCtor) {
5654 if (superCtor) {
5655 ctor.super_ = superCtor
5656 var TempCtor = function () {}
5657 TempCtor.prototype = superCtor.prototype
5658 ctor.prototype = new TempCtor()
5659 ctor.prototype.constructor = ctor
5660 }
5661 }
5662}
5663
5664},{}],19:[function(_dereq_,module,exports){
5665/*!
5666 * Determine if an object is a Buffer
5667 *
5668 * @author Feross Aboukhadijeh <https://feross.org>
5669 * @license MIT
5670 */
5671
5672// The _isBuffer check is for Safari 5-7 support, because it's missing
5673// Object.prototype.constructor. Remove this eventually
5674module.exports = function (obj) {
5675 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
5676}
5677
5678function isBuffer (obj) {
5679 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
5680}
5681
5682// For Node v0.10 support. Remove this eventually.
5683function isSlowBuffer (obj) {
5684 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
5685}
5686
5687},{}],20:[function(_dereq_,module,exports){
5688module.exports = Array.isArray || function (arr) {
5689 return Object.prototype.toString.call(arr) == '[object Array]';
5690};
5691
5692},{}],21:[function(_dereq_,module,exports){
5693var encodings = _dereq_(22)
5694
5695module.exports = Codec
5696
5697function Codec (opts) {
5698 if (!(this instanceof Codec)) {
5699 return new Codec(opts)
5700 }
5701 this.opts = opts || {}
5702 this.encodings = encodings
5703}
5704
5705Codec.prototype._encoding = function (encoding) {
5706 if (typeof encoding === 'string') encoding = encodings[encoding]
5707 if (!encoding) encoding = encodings.id
5708 return encoding
5709}
5710
5711Codec.prototype._keyEncoding = function (opts, batchOpts) {
5712 return this._encoding((batchOpts && batchOpts.keyEncoding) ||
5713 (opts && opts.keyEncoding) ||
5714 this.opts.keyEncoding)
5715}
5716
5717Codec.prototype._valueEncoding = function (opts, batchOpts) {
5718 return this._encoding((batchOpts && (batchOpts.valueEncoding || batchOpts.encoding)) ||
5719 (opts && (opts.valueEncoding || opts.encoding)) ||
5720 (this.opts.valueEncoding || this.opts.encoding))
5721}
5722
5723Codec.prototype.encodeKey = function (key, opts, batchOpts) {
5724 return this._keyEncoding(opts, batchOpts).encode(key)
5725}
5726
5727Codec.prototype.encodeValue = function (value, opts, batchOpts) {
5728 return this._valueEncoding(opts, batchOpts).encode(value)
5729}
5730
5731Codec.prototype.decodeKey = function (key, opts) {
5732 return this._keyEncoding(opts).decode(key)
5733}
5734
5735Codec.prototype.decodeValue = function (value, opts) {
5736 return this._valueEncoding(opts).decode(value)
5737}
5738
5739Codec.prototype.encodeBatch = function (ops, opts) {
5740 var self = this
5741
5742 return ops.map(function (_op) {
5743 var op = {
5744 type: _op.type,
5745 key: self.encodeKey(_op.key, opts, _op)
5746 }
5747 if (self.keyAsBuffer(opts, _op)) op.keyEncoding = 'binary'
5748 if (_op.prefix) op.prefix = _op.prefix
5749 if ('value' in _op) {
5750 op.value = self.encodeValue(_op.value, opts, _op)
5751 if (self.valueAsBuffer(opts, _op)) op.valueEncoding = 'binary'
5752 }
5753 return op
5754 })
5755}
5756
5757var ltgtKeys = ['lt', 'gt', 'lte', 'gte', 'start', 'end']
5758
5759Codec.prototype.encodeLtgt = function (ltgt) {
5760 var self = this
5761 var ret = {}
5762 Object.keys(ltgt).forEach(function (key) {
5763 ret[key] = ltgtKeys.indexOf(key) > -1
5764 ? self.encodeKey(ltgt[key], ltgt)
5765 : ltgt[key]
5766 })
5767 return ret
5768}
5769
5770Codec.prototype.createStreamDecoder = function (opts) {
5771 var self = this
5772
5773 if (opts.keys && opts.values) {
5774 return function (key, value) {
5775 return {
5776 key: self.decodeKey(key, opts),
5777 value: self.decodeValue(value, opts)
5778 }
5779 }
5780 } else if (opts.keys) {
5781 return function (key) {
5782 return self.decodeKey(key, opts)
5783 }
5784 } else if (opts.values) {
5785 return function (_, value) {
5786 return self.decodeValue(value, opts)
5787 }
5788 } else {
5789 return function () {}
5790 }
5791}
5792
5793Codec.prototype.keyAsBuffer = function (opts) {
5794 return this._keyEncoding(opts).buffer
5795}
5796
5797Codec.prototype.valueAsBuffer = function (opts) {
5798 return this._valueEncoding(opts).buffer
5799}
5800
5801},{"22":22}],22:[function(_dereq_,module,exports){
5802(function (Buffer){
5803exports.utf8 = exports['utf-8'] = {
5804 encode: function (data) {
5805 return isBinary(data) ? data : String(data)
5806 },
5807 decode: identity,
5808 buffer: false,
5809 type: 'utf8'
5810}
5811
5812exports.json = {
5813 encode: JSON.stringify,
5814 decode: JSON.parse,
5815 buffer: false,
5816 type: 'json'
5817}
5818
5819exports.binary = {
5820 encode: function (data) {
5821 return isBinary(data) ? data : Buffer.from(data)
5822 },
5823 decode: identity,
5824 buffer: true,
5825 type: 'binary'
5826}
5827
5828exports.none = {
5829 encode: identity,
5830 decode: identity,
5831 buffer: false,
5832 type: 'id'
5833}
5834
5835exports.id = exports.none
5836
5837var bufferEncodings = [
5838 'hex',
5839 'ascii',
5840 'base64',
5841 'ucs2',
5842 'ucs-2',
5843 'utf16le',
5844 'utf-16le'
5845]
5846
5847bufferEncodings.forEach(function (type) {
5848 exports[type] = {
5849 encode: function (data) {
5850 return isBinary(data) ? data : Buffer.from(data, type)
5851 },
5852 decode: function (buffer) {
5853 return buffer.toString(type)
5854 },
5855 buffer: true,
5856 type: type
5857 }
5858})
5859
5860function identity (value) {
5861 return value
5862}
5863
5864function isBinary (data) {
5865 return data === undefined || data === null || Buffer.isBuffer(data)
5866}
5867
5868}).call(this,_dereq_(9).Buffer)
5869},{"9":9}],23:[function(_dereq_,module,exports){
5870var createError = _dereq_(13).create
5871var LevelUPError = createError('LevelUPError')
5872var NotFoundError = createError('NotFoundError', LevelUPError)
5873
5874NotFoundError.prototype.notFound = true
5875NotFoundError.prototype.status = 404
5876
5877module.exports = {
5878 LevelUPError: LevelUPError,
5879 InitializationError: createError('InitializationError', LevelUPError),
5880 OpenError: createError('OpenError', LevelUPError),
5881 ReadError: createError('ReadError', LevelUPError),
5882 WriteError: createError('WriteError', LevelUPError),
5883 NotFoundError: NotFoundError,
5884 EncodingError: createError('EncodingError', LevelUPError)
5885}
5886
5887},{"13":13}],24:[function(_dereq_,module,exports){
5888var inherits = _dereq_(18)
5889var Readable = _dereq_(39).Readable
5890var extend = _dereq_(40)
5891
5892module.exports = ReadStream
5893inherits(ReadStream, Readable)
5894
5895function ReadStream (iterator, options) {
5896 if (!(this instanceof ReadStream)) return new ReadStream(iterator, options)
5897 options = options || {}
5898 Readable.call(this, extend(options, {
5899 objectMode: true
5900 }))
5901 this._iterator = iterator
5902 this._options = options
5903 this.on('end', this.destroy.bind(this, null, null))
5904}
5905
5906ReadStream.prototype._read = function () {
5907 var self = this
5908 var options = this._options
5909 if (this.destroyed) return
5910
5911 this._iterator.next(function (err, key, value) {
5912 if (self.destroyed) return
5913 if (err) return self.destroy(err)
5914
5915 if (key === undefined && value === undefined) {
5916 self.push(null)
5917 } else if (options.keys !== false && options.values === false) {
5918 self.push(key)
5919 } else if (options.keys === false && options.values !== false) {
5920 self.push(value)
5921 } else {
5922 self.push({ key: key, value: value })
5923 }
5924 })
5925}
5926
5927ReadStream.prototype._destroy = function (err, callback) {
5928 this._iterator.end(function (err2) {
5929 callback(err || err2)
5930 })
5931}
5932
5933},{"18":18,"39":39,"40":40}],25:[function(_dereq_,module,exports){
5934'use strict';
5935
5936function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
5937
5938var codes = {};
5939
5940function createErrorType(code, message, Base) {
5941 if (!Base) {
5942 Base = Error;
5943 }
5944
5945 function getMessage(arg1, arg2, arg3) {
5946 if (typeof message === 'string') {
5947 return message;
5948 } else {
5949 return message(arg1, arg2, arg3);
5950 }
5951 }
5952
5953 var NodeError =
5954 /*#__PURE__*/
5955 function (_Base) {
5956 _inheritsLoose(NodeError, _Base);
5957
5958 function NodeError(arg1, arg2, arg3) {
5959 return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
5960 }
5961
5962 return NodeError;
5963 }(Base);
5964
5965 NodeError.prototype.name = Base.name;
5966 NodeError.prototype.code = code;
5967 codes[code] = NodeError;
5968} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
5969
5970
5971function oneOf(expected, thing) {
5972 if (Array.isArray(expected)) {
5973 var len = expected.length;
5974 expected = expected.map(function (i) {
5975 return String(i);
5976 });
5977
5978 if (len > 2) {
5979 return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
5980 } else if (len === 2) {
5981 return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
5982 } else {
5983 return "of ".concat(thing, " ").concat(expected[0]);
5984 }
5985 } else {
5986 return "of ".concat(thing, " ").concat(String(expected));
5987 }
5988} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
5989
5990
5991function startsWith(str, search, pos) {
5992 return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
5993} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
5994
5995
5996function endsWith(str, search, this_len) {
5997 if (this_len === undefined || this_len > str.length) {
5998 this_len = str.length;
5999 }
6000
6001 return str.substring(this_len - search.length, this_len) === search;
6002} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
6003
6004
6005function includes(str, search, start) {
6006 if (typeof start !== 'number') {
6007 start = 0;
6008 }
6009
6010 if (start + search.length > str.length) {
6011 return false;
6012 } else {
6013 return str.indexOf(search, start) !== -1;
6014 }
6015}
6016
6017createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
6018 return 'The value "' + value + '" is invalid for option "' + name + '"';
6019}, TypeError);
6020createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
6021 // determiner: 'must be' or 'must not be'
6022 var determiner;
6023
6024 if (typeof expected === 'string' && startsWith(expected, 'not ')) {
6025 determiner = 'must not be';
6026 expected = expected.replace(/^not /, '');
6027 } else {
6028 determiner = 'must be';
6029 }
6030
6031 var msg;
6032
6033 if (endsWith(name, ' argument')) {
6034 // For cases like 'first argument'
6035 msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
6036 } else {
6037 var type = includes(name, '.') ? 'property' : 'argument';
6038 msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
6039 }
6040
6041 msg += ". Received type ".concat(typeof actual);
6042 return msg;
6043}, TypeError);
6044createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
6045createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
6046 return 'The ' + name + ' method is not implemented';
6047});
6048createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
6049createErrorType('ERR_STREAM_DESTROYED', function (name) {
6050 return 'Cannot call ' + name + ' after a stream was destroyed';
6051});
6052createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
6053createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
6054createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
6055createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
6056createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
6057 return 'Unknown encoding: ' + arg;
6058}, TypeError);
6059createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
6060module.exports.codes = codes;
6061
6062},{}],26:[function(_dereq_,module,exports){
6063(function (process){
6064// Copyright Joyent, Inc. and other Node contributors.
6065//
6066// Permission is hereby granted, free of charge, to any person obtaining a
6067// copy of this software and associated documentation files (the
6068// "Software"), to deal in the Software without restriction, including
6069// without limitation the rights to use, copy, modify, merge, publish,
6070// distribute, sublicense, and/or sell copies of the Software, and to permit
6071// persons to whom the Software is furnished to do so, subject to the
6072// following conditions:
6073//
6074// The above copyright notice and this permission notice shall be included
6075// in all copies or substantial portions of the Software.
6076//
6077// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6078// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6079// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6080// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6081// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6082// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6083// USE OR OTHER DEALINGS IN THE SOFTWARE.
6084// a duplex stream is just a stream that is both readable and writable.
6085// Since JS doesn't have multiple prototypal inheritance, this class
6086// prototypally inherits from Readable, and then parasitically from
6087// Writable.
6088'use strict';
6089/*<replacement>*/
6090
6091var objectKeys = Object.keys || function (obj) {
6092 var keys = [];
6093
6094 for (var key in obj) {
6095 keys.push(key);
6096 }
6097
6098 return keys;
6099};
6100/*</replacement>*/
6101
6102
6103module.exports = Duplex;
6104
6105var Readable = _dereq_(28);
6106
6107var Writable = _dereq_(30);
6108
6109_dereq_(18)(Duplex, Readable);
6110
6111{
6112 // Allow the keys array to be GC'ed.
6113 var keys = objectKeys(Writable.prototype);
6114
6115 for (var v = 0; v < keys.length; v++) {
6116 var method = keys[v];
6117 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
6118 }
6119}
6120
6121function Duplex(options) {
6122 if (!(this instanceof Duplex)) return new Duplex(options);
6123 Readable.call(this, options);
6124 Writable.call(this, options);
6125 this.allowHalfOpen = true;
6126
6127 if (options) {
6128 if (options.readable === false) this.readable = false;
6129 if (options.writable === false) this.writable = false;
6130
6131 if (options.allowHalfOpen === false) {
6132 this.allowHalfOpen = false;
6133 this.once('end', onend);
6134 }
6135 }
6136}
6137
6138Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
6139 // making it explicit this property is not enumerable
6140 // because otherwise some prototype manipulation in
6141 // userland will fail
6142 enumerable: false,
6143 get: function get() {
6144 return this._writableState.highWaterMark;
6145 }
6146});
6147Object.defineProperty(Duplex.prototype, 'writableBuffer', {
6148 // making it explicit this property is not enumerable
6149 // because otherwise some prototype manipulation in
6150 // userland will fail
6151 enumerable: false,
6152 get: function get() {
6153 return this._writableState && this._writableState.getBuffer();
6154 }
6155});
6156Object.defineProperty(Duplex.prototype, 'writableLength', {
6157 // making it explicit this property is not enumerable
6158 // because otherwise some prototype manipulation in
6159 // userland will fail
6160 enumerable: false,
6161 get: function get() {
6162 return this._writableState.length;
6163 }
6164}); // the no-half-open enforcer
6165
6166function onend() {
6167 // If the writable side ended, then we're ok.
6168 if (this._writableState.ended) return; // no more data can be written.
6169 // But allow more writes to happen in this tick.
6170
6171 process.nextTick(onEndNT, this);
6172}
6173
6174function onEndNT(self) {
6175 self.end();
6176}
6177
6178Object.defineProperty(Duplex.prototype, 'destroyed', {
6179 // making it explicit this property is not enumerable
6180 // because otherwise some prototype manipulation in
6181 // userland will fail
6182 enumerable: false,
6183 get: function get() {
6184 if (this._readableState === undefined || this._writableState === undefined) {
6185 return false;
6186 }
6187
6188 return this._readableState.destroyed && this._writableState.destroyed;
6189 },
6190 set: function set(value) {
6191 // we ignore the value if the stream
6192 // has not been initialized yet
6193 if (this._readableState === undefined || this._writableState === undefined) {
6194 return;
6195 } // backward compatibility, the user is explicitly
6196 // managing destroyed
6197
6198
6199 this._readableState.destroyed = value;
6200 this._writableState.destroyed = value;
6201 }
6202});
6203}).call(this,_dereq_(70))
6204},{"18":18,"28":28,"30":30,"70":70}],27:[function(_dereq_,module,exports){
6205// Copyright Joyent, Inc. and other Node contributors.
6206//
6207// Permission is hereby granted, free of charge, to any person obtaining a
6208// copy of this software and associated documentation files (the
6209// "Software"), to deal in the Software without restriction, including
6210// without limitation the rights to use, copy, modify, merge, publish,
6211// distribute, sublicense, and/or sell copies of the Software, and to permit
6212// persons to whom the Software is furnished to do so, subject to the
6213// following conditions:
6214//
6215// The above copyright notice and this permission notice shall be included
6216// in all copies or substantial portions of the Software.
6217//
6218// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6219// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6220// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6221// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6222// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6223// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6224// USE OR OTHER DEALINGS IN THE SOFTWARE.
6225// a passthrough stream.
6226// basically just the most minimal sort of Transform stream.
6227// Every written chunk gets output as-is.
6228'use strict';
6229
6230module.exports = PassThrough;
6231
6232var Transform = _dereq_(29);
6233
6234_dereq_(18)(PassThrough, Transform);
6235
6236function PassThrough(options) {
6237 if (!(this instanceof PassThrough)) return new PassThrough(options);
6238 Transform.call(this, options);
6239}
6240
6241PassThrough.prototype._transform = function (chunk, encoding, cb) {
6242 cb(null, chunk);
6243};
6244},{"18":18,"29":29}],28:[function(_dereq_,module,exports){
6245(function (process,global){
6246// Copyright Joyent, Inc. and other Node contributors.
6247//
6248// Permission is hereby granted, free of charge, to any person obtaining a
6249// copy of this software and associated documentation files (the
6250// "Software"), to deal in the Software without restriction, including
6251// without limitation the rights to use, copy, modify, merge, publish,
6252// distribute, sublicense, and/or sell copies of the Software, and to permit
6253// persons to whom the Software is furnished to do so, subject to the
6254// following conditions:
6255//
6256// The above copyright notice and this permission notice shall be included
6257// in all copies or substantial portions of the Software.
6258//
6259// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6260// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6261// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6262// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6263// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6264// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6265// USE OR OTHER DEALINGS IN THE SOFTWARE.
6266'use strict';
6267
6268module.exports = Readable;
6269/*<replacement>*/
6270
6271var Duplex;
6272/*</replacement>*/
6273
6274Readable.ReadableState = ReadableState;
6275/*<replacement>*/
6276
6277var EE = _dereq_(14).EventEmitter;
6278
6279var EElistenerCount = function EElistenerCount(emitter, type) {
6280 return emitter.listeners(type).length;
6281};
6282/*</replacement>*/
6283
6284/*<replacement>*/
6285
6286
6287var Stream = _dereq_(38);
6288/*</replacement>*/
6289
6290
6291var Buffer = _dereq_(9).Buffer;
6292
6293var OurUint8Array = global.Uint8Array || function () {};
6294
6295function _uint8ArrayToBuffer(chunk) {
6296 return Buffer.from(chunk);
6297}
6298
6299function _isUint8Array(obj) {
6300 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
6301}
6302/*<replacement>*/
6303
6304
6305var debugUtil = _dereq_(7);
6306
6307var debug;
6308
6309if (debugUtil && debugUtil.debuglog) {
6310 debug = debugUtil.debuglog('stream');
6311} else {
6312 debug = function debug() {};
6313}
6314/*</replacement>*/
6315
6316
6317var BufferList = _dereq_(32);
6318
6319var destroyImpl = _dereq_(33);
6320
6321var _require = _dereq_(37),
6322 getHighWaterMark = _require.getHighWaterMark;
6323
6324var _require$codes = _dereq_(25).codes,
6325 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
6326 ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
6327 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
6328 ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.
6329
6330
6331var StringDecoder;
6332var createReadableStreamAsyncIterator;
6333var from;
6334
6335_dereq_(18)(Readable, Stream);
6336
6337var errorOrDestroy = destroyImpl.errorOrDestroy;
6338var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
6339
6340function prependListener(emitter, event, fn) {
6341 // Sadly this is not cacheable as some libraries bundle their own
6342 // event emitter implementation with them.
6343 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any
6344 // userland ones. NEVER DO THIS. This is here only because this code needs
6345 // to continue to work with older versions of Node.js that do not include
6346 // the prependListener() method. The goal is to eventually remove this hack.
6347
6348 if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
6349}
6350
6351function ReadableState(options, stream, isDuplex) {
6352 Duplex = Duplex || _dereq_(26);
6353 options = options || {}; // Duplex streams are both readable and writable, but share
6354 // the same options object.
6355 // However, some cases require setting options to different
6356 // values for the readable and the writable sides of the duplex stream.
6357 // These options can be provided separately as readableXXX and writableXXX.
6358
6359 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to
6360 // make all the buffer merging and length checks go away
6361
6362 this.objectMode = !!options.objectMode;
6363 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
6364 // Note: 0 is a valid value, means "don't call _read preemptively ever"
6365
6366 this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the
6367 // linked list can remove elements from the beginning faster than
6368 // array.shift()
6369
6370 this.buffer = new BufferList();
6371 this.length = 0;
6372 this.pipes = null;
6373 this.pipesCount = 0;
6374 this.flowing = null;
6375 this.ended = false;
6376 this.endEmitted = false;
6377 this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted
6378 // immediately, or on a later tick. We set this to true at first, because
6379 // any actions that shouldn't happen until "later" should generally also
6380 // not happen before the first read call.
6381
6382 this.sync = true; // whenever we return null, then we set a flag to say
6383 // that we're awaiting a 'readable' event emission.
6384
6385 this.needReadable = false;
6386 this.emittedReadable = false;
6387 this.readableListening = false;
6388 this.resumeScheduled = false;
6389 this.paused = true; // Should close be emitted on destroy. Defaults to true.
6390
6391 this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')
6392
6393 this.autoDestroy = !!options.autoDestroy; // has it been destroyed
6394
6395 this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string
6396 // encoding is 'binary' so we have to make this configurable.
6397 // Everything else in the universe uses 'utf8', though.
6398
6399 this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s
6400
6401 this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled
6402
6403 this.readingMore = false;
6404 this.decoder = null;
6405 this.encoding = null;
6406
6407 if (options.encoding) {
6408 if (!StringDecoder) StringDecoder = _dereq_(98).StringDecoder;
6409 this.decoder = new StringDecoder(options.encoding);
6410 this.encoding = options.encoding;
6411 }
6412}
6413
6414function Readable(options) {
6415 Duplex = Duplex || _dereq_(26);
6416 if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside
6417 // the ReadableState constructor, at least with V8 6.5
6418
6419 var isDuplex = this instanceof Duplex;
6420 this._readableState = new ReadableState(options, this, isDuplex); // legacy
6421
6422 this.readable = true;
6423
6424 if (options) {
6425 if (typeof options.read === 'function') this._read = options.read;
6426 if (typeof options.destroy === 'function') this._destroy = options.destroy;
6427 }
6428
6429 Stream.call(this);
6430}
6431
6432Object.defineProperty(Readable.prototype, 'destroyed', {
6433 // making it explicit this property is not enumerable
6434 // because otherwise some prototype manipulation in
6435 // userland will fail
6436 enumerable: false,
6437 get: function get() {
6438 if (this._readableState === undefined) {
6439 return false;
6440 }
6441
6442 return this._readableState.destroyed;
6443 },
6444 set: function set(value) {
6445 // we ignore the value if the stream
6446 // has not been initialized yet
6447 if (!this._readableState) {
6448 return;
6449 } // backward compatibility, the user is explicitly
6450 // managing destroyed
6451
6452
6453 this._readableState.destroyed = value;
6454 }
6455});
6456Readable.prototype.destroy = destroyImpl.destroy;
6457Readable.prototype._undestroy = destroyImpl.undestroy;
6458
6459Readable.prototype._destroy = function (err, cb) {
6460 cb(err);
6461}; // Manually shove something into the read() buffer.
6462// This returns true if the highWaterMark has not been hit yet,
6463// similar to how Writable.write() returns true if you should
6464// write() some more.
6465
6466
6467Readable.prototype.push = function (chunk, encoding) {
6468 var state = this._readableState;
6469 var skipChunkCheck;
6470
6471 if (!state.objectMode) {
6472 if (typeof chunk === 'string') {
6473 encoding = encoding || state.defaultEncoding;
6474
6475 if (encoding !== state.encoding) {
6476 chunk = Buffer.from(chunk, encoding);
6477 encoding = '';
6478 }
6479
6480 skipChunkCheck = true;
6481 }
6482 } else {
6483 skipChunkCheck = true;
6484 }
6485
6486 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
6487}; // Unshift should *always* be something directly out of read()
6488
6489
6490Readable.prototype.unshift = function (chunk) {
6491 return readableAddChunk(this, chunk, null, true, false);
6492};
6493
6494function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
6495 debug('readableAddChunk', chunk);
6496 var state = stream._readableState;
6497
6498 if (chunk === null) {
6499 state.reading = false;
6500 onEofChunk(stream, state);
6501 } else {
6502 var er;
6503 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
6504
6505 if (er) {
6506 errorOrDestroy(stream, er);
6507 } else if (state.objectMode || chunk && chunk.length > 0) {
6508 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
6509 chunk = _uint8ArrayToBuffer(chunk);
6510 }
6511
6512 if (addToFront) {
6513 if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
6514 } else if (state.ended) {
6515 errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
6516 } else if (state.destroyed) {
6517 return false;
6518 } else {
6519 state.reading = false;
6520
6521 if (state.decoder && !encoding) {
6522 chunk = state.decoder.write(chunk);
6523 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
6524 } else {
6525 addChunk(stream, state, chunk, false);
6526 }
6527 }
6528 } else if (!addToFront) {
6529 state.reading = false;
6530 maybeReadMore(stream, state);
6531 }
6532 } // We can push more data if we are below the highWaterMark.
6533 // Also, if we have no data yet, we can stand some more bytes.
6534 // This is to work around cases where hwm=0, such as the repl.
6535
6536
6537 return !state.ended && (state.length < state.highWaterMark || state.length === 0);
6538}
6539
6540function addChunk(stream, state, chunk, addToFront) {
6541 if (state.flowing && state.length === 0 && !state.sync) {
6542 state.awaitDrain = 0;
6543 stream.emit('data', chunk);
6544 } else {
6545 // update the buffer info.
6546 state.length += state.objectMode ? 1 : chunk.length;
6547 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
6548 if (state.needReadable) emitReadable(stream);
6549 }
6550
6551 maybeReadMore(stream, state);
6552}
6553
6554function chunkInvalid(state, chunk) {
6555 var er;
6556
6557 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
6558 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
6559 }
6560
6561 return er;
6562}
6563
6564Readable.prototype.isPaused = function () {
6565 return this._readableState.flowing === false;
6566}; // backwards compatibility.
6567
6568
6569Readable.prototype.setEncoding = function (enc) {
6570 if (!StringDecoder) StringDecoder = _dereq_(98).StringDecoder;
6571 var decoder = new StringDecoder(enc);
6572 this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8
6573
6574 this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:
6575
6576 var p = this._readableState.buffer.head;
6577 var content = '';
6578
6579 while (p !== null) {
6580 content += decoder.write(p.data);
6581 p = p.next;
6582 }
6583
6584 this._readableState.buffer.clear();
6585
6586 if (content !== '') this._readableState.buffer.push(content);
6587 this._readableState.length = content.length;
6588 return this;
6589}; // Don't raise the hwm > 1GB
6590
6591
6592var MAX_HWM = 0x40000000;
6593
6594function computeNewHighWaterMark(n) {
6595 if (n >= MAX_HWM) {
6596 // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
6597 n = MAX_HWM;
6598 } else {
6599 // Get the next highest power of 2 to prevent increasing hwm excessively in
6600 // tiny amounts
6601 n--;
6602 n |= n >>> 1;
6603 n |= n >>> 2;
6604 n |= n >>> 4;
6605 n |= n >>> 8;
6606 n |= n >>> 16;
6607 n++;
6608 }
6609
6610 return n;
6611} // This function is designed to be inlinable, so please take care when making
6612// changes to the function body.
6613
6614
6615function howMuchToRead(n, state) {
6616 if (n <= 0 || state.length === 0 && state.ended) return 0;
6617 if (state.objectMode) return 1;
6618
6619 if (n !== n) {
6620 // Only flow one buffer at a time
6621 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
6622 } // If we're asking for more than the current hwm, then raise the hwm.
6623
6624
6625 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
6626 if (n <= state.length) return n; // Don't have enough
6627
6628 if (!state.ended) {
6629 state.needReadable = true;
6630 return 0;
6631 }
6632
6633 return state.length;
6634} // you can override either this method, or the async _read(n) below.
6635
6636
6637Readable.prototype.read = function (n) {
6638 debug('read', n);
6639 n = parseInt(n, 10);
6640 var state = this._readableState;
6641 var nOrig = n;
6642 if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we
6643 // already have a bunch of data in the buffer, then just trigger
6644 // the 'readable' event and move on.
6645
6646 if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
6647 debug('read: emitReadable', state.length, state.ended);
6648 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
6649 return null;
6650 }
6651
6652 n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.
6653
6654 if (n === 0 && state.ended) {
6655 if (state.length === 0) endReadable(this);
6656 return null;
6657 } // All the actual chunk generation logic needs to be
6658 // *below* the call to _read. The reason is that in certain
6659 // synthetic stream cases, such as passthrough streams, _read
6660 // may be a completely synchronous operation which may change
6661 // the state of the read buffer, providing enough data when
6662 // before there was *not* enough.
6663 //
6664 // So, the steps are:
6665 // 1. Figure out what the state of things will be after we do
6666 // a read from the buffer.
6667 //
6668 // 2. If that resulting state will trigger a _read, then call _read.
6669 // Note that this may be asynchronous, or synchronous. Yes, it is
6670 // deeply ugly to write APIs this way, but that still doesn't mean
6671 // that the Readable class should behave improperly, as streams are
6672 // designed to be sync/async agnostic.
6673 // Take note if the _read call is sync or async (ie, if the read call
6674 // has returned yet), so that we know whether or not it's safe to emit
6675 // 'readable' etc.
6676 //
6677 // 3. Actually pull the requested chunks out of the buffer and return.
6678 // if we need a readable event, then we need to do some reading.
6679
6680
6681 var doRead = state.needReadable;
6682 debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some
6683
6684 if (state.length === 0 || state.length - n < state.highWaterMark) {
6685 doRead = true;
6686 debug('length less than watermark', doRead);
6687 } // however, if we've ended, then there's no point, and if we're already
6688 // reading, then it's unnecessary.
6689
6690
6691 if (state.ended || state.reading) {
6692 doRead = false;
6693 debug('reading or ended', doRead);
6694 } else if (doRead) {
6695 debug('do read');
6696 state.reading = true;
6697 state.sync = true; // if the length is currently zero, then we *need* a readable event.
6698
6699 if (state.length === 0) state.needReadable = true; // call internal read method
6700
6701 this._read(state.highWaterMark);
6702
6703 state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
6704 // and we need to re-evaluate how much data we can return to the user.
6705
6706 if (!state.reading) n = howMuchToRead(nOrig, state);
6707 }
6708
6709 var ret;
6710 if (n > 0) ret = fromList(n, state);else ret = null;
6711
6712 if (ret === null) {
6713 state.needReadable = state.length <= state.highWaterMark;
6714 n = 0;
6715 } else {
6716 state.length -= n;
6717 state.awaitDrain = 0;
6718 }
6719
6720 if (state.length === 0) {
6721 // If we have nothing in the buffer, then we want to know
6722 // as soon as we *do* get something into the buffer.
6723 if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
6724
6725 if (nOrig !== n && state.ended) endReadable(this);
6726 }
6727
6728 if (ret !== null) this.emit('data', ret);
6729 return ret;
6730};
6731
6732function onEofChunk(stream, state) {
6733 debug('onEofChunk');
6734 if (state.ended) return;
6735
6736 if (state.decoder) {
6737 var chunk = state.decoder.end();
6738
6739 if (chunk && chunk.length) {
6740 state.buffer.push(chunk);
6741 state.length += state.objectMode ? 1 : chunk.length;
6742 }
6743 }
6744
6745 state.ended = true;
6746
6747 if (state.sync) {
6748 // if we are sync, wait until next tick to emit the data.
6749 // Otherwise we risk emitting data in the flow()
6750 // the readable code triggers during a read() call
6751 emitReadable(stream);
6752 } else {
6753 // emit 'readable' now to make sure it gets picked up.
6754 state.needReadable = false;
6755
6756 if (!state.emittedReadable) {
6757 state.emittedReadable = true;
6758 emitReadable_(stream);
6759 }
6760 }
6761} // Don't emit readable right away in sync mode, because this can trigger
6762// another read() call => stack overflow. This way, it might trigger
6763// a nextTick recursion warning, but that's not so bad.
6764
6765
6766function emitReadable(stream) {
6767 var state = stream._readableState;
6768 debug('emitReadable', state.needReadable, state.emittedReadable);
6769 state.needReadable = false;
6770
6771 if (!state.emittedReadable) {
6772 debug('emitReadable', state.flowing);
6773 state.emittedReadable = true;
6774 process.nextTick(emitReadable_, stream);
6775 }
6776}
6777
6778function emitReadable_(stream) {
6779 var state = stream._readableState;
6780 debug('emitReadable_', state.destroyed, state.length, state.ended);
6781
6782 if (!state.destroyed && (state.length || state.ended)) {
6783 stream.emit('readable');
6784 state.emittedReadable = false;
6785 } // The stream needs another readable event if
6786 // 1. It is not flowing, as the flow mechanism will take
6787 // care of it.
6788 // 2. It is not ended.
6789 // 3. It is below the highWaterMark, so we can schedule
6790 // another readable later.
6791
6792
6793 state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
6794 flow(stream);
6795} // at this point, the user has presumably seen the 'readable' event,
6796// and called read() to consume some data. that may have triggered
6797// in turn another _read(n) call, in which case reading = true if
6798// it's in progress.
6799// However, if we're not ended, or reading, and the length < hwm,
6800// then go ahead and try to read some more preemptively.
6801
6802
6803function maybeReadMore(stream, state) {
6804 if (!state.readingMore) {
6805 state.readingMore = true;
6806 process.nextTick(maybeReadMore_, stream, state);
6807 }
6808}
6809
6810function maybeReadMore_(stream, state) {
6811 // Attempt to read more data if we should.
6812 //
6813 // The conditions for reading more data are (one of):
6814 // - Not enough data buffered (state.length < state.highWaterMark). The loop
6815 // is responsible for filling the buffer with enough data if such data
6816 // is available. If highWaterMark is 0 and we are not in the flowing mode
6817 // we should _not_ attempt to buffer any extra data. We'll get more data
6818 // when the stream consumer calls read() instead.
6819 // - No data in the buffer, and the stream is in flowing mode. In this mode
6820 // the loop below is responsible for ensuring read() is called. Failing to
6821 // call read here would abort the flow and there's no other mechanism for
6822 // continuing the flow if the stream consumer has just subscribed to the
6823 // 'data' event.
6824 //
6825 // In addition to the above conditions to keep reading data, the following
6826 // conditions prevent the data from being read:
6827 // - The stream has ended (state.ended).
6828 // - There is already a pending 'read' operation (state.reading). This is a
6829 // case where the the stream has called the implementation defined _read()
6830 // method, but they are processing the call asynchronously and have _not_
6831 // called push() with new data. In this case we skip performing more
6832 // read()s. The execution ends in this method again after the _read() ends
6833 // up calling push() with more data.
6834 while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
6835 var len = state.length;
6836 debug('maybeReadMore read 0');
6837 stream.read(0);
6838 if (len === state.length) // didn't get any data, stop spinning.
6839 break;
6840 }
6841
6842 state.readingMore = false;
6843} // abstract method. to be overridden in specific implementation classes.
6844// call cb(er, data) where data is <= n in length.
6845// for virtual (non-string, non-buffer) streams, "length" is somewhat
6846// arbitrary, and perhaps not very meaningful.
6847
6848
6849Readable.prototype._read = function (n) {
6850 errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
6851};
6852
6853Readable.prototype.pipe = function (dest, pipeOpts) {
6854 var src = this;
6855 var state = this._readableState;
6856
6857 switch (state.pipesCount) {
6858 case 0:
6859 state.pipes = dest;
6860 break;
6861
6862 case 1:
6863 state.pipes = [state.pipes, dest];
6864 break;
6865
6866 default:
6867 state.pipes.push(dest);
6868 break;
6869 }
6870
6871 state.pipesCount += 1;
6872 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
6873 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
6874 var endFn = doEnd ? onend : unpipe;
6875 if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
6876 dest.on('unpipe', onunpipe);
6877
6878 function onunpipe(readable, unpipeInfo) {
6879 debug('onunpipe');
6880
6881 if (readable === src) {
6882 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
6883 unpipeInfo.hasUnpiped = true;
6884 cleanup();
6885 }
6886 }
6887 }
6888
6889 function onend() {
6890 debug('onend');
6891 dest.end();
6892 } // when the dest drains, it reduces the awaitDrain counter
6893 // on the source. This would be more elegant with a .once()
6894 // handler in flow(), but adding and removing repeatedly is
6895 // too slow.
6896
6897
6898 var ondrain = pipeOnDrain(src);
6899 dest.on('drain', ondrain);
6900 var cleanedUp = false;
6901
6902 function cleanup() {
6903 debug('cleanup'); // cleanup event handlers once the pipe is broken
6904
6905 dest.removeListener('close', onclose);
6906 dest.removeListener('finish', onfinish);
6907 dest.removeListener('drain', ondrain);
6908 dest.removeListener('error', onerror);
6909 dest.removeListener('unpipe', onunpipe);
6910 src.removeListener('end', onend);
6911 src.removeListener('end', unpipe);
6912 src.removeListener('data', ondata);
6913 cleanedUp = true; // if the reader is waiting for a drain event from this
6914 // specific writer, then it would cause it to never start
6915 // flowing again.
6916 // So, if this is awaiting a drain, then we just call it now.
6917 // If we don't know, then assume that we are waiting for one.
6918
6919 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
6920 }
6921
6922 src.on('data', ondata);
6923
6924 function ondata(chunk) {
6925 debug('ondata');
6926 var ret = dest.write(chunk);
6927 debug('dest.write', ret);
6928
6929 if (ret === false) {
6930 // If the user unpiped during `dest.write()`, it is possible
6931 // to get stuck in a permanently paused state if that write
6932 // also returned false.
6933 // => Check whether `dest` is still a piping destination.
6934 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
6935 debug('false write response, pause', state.awaitDrain);
6936 state.awaitDrain++;
6937 }
6938
6939 src.pause();
6940 }
6941 } // if the dest has an error, then stop piping into it.
6942 // however, don't suppress the throwing behavior for this.
6943
6944
6945 function onerror(er) {
6946 debug('onerror', er);
6947 unpipe();
6948 dest.removeListener('error', onerror);
6949 if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
6950 } // Make sure our error handler is attached before userland ones.
6951
6952
6953 prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
6954
6955 function onclose() {
6956 dest.removeListener('finish', onfinish);
6957 unpipe();
6958 }
6959
6960 dest.once('close', onclose);
6961
6962 function onfinish() {
6963 debug('onfinish');
6964 dest.removeListener('close', onclose);
6965 unpipe();
6966 }
6967
6968 dest.once('finish', onfinish);
6969
6970 function unpipe() {
6971 debug('unpipe');
6972 src.unpipe(dest);
6973 } // tell the dest that it's being piped to
6974
6975
6976 dest.emit('pipe', src); // start the flow if it hasn't been started already.
6977
6978 if (!state.flowing) {
6979 debug('pipe resume');
6980 src.resume();
6981 }
6982
6983 return dest;
6984};
6985
6986function pipeOnDrain(src) {
6987 return function pipeOnDrainFunctionResult() {
6988 var state = src._readableState;
6989 debug('pipeOnDrain', state.awaitDrain);
6990 if (state.awaitDrain) state.awaitDrain--;
6991
6992 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
6993 state.flowing = true;
6994 flow(src);
6995 }
6996 };
6997}
6998
6999Readable.prototype.unpipe = function (dest) {
7000 var state = this._readableState;
7001 var unpipeInfo = {
7002 hasUnpiped: false
7003 }; // if we're not piping anywhere, then do nothing.
7004
7005 if (state.pipesCount === 0) return this; // just one destination. most common case.
7006
7007 if (state.pipesCount === 1) {
7008 // passed in one, but it's not the right one.
7009 if (dest && dest !== state.pipes) return this;
7010 if (!dest) dest = state.pipes; // got a match.
7011
7012 state.pipes = null;
7013 state.pipesCount = 0;
7014 state.flowing = false;
7015 if (dest) dest.emit('unpipe', this, unpipeInfo);
7016 return this;
7017 } // slow case. multiple pipe destinations.
7018
7019
7020 if (!dest) {
7021 // remove all.
7022 var dests = state.pipes;
7023 var len = state.pipesCount;
7024 state.pipes = null;
7025 state.pipesCount = 0;
7026 state.flowing = false;
7027
7028 for (var i = 0; i < len; i++) {
7029 dests[i].emit('unpipe', this, {
7030 hasUnpiped: false
7031 });
7032 }
7033
7034 return this;
7035 } // try to find the right one.
7036
7037
7038 var index = indexOf(state.pipes, dest);
7039 if (index === -1) return this;
7040 state.pipes.splice(index, 1);
7041 state.pipesCount -= 1;
7042 if (state.pipesCount === 1) state.pipes = state.pipes[0];
7043 dest.emit('unpipe', this, unpipeInfo);
7044 return this;
7045}; // set up data events if they are asked for
7046// Ensure readable listeners eventually get something
7047
7048
7049Readable.prototype.on = function (ev, fn) {
7050 var res = Stream.prototype.on.call(this, ev, fn);
7051 var state = this._readableState;
7052
7053 if (ev === 'data') {
7054 // update readableListening so that resume() may be a no-op
7055 // a few lines down. This is needed to support once('readable').
7056 state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused
7057
7058 if (state.flowing !== false) this.resume();
7059 } else if (ev === 'readable') {
7060 if (!state.endEmitted && !state.readableListening) {
7061 state.readableListening = state.needReadable = true;
7062 state.flowing = false;
7063 state.emittedReadable = false;
7064 debug('on readable', state.length, state.reading);
7065
7066 if (state.length) {
7067 emitReadable(this);
7068 } else if (!state.reading) {
7069 process.nextTick(nReadingNextTick, this);
7070 }
7071 }
7072 }
7073
7074 return res;
7075};
7076
7077Readable.prototype.addListener = Readable.prototype.on;
7078
7079Readable.prototype.removeListener = function (ev, fn) {
7080 var res = Stream.prototype.removeListener.call(this, ev, fn);
7081
7082 if (ev === 'readable') {
7083 // We need to check if there is someone still listening to
7084 // readable and reset the state. However this needs to happen
7085 // after readable has been emitted but before I/O (nextTick) to
7086 // support once('readable', fn) cycles. This means that calling
7087 // resume within the same tick will have no
7088 // effect.
7089 process.nextTick(updateReadableListening, this);
7090 }
7091
7092 return res;
7093};
7094
7095Readable.prototype.removeAllListeners = function (ev) {
7096 var res = Stream.prototype.removeAllListeners.apply(this, arguments);
7097
7098 if (ev === 'readable' || ev === undefined) {
7099 // We need to check if there is someone still listening to
7100 // readable and reset the state. However this needs to happen
7101 // after readable has been emitted but before I/O (nextTick) to
7102 // support once('readable', fn) cycles. This means that calling
7103 // resume within the same tick will have no
7104 // effect.
7105 process.nextTick(updateReadableListening, this);
7106 }
7107
7108 return res;
7109};
7110
7111function updateReadableListening(self) {
7112 var state = self._readableState;
7113 state.readableListening = self.listenerCount('readable') > 0;
7114
7115 if (state.resumeScheduled && !state.paused) {
7116 // flowing needs to be set to true now, otherwise
7117 // the upcoming resume will not flow.
7118 state.flowing = true; // crude way to check if we should resume
7119 } else if (self.listenerCount('data') > 0) {
7120 self.resume();
7121 }
7122}
7123
7124function nReadingNextTick(self) {
7125 debug('readable nexttick read 0');
7126 self.read(0);
7127} // pause() and resume() are remnants of the legacy readable stream API
7128// If the user uses them, then switch into old mode.
7129
7130
7131Readable.prototype.resume = function () {
7132 var state = this._readableState;
7133
7134 if (!state.flowing) {
7135 debug('resume'); // we flow only if there is no one listening
7136 // for readable, but we still have to call
7137 // resume()
7138
7139 state.flowing = !state.readableListening;
7140 resume(this, state);
7141 }
7142
7143 state.paused = false;
7144 return this;
7145};
7146
7147function resume(stream, state) {
7148 if (!state.resumeScheduled) {
7149 state.resumeScheduled = true;
7150 process.nextTick(resume_, stream, state);
7151 }
7152}
7153
7154function resume_(stream, state) {
7155 debug('resume', state.reading);
7156
7157 if (!state.reading) {
7158 stream.read(0);
7159 }
7160
7161 state.resumeScheduled = false;
7162 stream.emit('resume');
7163 flow(stream);
7164 if (state.flowing && !state.reading) stream.read(0);
7165}
7166
7167Readable.prototype.pause = function () {
7168 debug('call pause flowing=%j', this._readableState.flowing);
7169
7170 if (this._readableState.flowing !== false) {
7171 debug('pause');
7172 this._readableState.flowing = false;
7173 this.emit('pause');
7174 }
7175
7176 this._readableState.paused = true;
7177 return this;
7178};
7179
7180function flow(stream) {
7181 var state = stream._readableState;
7182 debug('flow', state.flowing);
7183
7184 while (state.flowing && stream.read() !== null) {
7185 ;
7186 }
7187} // wrap an old-style stream as the async data source.
7188// This is *not* part of the readable stream interface.
7189// It is an ugly unfortunate mess of history.
7190
7191
7192Readable.prototype.wrap = function (stream) {
7193 var _this = this;
7194
7195 var state = this._readableState;
7196 var paused = false;
7197 stream.on('end', function () {
7198 debug('wrapped end');
7199
7200 if (state.decoder && !state.ended) {
7201 var chunk = state.decoder.end();
7202 if (chunk && chunk.length) _this.push(chunk);
7203 }
7204
7205 _this.push(null);
7206 });
7207 stream.on('data', function (chunk) {
7208 debug('wrapped data');
7209 if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
7210
7211 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
7212
7213 var ret = _this.push(chunk);
7214
7215 if (!ret) {
7216 paused = true;
7217 stream.pause();
7218 }
7219 }); // proxy all the other methods.
7220 // important when wrapping filters and duplexes.
7221
7222 for (var i in stream) {
7223 if (this[i] === undefined && typeof stream[i] === 'function') {
7224 this[i] = function methodWrap(method) {
7225 return function methodWrapReturnFunction() {
7226 return stream[method].apply(stream, arguments);
7227 };
7228 }(i);
7229 }
7230 } // proxy certain important events.
7231
7232
7233 for (var n = 0; n < kProxyEvents.length; n++) {
7234 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
7235 } // when we try to consume some more bytes, simply unpause the
7236 // underlying stream.
7237
7238
7239 this._read = function (n) {
7240 debug('wrapped _read', n);
7241
7242 if (paused) {
7243 paused = false;
7244 stream.resume();
7245 }
7246 };
7247
7248 return this;
7249};
7250
7251if (typeof Symbol === 'function') {
7252 Readable.prototype[Symbol.asyncIterator] = function () {
7253 if (createReadableStreamAsyncIterator === undefined) {
7254 createReadableStreamAsyncIterator = _dereq_(31);
7255 }
7256
7257 return createReadableStreamAsyncIterator(this);
7258 };
7259}
7260
7261Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
7262 // making it explicit this property is not enumerable
7263 // because otherwise some prototype manipulation in
7264 // userland will fail
7265 enumerable: false,
7266 get: function get() {
7267 return this._readableState.highWaterMark;
7268 }
7269});
7270Object.defineProperty(Readable.prototype, 'readableBuffer', {
7271 // making it explicit this property is not enumerable
7272 // because otherwise some prototype manipulation in
7273 // userland will fail
7274 enumerable: false,
7275 get: function get() {
7276 return this._readableState && this._readableState.buffer;
7277 }
7278});
7279Object.defineProperty(Readable.prototype, 'readableFlowing', {
7280 // making it explicit this property is not enumerable
7281 // because otherwise some prototype manipulation in
7282 // userland will fail
7283 enumerable: false,
7284 get: function get() {
7285 return this._readableState.flowing;
7286 },
7287 set: function set(state) {
7288 if (this._readableState) {
7289 this._readableState.flowing = state;
7290 }
7291 }
7292}); // exposed for testing purposes only.
7293
7294Readable._fromList = fromList;
7295Object.defineProperty(Readable.prototype, 'readableLength', {
7296 // making it explicit this property is not enumerable
7297 // because otherwise some prototype manipulation in
7298 // userland will fail
7299 enumerable: false,
7300 get: function get() {
7301 return this._readableState.length;
7302 }
7303}); // Pluck off n bytes from an array of buffers.
7304// Length is the combined lengths of all the buffers in the list.
7305// This function is designed to be inlinable, so please take care when making
7306// changes to the function body.
7307
7308function fromList(n, state) {
7309 // nothing buffered
7310 if (state.length === 0) return null;
7311 var ret;
7312 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
7313 // read it all, truncate the list
7314 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
7315 state.buffer.clear();
7316 } else {
7317 // read part of list
7318 ret = state.buffer.consume(n, state.decoder);
7319 }
7320 return ret;
7321}
7322
7323function endReadable(stream) {
7324 var state = stream._readableState;
7325 debug('endReadable', state.endEmitted);
7326
7327 if (!state.endEmitted) {
7328 state.ended = true;
7329 process.nextTick(endReadableNT, state, stream);
7330 }
7331}
7332
7333function endReadableNT(state, stream) {
7334 debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.
7335
7336 if (!state.endEmitted && state.length === 0) {
7337 state.endEmitted = true;
7338 stream.readable = false;
7339 stream.emit('end');
7340
7341 if (state.autoDestroy) {
7342 // In case of duplex streams we need a way to detect
7343 // if the writable side is ready for autoDestroy as well
7344 var wState = stream._writableState;
7345
7346 if (!wState || wState.autoDestroy && wState.finished) {
7347 stream.destroy();
7348 }
7349 }
7350 }
7351}
7352
7353if (typeof Symbol === 'function') {
7354 Readable.from = function (iterable, opts) {
7355 if (from === undefined) {
7356 from = _dereq_(35);
7357 }
7358
7359 return from(Readable, iterable, opts);
7360 };
7361}
7362
7363function indexOf(xs, x) {
7364 for (var i = 0, l = xs.length; i < l; i++) {
7365 if (xs[i] === x) return i;
7366 }
7367
7368 return -1;
7369}
7370}).call(this,_dereq_(70),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
7371},{"14":14,"18":18,"25":25,"26":26,"31":31,"32":32,"33":33,"35":35,"37":37,"38":38,"7":7,"70":70,"9":9,"98":98}],29:[function(_dereq_,module,exports){
7372// Copyright Joyent, Inc. and other Node contributors.
7373//
7374// Permission is hereby granted, free of charge, to any person obtaining a
7375// copy of this software and associated documentation files (the
7376// "Software"), to deal in the Software without restriction, including
7377// without limitation the rights to use, copy, modify, merge, publish,
7378// distribute, sublicense, and/or sell copies of the Software, and to permit
7379// persons to whom the Software is furnished to do so, subject to the
7380// following conditions:
7381//
7382// The above copyright notice and this permission notice shall be included
7383// in all copies or substantial portions of the Software.
7384//
7385// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7386// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7387// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7388// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7389// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7390// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7391// USE OR OTHER DEALINGS IN THE SOFTWARE.
7392// a transform stream is a readable/writable stream where you do
7393// something with the data. Sometimes it's called a "filter",
7394// but that's not a great name for it, since that implies a thing where
7395// some bits pass through, and others are simply ignored. (That would
7396// be a valid example of a transform, of course.)
7397//
7398// While the output is causally related to the input, it's not a
7399// necessarily symmetric or synchronous transformation. For example,
7400// a zlib stream might take multiple plain-text writes(), and then
7401// emit a single compressed chunk some time in the future.
7402//
7403// Here's how this works:
7404//
7405// The Transform stream has all the aspects of the readable and writable
7406// stream classes. When you write(chunk), that calls _write(chunk,cb)
7407// internally, and returns false if there's a lot of pending writes
7408// buffered up. When you call read(), that calls _read(n) until
7409// there's enough pending readable data buffered up.
7410//
7411// In a transform stream, the written data is placed in a buffer. When
7412// _read(n) is called, it transforms the queued up data, calling the
7413// buffered _write cb's as it consumes chunks. If consuming a single
7414// written chunk would result in multiple output chunks, then the first
7415// outputted bit calls the readcb, and subsequent chunks just go into
7416// the read buffer, and will cause it to emit 'readable' if necessary.
7417//
7418// This way, back-pressure is actually determined by the reading side,
7419// since _read has to be called to start processing a new chunk. However,
7420// a pathological inflate type of transform can cause excessive buffering
7421// here. For example, imagine a stream where every byte of input is
7422// interpreted as an integer from 0-255, and then results in that many
7423// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
7424// 1kb of data being output. In this case, you could write a very small
7425// amount of input, and end up with a very large amount of output. In
7426// such a pathological inflating mechanism, there'd be no way to tell
7427// the system to stop doing the transform. A single 4MB write could
7428// cause the system to run out of memory.
7429//
7430// However, even in such a pathological case, only a single written chunk
7431// would be consumed, and then the rest would wait (un-transformed) until
7432// the results of the previous transformed chunk were consumed.
7433'use strict';
7434
7435module.exports = Transform;
7436
7437var _require$codes = _dereq_(25).codes,
7438 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
7439 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
7440 ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
7441 ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
7442
7443var Duplex = _dereq_(26);
7444
7445_dereq_(18)(Transform, Duplex);
7446
7447function afterTransform(er, data) {
7448 var ts = this._transformState;
7449 ts.transforming = false;
7450 var cb = ts.writecb;
7451
7452 if (cb === null) {
7453 return this.emit('error', new ERR_MULTIPLE_CALLBACK());
7454 }
7455
7456 ts.writechunk = null;
7457 ts.writecb = null;
7458 if (data != null) // single equals check for both `null` and `undefined`
7459 this.push(data);
7460 cb(er);
7461 var rs = this._readableState;
7462 rs.reading = false;
7463
7464 if (rs.needReadable || rs.length < rs.highWaterMark) {
7465 this._read(rs.highWaterMark);
7466 }
7467}
7468
7469function Transform(options) {
7470 if (!(this instanceof Transform)) return new Transform(options);
7471 Duplex.call(this, options);
7472 this._transformState = {
7473 afterTransform: afterTransform.bind(this),
7474 needTransform: false,
7475 transforming: false,
7476 writecb: null,
7477 writechunk: null,
7478 writeencoding: null
7479 }; // start out asking for a readable event once data is transformed.
7480
7481 this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
7482 // that Readable wants before the first _read call, so unset the
7483 // sync guard flag.
7484
7485 this._readableState.sync = false;
7486
7487 if (options) {
7488 if (typeof options.transform === 'function') this._transform = options.transform;
7489 if (typeof options.flush === 'function') this._flush = options.flush;
7490 } // When the writable side finishes, then flush out anything remaining.
7491
7492
7493 this.on('prefinish', prefinish);
7494}
7495
7496function prefinish() {
7497 var _this = this;
7498
7499 if (typeof this._flush === 'function' && !this._readableState.destroyed) {
7500 this._flush(function (er, data) {
7501 done(_this, er, data);
7502 });
7503 } else {
7504 done(this, null, null);
7505 }
7506}
7507
7508Transform.prototype.push = function (chunk, encoding) {
7509 this._transformState.needTransform = false;
7510 return Duplex.prototype.push.call(this, chunk, encoding);
7511}; // This is the part where you do stuff!
7512// override this function in implementation classes.
7513// 'chunk' is an input chunk.
7514//
7515// Call `push(newChunk)` to pass along transformed output
7516// to the readable side. You may call 'push' zero or more times.
7517//
7518// Call `cb(err)` when you are done with this chunk. If you pass
7519// an error, then that'll put the hurt on the whole operation. If you
7520// never call cb(), then you'll never get another chunk.
7521
7522
7523Transform.prototype._transform = function (chunk, encoding, cb) {
7524 cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
7525};
7526
7527Transform.prototype._write = function (chunk, encoding, cb) {
7528 var ts = this._transformState;
7529 ts.writecb = cb;
7530 ts.writechunk = chunk;
7531 ts.writeencoding = encoding;
7532
7533 if (!ts.transforming) {
7534 var rs = this._readableState;
7535 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
7536 }
7537}; // Doesn't matter what the args are here.
7538// _transform does all the work.
7539// That we got here means that the readable side wants more data.
7540
7541
7542Transform.prototype._read = function (n) {
7543 var ts = this._transformState;
7544
7545 if (ts.writechunk !== null && !ts.transforming) {
7546 ts.transforming = true;
7547
7548 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
7549 } else {
7550 // mark that we need a transform, so that any data that comes in
7551 // will get processed, now that we've asked for it.
7552 ts.needTransform = true;
7553 }
7554};
7555
7556Transform.prototype._destroy = function (err, cb) {
7557 Duplex.prototype._destroy.call(this, err, function (err2) {
7558 cb(err2);
7559 });
7560};
7561
7562function done(stream, er, data) {
7563 if (er) return stream.emit('error', er);
7564 if (data != null) // single equals check for both `null` and `undefined`
7565 stream.push(data); // TODO(BridgeAR): Write a test for these two error cases
7566 // if there's nothing in the write buffer, then that means
7567 // that nothing more will ever be provided
7568
7569 if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
7570 if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
7571 return stream.push(null);
7572}
7573},{"18":18,"25":25,"26":26}],30:[function(_dereq_,module,exports){
7574(function (process,global){
7575// Copyright Joyent, Inc. and other Node contributors.
7576//
7577// Permission is hereby granted, free of charge, to any person obtaining a
7578// copy of this software and associated documentation files (the
7579// "Software"), to deal in the Software without restriction, including
7580// without limitation the rights to use, copy, modify, merge, publish,
7581// distribute, sublicense, and/or sell copies of the Software, and to permit
7582// persons to whom the Software is furnished to do so, subject to the
7583// following conditions:
7584//
7585// The above copyright notice and this permission notice shall be included
7586// in all copies or substantial portions of the Software.
7587//
7588// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7589// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7590// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7591// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7592// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7593// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7594// USE OR OTHER DEALINGS IN THE SOFTWARE.
7595// A bit simpler than readable streams.
7596// Implement an async ._write(chunk, encoding, cb), and it'll handle all
7597// the drain event emission and buffering.
7598'use strict';
7599
7600module.exports = Writable;
7601/* <replacement> */
7602
7603function WriteReq(chunk, encoding, cb) {
7604 this.chunk = chunk;
7605 this.encoding = encoding;
7606 this.callback = cb;
7607 this.next = null;
7608} // It seems a linked list but it is not
7609// there will be only 2 of these for each stream
7610
7611
7612function CorkedRequest(state) {
7613 var _this = this;
7614
7615 this.next = null;
7616 this.entry = null;
7617
7618 this.finish = function () {
7619 onCorkedFinish(_this, state);
7620 };
7621}
7622/* </replacement> */
7623
7624/*<replacement>*/
7625
7626
7627var Duplex;
7628/*</replacement>*/
7629
7630Writable.WritableState = WritableState;
7631/*<replacement>*/
7632
7633var internalUtil = {
7634 deprecate: _dereq_(116)
7635};
7636/*</replacement>*/
7637
7638/*<replacement>*/
7639
7640var Stream = _dereq_(38);
7641/*</replacement>*/
7642
7643
7644var Buffer = _dereq_(9).Buffer;
7645
7646var OurUint8Array = global.Uint8Array || function () {};
7647
7648function _uint8ArrayToBuffer(chunk) {
7649 return Buffer.from(chunk);
7650}
7651
7652function _isUint8Array(obj) {
7653 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
7654}
7655
7656var destroyImpl = _dereq_(33);
7657
7658var _require = _dereq_(37),
7659 getHighWaterMark = _require.getHighWaterMark;
7660
7661var _require$codes = _dereq_(25).codes,
7662 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
7663 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
7664 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
7665 ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
7666 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
7667 ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
7668 ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
7669 ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
7670
7671var errorOrDestroy = destroyImpl.errorOrDestroy;
7672
7673_dereq_(18)(Writable, Stream);
7674
7675function nop() {}
7676
7677function WritableState(options, stream, isDuplex) {
7678 Duplex = Duplex || _dereq_(26);
7679 options = options || {}; // Duplex streams are both readable and writable, but share
7680 // the same options object.
7681 // However, some cases require setting options to different
7682 // values for the readable and the writable sides of the duplex stream,
7683 // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
7684
7685 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream
7686 // contains buffers or objects.
7687
7688 this.objectMode = !!options.objectMode;
7689 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
7690 // Note: 0 is a valid value, means that we always return false if
7691 // the entire buffer is not flushed immediately on write()
7692
7693 this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called
7694
7695 this.finalCalled = false; // drain event flag.
7696
7697 this.needDrain = false; // at the start of calling end()
7698
7699 this.ending = false; // when end() has been called, and returned
7700
7701 this.ended = false; // when 'finish' is emitted
7702
7703 this.finished = false; // has it been destroyed
7704
7705 this.destroyed = false; // should we decode strings into buffers before passing to _write?
7706 // this is here so that some node-core streams can optimize string
7707 // handling at a lower level.
7708
7709 var noDecode = options.decodeStrings === false;
7710 this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string
7711 // encoding is 'binary' so we have to make this configurable.
7712 // Everything else in the universe uses 'utf8', though.
7713
7714 this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement
7715 // of how much we're waiting to get pushed to some underlying
7716 // socket or file.
7717
7718 this.length = 0; // a flag to see when we're in the middle of a write.
7719
7720 this.writing = false; // when true all writes will be buffered until .uncork() call
7721
7722 this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,
7723 // or on a later tick. We set this to true at first, because any
7724 // actions that shouldn't happen until "later" should generally also
7725 // not happen before the first write call.
7726
7727 this.sync = true; // a flag to know if we're processing previously buffered items, which
7728 // may call the _write() callback in the same tick, so that we don't
7729 // end up in an overlapped onwrite situation.
7730
7731 this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)
7732
7733 this.onwrite = function (er) {
7734 onwrite(stream, er);
7735 }; // the callback that the user supplies to write(chunk,encoding,cb)
7736
7737
7738 this.writecb = null; // the amount that is being written when _write is called.
7739
7740 this.writelen = 0;
7741 this.bufferedRequest = null;
7742 this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
7743 // this must be 0 before 'finish' can be emitted
7744
7745 this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
7746 // This is relevant for synchronous Transform streams
7747
7748 this.prefinished = false; // True if the error was already emitted and should not be thrown again
7749
7750 this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.
7751
7752 this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')
7753
7754 this.autoDestroy = !!options.autoDestroy; // count buffered requests
7755
7756 this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always
7757 // one allocated and free to use, and we maintain at most two
7758
7759 this.corkedRequestsFree = new CorkedRequest(this);
7760}
7761
7762WritableState.prototype.getBuffer = function getBuffer() {
7763 var current = this.bufferedRequest;
7764 var out = [];
7765
7766 while (current) {
7767 out.push(current);
7768 current = current.next;
7769 }
7770
7771 return out;
7772};
7773
7774(function () {
7775 try {
7776 Object.defineProperty(WritableState.prototype, 'buffer', {
7777 get: internalUtil.deprecate(function writableStateBufferGetter() {
7778 return this.getBuffer();
7779 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
7780 });
7781 } catch (_) {}
7782})(); // Test _writableState for inheritance to account for Duplex streams,
7783// whose prototype chain only points to Readable.
7784
7785
7786var realHasInstance;
7787
7788if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
7789 realHasInstance = Function.prototype[Symbol.hasInstance];
7790 Object.defineProperty(Writable, Symbol.hasInstance, {
7791 value: function value(object) {
7792 if (realHasInstance.call(this, object)) return true;
7793 if (this !== Writable) return false;
7794 return object && object._writableState instanceof WritableState;
7795 }
7796 });
7797} else {
7798 realHasInstance = function realHasInstance(object) {
7799 return object instanceof this;
7800 };
7801}
7802
7803function Writable(options) {
7804 Duplex = Duplex || _dereq_(26); // Writable ctor is applied to Duplexes, too.
7805 // `realHasInstance` is necessary because using plain `instanceof`
7806 // would return false, as no `_writableState` property is attached.
7807 // Trying to use the custom `instanceof` for Writable here will also break the
7808 // Node.js LazyTransform implementation, which has a non-trivial getter for
7809 // `_writableState` that would lead to infinite recursion.
7810 // Checking for a Stream.Duplex instance is faster here instead of inside
7811 // the WritableState constructor, at least with V8 6.5
7812
7813 var isDuplex = this instanceof Duplex;
7814 if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
7815 this._writableState = new WritableState(options, this, isDuplex); // legacy.
7816
7817 this.writable = true;
7818
7819 if (options) {
7820 if (typeof options.write === 'function') this._write = options.write;
7821 if (typeof options.writev === 'function') this._writev = options.writev;
7822 if (typeof options.destroy === 'function') this._destroy = options.destroy;
7823 if (typeof options.final === 'function') this._final = options.final;
7824 }
7825
7826 Stream.call(this);
7827} // Otherwise people can pipe Writable streams, which is just wrong.
7828
7829
7830Writable.prototype.pipe = function () {
7831 errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
7832};
7833
7834function writeAfterEnd(stream, cb) {
7835 var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
7836
7837 errorOrDestroy(stream, er);
7838 process.nextTick(cb, er);
7839} // Checks that a user-supplied chunk is valid, especially for the particular
7840// mode the stream is in. Currently this means that `null` is never accepted
7841// and undefined/non-string values are only allowed in object mode.
7842
7843
7844function validChunk(stream, state, chunk, cb) {
7845 var er;
7846
7847 if (chunk === null) {
7848 er = new ERR_STREAM_NULL_VALUES();
7849 } else if (typeof chunk !== 'string' && !state.objectMode) {
7850 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
7851 }
7852
7853 if (er) {
7854 errorOrDestroy(stream, er);
7855 process.nextTick(cb, er);
7856 return false;
7857 }
7858
7859 return true;
7860}
7861
7862Writable.prototype.write = function (chunk, encoding, cb) {
7863 var state = this._writableState;
7864 var ret = false;
7865
7866 var isBuf = !state.objectMode && _isUint8Array(chunk);
7867
7868 if (isBuf && !Buffer.isBuffer(chunk)) {
7869 chunk = _uint8ArrayToBuffer(chunk);
7870 }
7871
7872 if (typeof encoding === 'function') {
7873 cb = encoding;
7874 encoding = null;
7875 }
7876
7877 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
7878 if (typeof cb !== 'function') cb = nop;
7879 if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
7880 state.pendingcb++;
7881 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
7882 }
7883 return ret;
7884};
7885
7886Writable.prototype.cork = function () {
7887 this._writableState.corked++;
7888};
7889
7890Writable.prototype.uncork = function () {
7891 var state = this._writableState;
7892
7893 if (state.corked) {
7894 state.corked--;
7895 if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
7896 }
7897};
7898
7899Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
7900 // node::ParseEncoding() requires lower case.
7901 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
7902 if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
7903 this._writableState.defaultEncoding = encoding;
7904 return this;
7905};
7906
7907Object.defineProperty(Writable.prototype, 'writableBuffer', {
7908 // making it explicit this property is not enumerable
7909 // because otherwise some prototype manipulation in
7910 // userland will fail
7911 enumerable: false,
7912 get: function get() {
7913 return this._writableState && this._writableState.getBuffer();
7914 }
7915});
7916
7917function decodeChunk(state, chunk, encoding) {
7918 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
7919 chunk = Buffer.from(chunk, encoding);
7920 }
7921
7922 return chunk;
7923}
7924
7925Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
7926 // making it explicit this property is not enumerable
7927 // because otherwise some prototype manipulation in
7928 // userland will fail
7929 enumerable: false,
7930 get: function get() {
7931 return this._writableState.highWaterMark;
7932 }
7933}); // if we're already writing something, then just put this
7934// in the queue, and wait our turn. Otherwise, call _write
7935// If we return false, then we need a drain event, so set that flag.
7936
7937function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
7938 if (!isBuf) {
7939 var newChunk = decodeChunk(state, chunk, encoding);
7940
7941 if (chunk !== newChunk) {
7942 isBuf = true;
7943 encoding = 'buffer';
7944 chunk = newChunk;
7945 }
7946 }
7947
7948 var len = state.objectMode ? 1 : chunk.length;
7949 state.length += len;
7950 var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
7951
7952 if (!ret) state.needDrain = true;
7953
7954 if (state.writing || state.corked) {
7955 var last = state.lastBufferedRequest;
7956 state.lastBufferedRequest = {
7957 chunk: chunk,
7958 encoding: encoding,
7959 isBuf: isBuf,
7960 callback: cb,
7961 next: null
7962 };
7963
7964 if (last) {
7965 last.next = state.lastBufferedRequest;
7966 } else {
7967 state.bufferedRequest = state.lastBufferedRequest;
7968 }
7969
7970 state.bufferedRequestCount += 1;
7971 } else {
7972 doWrite(stream, state, false, len, chunk, encoding, cb);
7973 }
7974
7975 return ret;
7976}
7977
7978function doWrite(stream, state, writev, len, chunk, encoding, cb) {
7979 state.writelen = len;
7980 state.writecb = cb;
7981 state.writing = true;
7982 state.sync = true;
7983 if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
7984 state.sync = false;
7985}
7986
7987function onwriteError(stream, state, sync, er, cb) {
7988 --state.pendingcb;
7989
7990 if (sync) {
7991 // defer the callback if we are being called synchronously
7992 // to avoid piling up things on the stack
7993 process.nextTick(cb, er); // this can emit finish, and it will always happen
7994 // after error
7995
7996 process.nextTick(finishMaybe, stream, state);
7997 stream._writableState.errorEmitted = true;
7998 errorOrDestroy(stream, er);
7999 } else {
8000 // the caller expect this to happen before if
8001 // it is async
8002 cb(er);
8003 stream._writableState.errorEmitted = true;
8004 errorOrDestroy(stream, er); // this can emit finish, but finish must
8005 // always follow error
8006
8007 finishMaybe(stream, state);
8008 }
8009}
8010
8011function onwriteStateUpdate(state) {
8012 state.writing = false;
8013 state.writecb = null;
8014 state.length -= state.writelen;
8015 state.writelen = 0;
8016}
8017
8018function onwrite(stream, er) {
8019 var state = stream._writableState;
8020 var sync = state.sync;
8021 var cb = state.writecb;
8022 if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
8023 onwriteStateUpdate(state);
8024 if (er) onwriteError(stream, state, sync, er, cb);else {
8025 // Check if we're actually ready to finish, but don't emit yet
8026 var finished = needFinish(state) || stream.destroyed;
8027
8028 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
8029 clearBuffer(stream, state);
8030 }
8031
8032 if (sync) {
8033 process.nextTick(afterWrite, stream, state, finished, cb);
8034 } else {
8035 afterWrite(stream, state, finished, cb);
8036 }
8037 }
8038}
8039
8040function afterWrite(stream, state, finished, cb) {
8041 if (!finished) onwriteDrain(stream, state);
8042 state.pendingcb--;
8043 cb();
8044 finishMaybe(stream, state);
8045} // Must force callback to be called on nextTick, so that we don't
8046// emit 'drain' before the write() consumer gets the 'false' return
8047// value, and has a chance to attach a 'drain' listener.
8048
8049
8050function onwriteDrain(stream, state) {
8051 if (state.length === 0 && state.needDrain) {
8052 state.needDrain = false;
8053 stream.emit('drain');
8054 }
8055} // if there's something in the buffer waiting, then process it
8056
8057
8058function clearBuffer(stream, state) {
8059 state.bufferProcessing = true;
8060 var entry = state.bufferedRequest;
8061
8062 if (stream._writev && entry && entry.next) {
8063 // Fast case, write everything using _writev()
8064 var l = state.bufferedRequestCount;
8065 var buffer = new Array(l);
8066 var holder = state.corkedRequestsFree;
8067 holder.entry = entry;
8068 var count = 0;
8069 var allBuffers = true;
8070
8071 while (entry) {
8072 buffer[count] = entry;
8073 if (!entry.isBuf) allBuffers = false;
8074 entry = entry.next;
8075 count += 1;
8076 }
8077
8078 buffer.allBuffers = allBuffers;
8079 doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
8080 // as the hot path ends with doWrite
8081
8082 state.pendingcb++;
8083 state.lastBufferedRequest = null;
8084
8085 if (holder.next) {
8086 state.corkedRequestsFree = holder.next;
8087 holder.next = null;
8088 } else {
8089 state.corkedRequestsFree = new CorkedRequest(state);
8090 }
8091
8092 state.bufferedRequestCount = 0;
8093 } else {
8094 // Slow case, write chunks one-by-one
8095 while (entry) {
8096 var chunk = entry.chunk;
8097 var encoding = entry.encoding;
8098 var cb = entry.callback;
8099 var len = state.objectMode ? 1 : chunk.length;
8100 doWrite(stream, state, false, len, chunk, encoding, cb);
8101 entry = entry.next;
8102 state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then
8103 // it means that we need to wait until it does.
8104 // also, that means that the chunk and cb are currently
8105 // being processed, so move the buffer counter past them.
8106
8107 if (state.writing) {
8108 break;
8109 }
8110 }
8111
8112 if (entry === null) state.lastBufferedRequest = null;
8113 }
8114
8115 state.bufferedRequest = entry;
8116 state.bufferProcessing = false;
8117}
8118
8119Writable.prototype._write = function (chunk, encoding, cb) {
8120 cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
8121};
8122
8123Writable.prototype._writev = null;
8124
8125Writable.prototype.end = function (chunk, encoding, cb) {
8126 var state = this._writableState;
8127
8128 if (typeof chunk === 'function') {
8129 cb = chunk;
8130 chunk = null;
8131 encoding = null;
8132 } else if (typeof encoding === 'function') {
8133 cb = encoding;
8134 encoding = null;
8135 }
8136
8137 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks
8138
8139 if (state.corked) {
8140 state.corked = 1;
8141 this.uncork();
8142 } // ignore unnecessary end() calls.
8143
8144
8145 if (!state.ending) endWritable(this, state, cb);
8146 return this;
8147};
8148
8149Object.defineProperty(Writable.prototype, 'writableLength', {
8150 // making it explicit this property is not enumerable
8151 // because otherwise some prototype manipulation in
8152 // userland will fail
8153 enumerable: false,
8154 get: function get() {
8155 return this._writableState.length;
8156 }
8157});
8158
8159function needFinish(state) {
8160 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
8161}
8162
8163function callFinal(stream, state) {
8164 stream._final(function (err) {
8165 state.pendingcb--;
8166
8167 if (err) {
8168 errorOrDestroy(stream, err);
8169 }
8170
8171 state.prefinished = true;
8172 stream.emit('prefinish');
8173 finishMaybe(stream, state);
8174 });
8175}
8176
8177function prefinish(stream, state) {
8178 if (!state.prefinished && !state.finalCalled) {
8179 if (typeof stream._final === 'function' && !state.destroyed) {
8180 state.pendingcb++;
8181 state.finalCalled = true;
8182 process.nextTick(callFinal, stream, state);
8183 } else {
8184 state.prefinished = true;
8185 stream.emit('prefinish');
8186 }
8187 }
8188}
8189
8190function finishMaybe(stream, state) {
8191 var need = needFinish(state);
8192
8193 if (need) {
8194 prefinish(stream, state);
8195
8196 if (state.pendingcb === 0) {
8197 state.finished = true;
8198 stream.emit('finish');
8199
8200 if (state.autoDestroy) {
8201 // In case of duplex streams we need a way to detect
8202 // if the readable side is ready for autoDestroy as well
8203 var rState = stream._readableState;
8204
8205 if (!rState || rState.autoDestroy && rState.endEmitted) {
8206 stream.destroy();
8207 }
8208 }
8209 }
8210 }
8211
8212 return need;
8213}
8214
8215function endWritable(stream, state, cb) {
8216 state.ending = true;
8217 finishMaybe(stream, state);
8218
8219 if (cb) {
8220 if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
8221 }
8222
8223 state.ended = true;
8224 stream.writable = false;
8225}
8226
8227function onCorkedFinish(corkReq, state, err) {
8228 var entry = corkReq.entry;
8229 corkReq.entry = null;
8230
8231 while (entry) {
8232 var cb = entry.callback;
8233 state.pendingcb--;
8234 cb(err);
8235 entry = entry.next;
8236 } // reuse the free corkReq.
8237
8238
8239 state.corkedRequestsFree.next = corkReq;
8240}
8241
8242Object.defineProperty(Writable.prototype, 'destroyed', {
8243 // making it explicit this property is not enumerable
8244 // because otherwise some prototype manipulation in
8245 // userland will fail
8246 enumerable: false,
8247 get: function get() {
8248 if (this._writableState === undefined) {
8249 return false;
8250 }
8251
8252 return this._writableState.destroyed;
8253 },
8254 set: function set(value) {
8255 // we ignore the value if the stream
8256 // has not been initialized yet
8257 if (!this._writableState) {
8258 return;
8259 } // backward compatibility, the user is explicitly
8260 // managing destroyed
8261
8262
8263 this._writableState.destroyed = value;
8264 }
8265});
8266Writable.prototype.destroy = destroyImpl.destroy;
8267Writable.prototype._undestroy = destroyImpl.undestroy;
8268
8269Writable.prototype._destroy = function (err, cb) {
8270 cb(err);
8271};
8272}).call(this,_dereq_(70),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
8273},{"116":116,"18":18,"25":25,"26":26,"33":33,"37":37,"38":38,"70":70,"9":9}],31:[function(_dereq_,module,exports){
8274(function (process){
8275'use strict';
8276
8277var _Object$setPrototypeO;
8278
8279function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
8280
8281var finished = _dereq_(34);
8282
8283var kLastResolve = Symbol('lastResolve');
8284var kLastReject = Symbol('lastReject');
8285var kError = Symbol('error');
8286var kEnded = Symbol('ended');
8287var kLastPromise = Symbol('lastPromise');
8288var kHandlePromise = Symbol('handlePromise');
8289var kStream = Symbol('stream');
8290
8291function createIterResult(value, done) {
8292 return {
8293 value: value,
8294 done: done
8295 };
8296}
8297
8298function readAndResolve(iter) {
8299 var resolve = iter[kLastResolve];
8300
8301 if (resolve !== null) {
8302 var data = iter[kStream].read(); // we defer if data is null
8303 // we can be expecting either 'end' or
8304 // 'error'
8305
8306 if (data !== null) {
8307 iter[kLastPromise] = null;
8308 iter[kLastResolve] = null;
8309 iter[kLastReject] = null;
8310 resolve(createIterResult(data, false));
8311 }
8312 }
8313}
8314
8315function onReadable(iter) {
8316 // we wait for the next tick, because it might
8317 // emit an error with process.nextTick
8318 process.nextTick(readAndResolve, iter);
8319}
8320
8321function wrapForNext(lastPromise, iter) {
8322 return function (resolve, reject) {
8323 lastPromise.then(function () {
8324 if (iter[kEnded]) {
8325 resolve(createIterResult(undefined, true));
8326 return;
8327 }
8328
8329 iter[kHandlePromise](resolve, reject);
8330 }, reject);
8331 };
8332}
8333
8334var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
8335var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
8336 get stream() {
8337 return this[kStream];
8338 },
8339
8340 next: function next() {
8341 var _this = this;
8342
8343 // if we have detected an error in the meanwhile
8344 // reject straight away
8345 var error = this[kError];
8346
8347 if (error !== null) {
8348 return Promise.reject(error);
8349 }
8350
8351 if (this[kEnded]) {
8352 return Promise.resolve(createIterResult(undefined, true));
8353 }
8354
8355 if (this[kStream].destroyed) {
8356 // We need to defer via nextTick because if .destroy(err) is
8357 // called, the error will be emitted via nextTick, and
8358 // we cannot guarantee that there is no error lingering around
8359 // waiting to be emitted.
8360 return new Promise(function (resolve, reject) {
8361 process.nextTick(function () {
8362 if (_this[kError]) {
8363 reject(_this[kError]);
8364 } else {
8365 resolve(createIterResult(undefined, true));
8366 }
8367 });
8368 });
8369 } // if we have multiple next() calls
8370 // we will wait for the previous Promise to finish
8371 // this logic is optimized to support for await loops,
8372 // where next() is only called once at a time
8373
8374
8375 var lastPromise = this[kLastPromise];
8376 var promise;
8377
8378 if (lastPromise) {
8379 promise = new Promise(wrapForNext(lastPromise, this));
8380 } else {
8381 // fast path needed to support multiple this.push()
8382 // without triggering the next() queue
8383 var data = this[kStream].read();
8384
8385 if (data !== null) {
8386 return Promise.resolve(createIterResult(data, false));
8387 }
8388
8389 promise = new Promise(this[kHandlePromise]);
8390 }
8391
8392 this[kLastPromise] = promise;
8393 return promise;
8394 }
8395}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
8396 return this;
8397}), _defineProperty(_Object$setPrototypeO, "return", function _return() {
8398 var _this2 = this;
8399
8400 // destroy(err, cb) is a private API
8401 // we can guarantee we have that here, because we control the
8402 // Readable class this is attached to
8403 return new Promise(function (resolve, reject) {
8404 _this2[kStream].destroy(null, function (err) {
8405 if (err) {
8406 reject(err);
8407 return;
8408 }
8409
8410 resolve(createIterResult(undefined, true));
8411 });
8412 });
8413}), _Object$setPrototypeO), AsyncIteratorPrototype);
8414
8415var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
8416 var _Object$create;
8417
8418 var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
8419 value: stream,
8420 writable: true
8421 }), _defineProperty(_Object$create, kLastResolve, {
8422 value: null,
8423 writable: true
8424 }), _defineProperty(_Object$create, kLastReject, {
8425 value: null,
8426 writable: true
8427 }), _defineProperty(_Object$create, kError, {
8428 value: null,
8429 writable: true
8430 }), _defineProperty(_Object$create, kEnded, {
8431 value: stream._readableState.endEmitted,
8432 writable: true
8433 }), _defineProperty(_Object$create, kHandlePromise, {
8434 value: function value(resolve, reject) {
8435 var data = iterator[kStream].read();
8436
8437 if (data) {
8438 iterator[kLastPromise] = null;
8439 iterator[kLastResolve] = null;
8440 iterator[kLastReject] = null;
8441 resolve(createIterResult(data, false));
8442 } else {
8443 iterator[kLastResolve] = resolve;
8444 iterator[kLastReject] = reject;
8445 }
8446 },
8447 writable: true
8448 }), _Object$create));
8449 iterator[kLastPromise] = null;
8450 finished(stream, function (err) {
8451 if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
8452 var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise
8453 // returned by next() and store the error
8454
8455 if (reject !== null) {
8456 iterator[kLastPromise] = null;
8457 iterator[kLastResolve] = null;
8458 iterator[kLastReject] = null;
8459 reject(err);
8460 }
8461
8462 iterator[kError] = err;
8463 return;
8464 }
8465
8466 var resolve = iterator[kLastResolve];
8467
8468 if (resolve !== null) {
8469 iterator[kLastPromise] = null;
8470 iterator[kLastResolve] = null;
8471 iterator[kLastReject] = null;
8472 resolve(createIterResult(undefined, true));
8473 }
8474
8475 iterator[kEnded] = true;
8476 });
8477 stream.on('readable', onReadable.bind(null, iterator));
8478 return iterator;
8479};
8480
8481module.exports = createReadableStreamAsyncIterator;
8482}).call(this,_dereq_(70))
8483},{"34":34,"70":70}],32:[function(_dereq_,module,exports){
8484'use strict';
8485
8486function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
8487
8488function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
8489
8490function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
8491
8492function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
8493
8494function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
8495
8496function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
8497
8498var _require = _dereq_(9),
8499 Buffer = _require.Buffer;
8500
8501var _require2 = _dereq_(7),
8502 inspect = _require2.inspect;
8503
8504var custom = inspect && inspect.custom || 'inspect';
8505
8506function copyBuffer(src, target, offset) {
8507 Buffer.prototype.copy.call(src, target, offset);
8508}
8509
8510module.exports =
8511/*#__PURE__*/
8512function () {
8513 function BufferList() {
8514 _classCallCheck(this, BufferList);
8515
8516 this.head = null;
8517 this.tail = null;
8518 this.length = 0;
8519 }
8520
8521 _createClass(BufferList, [{
8522 key: "push",
8523 value: function push(v) {
8524 var entry = {
8525 data: v,
8526 next: null
8527 };
8528 if (this.length > 0) this.tail.next = entry;else this.head = entry;
8529 this.tail = entry;
8530 ++this.length;
8531 }
8532 }, {
8533 key: "unshift",
8534 value: function unshift(v) {
8535 var entry = {
8536 data: v,
8537 next: this.head
8538 };
8539 if (this.length === 0) this.tail = entry;
8540 this.head = entry;
8541 ++this.length;
8542 }
8543 }, {
8544 key: "shift",
8545 value: function shift() {
8546 if (this.length === 0) return;
8547 var ret = this.head.data;
8548 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
8549 --this.length;
8550 return ret;
8551 }
8552 }, {
8553 key: "clear",
8554 value: function clear() {
8555 this.head = this.tail = null;
8556 this.length = 0;
8557 }
8558 }, {
8559 key: "join",
8560 value: function join(s) {
8561 if (this.length === 0) return '';
8562 var p = this.head;
8563 var ret = '' + p.data;
8564
8565 while (p = p.next) {
8566 ret += s + p.data;
8567 }
8568
8569 return ret;
8570 }
8571 }, {
8572 key: "concat",
8573 value: function concat(n) {
8574 if (this.length === 0) return Buffer.alloc(0);
8575 var ret = Buffer.allocUnsafe(n >>> 0);
8576 var p = this.head;
8577 var i = 0;
8578
8579 while (p) {
8580 copyBuffer(p.data, ret, i);
8581 i += p.data.length;
8582 p = p.next;
8583 }
8584
8585 return ret;
8586 } // Consumes a specified amount of bytes or characters from the buffered data.
8587
8588 }, {
8589 key: "consume",
8590 value: function consume(n, hasStrings) {
8591 var ret;
8592
8593 if (n < this.head.data.length) {
8594 // `slice` is the same for buffers and strings.
8595 ret = this.head.data.slice(0, n);
8596 this.head.data = this.head.data.slice(n);
8597 } else if (n === this.head.data.length) {
8598 // First chunk is a perfect match.
8599 ret = this.shift();
8600 } else {
8601 // Result spans more than one buffer.
8602 ret = hasStrings ? this._getString(n) : this._getBuffer(n);
8603 }
8604
8605 return ret;
8606 }
8607 }, {
8608 key: "first",
8609 value: function first() {
8610 return this.head.data;
8611 } // Consumes a specified amount of characters from the buffered data.
8612
8613 }, {
8614 key: "_getString",
8615 value: function _getString(n) {
8616 var p = this.head;
8617 var c = 1;
8618 var ret = p.data;
8619 n -= ret.length;
8620
8621 while (p = p.next) {
8622 var str = p.data;
8623 var nb = n > str.length ? str.length : n;
8624 if (nb === str.length) ret += str;else ret += str.slice(0, n);
8625 n -= nb;
8626
8627 if (n === 0) {
8628 if (nb === str.length) {
8629 ++c;
8630 if (p.next) this.head = p.next;else this.head = this.tail = null;
8631 } else {
8632 this.head = p;
8633 p.data = str.slice(nb);
8634 }
8635
8636 break;
8637 }
8638
8639 ++c;
8640 }
8641
8642 this.length -= c;
8643 return ret;
8644 } // Consumes a specified amount of bytes from the buffered data.
8645
8646 }, {
8647 key: "_getBuffer",
8648 value: function _getBuffer(n) {
8649 var ret = Buffer.allocUnsafe(n);
8650 var p = this.head;
8651 var c = 1;
8652 p.data.copy(ret);
8653 n -= p.data.length;
8654
8655 while (p = p.next) {
8656 var buf = p.data;
8657 var nb = n > buf.length ? buf.length : n;
8658 buf.copy(ret, ret.length - n, 0, nb);
8659 n -= nb;
8660
8661 if (n === 0) {
8662 if (nb === buf.length) {
8663 ++c;
8664 if (p.next) this.head = p.next;else this.head = this.tail = null;
8665 } else {
8666 this.head = p;
8667 p.data = buf.slice(nb);
8668 }
8669
8670 break;
8671 }
8672
8673 ++c;
8674 }
8675
8676 this.length -= c;
8677 return ret;
8678 } // Make sure the linked list only shows the minimal necessary information.
8679
8680 }, {
8681 key: custom,
8682 value: function value(_, options) {
8683 return inspect(this, _objectSpread({}, options, {
8684 // Only inspect one level.
8685 depth: 0,
8686 // It should not recurse.
8687 customInspect: false
8688 }));
8689 }
8690 }]);
8691
8692 return BufferList;
8693}();
8694},{"7":7,"9":9}],33:[function(_dereq_,module,exports){
8695(function (process){
8696'use strict'; // undocumented cb() API, needed for core, not for public API
8697
8698function destroy(err, cb) {
8699 var _this = this;
8700
8701 var readableDestroyed = this._readableState && this._readableState.destroyed;
8702 var writableDestroyed = this._writableState && this._writableState.destroyed;
8703
8704 if (readableDestroyed || writableDestroyed) {
8705 if (cb) {
8706 cb(err);
8707 } else if (err) {
8708 if (!this._writableState) {
8709 process.nextTick(emitErrorNT, this, err);
8710 } else if (!this._writableState.errorEmitted) {
8711 this._writableState.errorEmitted = true;
8712 process.nextTick(emitErrorNT, this, err);
8713 }
8714 }
8715
8716 return this;
8717 } // we set destroyed to true before firing error callbacks in order
8718 // to make it re-entrance safe in case destroy() is called within callbacks
8719
8720
8721 if (this._readableState) {
8722 this._readableState.destroyed = true;
8723 } // if this is a duplex stream mark the writable part as destroyed as well
8724
8725
8726 if (this._writableState) {
8727 this._writableState.destroyed = true;
8728 }
8729
8730 this._destroy(err || null, function (err) {
8731 if (!cb && err) {
8732 if (!_this._writableState) {
8733 process.nextTick(emitErrorAndCloseNT, _this, err);
8734 } else if (!_this._writableState.errorEmitted) {
8735 _this._writableState.errorEmitted = true;
8736 process.nextTick(emitErrorAndCloseNT, _this, err);
8737 } else {
8738 process.nextTick(emitCloseNT, _this);
8739 }
8740 } else if (cb) {
8741 process.nextTick(emitCloseNT, _this);
8742 cb(err);
8743 } else {
8744 process.nextTick(emitCloseNT, _this);
8745 }
8746 });
8747
8748 return this;
8749}
8750
8751function emitErrorAndCloseNT(self, err) {
8752 emitErrorNT(self, err);
8753 emitCloseNT(self);
8754}
8755
8756function emitCloseNT(self) {
8757 if (self._writableState && !self._writableState.emitClose) return;
8758 if (self._readableState && !self._readableState.emitClose) return;
8759 self.emit('close');
8760}
8761
8762function undestroy() {
8763 if (this._readableState) {
8764 this._readableState.destroyed = false;
8765 this._readableState.reading = false;
8766 this._readableState.ended = false;
8767 this._readableState.endEmitted = false;
8768 }
8769
8770 if (this._writableState) {
8771 this._writableState.destroyed = false;
8772 this._writableState.ended = false;
8773 this._writableState.ending = false;
8774 this._writableState.finalCalled = false;
8775 this._writableState.prefinished = false;
8776 this._writableState.finished = false;
8777 this._writableState.errorEmitted = false;
8778 }
8779}
8780
8781function emitErrorNT(self, err) {
8782 self.emit('error', err);
8783}
8784
8785function errorOrDestroy(stream, err) {
8786 // We have tests that rely on errors being emitted
8787 // in the same tick, so changing this is semver major.
8788 // For now when you opt-in to autoDestroy we allow
8789 // the error to be emitted nextTick. In a future
8790 // semver major update we should change the default to this.
8791 var rState = stream._readableState;
8792 var wState = stream._writableState;
8793 if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
8794}
8795
8796module.exports = {
8797 destroy: destroy,
8798 undestroy: undestroy,
8799 errorOrDestroy: errorOrDestroy
8800};
8801}).call(this,_dereq_(70))
8802},{"70":70}],34:[function(_dereq_,module,exports){
8803// Ported from https://github.com/mafintosh/end-of-stream with
8804// permission from the author, Mathias Buus (@mafintosh).
8805'use strict';
8806
8807var ERR_STREAM_PREMATURE_CLOSE = _dereq_(25).codes.ERR_STREAM_PREMATURE_CLOSE;
8808
8809function once(callback) {
8810 var called = false;
8811 return function () {
8812 if (called) return;
8813 called = true;
8814
8815 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
8816 args[_key] = arguments[_key];
8817 }
8818
8819 callback.apply(this, args);
8820 };
8821}
8822
8823function noop() {}
8824
8825function isRequest(stream) {
8826 return stream.setHeader && typeof stream.abort === 'function';
8827}
8828
8829function eos(stream, opts, callback) {
8830 if (typeof opts === 'function') return eos(stream, null, opts);
8831 if (!opts) opts = {};
8832 callback = once(callback || noop);
8833 var readable = opts.readable || opts.readable !== false && stream.readable;
8834 var writable = opts.writable || opts.writable !== false && stream.writable;
8835
8836 var onlegacyfinish = function onlegacyfinish() {
8837 if (!stream.writable) onfinish();
8838 };
8839
8840 var writableEnded = stream._writableState && stream._writableState.finished;
8841
8842 var onfinish = function onfinish() {
8843 writable = false;
8844 writableEnded = true;
8845 if (!readable) callback.call(stream);
8846 };
8847
8848 var readableEnded = stream._readableState && stream._readableState.endEmitted;
8849
8850 var onend = function onend() {
8851 readable = false;
8852 readableEnded = true;
8853 if (!writable) callback.call(stream);
8854 };
8855
8856 var onerror = function onerror(err) {
8857 callback.call(stream, err);
8858 };
8859
8860 var onclose = function onclose() {
8861 var err;
8862
8863 if (readable && !readableEnded) {
8864 if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
8865 return callback.call(stream, err);
8866 }
8867
8868 if (writable && !writableEnded) {
8869 if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
8870 return callback.call(stream, err);
8871 }
8872 };
8873
8874 var onrequest = function onrequest() {
8875 stream.req.on('finish', onfinish);
8876 };
8877
8878 if (isRequest(stream)) {
8879 stream.on('complete', onfinish);
8880 stream.on('abort', onclose);
8881 if (stream.req) onrequest();else stream.on('request', onrequest);
8882 } else if (writable && !stream._writableState) {
8883 // legacy streams
8884 stream.on('end', onlegacyfinish);
8885 stream.on('close', onlegacyfinish);
8886 }
8887
8888 stream.on('end', onend);
8889 stream.on('finish', onfinish);
8890 if (opts.error !== false) stream.on('error', onerror);
8891 stream.on('close', onclose);
8892 return function () {
8893 stream.removeListener('complete', onfinish);
8894 stream.removeListener('abort', onclose);
8895 stream.removeListener('request', onrequest);
8896 if (stream.req) stream.req.removeListener('finish', onfinish);
8897 stream.removeListener('end', onlegacyfinish);
8898 stream.removeListener('close', onlegacyfinish);
8899 stream.removeListener('finish', onfinish);
8900 stream.removeListener('end', onend);
8901 stream.removeListener('error', onerror);
8902 stream.removeListener('close', onclose);
8903 };
8904}
8905
8906module.exports = eos;
8907},{"25":25}],35:[function(_dereq_,module,exports){
8908module.exports = function () {
8909 throw new Error('Readable.from is not available in the browser')
8910};
8911
8912},{}],36:[function(_dereq_,module,exports){
8913// Ported from https://github.com/mafintosh/pump with
8914// permission from the author, Mathias Buus (@mafintosh).
8915'use strict';
8916
8917var eos;
8918
8919function once(callback) {
8920 var called = false;
8921 return function () {
8922 if (called) return;
8923 called = true;
8924 callback.apply(void 0, arguments);
8925 };
8926}
8927
8928var _require$codes = _dereq_(25).codes,
8929 ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
8930 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
8931
8932function noop(err) {
8933 // Rethrow the error if it exists to avoid swallowing it
8934 if (err) throw err;
8935}
8936
8937function isRequest(stream) {
8938 return stream.setHeader && typeof stream.abort === 'function';
8939}
8940
8941function destroyer(stream, reading, writing, callback) {
8942 callback = once(callback);
8943 var closed = false;
8944 stream.on('close', function () {
8945 closed = true;
8946 });
8947 if (eos === undefined) eos = _dereq_(34);
8948 eos(stream, {
8949 readable: reading,
8950 writable: writing
8951 }, function (err) {
8952 if (err) return callback(err);
8953 closed = true;
8954 callback();
8955 });
8956 var destroyed = false;
8957 return function (err) {
8958 if (closed) return;
8959 if (destroyed) return;
8960 destroyed = true; // request.destroy just do .end - .abort is what we want
8961
8962 if (isRequest(stream)) return stream.abort();
8963 if (typeof stream.destroy === 'function') return stream.destroy();
8964 callback(err || new ERR_STREAM_DESTROYED('pipe'));
8965 };
8966}
8967
8968function call(fn) {
8969 fn();
8970}
8971
8972function pipe(from, to) {
8973 return from.pipe(to);
8974}
8975
8976function popCallback(streams) {
8977 if (!streams.length) return noop;
8978 if (typeof streams[streams.length - 1] !== 'function') return noop;
8979 return streams.pop();
8980}
8981
8982function pipeline() {
8983 for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
8984 streams[_key] = arguments[_key];
8985 }
8986
8987 var callback = popCallback(streams);
8988 if (Array.isArray(streams[0])) streams = streams[0];
8989
8990 if (streams.length < 2) {
8991 throw new ERR_MISSING_ARGS('streams');
8992 }
8993
8994 var error;
8995 var destroys = streams.map(function (stream, i) {
8996 var reading = i < streams.length - 1;
8997 var writing = i > 0;
8998 return destroyer(stream, reading, writing, function (err) {
8999 if (!error) error = err;
9000 if (err) destroys.forEach(call);
9001 if (reading) return;
9002 destroys.forEach(call);
9003 callback(error);
9004 });
9005 });
9006 return streams.reduce(pipe);
9007}
9008
9009module.exports = pipeline;
9010},{"25":25,"34":34}],37:[function(_dereq_,module,exports){
9011'use strict';
9012
9013var ERR_INVALID_OPT_VALUE = _dereq_(25).codes.ERR_INVALID_OPT_VALUE;
9014
9015function highWaterMarkFrom(options, isDuplex, duplexKey) {
9016 return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
9017}
9018
9019function getHighWaterMark(state, options, duplexKey, isDuplex) {
9020 var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
9021
9022 if (hwm != null) {
9023 if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
9024 var name = isDuplex ? duplexKey : 'highWaterMark';
9025 throw new ERR_INVALID_OPT_VALUE(name, hwm);
9026 }
9027
9028 return Math.floor(hwm);
9029 } // Default value
9030
9031
9032 return state.objectMode ? 16 : 16 * 1024;
9033}
9034
9035module.exports = {
9036 getHighWaterMark: getHighWaterMark
9037};
9038},{"25":25}],38:[function(_dereq_,module,exports){
9039module.exports = _dereq_(14).EventEmitter;
9040
9041},{"14":14}],39:[function(_dereq_,module,exports){
9042exports = module.exports = _dereq_(28);
9043exports.Stream = exports;
9044exports.Readable = exports;
9045exports.Writable = _dereq_(30);
9046exports.Duplex = _dereq_(26);
9047exports.Transform = _dereq_(29);
9048exports.PassThrough = _dereq_(27);
9049exports.finished = _dereq_(34);
9050exports.pipeline = _dereq_(36);
9051
9052},{"26":26,"27":27,"28":28,"29":29,"30":30,"34":34,"36":36}],40:[function(_dereq_,module,exports){
9053module.exports = extend
9054
9055var hasOwnProperty = Object.prototype.hasOwnProperty;
9056
9057function extend() {
9058 var target = {}
9059
9060 for (var i = 0; i < arguments.length; i++) {
9061 var source = arguments[i]
9062
9063 for (var key in source) {
9064 if (hasOwnProperty.call(source, key)) {
9065 target[key] = source[key]
9066 }
9067 }
9068 }
9069
9070 return target
9071}
9072
9073},{}],41:[function(_dereq_,module,exports){
9074var WriteError = _dereq_(23).WriteError
9075var promisify = _dereq_(44)
9076var getCallback = _dereq_(42).getCallback
9077var getOptions = _dereq_(42).getOptions
9078
9079function Batch (levelup) {
9080 this._levelup = levelup
9081 this.batch = levelup.db.batch()
9082 this.ops = []
9083 this.length = 0
9084}
9085
9086Batch.prototype.put = function (key, value) {
9087 try {
9088 this.batch.put(key, value)
9089 } catch (e) {
9090 throw new WriteError(e)
9091 }
9092
9093 this.ops.push({ type: 'put', key: key, value: value })
9094 this.length++
9095
9096 return this
9097}
9098
9099Batch.prototype.del = function (key) {
9100 try {
9101 this.batch.del(key)
9102 } catch (err) {
9103 throw new WriteError(err)
9104 }
9105
9106 this.ops.push({ type: 'del', key: key })
9107 this.length++
9108
9109 return this
9110}
9111
9112Batch.prototype.clear = function () {
9113 try {
9114 this.batch.clear()
9115 } catch (err) {
9116 throw new WriteError(err)
9117 }
9118
9119 this.ops = []
9120 this.length = 0
9121
9122 return this
9123}
9124
9125Batch.prototype.write = function (options, callback) {
9126 var levelup = this._levelup
9127 var ops = this.ops
9128 var promise
9129
9130 callback = getCallback(options, callback)
9131
9132 if (!callback) {
9133 callback = promisify()
9134 promise = callback.promise
9135 }
9136
9137 options = getOptions(options)
9138
9139 try {
9140 this.batch.write(options, function (err) {
9141 if (err) { return callback(new WriteError(err)) }
9142 levelup.emit('batch', ops)
9143 callback()
9144 })
9145 } catch (err) {
9146 throw new WriteError(err)
9147 }
9148
9149 return promise
9150}
9151
9152module.exports = Batch
9153
9154},{"23":23,"42":42,"44":44}],42:[function(_dereq_,module,exports){
9155exports.getCallback = function (options, callback) {
9156 return typeof options === 'function' ? options : callback
9157}
9158
9159exports.getOptions = function (options) {
9160 return typeof options === 'object' && options !== null ? options : {}
9161}
9162
9163},{}],43:[function(_dereq_,module,exports){
9164(function (process){
9165var EventEmitter = _dereq_(14).EventEmitter
9166var inherits = _dereq_(119).inherits
9167var extend = _dereq_(51)
9168var DeferredLevelDOWN = _dereq_(50)
9169var IteratorStream = _dereq_(24)
9170var Batch = _dereq_(41)
9171var errors = _dereq_(23)
9172var assert = _dereq_(2)
9173var promisify = _dereq_(44)
9174var getCallback = _dereq_(42).getCallback
9175var getOptions = _dereq_(42).getOptions
9176
9177var WriteError = errors.WriteError
9178var ReadError = errors.ReadError
9179var NotFoundError = errors.NotFoundError
9180var OpenError = errors.OpenError
9181var InitializationError = errors.InitializationError
9182
9183// Possible AbstractLevelDOWN#status values:
9184// - 'new' - newly created, not opened or closed
9185// - 'opening' - waiting for the database to be opened, post open()
9186// - 'open' - successfully opened the database, available for use
9187// - 'closing' - waiting for the database to be closed, post close()
9188// - 'closed' - database has been successfully closed, should not be
9189// used except for another open() operation
9190
9191function LevelUP (db, options, callback) {
9192 if (!(this instanceof LevelUP)) {
9193 return new LevelUP(db, options, callback)
9194 }
9195
9196 var error
9197
9198 EventEmitter.call(this)
9199 this.setMaxListeners(Infinity)
9200
9201 if (typeof options === 'function') {
9202 callback = options
9203 options = {}
9204 }
9205
9206 options = options || {}
9207
9208 if (!db || typeof db !== 'object') {
9209 error = new InitializationError('First argument must be an abstract-leveldown compliant store')
9210 if (typeof callback === 'function') {
9211 return process.nextTick(callback, error)
9212 }
9213 throw error
9214 }
9215
9216 assert.strictEqual(typeof db.status, 'string', '.status required, old abstract-leveldown')
9217
9218 this.options = getOptions(options)
9219 this._db = db
9220 this.db = new DeferredLevelDOWN(db)
9221 this.open(callback)
9222}
9223
9224LevelUP.prototype.emit = EventEmitter.prototype.emit
9225LevelUP.prototype.once = EventEmitter.prototype.once
9226inherits(LevelUP, EventEmitter)
9227
9228LevelUP.prototype.open = function (opts, callback) {
9229 var self = this
9230 var promise
9231
9232 if (typeof opts === 'function') {
9233 callback = opts
9234 opts = null
9235 }
9236
9237 if (!callback) {
9238 callback = promisify()
9239 promise = callback.promise
9240 }
9241
9242 if (!opts) {
9243 opts = this.options
9244 }
9245
9246 if (this.isOpen()) {
9247 process.nextTick(callback, null, self)
9248 return promise
9249 }
9250
9251 if (this._isOpening()) {
9252 this.once('open', function () { callback(null, self) })
9253 return promise
9254 }
9255
9256 this.emit('opening')
9257
9258 this.db.open(opts, function (err) {
9259 if (err) {
9260 return callback(new OpenError(err))
9261 }
9262 self.db = self._db
9263 callback(null, self)
9264 self.emit('open')
9265 self.emit('ready')
9266 })
9267
9268 return promise
9269}
9270
9271LevelUP.prototype.close = function (callback) {
9272 var self = this
9273 var promise
9274
9275 if (!callback) {
9276 callback = promisify()
9277 promise = callback.promise
9278 }
9279
9280 if (this.isOpen()) {
9281 this.db.close(function () {
9282 self.emit('closed')
9283 callback.apply(null, arguments)
9284 })
9285 this.emit('closing')
9286 this.db = new DeferredLevelDOWN(this._db)
9287 } else if (this.isClosed()) {
9288 process.nextTick(callback)
9289 } else if (this.db.status === 'closing') {
9290 this.once('closed', callback)
9291 } else if (this._isOpening()) {
9292 this.once('open', function () {
9293 self.close(callback)
9294 })
9295 }
9296
9297 return promise
9298}
9299
9300LevelUP.prototype.isOpen = function () {
9301 return this.db.status === 'open'
9302}
9303
9304LevelUP.prototype._isOpening = function () {
9305 return this.db.status === 'opening'
9306}
9307
9308LevelUP.prototype.isClosed = function () {
9309 return (/^clos|new/).test(this.db.status)
9310}
9311
9312LevelUP.prototype.get = function (key, options, callback) {
9313 if (key === null || key === undefined) {
9314 throw new ReadError('get() requires a key argument')
9315 }
9316
9317 var promise
9318
9319 callback = getCallback(options, callback)
9320
9321 if (!callback) {
9322 callback = promisify()
9323 promise = callback.promise
9324 }
9325
9326 if (maybeError(this, callback)) { return promise }
9327
9328 options = getOptions(options)
9329
9330 this.db.get(key, options, function (err, value) {
9331 if (err) {
9332 if ((/notfound/i).test(err) || err.notFound) {
9333 err = new NotFoundError('Key not found in database [' + key + ']', err)
9334 } else {
9335 err = new ReadError(err)
9336 }
9337 return callback(err)
9338 }
9339 callback(null, value)
9340 })
9341
9342 return promise
9343}
9344
9345LevelUP.prototype.put = function (key, value, options, callback) {
9346 if (key === null || key === undefined) {
9347 throw new WriteError('put() requires a key argument')
9348 }
9349
9350 var self = this
9351 var promise
9352
9353 callback = getCallback(options, callback)
9354
9355 if (!callback) {
9356 callback = promisify()
9357 promise = callback.promise
9358 }
9359
9360 if (maybeError(this, callback)) { return promise }
9361
9362 options = getOptions(options)
9363
9364 this.db.put(key, value, options, function (err) {
9365 if (err) {
9366 return callback(new WriteError(err))
9367 }
9368 self.emit('put', key, value)
9369 callback()
9370 })
9371
9372 return promise
9373}
9374
9375LevelUP.prototype.del = function (key, options, callback) {
9376 if (key === null || key === undefined) {
9377 throw new WriteError('del() requires a key argument')
9378 }
9379
9380 var self = this
9381 var promise
9382
9383 callback = getCallback(options, callback)
9384
9385 if (!callback) {
9386 callback = promisify()
9387 promise = callback.promise
9388 }
9389
9390 if (maybeError(this, callback)) { return promise }
9391
9392 options = getOptions(options)
9393
9394 this.db.del(key, options, function (err) {
9395 if (err) {
9396 return callback(new WriteError(err))
9397 }
9398 self.emit('del', key)
9399 callback()
9400 })
9401
9402 return promise
9403}
9404
9405LevelUP.prototype.batch = function (arr, options, callback) {
9406 if (!arguments.length) {
9407 return new Batch(this)
9408 }
9409
9410 if (!Array.isArray(arr)) {
9411 throw new WriteError('batch() requires an array argument')
9412 }
9413
9414 var self = this
9415 var promise
9416
9417 callback = getCallback(options, callback)
9418
9419 if (!callback) {
9420 callback = promisify()
9421 promise = callback.promise
9422 }
9423
9424 if (maybeError(this, callback)) { return promise }
9425
9426 options = getOptions(options)
9427
9428 this.db.batch(arr, options, function (err) {
9429 if (err) {
9430 return callback(new WriteError(err))
9431 }
9432 self.emit('batch', arr)
9433 callback()
9434 })
9435
9436 return promise
9437}
9438
9439LevelUP.prototype.iterator = function (options) {
9440 return this.db.iterator(options)
9441}
9442
9443LevelUP.prototype.readStream =
9444LevelUP.prototype.createReadStream = function (options) {
9445 options = extend({ keys: true, values: true }, options)
9446 if (typeof options.limit !== 'number') { options.limit = -1 }
9447 return new IteratorStream(this.db.iterator(options), options)
9448}
9449
9450LevelUP.prototype.keyStream =
9451LevelUP.prototype.createKeyStream = function (options) {
9452 return this.createReadStream(extend(options, { keys: true, values: false }))
9453}
9454
9455LevelUP.prototype.valueStream =
9456LevelUP.prototype.createValueStream = function (options) {
9457 return this.createReadStream(extend(options, { keys: false, values: true }))
9458}
9459
9460LevelUP.prototype.toString = function () {
9461 return 'LevelUP'
9462}
9463
9464function maybeError (db, callback) {
9465 if (!db._isOpening() && !db.isOpen()) {
9466 process.nextTick(callback, new ReadError('Database is not open'))
9467 return true
9468 }
9469}
9470
9471LevelUP.errors = errors
9472module.exports = LevelUP.default = LevelUP
9473
9474}).call(this,_dereq_(70))
9475},{"119":119,"14":14,"2":2,"23":23,"24":24,"41":41,"42":42,"44":44,"50":50,"51":51,"70":70}],44:[function(_dereq_,module,exports){
9476function promisify () {
9477 var callback
9478 var promise = new Promise(function (resolve, reject) {
9479 callback = function callback (err, value) {
9480 if (err) reject(err)
9481 else resolve(value)
9482 }
9483 })
9484 callback.promise = promise
9485 return callback
9486}
9487
9488module.exports = promisify
9489
9490},{}],45:[function(_dereq_,module,exports){
9491function AbstractChainedBatch (db) {
9492 if (typeof db !== 'object' || db === null) {
9493 throw new TypeError('First argument must be an abstract-leveldown compliant store')
9494 }
9495
9496 this.db = db
9497 this._operations = []
9498 this._written = false
9499}
9500
9501AbstractChainedBatch.prototype._checkWritten = function () {
9502 if (this._written) {
9503 throw new Error('write() already called on this batch')
9504 }
9505}
9506
9507AbstractChainedBatch.prototype.put = function (key, value) {
9508 this._checkWritten()
9509
9510 var err = this.db._checkKey(key) || this.db._checkValue(value)
9511 if (err) throw err
9512
9513 key = this.db._serializeKey(key)
9514 value = this.db._serializeValue(value)
9515
9516 this._put(key, value)
9517
9518 return this
9519}
9520
9521AbstractChainedBatch.prototype._put = function (key, value) {
9522 this._operations.push({ type: 'put', key: key, value: value })
9523}
9524
9525AbstractChainedBatch.prototype.del = function (key) {
9526 this._checkWritten()
9527
9528 var err = this.db._checkKey(key)
9529 if (err) throw err
9530
9531 key = this.db._serializeKey(key)
9532 this._del(key)
9533
9534 return this
9535}
9536
9537AbstractChainedBatch.prototype._del = function (key) {
9538 this._operations.push({ type: 'del', key: key })
9539}
9540
9541AbstractChainedBatch.prototype.clear = function () {
9542 this._checkWritten()
9543 this._clear()
9544
9545 return this
9546}
9547
9548AbstractChainedBatch.prototype._clear = function () {
9549 this._operations = []
9550}
9551
9552AbstractChainedBatch.prototype.write = function (options, callback) {
9553 this._checkWritten()
9554
9555 if (typeof options === 'function') { callback = options }
9556 if (typeof callback !== 'function') {
9557 throw new Error('write() requires a callback argument')
9558 }
9559 if (typeof options !== 'object' || options === null) {
9560 options = {}
9561 }
9562
9563 this._written = true
9564 this._write(options, callback)
9565}
9566
9567AbstractChainedBatch.prototype._write = function (options, callback) {
9568 this.db._batch(this._operations, options, callback)
9569}
9570
9571module.exports = AbstractChainedBatch
9572
9573},{}],46:[function(_dereq_,module,exports){
9574(function (process){
9575function AbstractIterator (db) {
9576 if (typeof db !== 'object' || db === null) {
9577 throw new TypeError('First argument must be an abstract-leveldown compliant store')
9578 }
9579
9580 this.db = db
9581 this._ended = false
9582 this._nexting = false
9583}
9584
9585AbstractIterator.prototype.next = function (callback) {
9586 var self = this
9587
9588 if (typeof callback !== 'function') {
9589 throw new Error('next() requires a callback argument')
9590 }
9591
9592 if (self._ended) {
9593 process.nextTick(callback, new Error('cannot call next() after end()'))
9594 return self
9595 }
9596
9597 if (self._nexting) {
9598 process.nextTick(callback, new Error('cannot call next() before previous next() has completed'))
9599 return self
9600 }
9601
9602 self._nexting = true
9603 self._next(function () {
9604 self._nexting = false
9605 callback.apply(null, arguments)
9606 })
9607
9608 return self
9609}
9610
9611AbstractIterator.prototype._next = function (callback) {
9612 process.nextTick(callback)
9613}
9614
9615AbstractIterator.prototype.seek = function (target) {
9616 if (this._ended) {
9617 throw new Error('cannot call seek() after end()')
9618 }
9619 if (this._nexting) {
9620 throw new Error('cannot call seek() before next() has completed')
9621 }
9622
9623 target = this.db._serializeKey(target)
9624 this._seek(target)
9625}
9626
9627AbstractIterator.prototype._seek = function (target) {}
9628
9629AbstractIterator.prototype.end = function (callback) {
9630 if (typeof callback !== 'function') {
9631 throw new Error('end() requires a callback argument')
9632 }
9633
9634 if (this._ended) {
9635 return process.nextTick(callback, new Error('end() already called on iterator'))
9636 }
9637
9638 this._ended = true
9639 this._end(callback)
9640}
9641
9642AbstractIterator.prototype._end = function (callback) {
9643 process.nextTick(callback)
9644}
9645
9646module.exports = AbstractIterator
9647
9648}).call(this,_dereq_(70))
9649},{"70":70}],47:[function(_dereq_,module,exports){
9650(function (Buffer,process){
9651var xtend = _dereq_(51)
9652var AbstractIterator = _dereq_(46)
9653var AbstractChainedBatch = _dereq_(45)
9654var hasOwnProperty = Object.prototype.hasOwnProperty
9655var rangeOptions = 'start end gt gte lt lte'.split(' ')
9656
9657function AbstractLevelDOWN () {
9658 this.status = 'new'
9659}
9660
9661AbstractLevelDOWN.prototype.open = function (options, callback) {
9662 var self = this
9663 var oldStatus = this.status
9664
9665 if (typeof options === 'function') callback = options
9666
9667 if (typeof callback !== 'function') {
9668 throw new Error('open() requires a callback argument')
9669 }
9670
9671 if (typeof options !== 'object' || options === null) options = {}
9672
9673 options.createIfMissing = options.createIfMissing !== false
9674 options.errorIfExists = !!options.errorIfExists
9675
9676 this.status = 'opening'
9677 this._open(options, function (err) {
9678 if (err) {
9679 self.status = oldStatus
9680 return callback(err)
9681 }
9682 self.status = 'open'
9683 callback()
9684 })
9685}
9686
9687AbstractLevelDOWN.prototype._open = function (options, callback) {
9688 process.nextTick(callback)
9689}
9690
9691AbstractLevelDOWN.prototype.close = function (callback) {
9692 var self = this
9693 var oldStatus = this.status
9694
9695 if (typeof callback !== 'function') {
9696 throw new Error('close() requires a callback argument')
9697 }
9698
9699 this.status = 'closing'
9700 this._close(function (err) {
9701 if (err) {
9702 self.status = oldStatus
9703 return callback(err)
9704 }
9705 self.status = 'closed'
9706 callback()
9707 })
9708}
9709
9710AbstractLevelDOWN.prototype._close = function (callback) {
9711 process.nextTick(callback)
9712}
9713
9714AbstractLevelDOWN.prototype.get = function (key, options, callback) {
9715 if (typeof options === 'function') callback = options
9716
9717 if (typeof callback !== 'function') {
9718 throw new Error('get() requires a callback argument')
9719 }
9720
9721 var err = this._checkKey(key)
9722 if (err) return process.nextTick(callback, err)
9723
9724 key = this._serializeKey(key)
9725
9726 if (typeof options !== 'object' || options === null) options = {}
9727
9728 options.asBuffer = options.asBuffer !== false
9729
9730 this._get(key, options, callback)
9731}
9732
9733AbstractLevelDOWN.prototype._get = function (key, options, callback) {
9734 process.nextTick(function () { callback(new Error('NotFound')) })
9735}
9736
9737AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
9738 if (typeof options === 'function') callback = options
9739
9740 if (typeof callback !== 'function') {
9741 throw new Error('put() requires a callback argument')
9742 }
9743
9744 var err = this._checkKey(key) || this._checkValue(value)
9745 if (err) return process.nextTick(callback, err)
9746
9747 key = this._serializeKey(key)
9748 value = this._serializeValue(value)
9749
9750 if (typeof options !== 'object' || options === null) options = {}
9751
9752 this._put(key, value, options, callback)
9753}
9754
9755AbstractLevelDOWN.prototype._put = function (key, value, options, callback) {
9756 process.nextTick(callback)
9757}
9758
9759AbstractLevelDOWN.prototype.del = function (key, options, callback) {
9760 if (typeof options === 'function') callback = options
9761
9762 if (typeof callback !== 'function') {
9763 throw new Error('del() requires a callback argument')
9764 }
9765
9766 var err = this._checkKey(key)
9767 if (err) return process.nextTick(callback, err)
9768
9769 key = this._serializeKey(key)
9770
9771 if (typeof options !== 'object' || options === null) options = {}
9772
9773 this._del(key, options, callback)
9774}
9775
9776AbstractLevelDOWN.prototype._del = function (key, options, callback) {
9777 process.nextTick(callback)
9778}
9779
9780AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
9781 if (!arguments.length) return this._chainedBatch()
9782
9783 if (typeof options === 'function') callback = options
9784
9785 if (typeof array === 'function') callback = array
9786
9787 if (typeof callback !== 'function') {
9788 throw new Error('batch(array) requires a callback argument')
9789 }
9790
9791 if (!Array.isArray(array)) {
9792 return process.nextTick(callback, new Error('batch(array) requires an array argument'))
9793 }
9794
9795 if (array.length === 0) {
9796 return process.nextTick(callback)
9797 }
9798
9799 if (typeof options !== 'object' || options === null) options = {}
9800
9801 var serialized = new Array(array.length)
9802
9803 for (var i = 0; i < array.length; i++) {
9804 if (typeof array[i] !== 'object' || array[i] === null) {
9805 return process.nextTick(callback, new Error('batch(array) element must be an object and not `null`'))
9806 }
9807
9808 var e = xtend(array[i])
9809
9810 if (e.type !== 'put' && e.type !== 'del') {
9811 return process.nextTick(callback, new Error("`type` must be 'put' or 'del'"))
9812 }
9813
9814 var err = this._checkKey(e.key)
9815 if (err) return process.nextTick(callback, err)
9816
9817 e.key = this._serializeKey(e.key)
9818
9819 if (e.type === 'put') {
9820 var valueErr = this._checkValue(e.value)
9821 if (valueErr) return process.nextTick(callback, valueErr)
9822
9823 e.value = this._serializeValue(e.value)
9824 }
9825
9826 serialized[i] = e
9827 }
9828
9829 this._batch(serialized, options, callback)
9830}
9831
9832AbstractLevelDOWN.prototype._batch = function (array, options, callback) {
9833 process.nextTick(callback)
9834}
9835
9836AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
9837 options = cleanRangeOptions(this, options)
9838
9839 options.reverse = !!options.reverse
9840 options.keys = options.keys !== false
9841 options.values = options.values !== false
9842 options.limit = 'limit' in options ? options.limit : -1
9843 options.keyAsBuffer = options.keyAsBuffer !== false
9844 options.valueAsBuffer = options.valueAsBuffer !== false
9845
9846 return options
9847}
9848
9849function cleanRangeOptions (db, options) {
9850 var result = {}
9851
9852 for (var k in options) {
9853 if (!hasOwnProperty.call(options, k)) continue
9854
9855 var opt = options[k]
9856
9857 if (isRangeOption(k)) {
9858 // Note that we don't reject nullish and empty options here. While
9859 // those types are invalid as keys, they are valid as range options.
9860 opt = db._serializeKey(opt)
9861 }
9862
9863 result[k] = opt
9864 }
9865
9866 return result
9867}
9868
9869function isRangeOption (k) {
9870 return rangeOptions.indexOf(k) !== -1
9871}
9872
9873AbstractLevelDOWN.prototype.iterator = function (options) {
9874 if (typeof options !== 'object' || options === null) options = {}
9875 options = this._setupIteratorOptions(options)
9876 return this._iterator(options)
9877}
9878
9879AbstractLevelDOWN.prototype._iterator = function (options) {
9880 return new AbstractIterator(this)
9881}
9882
9883AbstractLevelDOWN.prototype._chainedBatch = function () {
9884 return new AbstractChainedBatch(this)
9885}
9886
9887AbstractLevelDOWN.prototype._serializeKey = function (key) {
9888 return key
9889}
9890
9891AbstractLevelDOWN.prototype._serializeValue = function (value) {
9892 return value
9893}
9894
9895AbstractLevelDOWN.prototype._checkKey = function (key) {
9896 if (key === null || key === undefined) {
9897 return new Error('key cannot be `null` or `undefined`')
9898 } else if (Buffer.isBuffer(key) && key.length === 0) {
9899 return new Error('key cannot be an empty Buffer')
9900 } else if (key === '') {
9901 return new Error('key cannot be an empty String')
9902 } else if (Array.isArray(key) && key.length === 0) {
9903 return new Error('key cannot be an empty Array')
9904 }
9905}
9906
9907AbstractLevelDOWN.prototype._checkValue = function (value) {
9908 if (value === null || value === undefined) {
9909 return new Error('value cannot be `null` or `undefined`')
9910 }
9911}
9912
9913module.exports = AbstractLevelDOWN
9914
9915}).call(this,{"isBuffer":_dereq_(19)},_dereq_(70))
9916},{"19":19,"45":45,"46":46,"51":51,"70":70}],48:[function(_dereq_,module,exports){
9917exports.AbstractLevelDOWN = _dereq_(47)
9918exports.AbstractIterator = _dereq_(46)
9919exports.AbstractChainedBatch = _dereq_(45)
9920
9921},{"45":45,"46":46,"47":47}],49:[function(_dereq_,module,exports){
9922var AbstractIterator = _dereq_(48).AbstractIterator
9923var inherits = _dereq_(18)
9924
9925function DeferredIterator (options) {
9926 AbstractIterator.call(this, options)
9927
9928 this._options = options
9929 this._iterator = null
9930 this._operations = []
9931}
9932
9933inherits(DeferredIterator, AbstractIterator)
9934
9935DeferredIterator.prototype.setDb = function (db) {
9936 var it = this._iterator = db.iterator(this._options)
9937 this._operations.forEach(function (op) {
9938 it[op.method].apply(it, op.args)
9939 })
9940}
9941
9942DeferredIterator.prototype._operation = function (method, args) {
9943 if (this._iterator) return this._iterator[method].apply(this._iterator, args)
9944 this._operations.push({ method: method, args: args })
9945}
9946
9947'next end'.split(' ').forEach(function (m) {
9948 DeferredIterator.prototype['_' + m] = function () {
9949 this._operation(m, arguments)
9950 }
9951})
9952
9953// Must defer seek() rather than _seek() because it requires db._serializeKey to be available
9954DeferredIterator.prototype.seek = function () {
9955 this._operation('seek', arguments)
9956}
9957
9958module.exports = DeferredIterator
9959
9960},{"18":18,"48":48}],50:[function(_dereq_,module,exports){
9961var AbstractLevelDOWN = _dereq_(48).AbstractLevelDOWN
9962var inherits = _dereq_(18)
9963var DeferredIterator = _dereq_(49)
9964var deferrables = 'put get del batch'.split(' ')
9965
9966function DeferredLevelDOWN (db) {
9967 AbstractLevelDOWN.call(this, '')
9968 this._db = db
9969 this._operations = []
9970 this._iterators = []
9971 closed(this)
9972}
9973
9974inherits(DeferredLevelDOWN, AbstractLevelDOWN)
9975
9976DeferredLevelDOWN.prototype._open = function (options, callback) {
9977 var self = this
9978
9979 this._db.open(options, function (err) {
9980 if (err) return callback(err)
9981
9982 self._operations.forEach(function (op) {
9983 self._db[op.method].apply(self._db, op.args)
9984 })
9985 self._operations = []
9986 self._iterators.forEach(function (it) {
9987 it.setDb(self._db)
9988 })
9989 self._iterators = []
9990 open(self)
9991 callback()
9992 })
9993}
9994
9995DeferredLevelDOWN.prototype._close = function (callback) {
9996 var self = this
9997
9998 this._db.close(function (err) {
9999 if (err) return callback(err)
10000 closed(self)
10001 callback()
10002 })
10003}
10004
10005function open (self) {
10006 deferrables.concat('iterator').forEach(function (m) {
10007 self['_' + m] = function () {
10008 return this._db[m].apply(this._db, arguments)
10009 }
10010 })
10011 if (self._db.approximateSize) {
10012 self.approximateSize = function () {
10013 return this._db.approximateSize.apply(this._db, arguments)
10014 }
10015 }
10016}
10017
10018function closed (self) {
10019 deferrables.forEach(function (m) {
10020 self['_' + m] = function () {
10021 this._operations.push({ method: m, args: arguments })
10022 }
10023 })
10024 if (typeof self._db.approximateSize === 'function') {
10025 self.approximateSize = function () {
10026 this._operations.push({
10027 method: 'approximateSize',
10028 args: arguments
10029 })
10030 }
10031 }
10032 self._iterator = function (options) {
10033 var it = new DeferredIterator(options)
10034 this._iterators.push(it)
10035 return it
10036 }
10037}
10038
10039DeferredLevelDOWN.prototype._serializeKey = function (key) {
10040 return key
10041}
10042
10043DeferredLevelDOWN.prototype._serializeValue = function (value) {
10044 return value
10045}
10046
10047module.exports = DeferredLevelDOWN
10048module.exports.DeferredIterator = DeferredIterator
10049
10050},{"18":18,"48":48,"49":49}],51:[function(_dereq_,module,exports){
10051arguments[4][40][0].apply(exports,arguments)
10052},{"40":40}],52:[function(_dereq_,module,exports){
10053(function (Buffer){
10054
10055exports.compare = function (a, b) {
10056
10057 if(Buffer.isBuffer(a)) {
10058 var l = Math.min(a.length, b.length)
10059 for(var i = 0; i < l; i++) {
10060 var cmp = a[i] - b[i]
10061 if(cmp) return cmp
10062 }
10063 return a.length - b.length
10064 }
10065
10066 return a < b ? -1 : a > b ? 1 : 0
10067}
10068
10069// to be compatible with the current abstract-leveldown tests
10070// nullish or empty strings.
10071// I could use !!val but I want to permit numbers and booleans,
10072// if possible.
10073
10074function isDef (val) {
10075 return val !== undefined && val !== ''
10076}
10077
10078function has (range, name) {
10079 return Object.hasOwnProperty.call(range, name)
10080}
10081
10082function hasKey(range, name) {
10083 return Object.hasOwnProperty.call(range, name) && name
10084}
10085
10086var lowerBoundKey = exports.lowerBoundKey = function (range) {
10087 return (
10088 hasKey(range, 'gt')
10089 || hasKey(range, 'gte')
10090 || hasKey(range, 'min')
10091 || (range.reverse ? hasKey(range, 'end') : hasKey(range, 'start'))
10092 || undefined
10093 )
10094}
10095
10096var lowerBound = exports.lowerBound = function (range, def) {
10097 var k = lowerBoundKey(range)
10098 return k ? range[k] : def
10099}
10100
10101var lowerBoundInclusive = exports.lowerBoundInclusive = function (range) {
10102 return has(range, 'gt') ? false : true
10103}
10104
10105var upperBoundInclusive = exports.upperBoundInclusive =
10106 function (range) {
10107 return (has(range, 'lt') /*&& !range.maxEx*/) ? false : true
10108 }
10109
10110var lowerBoundExclusive = exports.lowerBoundExclusive =
10111 function (range) {
10112 return !lowerBoundInclusive(range)
10113 }
10114
10115var upperBoundExclusive = exports.upperBoundExclusive =
10116 function (range) {
10117 return !upperBoundInclusive(range)
10118 }
10119
10120var upperBoundKey = exports.upperBoundKey = function (range) {
10121 return (
10122 hasKey(range, 'lt')
10123 || hasKey(range, 'lte')
10124 || hasKey(range, 'max')
10125 || (range.reverse ? hasKey(range, 'start') : hasKey(range, 'end'))
10126 || undefined
10127 )
10128}
10129
10130var upperBound = exports.upperBound = function (range, def) {
10131 var k = upperBoundKey(range)
10132 return k ? range[k] : def
10133}
10134
10135exports.start = function (range, def) {
10136 return range.reverse ? upperBound(range, def) : lowerBound(range, def)
10137}
10138exports.end = function (range, def) {
10139 return range.reverse ? lowerBound(range, def) : upperBound(range, def)
10140}
10141exports.startInclusive = function (range) {
10142 return (
10143 range.reverse
10144 ? upperBoundInclusive(range)
10145 : lowerBoundInclusive(range)
10146 )
10147}
10148exports.endInclusive = function (range) {
10149 return (
10150 range.reverse
10151 ? lowerBoundInclusive(range)
10152 : upperBoundInclusive(range)
10153 )
10154}
10155
10156function id (e) { return e }
10157
10158exports.toLtgt = function (range, _range, map, lower, upper) {
10159 _range = _range || {}
10160 map = map || id
10161 var defaults = arguments.length > 3
10162 var lb = exports.lowerBoundKey(range)
10163 var ub = exports.upperBoundKey(range)
10164 if(lb) {
10165 if(lb === 'gt') _range.gt = map(range.gt, false)
10166 else _range.gte = map(range[lb], false)
10167 }
10168 else if(defaults)
10169 _range.gte = map(lower, false)
10170
10171 if(ub) {
10172 if(ub === 'lt') _range.lt = map(range.lt, true)
10173 else _range.lte = map(range[ub], true)
10174 }
10175 else if(defaults)
10176 _range.lte = map(upper, true)
10177
10178 if(range.reverse != null)
10179 _range.reverse = !!range.reverse
10180
10181 //if range was used mutably
10182 //(in level-sublevel it's part of an options object
10183 //that has more properties on it.)
10184 if(has(_range, 'max')) delete _range.max
10185 if(has(_range, 'min')) delete _range.min
10186 if(has(_range, 'start')) delete _range.start
10187 if(has(_range, 'end')) delete _range.end
10188
10189 return _range
10190}
10191
10192exports.contains = function (range, key, compare) {
10193 compare = compare || exports.compare
10194
10195 var lb = lowerBound(range)
10196 if(isDef(lb)) {
10197 var cmp = compare(key, lb)
10198 if(cmp < 0 || (cmp === 0 && lowerBoundExclusive(range)))
10199 return false
10200 }
10201
10202 var ub = upperBound(range)
10203 if(isDef(ub)) {
10204 var cmp = compare(key, ub)
10205 if(cmp > 0 || (cmp === 0) && upperBoundExclusive(range))
10206 return false
10207 }
10208
10209 return true
10210}
10211
10212exports.filter = function (range, compare) {
10213 return function (key) {
10214 return exports.contains(range, key, compare)
10215 }
10216}
10217
10218
10219
10220}).call(this,{"isBuffer":_dereq_(19)})
10221},{"19":19}],53:[function(_dereq_,module,exports){
10222module.exports = _dereq_(60)
10223
10224},{"60":60}],54:[function(_dereq_,module,exports){
10225(function (Buffer){
10226var inherits = _dereq_(18)
10227 , AbstractLevelDOWN = _dereq_(58).AbstractLevelDOWN
10228 , AbstractIterator = _dereq_(58).AbstractIterator
10229 , ltgt = _dereq_(66)
10230 , createRBT = _dereq_(15)
10231 , globalStore = {}
10232
10233// In Node, use global.setImmediate. In the browser, use a consistent
10234// microtask library to give consistent microtask experience to all browsers
10235var setImmediate = _dereq_(53)
10236
10237function gt(value) {
10238 return ltgt.compare(value, this._end) > 0
10239}
10240
10241function gte(value) {
10242 return ltgt.compare(value, this._end) >= 0
10243}
10244
10245function lt(value) {
10246 return ltgt.compare(value, this._end) < 0
10247}
10248
10249function lte(value) {
10250 return ltgt.compare(value, this._end) <= 0
10251}
10252
10253
10254function MemIterator (db, options) {
10255 AbstractIterator.call(this, db)
10256 this._limit = options.limit
10257
10258 if (this._limit === -1)
10259 this._limit = Infinity
10260
10261 var tree = db._store[db._location]
10262
10263 this.keyAsBuffer = options.keyAsBuffer !== false
10264 this.valueAsBuffer = options.valueAsBuffer !== false
10265 this._reverse = options.reverse
10266 this._options = options
10267 this._done = 0
10268
10269 if (!this._reverse) {
10270 this._incr = 'next'
10271 this._start = ltgt.lowerBound(options)
10272 this._end = ltgt.upperBound(options)
10273
10274 if (typeof this._start === 'undefined')
10275 this._tree = tree.begin
10276 else if (ltgt.lowerBoundInclusive(options))
10277 this._tree = tree.ge(this._start)
10278 else
10279 this._tree = tree.gt(this._start)
10280
10281 if (this._end) {
10282 if (ltgt.upperBoundInclusive(options))
10283 this._test = lte
10284 else
10285 this._test = lt
10286 }
10287
10288 } else {
10289 this._incr = 'prev'
10290 this._start = ltgt.upperBound(options)
10291 this._end = ltgt.lowerBound(options)
10292
10293 if (typeof this._start === 'undefined')
10294 this._tree = tree.end
10295 else if (ltgt.upperBoundInclusive(options))
10296 this._tree = tree.le(this._start)
10297 else
10298 this._tree = tree.lt(this._start)
10299
10300 if (this._end) {
10301 if (ltgt.lowerBoundInclusive(options))
10302 this._test = gte
10303 else
10304 this._test = gt
10305 }
10306
10307 }
10308
10309}
10310
10311inherits(MemIterator, AbstractIterator)
10312
10313MemIterator.prototype._next = function (callback) {
10314 var key
10315 , value
10316
10317 if (this._done++ >= this._limit)
10318 return setImmediate(callback)
10319
10320 if (!this._tree.valid)
10321 return setImmediate(callback)
10322
10323 key = this._tree.key
10324 value = this._tree.value
10325
10326 if (!this._test(key))
10327 return setImmediate(callback)
10328
10329 if (this.keyAsBuffer)
10330 key = new Buffer(key)
10331
10332 if (this.valueAsBuffer)
10333 value = new Buffer(value)
10334
10335 this._tree[this._incr]()
10336
10337 setImmediate(function callNext() {
10338 callback(null, key, value)
10339 })
10340}
10341
10342MemIterator.prototype._test = function () {return true}
10343
10344function MemDOWN (location) {
10345 if (!(this instanceof MemDOWN))
10346 return new MemDOWN(location)
10347
10348 AbstractLevelDOWN.call(this, typeof location == 'string' ? location : '')
10349
10350 this._location = this.location ? ('$' + this.location) : '_tree'
10351 this._store = this.location ? globalStore: this
10352 this._store[this._location] = this._store[this._location] || createRBT(ltgt.compare)
10353}
10354
10355MemDOWN.clearGlobalStore = function (strict) {
10356 if (strict) {
10357 Object.keys(globalStore).forEach(function (key) {
10358 delete globalStore[key]
10359 })
10360 } else {
10361 globalStore = {}
10362 }
10363}
10364
10365inherits(MemDOWN, AbstractLevelDOWN)
10366
10367MemDOWN.prototype._open = function (options, callback) {
10368 var self = this
10369 setImmediate(function callNext() { callback(null, self) })
10370}
10371
10372MemDOWN.prototype._put = function (key, value, options, callback) {
10373 if (typeof value === 'undefined' || value === null) value = ''
10374
10375 var iter = this._store[this._location].find(key)
10376
10377 if (iter.valid) {
10378 this._store[this._location] = iter.update(value)
10379 } else {
10380 this._store[this._location] = this._store[this._location].insert(key, value)
10381 }
10382
10383 setImmediate(callback)
10384}
10385
10386MemDOWN.prototype._get = function (key, options, callback) {
10387 var value = this._store[this._location].get(key)
10388
10389 if (typeof value === 'undefined') {
10390 // 'NotFound' error, consistent with LevelDOWN API
10391 return setImmediate(function callNext() { callback(new Error('NotFound')) })
10392 }
10393
10394 if (options.asBuffer !== false && !this._isBuffer(value))
10395 value = new Buffer(String(value))
10396
10397 setImmediate(function callNext () {
10398 callback(null, value)
10399 })
10400
10401}
10402
10403MemDOWN.prototype._del = function (key, options, callback) {
10404 this._store[this._location] = this._store[this._location].remove(key)
10405 setImmediate(callback)
10406}
10407
10408MemDOWN.prototype._batch = function (array, options, callback) {
10409 var i = -1
10410 , key
10411 , value
10412 , iter
10413 , len = array.length
10414 , tree = this._store[this._location]
10415
10416 while (++i < len) {
10417 if (!array[i])
10418 continue
10419
10420 key = this._isBuffer(array[i].key) ? array[i].key : String(array[i].key)
10421 iter = tree.find(key)
10422
10423 if (array[i].type === 'put') {
10424 value = this._isBuffer(array[i].value) ? array[i].value : String(array[i].value)
10425 tree = iter.valid ? iter.update(value) : tree.insert(key, value)
10426 } else {
10427 tree = iter.remove()
10428 }
10429 }
10430
10431 this._store[this._location] = tree
10432
10433 setImmediate(callback)
10434}
10435
10436MemDOWN.prototype._iterator = function (options) {
10437 return new MemIterator(this, options)
10438}
10439
10440MemDOWN.prototype._isBuffer = function (obj) {
10441 return Buffer.isBuffer(obj)
10442}
10443
10444MemDOWN.destroy = function (name, callback) {
10445 var key = '$' + name
10446
10447 if (key in globalStore)
10448 delete globalStore[key]
10449
10450 setImmediate(callback)
10451}
10452
10453module.exports = MemDOWN
10454
10455}).call(this,_dereq_(9).Buffer)
10456},{"15":15,"18":18,"53":53,"58":58,"66":66,"9":9}],55:[function(_dereq_,module,exports){
10457(function (process){
10458/* Copyright (c) 2013 Rod Vagg, MIT License */
10459
10460function AbstractChainedBatch (db) {
10461 this._db = db
10462 this._operations = []
10463 this._written = false
10464}
10465
10466AbstractChainedBatch.prototype._checkWritten = function () {
10467 if (this._written)
10468 throw new Error('write() already called on this batch')
10469}
10470
10471AbstractChainedBatch.prototype.put = function (key, value) {
10472 this._checkWritten()
10473
10474 var err = this._db._checkKey(key, 'key', this._db._isBuffer)
10475 if (err)
10476 throw err
10477
10478 if (!this._db._isBuffer(key)) key = String(key)
10479 if (!this._db._isBuffer(value)) value = String(value)
10480
10481 if (typeof this._put == 'function' )
10482 this._put(key, value)
10483 else
10484 this._operations.push({ type: 'put', key: key, value: value })
10485
10486 return this
10487}
10488
10489AbstractChainedBatch.prototype.del = function (key) {
10490 this._checkWritten()
10491
10492 var err = this._db._checkKey(key, 'key', this._db._isBuffer)
10493 if (err) throw err
10494
10495 if (!this._db._isBuffer(key)) key = String(key)
10496
10497 if (typeof this._del == 'function' )
10498 this._del(key)
10499 else
10500 this._operations.push({ type: 'del', key: key })
10501
10502 return this
10503}
10504
10505AbstractChainedBatch.prototype.clear = function () {
10506 this._checkWritten()
10507
10508 this._operations = []
10509
10510 if (typeof this._clear == 'function' )
10511 this._clear()
10512
10513 return this
10514}
10515
10516AbstractChainedBatch.prototype.write = function (options, callback) {
10517 this._checkWritten()
10518
10519 if (typeof options == 'function')
10520 callback = options
10521 if (typeof callback != 'function')
10522 throw new Error('write() requires a callback argument')
10523 if (typeof options != 'object')
10524 options = {}
10525
10526 this._written = true
10527
10528 if (typeof this._write == 'function' )
10529 return this._write(callback)
10530
10531 if (typeof this._db._batch == 'function')
10532 return this._db._batch(this._operations, options, callback)
10533
10534 process.nextTick(callback)
10535}
10536
10537module.exports = AbstractChainedBatch
10538}).call(this,_dereq_(70))
10539},{"70":70}],56:[function(_dereq_,module,exports){
10540(function (process){
10541/* Copyright (c) 2013 Rod Vagg, MIT License */
10542
10543function AbstractIterator (db) {
10544 this.db = db
10545 this._ended = false
10546 this._nexting = false
10547}
10548
10549AbstractIterator.prototype.next = function (callback) {
10550 var self = this
10551
10552 if (typeof callback != 'function')
10553 throw new Error('next() requires a callback argument')
10554
10555 if (self._ended)
10556 return callback(new Error('cannot call next() after end()'))
10557 if (self._nexting)
10558 return callback(new Error('cannot call next() before previous next() has completed'))
10559
10560 self._nexting = true
10561 if (typeof self._next == 'function') {
10562 return self._next(function () {
10563 self._nexting = false
10564 callback.apply(null, arguments)
10565 })
10566 }
10567
10568 process.nextTick(function () {
10569 self._nexting = false
10570 callback()
10571 })
10572}
10573
10574AbstractIterator.prototype.end = function (callback) {
10575 if (typeof callback != 'function')
10576 throw new Error('end() requires a callback argument')
10577
10578 if (this._ended)
10579 return callback(new Error('end() already called on iterator'))
10580
10581 this._ended = true
10582
10583 if (typeof this._end == 'function')
10584 return this._end(callback)
10585
10586 process.nextTick(callback)
10587}
10588
10589module.exports = AbstractIterator
10590
10591}).call(this,_dereq_(70))
10592},{"70":70}],57:[function(_dereq_,module,exports){
10593(function (Buffer,process){
10594/* Copyright (c) 2013 Rod Vagg, MIT License */
10595
10596var xtend = _dereq_(67)
10597 , AbstractIterator = _dereq_(56)
10598 , AbstractChainedBatch = _dereq_(55)
10599
10600function AbstractLevelDOWN (location) {
10601 if (!arguments.length || location === undefined)
10602 throw new Error('constructor requires at least a location argument')
10603
10604 if (typeof location != 'string')
10605 throw new Error('constructor requires a location string argument')
10606
10607 this.location = location
10608 this.status = 'new'
10609}
10610
10611AbstractLevelDOWN.prototype.open = function (options, callback) {
10612 var self = this
10613 , oldStatus = this.status
10614
10615 if (typeof options == 'function')
10616 callback = options
10617
10618 if (typeof callback != 'function')
10619 throw new Error('open() requires a callback argument')
10620
10621 if (typeof options != 'object')
10622 options = {}
10623
10624 options.createIfMissing = options.createIfMissing != false
10625 options.errorIfExists = !!options.errorIfExists
10626
10627 if (typeof this._open == 'function') {
10628 this.status = 'opening'
10629 this._open(options, function (err) {
10630 if (err) {
10631 self.status = oldStatus
10632 return callback(err)
10633 }
10634 self.status = 'open'
10635 callback()
10636 })
10637 } else {
10638 this.status = 'open'
10639 process.nextTick(callback)
10640 }
10641}
10642
10643AbstractLevelDOWN.prototype.close = function (callback) {
10644 var self = this
10645 , oldStatus = this.status
10646
10647 if (typeof callback != 'function')
10648 throw new Error('close() requires a callback argument')
10649
10650 if (typeof this._close == 'function') {
10651 this.status = 'closing'
10652 this._close(function (err) {
10653 if (err) {
10654 self.status = oldStatus
10655 return callback(err)
10656 }
10657 self.status = 'closed'
10658 callback()
10659 })
10660 } else {
10661 this.status = 'closed'
10662 process.nextTick(callback)
10663 }
10664}
10665
10666AbstractLevelDOWN.prototype.get = function (key, options, callback) {
10667 var err
10668
10669 if (typeof options == 'function')
10670 callback = options
10671
10672 if (typeof callback != 'function')
10673 throw new Error('get() requires a callback argument')
10674
10675 if (err = this._checkKey(key, 'key', this._isBuffer))
10676 return callback(err)
10677
10678 if (!this._isBuffer(key))
10679 key = String(key)
10680
10681 if (typeof options != 'object')
10682 options = {}
10683
10684 options.asBuffer = options.asBuffer != false
10685
10686 if (typeof this._get == 'function')
10687 return this._get(key, options, callback)
10688
10689 process.nextTick(function () { callback(new Error('NotFound')) })
10690}
10691
10692AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
10693 var err
10694
10695 if (typeof options == 'function')
10696 callback = options
10697
10698 if (typeof callback != 'function')
10699 throw new Error('put() requires a callback argument')
10700
10701 if (err = this._checkKey(key, 'key', this._isBuffer))
10702 return callback(err)
10703
10704 if (!this._isBuffer(key))
10705 key = String(key)
10706
10707 // coerce value to string in node, don't touch it in browser
10708 // (indexeddb can store any JS type)
10709 if (value != null && !this._isBuffer(value) && !process.browser)
10710 value = String(value)
10711
10712 if (typeof options != 'object')
10713 options = {}
10714
10715 if (typeof this._put == 'function')
10716 return this._put(key, value, options, callback)
10717
10718 process.nextTick(callback)
10719}
10720
10721AbstractLevelDOWN.prototype.del = function (key, options, callback) {
10722 var err
10723
10724 if (typeof options == 'function')
10725 callback = options
10726
10727 if (typeof callback != 'function')
10728 throw new Error('del() requires a callback argument')
10729
10730 if (err = this._checkKey(key, 'key', this._isBuffer))
10731 return callback(err)
10732
10733 if (!this._isBuffer(key))
10734 key = String(key)
10735
10736 if (typeof options != 'object')
10737 options = {}
10738
10739 if (typeof this._del == 'function')
10740 return this._del(key, options, callback)
10741
10742 process.nextTick(callback)
10743}
10744
10745AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
10746 if (!arguments.length)
10747 return this._chainedBatch()
10748
10749 if (typeof options == 'function')
10750 callback = options
10751
10752 if (typeof array == 'function')
10753 callback = array
10754
10755 if (typeof callback != 'function')
10756 throw new Error('batch(array) requires a callback argument')
10757
10758 if (!Array.isArray(array))
10759 return callback(new Error('batch(array) requires an array argument'))
10760
10761 if (!options || typeof options != 'object')
10762 options = {}
10763
10764 var i = 0
10765 , l = array.length
10766 , e
10767 , err
10768
10769 for (; i < l; i++) {
10770 e = array[i]
10771 if (typeof e != 'object')
10772 continue
10773
10774 if (err = this._checkKey(e.type, 'type', this._isBuffer))
10775 return callback(err)
10776
10777 if (err = this._checkKey(e.key, 'key', this._isBuffer))
10778 return callback(err)
10779 }
10780
10781 if (typeof this._batch == 'function')
10782 return this._batch(array, options, callback)
10783
10784 process.nextTick(callback)
10785}
10786
10787//TODO: remove from here, not a necessary primitive
10788AbstractLevelDOWN.prototype.approximateSize = function (start, end, callback) {
10789 if ( start == null
10790 || end == null
10791 || typeof start == 'function'
10792 || typeof end == 'function') {
10793 throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments')
10794 }
10795
10796 if (typeof callback != 'function')
10797 throw new Error('approximateSize() requires a callback argument')
10798
10799 if (!this._isBuffer(start))
10800 start = String(start)
10801
10802 if (!this._isBuffer(end))
10803 end = String(end)
10804
10805 if (typeof this._approximateSize == 'function')
10806 return this._approximateSize(start, end, callback)
10807
10808 process.nextTick(function () {
10809 callback(null, 0)
10810 })
10811}
10812
10813AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
10814 var self = this
10815
10816 options = xtend(options)
10817
10818 ;[ 'start', 'end', 'gt', 'gte', 'lt', 'lte' ].forEach(function (o) {
10819 if (options[o] && self._isBuffer(options[o]) && options[o].length === 0)
10820 delete options[o]
10821 })
10822
10823 options.reverse = !!options.reverse
10824 options.keys = options.keys != false
10825 options.values = options.values != false
10826 options.limit = 'limit' in options ? options.limit : -1
10827 options.keyAsBuffer = options.keyAsBuffer != false
10828 options.valueAsBuffer = options.valueAsBuffer != false
10829
10830 return options
10831}
10832
10833AbstractLevelDOWN.prototype.iterator = function (options) {
10834 if (typeof options != 'object')
10835 options = {}
10836
10837 options = this._setupIteratorOptions(options)
10838
10839 if (typeof this._iterator == 'function')
10840 return this._iterator(options)
10841
10842 return new AbstractIterator(this)
10843}
10844
10845AbstractLevelDOWN.prototype._chainedBatch = function () {
10846 return new AbstractChainedBatch(this)
10847}
10848
10849AbstractLevelDOWN.prototype._isBuffer = function (obj) {
10850 return Buffer.isBuffer(obj)
10851}
10852
10853AbstractLevelDOWN.prototype._checkKey = function (obj, type) {
10854
10855 if (obj === null || obj === undefined)
10856 return new Error(type + ' cannot be `null` or `undefined`')
10857
10858 if (this._isBuffer(obj)) {
10859 if (obj.length === 0)
10860 return new Error(type + ' cannot be an empty Buffer')
10861 } else if (String(obj) === '')
10862 return new Error(type + ' cannot be an empty String')
10863}
10864
10865module.exports = AbstractLevelDOWN
10866
10867}).call(this,{"isBuffer":_dereq_(19)},_dereq_(70))
10868},{"19":19,"55":55,"56":56,"67":67,"70":70}],58:[function(_dereq_,module,exports){
10869exports.AbstractLevelDOWN = _dereq_(57)
10870exports.AbstractIterator = _dereq_(56)
10871exports.AbstractChainedBatch = _dereq_(55)
10872exports.isLevelDOWN = _dereq_(59)
10873
10874},{"55":55,"56":56,"57":57,"59":59}],59:[function(_dereq_,module,exports){
10875var AbstractLevelDOWN = _dereq_(57)
10876
10877function isLevelDOWN (db) {
10878 if (!db || typeof db !== 'object')
10879 return false
10880 return Object.keys(AbstractLevelDOWN.prototype).filter(function (name) {
10881 // TODO remove approximateSize check when method is gone
10882 return name[0] != '_' && name != 'approximateSize'
10883 }).every(function (name) {
10884 return typeof db[name] == 'function'
10885 })
10886}
10887
10888module.exports = isLevelDOWN
10889
10890},{"57":57}],60:[function(_dereq_,module,exports){
10891'use strict';
10892var types = [
10893 _dereq_(63),
10894 _dereq_(62),
10895 _dereq_(61),
10896 _dereq_(64),
10897 _dereq_(65)
10898];
10899var draining;
10900var currentQueue;
10901var queueIndex = -1;
10902var queue = [];
10903var scheduled = false;
10904function cleanUpNextTick() {
10905 if (!draining || !currentQueue) {
10906 return;
10907 }
10908 draining = false;
10909 if (currentQueue.length) {
10910 queue = currentQueue.concat(queue);
10911 } else {
10912 queueIndex = -1;
10913 }
10914 if (queue.length) {
10915 nextTick();
10916 }
10917}
10918
10919//named nextTick for less confusing stack traces
10920function nextTick() {
10921 if (draining) {
10922 return;
10923 }
10924 scheduled = false;
10925 draining = true;
10926 var len = queue.length;
10927 var timeout = setTimeout(cleanUpNextTick);
10928 while (len) {
10929 currentQueue = queue;
10930 queue = [];
10931 while (currentQueue && ++queueIndex < len) {
10932 currentQueue[queueIndex].run();
10933 }
10934 queueIndex = -1;
10935 len = queue.length;
10936 }
10937 currentQueue = null;
10938 queueIndex = -1;
10939 draining = false;
10940 clearTimeout(timeout);
10941}
10942var scheduleDrain;
10943var i = -1;
10944var len = types.length;
10945while (++i < len) {
10946 if (types[i] && types[i].test && types[i].test()) {
10947 scheduleDrain = types[i].install(nextTick);
10948 break;
10949 }
10950}
10951// v8 likes predictible objects
10952function Item(fun, array) {
10953 this.fun = fun;
10954 this.array = array;
10955}
10956Item.prototype.run = function () {
10957 var fun = this.fun;
10958 var array = this.array;
10959 switch (array.length) {
10960 case 0:
10961 return fun();
10962 case 1:
10963 return fun(array[0]);
10964 case 2:
10965 return fun(array[0], array[1]);
10966 case 3:
10967 return fun(array[0], array[1], array[2]);
10968 default:
10969 return fun.apply(null, array);
10970 }
10971
10972};
10973module.exports = immediate;
10974function immediate(task) {
10975 var args = new Array(arguments.length - 1);
10976 if (arguments.length > 1) {
10977 for (var i = 1; i < arguments.length; i++) {
10978 args[i - 1] = arguments[i];
10979 }
10980 }
10981 queue.push(new Item(task, args));
10982 if (!scheduled && !draining) {
10983 scheduled = true;
10984 scheduleDrain();
10985 }
10986}
10987
10988},{"61":61,"62":62,"63":63,"64":64,"65":65}],61:[function(_dereq_,module,exports){
10989(function (global){
10990'use strict';
10991
10992exports.test = function () {
10993 if (global.setImmediate) {
10994 // we can only get here in IE10
10995 // which doesn't handel postMessage well
10996 return false;
10997 }
10998 return typeof global.MessageChannel !== 'undefined';
10999};
11000
11001exports.install = function (func) {
11002 var channel = new global.MessageChannel();
11003 channel.port1.onmessage = func;
11004 return function () {
11005 channel.port2.postMessage(0);
11006 };
11007};
11008}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
11009},{}],62:[function(_dereq_,module,exports){
11010(function (global){
11011'use strict';
11012//based off rsvp https://github.com/tildeio/rsvp.js
11013//license https://github.com/tildeio/rsvp.js/blob/master/LICENSE
11014//https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/asap.js
11015
11016var Mutation = global.MutationObserver || global.WebKitMutationObserver;
11017
11018exports.test = function () {
11019 return Mutation;
11020};
11021
11022exports.install = function (handle) {
11023 var called = 0;
11024 var observer = new Mutation(handle);
11025 var element = global.document.createTextNode('');
11026 observer.observe(element, {
11027 characterData: true
11028 });
11029 return function () {
11030 element.data = (called = ++called % 2);
11031 };
11032};
11033}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
11034},{}],63:[function(_dereq_,module,exports){
11035(function (process){
11036'use strict';
11037exports.test = function () {
11038 // Don't get fooled by e.g. browserify environments.
11039 return (typeof process !== 'undefined') && !process.browser;
11040};
11041
11042exports.install = function (func) {
11043 return function () {
11044 process.nextTick(func);
11045 };
11046};
11047
11048}).call(this,_dereq_(70))
11049},{"70":70}],64:[function(_dereq_,module,exports){
11050(function (global){
11051'use strict';
11052
11053exports.test = function () {
11054 return 'document' in global && 'onreadystatechange' in global.document.createElement('script');
11055};
11056
11057exports.install = function (handle) {
11058 return function () {
11059
11060 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
11061 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
11062 var scriptEl = global.document.createElement('script');
11063 scriptEl.onreadystatechange = function () {
11064 handle();
11065
11066 scriptEl.onreadystatechange = null;
11067 scriptEl.parentNode.removeChild(scriptEl);
11068 scriptEl = null;
11069 };
11070 global.document.documentElement.appendChild(scriptEl);
11071
11072 return handle;
11073 };
11074};
11075}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
11076},{}],65:[function(_dereq_,module,exports){
11077'use strict';
11078exports.test = function () {
11079 return true;
11080};
11081
11082exports.install = function (t) {
11083 return function () {
11084 setTimeout(t, 0);
11085 };
11086};
11087},{}],66:[function(_dereq_,module,exports){
11088(function (Buffer){
11089
11090exports.compare = function (a, b) {
11091
11092 if(Buffer.isBuffer(a)) {
11093 var l = Math.min(a.length, b.length)
11094 for(var i = 0; i < l; i++) {
11095 var cmp = a[i] - b[i]
11096 if(cmp) return cmp
11097 }
11098 return a.length - b.length
11099 }
11100
11101 return a < b ? -1 : a > b ? 1 : 0
11102}
11103
11104function has(obj, key) {
11105 return Object.hasOwnProperty.call(obj, key)
11106}
11107
11108// to be compatible with the current abstract-leveldown tests
11109// nullish or empty strings.
11110// I could use !!val but I want to permit numbers and booleans,
11111// if possible.
11112
11113function isDef (val) {
11114 return val !== undefined && val !== ''
11115}
11116
11117function has (range, name) {
11118 return Object.hasOwnProperty.call(range, name)
11119}
11120
11121function hasKey(range, name) {
11122 return Object.hasOwnProperty.call(range, name) && name
11123}
11124
11125var lowerBoundKey = exports.lowerBoundKey = function (range) {
11126 return (
11127 hasKey(range, 'gt')
11128 || hasKey(range, 'gte')
11129 || hasKey(range, 'min')
11130 || (range.reverse ? hasKey(range, 'end') : hasKey(range, 'start'))
11131 || undefined
11132 )
11133}
11134
11135var lowerBound = exports.lowerBound = function (range) {
11136 var k = lowerBoundKey(range)
11137 return k && range[k]
11138}
11139
11140var lowerBoundInclusive = exports.lowerBoundInclusive = function (range) {
11141 return has(range, 'gt') ? false : true
11142}
11143
11144var upperBoundInclusive = exports.upperBoundInclusive =
11145 function (range) {
11146 return (has(range, 'lt') /*&& !range.maxEx*/) ? false : true
11147 }
11148
11149var lowerBoundExclusive = exports.lowerBoundExclusive =
11150 function (range) {
11151 return !lowerBoundInclusive(range)
11152 }
11153
11154var upperBoundExclusive = exports.upperBoundExclusive =
11155 function (range) {
11156 return !upperBoundInclusive(range)
11157 }
11158
11159var upperBoundKey = exports.upperBoundKey = function (range) {
11160 return (
11161 hasKey(range, 'lt')
11162 || hasKey(range, 'lte')
11163 || hasKey(range, 'max')
11164 || (range.reverse ? hasKey(range, 'start') : hasKey(range, 'end'))
11165 || undefined
11166 )
11167}
11168
11169var upperBound = exports.upperBound = function (range) {
11170 var k = upperBoundKey(range)
11171 return k && range[k]
11172}
11173
11174function id (e) { return e }
11175
11176exports.toLtgt = function (range, _range, map, lower, upper) {
11177 _range = _range || {}
11178 map = map || id
11179 var defaults = arguments.length > 3
11180 var lb = exports.lowerBoundKey(range)
11181 var ub = exports.upperBoundKey(range)
11182 if(lb) {
11183 if(lb === 'gt') _range.gt = map(range.gt, false)
11184 else _range.gte = map(range[lb], false)
11185 }
11186 else if(defaults)
11187 _range.gte = map(lower, false)
11188
11189 if(ub) {
11190 if(ub === 'lt') _range.lt = map(range.lt, true)
11191 else _range.lte = map(range[ub], true)
11192 }
11193 else if(defaults)
11194 _range.lte = map(upper, true)
11195
11196 if(range.reverse != null)
11197 _range.reverse = !!range.reverse
11198
11199 //if range was used mutably
11200 //(in level-sublevel it's part of an options object
11201 //that has more properties on it.)
11202 if(has(_range, 'max')) delete _range.max
11203 if(has(_range, 'min')) delete _range.min
11204 if(has(_range, 'start')) delete _range.start
11205 if(has(_range, 'end')) delete _range.end
11206
11207 return _range
11208}
11209
11210exports.contains = function (range, key, compare) {
11211 compare = compare || exports.compare
11212
11213 var lb = lowerBound(range)
11214 if(isDef(lb)) {
11215 var cmp = compare(key, lb)
11216 if(cmp < 0 || (cmp === 0 && lowerBoundExclusive(range)))
11217 return false
11218 }
11219
11220 var ub = upperBound(range)
11221 if(isDef(ub)) {
11222 var cmp = compare(key, ub)
11223 if(cmp > 0 || (cmp === 0) && upperBoundExclusive(range))
11224 return false
11225 }
11226
11227 return true
11228}
11229
11230exports.filter = function (range, compare) {
11231 return function (key) {
11232 return exports.contains(range, key, compare)
11233 }
11234}
11235
11236
11237
11238
11239
11240
11241}).call(this,{"isBuffer":_dereq_(19)})
11242},{"19":19}],67:[function(_dereq_,module,exports){
11243arguments[4][40][0].apply(exports,arguments)
11244},{"40":40}],68:[function(_dereq_,module,exports){
11245/*
11246object-assign
11247(c) Sindre Sorhus
11248@license MIT
11249*/
11250
11251'use strict';
11252/* eslint-disable no-unused-vars */
11253var getOwnPropertySymbols = Object.getOwnPropertySymbols;
11254var hasOwnProperty = Object.prototype.hasOwnProperty;
11255var propIsEnumerable = Object.prototype.propertyIsEnumerable;
11256
11257function toObject(val) {
11258 if (val === null || val === undefined) {
11259 throw new TypeError('Object.assign cannot be called with null or undefined');
11260 }
11261
11262 return Object(val);
11263}
11264
11265function shouldUseNative() {
11266 try {
11267 if (!Object.assign) {
11268 return false;
11269 }
11270
11271 // Detect buggy property enumeration order in older V8 versions.
11272
11273 // https://bugs.chromium.org/p/v8/issues/detail?id=4118
11274 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
11275 test1[5] = 'de';
11276 if (Object.getOwnPropertyNames(test1)[0] === '5') {
11277 return false;
11278 }
11279
11280 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
11281 var test2 = {};
11282 for (var i = 0; i < 10; i++) {
11283 test2['_' + String.fromCharCode(i)] = i;
11284 }
11285 var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
11286 return test2[n];
11287 });
11288 if (order2.join('') !== '0123456789') {
11289 return false;
11290 }
11291
11292 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
11293 var test3 = {};
11294 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
11295 test3[letter] = letter;
11296 });
11297 if (Object.keys(Object.assign({}, test3)).join('') !==
11298 'abcdefghijklmnopqrst') {
11299 return false;
11300 }
11301
11302 return true;
11303 } catch (err) {
11304 // We don't expect any of the above to throw, but better to be safe.
11305 return false;
11306 }
11307}
11308
11309module.exports = shouldUseNative() ? Object.assign : function (target, source) {
11310 var from;
11311 var to = toObject(target);
11312 var symbols;
11313
11314 for (var s = 1; s < arguments.length; s++) {
11315 from = Object(arguments[s]);
11316
11317 for (var key in from) {
11318 if (hasOwnProperty.call(from, key)) {
11319 to[key] = from[key];
11320 }
11321 }
11322
11323 if (getOwnPropertySymbols) {
11324 symbols = getOwnPropertySymbols(from);
11325 for (var i = 0; i < symbols.length; i++) {
11326 if (propIsEnumerable.call(from, symbols[i])) {
11327 to[symbols[i]] = from[symbols[i]];
11328 }
11329 }
11330 }
11331 }
11332
11333 return to;
11334};
11335
11336},{}],69:[function(_dereq_,module,exports){
11337(function (process){
11338'use strict';
11339
11340if (typeof process === 'undefined' ||
11341 !process.version ||
11342 process.version.indexOf('v0.') === 0 ||
11343 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
11344 module.exports = { nextTick: nextTick };
11345} else {
11346 module.exports = process
11347}
11348
11349function nextTick(fn, arg1, arg2, arg3) {
11350 if (typeof fn !== 'function') {
11351 throw new TypeError('"callback" argument must be a function');
11352 }
11353 var len = arguments.length;
11354 var args, i;
11355 switch (len) {
11356 case 0:
11357 case 1:
11358 return process.nextTick(fn);
11359 case 2:
11360 return process.nextTick(function afterTickOne() {
11361 fn.call(null, arg1);
11362 });
11363 case 3:
11364 return process.nextTick(function afterTickTwo() {
11365 fn.call(null, arg1, arg2);
11366 });
11367 case 4:
11368 return process.nextTick(function afterTickThree() {
11369 fn.call(null, arg1, arg2, arg3);
11370 });
11371 default:
11372 args = new Array(len - 1);
11373 i = 0;
11374 while (i < args.length) {
11375 args[i++] = arguments[i];
11376 }
11377 return process.nextTick(function afterTick() {
11378 fn.apply(null, args);
11379 });
11380 }
11381}
11382
11383
11384}).call(this,_dereq_(70))
11385},{"70":70}],70:[function(_dereq_,module,exports){
11386// shim for using process in browser
11387var process = module.exports = {};
11388
11389// cached from whatever global is present so that test runners that stub it
11390// don't break things. But we need to wrap it in a try catch in case it is
11391// wrapped in strict mode code which doesn't define any globals. It's inside a
11392// function because try/catches deoptimize in certain engines.
11393
11394var cachedSetTimeout;
11395var cachedClearTimeout;
11396
11397function defaultSetTimout() {
11398 throw new Error('setTimeout has not been defined');
11399}
11400function defaultClearTimeout () {
11401 throw new Error('clearTimeout has not been defined');
11402}
11403(function () {
11404 try {
11405 if (typeof setTimeout === 'function') {
11406 cachedSetTimeout = setTimeout;
11407 } else {
11408 cachedSetTimeout = defaultSetTimout;
11409 }
11410 } catch (e) {
11411 cachedSetTimeout = defaultSetTimout;
11412 }
11413 try {
11414 if (typeof clearTimeout === 'function') {
11415 cachedClearTimeout = clearTimeout;
11416 } else {
11417 cachedClearTimeout = defaultClearTimeout;
11418 }
11419 } catch (e) {
11420 cachedClearTimeout = defaultClearTimeout;
11421 }
11422} ())
11423function runTimeout(fun) {
11424 if (cachedSetTimeout === setTimeout) {
11425 //normal enviroments in sane situations
11426 return setTimeout(fun, 0);
11427 }
11428 // if setTimeout wasn't available but was latter defined
11429 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
11430 cachedSetTimeout = setTimeout;
11431 return setTimeout(fun, 0);
11432 }
11433 try {
11434 // when when somebody has screwed with setTimeout but no I.E. maddness
11435 return cachedSetTimeout(fun, 0);
11436 } catch(e){
11437 try {
11438 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
11439 return cachedSetTimeout.call(null, fun, 0);
11440 } catch(e){
11441 // 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
11442 return cachedSetTimeout.call(this, fun, 0);
11443 }
11444 }
11445
11446
11447}
11448function runClearTimeout(marker) {
11449 if (cachedClearTimeout === clearTimeout) {
11450 //normal enviroments in sane situations
11451 return clearTimeout(marker);
11452 }
11453 // if clearTimeout wasn't available but was latter defined
11454 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
11455 cachedClearTimeout = clearTimeout;
11456 return clearTimeout(marker);
11457 }
11458 try {
11459 // when when somebody has screwed with setTimeout but no I.E. maddness
11460 return cachedClearTimeout(marker);
11461 } catch (e){
11462 try {
11463 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
11464 return cachedClearTimeout.call(null, marker);
11465 } catch (e){
11466 // 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.
11467 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
11468 return cachedClearTimeout.call(this, marker);
11469 }
11470 }
11471
11472
11473
11474}
11475var queue = [];
11476var draining = false;
11477var currentQueue;
11478var queueIndex = -1;
11479
11480function cleanUpNextTick() {
11481 if (!draining || !currentQueue) {
11482 return;
11483 }
11484 draining = false;
11485 if (currentQueue.length) {
11486 queue = currentQueue.concat(queue);
11487 } else {
11488 queueIndex = -1;
11489 }
11490 if (queue.length) {
11491 drainQueue();
11492 }
11493}
11494
11495function drainQueue() {
11496 if (draining) {
11497 return;
11498 }
11499 var timeout = runTimeout(cleanUpNextTick);
11500 draining = true;
11501
11502 var len = queue.length;
11503 while(len) {
11504 currentQueue = queue;
11505 queue = [];
11506 while (++queueIndex < len) {
11507 if (currentQueue) {
11508 currentQueue[queueIndex].run();
11509 }
11510 }
11511 queueIndex = -1;
11512 len = queue.length;
11513 }
11514 currentQueue = null;
11515 draining = false;
11516 runClearTimeout(timeout);
11517}
11518
11519process.nextTick = function (fun) {
11520 var args = new Array(arguments.length - 1);
11521 if (arguments.length > 1) {
11522 for (var i = 1; i < arguments.length; i++) {
11523 args[i - 1] = arguments[i];
11524 }
11525 }
11526 queue.push(new Item(fun, args));
11527 if (queue.length === 1 && !draining) {
11528 runTimeout(drainQueue);
11529 }
11530};
11531
11532// v8 likes predictible objects
11533function Item(fun, array) {
11534 this.fun = fun;
11535 this.array = array;
11536}
11537Item.prototype.run = function () {
11538 this.fun.apply(null, this.array);
11539};
11540process.title = 'browser';
11541process.browser = true;
11542process.env = {};
11543process.argv = [];
11544process.version = ''; // empty string to avoid regexp issues
11545process.versions = {};
11546
11547function noop() {}
11548
11549process.on = noop;
11550process.addListener = noop;
11551process.once = noop;
11552process.off = noop;
11553process.removeListener = noop;
11554process.removeAllListeners = noop;
11555process.emit = noop;
11556process.prependListener = noop;
11557process.prependOnceListener = noop;
11558
11559process.listeners = function (name) { return [] }
11560
11561process.binding = function (name) {
11562 throw new Error('process.binding is not supported');
11563};
11564
11565process.cwd = function () { return '/' };
11566process.chdir = function (dir) {
11567 throw new Error('process.chdir is not supported');
11568};
11569process.umask = function() { return 0; };
11570
11571},{}],71:[function(_dereq_,module,exports){
11572/*!
11573 * prr
11574 * (c) 2013 Rod Vagg <rod@vagg.org>
11575 * https://github.com/rvagg/prr
11576 * License: MIT
11577 */
11578
11579(function (name, context, definition) {
11580 if (typeof module != 'undefined' && module.exports)
11581 module.exports = definition()
11582 else
11583 context[name] = definition()
11584})('prr', this, function() {
11585
11586 var setProperty = typeof Object.defineProperty == 'function'
11587 ? function (obj, key, options) {
11588 Object.defineProperty(obj, key, options)
11589 return obj
11590 }
11591 : function (obj, key, options) { // < es5
11592 obj[key] = options.value
11593 return obj
11594 }
11595
11596 , makeOptions = function (value, options) {
11597 var oo = typeof options == 'object'
11598 , os = !oo && typeof options == 'string'
11599 , op = function (p) {
11600 return oo
11601 ? !!options[p]
11602 : os
11603 ? options.indexOf(p[0]) > -1
11604 : false
11605 }
11606
11607 return {
11608 enumerable : op('enumerable')
11609 , configurable : op('configurable')
11610 , writable : op('writable')
11611 , value : value
11612 }
11613 }
11614
11615 , prr = function (obj, key, value, options) {
11616 var k
11617
11618 options = makeOptions(value, options)
11619
11620 if (typeof key == 'object') {
11621 for (k in key) {
11622 if (Object.hasOwnProperty.call(key, k)) {
11623 options.value = key[k]
11624 setProperty(obj, k, options)
11625 }
11626 }
11627 return obj
11628 }
11629
11630 return setProperty(obj, key, options)
11631 }
11632
11633 return prr
11634})
11635},{}],72:[function(_dereq_,module,exports){
11636(function (process){
11637// Copyright Joyent, Inc. and other Node contributors.
11638//
11639// Permission is hereby granted, free of charge, to any person obtaining a
11640// copy of this software and associated documentation files (the
11641// "Software"), to deal in the Software without restriction, including
11642// without limitation the rights to use, copy, modify, merge, publish,
11643// distribute, sublicense, and/or sell copies of the Software, and to permit
11644// persons to whom the Software is furnished to do so, subject to the
11645// following conditions:
11646//
11647// The above copyright notice and this permission notice shall be included
11648// in all copies or substantial portions of the Software.
11649//
11650// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11651// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11652// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11653// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11654// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11655// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11656// USE OR OTHER DEALINGS IN THE SOFTWARE.
11657
11658// a duplex stream is just a stream that is both readable and writable.
11659// Since JS doesn't have multiple prototypal inheritance, this class
11660// prototypally inherits from Readable, and then parasitically from
11661// Writable.
11662
11663module.exports = Duplex;
11664
11665/*<replacement>*/
11666var objectKeys = Object.keys || function (obj) {
11667 var keys = [];
11668 for (var key in obj) keys.push(key);
11669 return keys;
11670}
11671/*</replacement>*/
11672
11673
11674/*<replacement>*/
11675var util = _dereq_(10);
11676util.inherits = _dereq_(18);
11677/*</replacement>*/
11678
11679var Readable = _dereq_(74);
11680var Writable = _dereq_(76);
11681
11682util.inherits(Duplex, Readable);
11683
11684forEach(objectKeys(Writable.prototype), function(method) {
11685 if (!Duplex.prototype[method])
11686 Duplex.prototype[method] = Writable.prototype[method];
11687});
11688
11689function Duplex(options) {
11690 if (!(this instanceof Duplex))
11691 return new Duplex(options);
11692
11693 Readable.call(this, options);
11694 Writable.call(this, options);
11695
11696 if (options && options.readable === false)
11697 this.readable = false;
11698
11699 if (options && options.writable === false)
11700 this.writable = false;
11701
11702 this.allowHalfOpen = true;
11703 if (options && options.allowHalfOpen === false)
11704 this.allowHalfOpen = false;
11705
11706 this.once('end', onend);
11707}
11708
11709// the no-half-open enforcer
11710function onend() {
11711 // if we allow half-open state, or if the writable side ended,
11712 // then we're ok.
11713 if (this.allowHalfOpen || this._writableState.ended)
11714 return;
11715
11716 // no more data can be written.
11717 // But allow more writes to happen in this tick.
11718 process.nextTick(this.end.bind(this));
11719}
11720
11721function forEach (xs, f) {
11722 for (var i = 0, l = xs.length; i < l; i++) {
11723 f(xs[i], i);
11724 }
11725}
11726
11727}).call(this,_dereq_(70))
11728},{"10":10,"18":18,"70":70,"74":74,"76":76}],73:[function(_dereq_,module,exports){
11729// Copyright Joyent, Inc. and other Node contributors.
11730//
11731// Permission is hereby granted, free of charge, to any person obtaining a
11732// copy of this software and associated documentation files (the
11733// "Software"), to deal in the Software without restriction, including
11734// without limitation the rights to use, copy, modify, merge, publish,
11735// distribute, sublicense, and/or sell copies of the Software, and to permit
11736// persons to whom the Software is furnished to do so, subject to the
11737// following conditions:
11738//
11739// The above copyright notice and this permission notice shall be included
11740// in all copies or substantial portions of the Software.
11741//
11742// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11743// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11744// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11745// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11746// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11747// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11748// USE OR OTHER DEALINGS IN THE SOFTWARE.
11749
11750// a passthrough stream.
11751// basically just the most minimal sort of Transform stream.
11752// Every written chunk gets output as-is.
11753
11754module.exports = PassThrough;
11755
11756var Transform = _dereq_(75);
11757
11758/*<replacement>*/
11759var util = _dereq_(10);
11760util.inherits = _dereq_(18);
11761/*</replacement>*/
11762
11763util.inherits(PassThrough, Transform);
11764
11765function PassThrough(options) {
11766 if (!(this instanceof PassThrough))
11767 return new PassThrough(options);
11768
11769 Transform.call(this, options);
11770}
11771
11772PassThrough.prototype._transform = function(chunk, encoding, cb) {
11773 cb(null, chunk);
11774};
11775
11776},{"10":10,"18":18,"75":75}],74:[function(_dereq_,module,exports){
11777(function (process){
11778// Copyright Joyent, Inc. and other Node contributors.
11779//
11780// Permission is hereby granted, free of charge, to any person obtaining a
11781// copy of this software and associated documentation files (the
11782// "Software"), to deal in the Software without restriction, including
11783// without limitation the rights to use, copy, modify, merge, publish,
11784// distribute, sublicense, and/or sell copies of the Software, and to permit
11785// persons to whom the Software is furnished to do so, subject to the
11786// following conditions:
11787//
11788// The above copyright notice and this permission notice shall be included
11789// in all copies or substantial portions of the Software.
11790//
11791// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11792// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11793// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11794// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11795// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11796// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11797// USE OR OTHER DEALINGS IN THE SOFTWARE.
11798
11799module.exports = Readable;
11800
11801/*<replacement>*/
11802var isArray = _dereq_(20);
11803/*</replacement>*/
11804
11805
11806/*<replacement>*/
11807var Buffer = _dereq_(9).Buffer;
11808/*</replacement>*/
11809
11810Readable.ReadableState = ReadableState;
11811
11812var EE = _dereq_(14).EventEmitter;
11813
11814/*<replacement>*/
11815if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
11816 return emitter.listeners(type).length;
11817};
11818/*</replacement>*/
11819
11820var Stream = _dereq_(81);
11821
11822/*<replacement>*/
11823var util = _dereq_(10);
11824util.inherits = _dereq_(18);
11825/*</replacement>*/
11826
11827var StringDecoder;
11828
11829util.inherits(Readable, Stream);
11830
11831function ReadableState(options, stream) {
11832 options = options || {};
11833
11834 // the point at which it stops calling _read() to fill the buffer
11835 // Note: 0 is a valid value, means "don't call _read preemptively ever"
11836 var hwm = options.highWaterMark;
11837 this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
11838
11839 // cast to ints.
11840 this.highWaterMark = ~~this.highWaterMark;
11841
11842 this.buffer = [];
11843 this.length = 0;
11844 this.pipes = null;
11845 this.pipesCount = 0;
11846 this.flowing = false;
11847 this.ended = false;
11848 this.endEmitted = false;
11849 this.reading = false;
11850
11851 // In streams that never have any data, and do push(null) right away,
11852 // the consumer can miss the 'end' event if they do some I/O before
11853 // consuming the stream. So, we don't emit('end') until some reading
11854 // happens.
11855 this.calledRead = false;
11856
11857 // a flag to be able to tell if the onwrite cb is called immediately,
11858 // or on a later tick. We set this to true at first, becuase any
11859 // actions that shouldn't happen until "later" should generally also
11860 // not happen before the first write call.
11861 this.sync = true;
11862
11863 // whenever we return null, then we set a flag to say
11864 // that we're awaiting a 'readable' event emission.
11865 this.needReadable = false;
11866 this.emittedReadable = false;
11867 this.readableListening = false;
11868
11869
11870 // object stream flag. Used to make read(n) ignore n and to
11871 // make all the buffer merging and length checks go away
11872 this.objectMode = !!options.objectMode;
11873
11874 // Crypto is kind of old and crusty. Historically, its default string
11875 // encoding is 'binary' so we have to make this configurable.
11876 // Everything else in the universe uses 'utf8', though.
11877 this.defaultEncoding = options.defaultEncoding || 'utf8';
11878
11879 // when piping, we only care about 'readable' events that happen
11880 // after read()ing all the bytes and not getting any pushback.
11881 this.ranOut = false;
11882
11883 // the number of writers that are awaiting a drain event in .pipe()s
11884 this.awaitDrain = 0;
11885
11886 // if true, a maybeReadMore has been scheduled
11887 this.readingMore = false;
11888
11889 this.decoder = null;
11890 this.encoding = null;
11891 if (options.encoding) {
11892 if (!StringDecoder)
11893 StringDecoder = _dereq_(77).StringDecoder;
11894 this.decoder = new StringDecoder(options.encoding);
11895 this.encoding = options.encoding;
11896 }
11897}
11898
11899function Readable(options) {
11900 if (!(this instanceof Readable))
11901 return new Readable(options);
11902
11903 this._readableState = new ReadableState(options, this);
11904
11905 // legacy
11906 this.readable = true;
11907
11908 Stream.call(this);
11909}
11910
11911// Manually shove something into the read() buffer.
11912// This returns true if the highWaterMark has not been hit yet,
11913// similar to how Writable.write() returns true if you should
11914// write() some more.
11915Readable.prototype.push = function(chunk, encoding) {
11916 var state = this._readableState;
11917
11918 if (typeof chunk === 'string' && !state.objectMode) {
11919 encoding = encoding || state.defaultEncoding;
11920 if (encoding !== state.encoding) {
11921 chunk = new Buffer(chunk, encoding);
11922 encoding = '';
11923 }
11924 }
11925
11926 return readableAddChunk(this, state, chunk, encoding, false);
11927};
11928
11929// Unshift should *always* be something directly out of read()
11930Readable.prototype.unshift = function(chunk) {
11931 var state = this._readableState;
11932 return readableAddChunk(this, state, chunk, '', true);
11933};
11934
11935function readableAddChunk(stream, state, chunk, encoding, addToFront) {
11936 var er = chunkInvalid(state, chunk);
11937 if (er) {
11938 stream.emit('error', er);
11939 } else if (chunk === null || chunk === undefined) {
11940 state.reading = false;
11941 if (!state.ended)
11942 onEofChunk(stream, state);
11943 } else if (state.objectMode || chunk && chunk.length > 0) {
11944 if (state.ended && !addToFront) {
11945 var e = new Error('stream.push() after EOF');
11946 stream.emit('error', e);
11947 } else if (state.endEmitted && addToFront) {
11948 var e = new Error('stream.unshift() after end event');
11949 stream.emit('error', e);
11950 } else {
11951 if (state.decoder && !addToFront && !encoding)
11952 chunk = state.decoder.write(chunk);
11953
11954 // update the buffer info.
11955 state.length += state.objectMode ? 1 : chunk.length;
11956 if (addToFront) {
11957 state.buffer.unshift(chunk);
11958 } else {
11959 state.reading = false;
11960 state.buffer.push(chunk);
11961 }
11962
11963 if (state.needReadable)
11964 emitReadable(stream);
11965
11966 maybeReadMore(stream, state);
11967 }
11968 } else if (!addToFront) {
11969 state.reading = false;
11970 }
11971
11972 return needMoreData(state);
11973}
11974
11975
11976
11977// if it's past the high water mark, we can push in some more.
11978// Also, if we have no data yet, we can stand some
11979// more bytes. This is to work around cases where hwm=0,
11980// such as the repl. Also, if the push() triggered a
11981// readable event, and the user called read(largeNumber) such that
11982// needReadable was set, then we ought to push more, so that another
11983// 'readable' event will be triggered.
11984function needMoreData(state) {
11985 return !state.ended &&
11986 (state.needReadable ||
11987 state.length < state.highWaterMark ||
11988 state.length === 0);
11989}
11990
11991// backwards compatibility.
11992Readable.prototype.setEncoding = function(enc) {
11993 if (!StringDecoder)
11994 StringDecoder = _dereq_(77).StringDecoder;
11995 this._readableState.decoder = new StringDecoder(enc);
11996 this._readableState.encoding = enc;
11997};
11998
11999// Don't raise the hwm > 128MB
12000var MAX_HWM = 0x800000;
12001function roundUpToNextPowerOf2(n) {
12002 if (n >= MAX_HWM) {
12003 n = MAX_HWM;
12004 } else {
12005 // Get the next highest power of 2
12006 n--;
12007 for (var p = 1; p < 32; p <<= 1) n |= n >> p;
12008 n++;
12009 }
12010 return n;
12011}
12012
12013function howMuchToRead(n, state) {
12014 if (state.length === 0 && state.ended)
12015 return 0;
12016
12017 if (state.objectMode)
12018 return n === 0 ? 0 : 1;
12019
12020 if (n === null || isNaN(n)) {
12021 // only flow one buffer at a time
12022 if (state.flowing && state.buffer.length)
12023 return state.buffer[0].length;
12024 else
12025 return state.length;
12026 }
12027
12028 if (n <= 0)
12029 return 0;
12030
12031 // If we're asking for more than the target buffer level,
12032 // then raise the water mark. Bump up to the next highest
12033 // power of 2, to prevent increasing it excessively in tiny
12034 // amounts.
12035 if (n > state.highWaterMark)
12036 state.highWaterMark = roundUpToNextPowerOf2(n);
12037
12038 // don't have that much. return null, unless we've ended.
12039 if (n > state.length) {
12040 if (!state.ended) {
12041 state.needReadable = true;
12042 return 0;
12043 } else
12044 return state.length;
12045 }
12046
12047 return n;
12048}
12049
12050// you can override either this method, or the async _read(n) below.
12051Readable.prototype.read = function(n) {
12052 var state = this._readableState;
12053 state.calledRead = true;
12054 var nOrig = n;
12055 var ret;
12056
12057 if (typeof n !== 'number' || n > 0)
12058 state.emittedReadable = false;
12059
12060 // if we're doing read(0) to trigger a readable event, but we
12061 // already have a bunch of data in the buffer, then just trigger
12062 // the 'readable' event and move on.
12063 if (n === 0 &&
12064 state.needReadable &&
12065 (state.length >= state.highWaterMark || state.ended)) {
12066 emitReadable(this);
12067 return null;
12068 }
12069
12070 n = howMuchToRead(n, state);
12071
12072 // if we've ended, and we're now clear, then finish it up.
12073 if (n === 0 && state.ended) {
12074 ret = null;
12075
12076 // In cases where the decoder did not receive enough data
12077 // to produce a full chunk, then immediately received an
12078 // EOF, state.buffer will contain [<Buffer >, <Buffer 00 ...>].
12079 // howMuchToRead will see this and coerce the amount to
12080 // read to zero (because it's looking at the length of the
12081 // first <Buffer > in state.buffer), and we'll end up here.
12082 //
12083 // This can only happen via state.decoder -- no other venue
12084 // exists for pushing a zero-length chunk into state.buffer
12085 // and triggering this behavior. In this case, we return our
12086 // remaining data and end the stream, if appropriate.
12087 if (state.length > 0 && state.decoder) {
12088 ret = fromList(n, state);
12089 state.length -= ret.length;
12090 }
12091
12092 if (state.length === 0)
12093 endReadable(this);
12094
12095 return ret;
12096 }
12097
12098 // All the actual chunk generation logic needs to be
12099 // *below* the call to _read. The reason is that in certain
12100 // synthetic stream cases, such as passthrough streams, _read
12101 // may be a completely synchronous operation which may change
12102 // the state of the read buffer, providing enough data when
12103 // before there was *not* enough.
12104 //
12105 // So, the steps are:
12106 // 1. Figure out what the state of things will be after we do
12107 // a read from the buffer.
12108 //
12109 // 2. If that resulting state will trigger a _read, then call _read.
12110 // Note that this may be asynchronous, or synchronous. Yes, it is
12111 // deeply ugly to write APIs this way, but that still doesn't mean
12112 // that the Readable class should behave improperly, as streams are
12113 // designed to be sync/async agnostic.
12114 // Take note if the _read call is sync or async (ie, if the read call
12115 // has returned yet), so that we know whether or not it's safe to emit
12116 // 'readable' etc.
12117 //
12118 // 3. Actually pull the requested chunks out of the buffer and return.
12119
12120 // if we need a readable event, then we need to do some reading.
12121 var doRead = state.needReadable;
12122
12123 // if we currently have less than the highWaterMark, then also read some
12124 if (state.length - n <= state.highWaterMark)
12125 doRead = true;
12126
12127 // however, if we've ended, then there's no point, and if we're already
12128 // reading, then it's unnecessary.
12129 if (state.ended || state.reading)
12130 doRead = false;
12131
12132 if (doRead) {
12133 state.reading = true;
12134 state.sync = true;
12135 // if the length is currently zero, then we *need* a readable event.
12136 if (state.length === 0)
12137 state.needReadable = true;
12138 // call internal read method
12139 this._read(state.highWaterMark);
12140 state.sync = false;
12141 }
12142
12143 // If _read called its callback synchronously, then `reading`
12144 // will be false, and we need to re-evaluate how much data we
12145 // can return to the user.
12146 if (doRead && !state.reading)
12147 n = howMuchToRead(nOrig, state);
12148
12149 if (n > 0)
12150 ret = fromList(n, state);
12151 else
12152 ret = null;
12153
12154 if (ret === null) {
12155 state.needReadable = true;
12156 n = 0;
12157 }
12158
12159 state.length -= n;
12160
12161 // If we have nothing in the buffer, then we want to know
12162 // as soon as we *do* get something into the buffer.
12163 if (state.length === 0 && !state.ended)
12164 state.needReadable = true;
12165
12166 // If we happened to read() exactly the remaining amount in the
12167 // buffer, and the EOF has been seen at this point, then make sure
12168 // that we emit 'end' on the very next tick.
12169 if (state.ended && !state.endEmitted && state.length === 0)
12170 endReadable(this);
12171
12172 return ret;
12173};
12174
12175function chunkInvalid(state, chunk) {
12176 var er = null;
12177 if (!Buffer.isBuffer(chunk) &&
12178 'string' !== typeof chunk &&
12179 chunk !== null &&
12180 chunk !== undefined &&
12181 !state.objectMode) {
12182 er = new TypeError('Invalid non-string/buffer chunk');
12183 }
12184 return er;
12185}
12186
12187
12188function onEofChunk(stream, state) {
12189 if (state.decoder && !state.ended) {
12190 var chunk = state.decoder.end();
12191 if (chunk && chunk.length) {
12192 state.buffer.push(chunk);
12193 state.length += state.objectMode ? 1 : chunk.length;
12194 }
12195 }
12196 state.ended = true;
12197
12198 // if we've ended and we have some data left, then emit
12199 // 'readable' now to make sure it gets picked up.
12200 if (state.length > 0)
12201 emitReadable(stream);
12202 else
12203 endReadable(stream);
12204}
12205
12206// Don't emit readable right away in sync mode, because this can trigger
12207// another read() call => stack overflow. This way, it might trigger
12208// a nextTick recursion warning, but that's not so bad.
12209function emitReadable(stream) {
12210 var state = stream._readableState;
12211 state.needReadable = false;
12212 if (state.emittedReadable)
12213 return;
12214
12215 state.emittedReadable = true;
12216 if (state.sync)
12217 process.nextTick(function() {
12218 emitReadable_(stream);
12219 });
12220 else
12221 emitReadable_(stream);
12222}
12223
12224function emitReadable_(stream) {
12225 stream.emit('readable');
12226}
12227
12228
12229// at this point, the user has presumably seen the 'readable' event,
12230// and called read() to consume some data. that may have triggered
12231// in turn another _read(n) call, in which case reading = true if
12232// it's in progress.
12233// However, if we're not ended, or reading, and the length < hwm,
12234// then go ahead and try to read some more preemptively.
12235function maybeReadMore(stream, state) {
12236 if (!state.readingMore) {
12237 state.readingMore = true;
12238 process.nextTick(function() {
12239 maybeReadMore_(stream, state);
12240 });
12241 }
12242}
12243
12244function maybeReadMore_(stream, state) {
12245 var len = state.length;
12246 while (!state.reading && !state.flowing && !state.ended &&
12247 state.length < state.highWaterMark) {
12248 stream.read(0);
12249 if (len === state.length)
12250 // didn't get any data, stop spinning.
12251 break;
12252 else
12253 len = state.length;
12254 }
12255 state.readingMore = false;
12256}
12257
12258// abstract method. to be overridden in specific implementation classes.
12259// call cb(er, data) where data is <= n in length.
12260// for virtual (non-string, non-buffer) streams, "length" is somewhat
12261// arbitrary, and perhaps not very meaningful.
12262Readable.prototype._read = function(n) {
12263 this.emit('error', new Error('not implemented'));
12264};
12265
12266Readable.prototype.pipe = function(dest, pipeOpts) {
12267 var src = this;
12268 var state = this._readableState;
12269
12270 switch (state.pipesCount) {
12271 case 0:
12272 state.pipes = dest;
12273 break;
12274 case 1:
12275 state.pipes = [state.pipes, dest];
12276 break;
12277 default:
12278 state.pipes.push(dest);
12279 break;
12280 }
12281 state.pipesCount += 1;
12282
12283 var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
12284 dest !== process.stdout &&
12285 dest !== process.stderr;
12286
12287 var endFn = doEnd ? onend : cleanup;
12288 if (state.endEmitted)
12289 process.nextTick(endFn);
12290 else
12291 src.once('end', endFn);
12292
12293 dest.on('unpipe', onunpipe);
12294 function onunpipe(readable) {
12295 if (readable !== src) return;
12296 cleanup();
12297 }
12298
12299 function onend() {
12300 dest.end();
12301 }
12302
12303 // when the dest drains, it reduces the awaitDrain counter
12304 // on the source. This would be more elegant with a .once()
12305 // handler in flow(), but adding and removing repeatedly is
12306 // too slow.
12307 var ondrain = pipeOnDrain(src);
12308 dest.on('drain', ondrain);
12309
12310 function cleanup() {
12311 // cleanup event handlers once the pipe is broken
12312 dest.removeListener('close', onclose);
12313 dest.removeListener('finish', onfinish);
12314 dest.removeListener('drain', ondrain);
12315 dest.removeListener('error', onerror);
12316 dest.removeListener('unpipe', onunpipe);
12317 src.removeListener('end', onend);
12318 src.removeListener('end', cleanup);
12319
12320 // if the reader is waiting for a drain event from this
12321 // specific writer, then it would cause it to never start
12322 // flowing again.
12323 // So, if this is awaiting a drain, then we just call it now.
12324 // If we don't know, then assume that we are waiting for one.
12325 if (!dest._writableState || dest._writableState.needDrain)
12326 ondrain();
12327 }
12328
12329 // if the dest has an error, then stop piping into it.
12330 // however, don't suppress the throwing behavior for this.
12331 function onerror(er) {
12332 unpipe();
12333 dest.removeListener('error', onerror);
12334 if (EE.listenerCount(dest, 'error') === 0)
12335 dest.emit('error', er);
12336 }
12337 // This is a brutally ugly hack to make sure that our error handler
12338 // is attached before any userland ones. NEVER DO THIS.
12339 if (!dest._events || !dest._events.error)
12340 dest.on('error', onerror);
12341 else if (isArray(dest._events.error))
12342 dest._events.error.unshift(onerror);
12343 else
12344 dest._events.error = [onerror, dest._events.error];
12345
12346
12347
12348 // Both close and finish should trigger unpipe, but only once.
12349 function onclose() {
12350 dest.removeListener('finish', onfinish);
12351 unpipe();
12352 }
12353 dest.once('close', onclose);
12354 function onfinish() {
12355 dest.removeListener('close', onclose);
12356 unpipe();
12357 }
12358 dest.once('finish', onfinish);
12359
12360 function unpipe() {
12361 src.unpipe(dest);
12362 }
12363
12364 // tell the dest that it's being piped to
12365 dest.emit('pipe', src);
12366
12367 // start the flow if it hasn't been started already.
12368 if (!state.flowing) {
12369 // the handler that waits for readable events after all
12370 // the data gets sucked out in flow.
12371 // This would be easier to follow with a .once() handler
12372 // in flow(), but that is too slow.
12373 this.on('readable', pipeOnReadable);
12374
12375 state.flowing = true;
12376 process.nextTick(function() {
12377 flow(src);
12378 });
12379 }
12380
12381 return dest;
12382};
12383
12384function pipeOnDrain(src) {
12385 return function() {
12386 var dest = this;
12387 var state = src._readableState;
12388 state.awaitDrain--;
12389 if (state.awaitDrain === 0)
12390 flow(src);
12391 };
12392}
12393
12394function flow(src) {
12395 var state = src._readableState;
12396 var chunk;
12397 state.awaitDrain = 0;
12398
12399 function write(dest, i, list) {
12400 var written = dest.write(chunk);
12401 if (false === written) {
12402 state.awaitDrain++;
12403 }
12404 }
12405
12406 while (state.pipesCount && null !== (chunk = src.read())) {
12407
12408 if (state.pipesCount === 1)
12409 write(state.pipes, 0, null);
12410 else
12411 forEach(state.pipes, write);
12412
12413 src.emit('data', chunk);
12414
12415 // if anyone needs a drain, then we have to wait for that.
12416 if (state.awaitDrain > 0)
12417 return;
12418 }
12419
12420 // if every destination was unpiped, either before entering this
12421 // function, or in the while loop, then stop flowing.
12422 //
12423 // NB: This is a pretty rare edge case.
12424 if (state.pipesCount === 0) {
12425 state.flowing = false;
12426
12427 // if there were data event listeners added, then switch to old mode.
12428 if (EE.listenerCount(src, 'data') > 0)
12429 emitDataEvents(src);
12430 return;
12431 }
12432
12433 // at this point, no one needed a drain, so we just ran out of data
12434 // on the next readable event, start it over again.
12435 state.ranOut = true;
12436}
12437
12438function pipeOnReadable() {
12439 if (this._readableState.ranOut) {
12440 this._readableState.ranOut = false;
12441 flow(this);
12442 }
12443}
12444
12445
12446Readable.prototype.unpipe = function(dest) {
12447 var state = this._readableState;
12448
12449 // if we're not piping anywhere, then do nothing.
12450 if (state.pipesCount === 0)
12451 return this;
12452
12453 // just one destination. most common case.
12454 if (state.pipesCount === 1) {
12455 // passed in one, but it's not the right one.
12456 if (dest && dest !== state.pipes)
12457 return this;
12458
12459 if (!dest)
12460 dest = state.pipes;
12461
12462 // got a match.
12463 state.pipes = null;
12464 state.pipesCount = 0;
12465 this.removeListener('readable', pipeOnReadable);
12466 state.flowing = false;
12467 if (dest)
12468 dest.emit('unpipe', this);
12469 return this;
12470 }
12471
12472 // slow case. multiple pipe destinations.
12473
12474 if (!dest) {
12475 // remove all.
12476 var dests = state.pipes;
12477 var len = state.pipesCount;
12478 state.pipes = null;
12479 state.pipesCount = 0;
12480 this.removeListener('readable', pipeOnReadable);
12481 state.flowing = false;
12482
12483 for (var i = 0; i < len; i++)
12484 dests[i].emit('unpipe', this);
12485 return this;
12486 }
12487
12488 // try to find the right one.
12489 var i = indexOf(state.pipes, dest);
12490 if (i === -1)
12491 return this;
12492
12493 state.pipes.splice(i, 1);
12494 state.pipesCount -= 1;
12495 if (state.pipesCount === 1)
12496 state.pipes = state.pipes[0];
12497
12498 dest.emit('unpipe', this);
12499
12500 return this;
12501};
12502
12503// set up data events if they are asked for
12504// Ensure readable listeners eventually get something
12505Readable.prototype.on = function(ev, fn) {
12506 var res = Stream.prototype.on.call(this, ev, fn);
12507
12508 if (ev === 'data' && !this._readableState.flowing)
12509 emitDataEvents(this);
12510
12511 if (ev === 'readable' && this.readable) {
12512 var state = this._readableState;
12513 if (!state.readableListening) {
12514 state.readableListening = true;
12515 state.emittedReadable = false;
12516 state.needReadable = true;
12517 if (!state.reading) {
12518 this.read(0);
12519 } else if (state.length) {
12520 emitReadable(this, state);
12521 }
12522 }
12523 }
12524
12525 return res;
12526};
12527Readable.prototype.addListener = Readable.prototype.on;
12528
12529// pause() and resume() are remnants of the legacy readable stream API
12530// If the user uses them, then switch into old mode.
12531Readable.prototype.resume = function() {
12532 emitDataEvents(this);
12533 this.read(0);
12534 this.emit('resume');
12535};
12536
12537Readable.prototype.pause = function() {
12538 emitDataEvents(this, true);
12539 this.emit('pause');
12540};
12541
12542function emitDataEvents(stream, startPaused) {
12543 var state = stream._readableState;
12544
12545 if (state.flowing) {
12546 // https://github.com/isaacs/readable-stream/issues/16
12547 throw new Error('Cannot switch to old mode now.');
12548 }
12549
12550 var paused = startPaused || false;
12551 var readable = false;
12552
12553 // convert to an old-style stream.
12554 stream.readable = true;
12555 stream.pipe = Stream.prototype.pipe;
12556 stream.on = stream.addListener = Stream.prototype.on;
12557
12558 stream.on('readable', function() {
12559 readable = true;
12560
12561 var c;
12562 while (!paused && (null !== (c = stream.read())))
12563 stream.emit('data', c);
12564
12565 if (c === null) {
12566 readable = false;
12567 stream._readableState.needReadable = true;
12568 }
12569 });
12570
12571 stream.pause = function() {
12572 paused = true;
12573 this.emit('pause');
12574 };
12575
12576 stream.resume = function() {
12577 paused = false;
12578 if (readable)
12579 process.nextTick(function() {
12580 stream.emit('readable');
12581 });
12582 else
12583 this.read(0);
12584 this.emit('resume');
12585 };
12586
12587 // now make it start, just in case it hadn't already.
12588 stream.emit('readable');
12589}
12590
12591// wrap an old-style stream as the async data source.
12592// This is *not* part of the readable stream interface.
12593// It is an ugly unfortunate mess of history.
12594Readable.prototype.wrap = function(stream) {
12595 var state = this._readableState;
12596 var paused = false;
12597
12598 var self = this;
12599 stream.on('end', function() {
12600 if (state.decoder && !state.ended) {
12601 var chunk = state.decoder.end();
12602 if (chunk && chunk.length)
12603 self.push(chunk);
12604 }
12605
12606 self.push(null);
12607 });
12608
12609 stream.on('data', function(chunk) {
12610 if (state.decoder)
12611 chunk = state.decoder.write(chunk);
12612
12613 // don't skip over falsy values in objectMode
12614 //if (state.objectMode && util.isNullOrUndefined(chunk))
12615 if (state.objectMode && (chunk === null || chunk === undefined))
12616 return;
12617 else if (!state.objectMode && (!chunk || !chunk.length))
12618 return;
12619
12620 var ret = self.push(chunk);
12621 if (!ret) {
12622 paused = true;
12623 stream.pause();
12624 }
12625 });
12626
12627 // proxy all the other methods.
12628 // important when wrapping filters and duplexes.
12629 for (var i in stream) {
12630 if (typeof stream[i] === 'function' &&
12631 typeof this[i] === 'undefined') {
12632 this[i] = function(method) { return function() {
12633 return stream[method].apply(stream, arguments);
12634 }}(i);
12635 }
12636 }
12637
12638 // proxy certain important events.
12639 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
12640 forEach(events, function(ev) {
12641 stream.on(ev, self.emit.bind(self, ev));
12642 });
12643
12644 // when we try to consume some more bytes, simply unpause the
12645 // underlying stream.
12646 self._read = function(n) {
12647 if (paused) {
12648 paused = false;
12649 stream.resume();
12650 }
12651 };
12652
12653 return self;
12654};
12655
12656
12657
12658// exposed for testing purposes only.
12659Readable._fromList = fromList;
12660
12661// Pluck off n bytes from an array of buffers.
12662// Length is the combined lengths of all the buffers in the list.
12663function fromList(n, state) {
12664 var list = state.buffer;
12665 var length = state.length;
12666 var stringMode = !!state.decoder;
12667 var objectMode = !!state.objectMode;
12668 var ret;
12669
12670 // nothing in the list, definitely empty.
12671 if (list.length === 0)
12672 return null;
12673
12674 if (length === 0)
12675 ret = null;
12676 else if (objectMode)
12677 ret = list.shift();
12678 else if (!n || n >= length) {
12679 // read it all, truncate the array.
12680 if (stringMode)
12681 ret = list.join('');
12682 else
12683 ret = Buffer.concat(list, length);
12684 list.length = 0;
12685 } else {
12686 // read just some of it.
12687 if (n < list[0].length) {
12688 // just take a part of the first list item.
12689 // slice is the same for buffers and strings.
12690 var buf = list[0];
12691 ret = buf.slice(0, n);
12692 list[0] = buf.slice(n);
12693 } else if (n === list[0].length) {
12694 // first list is a perfect match
12695 ret = list.shift();
12696 } else {
12697 // complex case.
12698 // we have enough to cover it, but it spans past the first buffer.
12699 if (stringMode)
12700 ret = '';
12701 else
12702 ret = new Buffer(n);
12703
12704 var c = 0;
12705 for (var i = 0, l = list.length; i < l && c < n; i++) {
12706 var buf = list[0];
12707 var cpy = Math.min(n - c, buf.length);
12708
12709 if (stringMode)
12710 ret += buf.slice(0, cpy);
12711 else
12712 buf.copy(ret, c, 0, cpy);
12713
12714 if (cpy < buf.length)
12715 list[0] = buf.slice(cpy);
12716 else
12717 list.shift();
12718
12719 c += cpy;
12720 }
12721 }
12722 }
12723
12724 return ret;
12725}
12726
12727function endReadable(stream) {
12728 var state = stream._readableState;
12729
12730 // If we get here before consuming all the bytes, then that is a
12731 // bug in node. Should never happen.
12732 if (state.length > 0)
12733 throw new Error('endReadable called on non-empty stream');
12734
12735 if (!state.endEmitted && state.calledRead) {
12736 state.ended = true;
12737 process.nextTick(function() {
12738 // Check that we didn't get one last unshift.
12739 if (!state.endEmitted && state.length === 0) {
12740 state.endEmitted = true;
12741 stream.readable = false;
12742 stream.emit('end');
12743 }
12744 });
12745 }
12746}
12747
12748function forEach (xs, f) {
12749 for (var i = 0, l = xs.length; i < l; i++) {
12750 f(xs[i], i);
12751 }
12752}
12753
12754function indexOf (xs, x) {
12755 for (var i = 0, l = xs.length; i < l; i++) {
12756 if (xs[i] === x) return i;
12757 }
12758 return -1;
12759}
12760
12761}).call(this,_dereq_(70))
12762},{"10":10,"14":14,"18":18,"20":20,"70":70,"77":77,"81":81,"9":9}],75:[function(_dereq_,module,exports){
12763// Copyright Joyent, Inc. and other Node contributors.
12764//
12765// Permission is hereby granted, free of charge, to any person obtaining a
12766// copy of this software and associated documentation files (the
12767// "Software"), to deal in the Software without restriction, including
12768// without limitation the rights to use, copy, modify, merge, publish,
12769// distribute, sublicense, and/or sell copies of the Software, and to permit
12770// persons to whom the Software is furnished to do so, subject to the
12771// following conditions:
12772//
12773// The above copyright notice and this permission notice shall be included
12774// in all copies or substantial portions of the Software.
12775//
12776// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12777// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12778// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12779// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12780// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12781// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12782// USE OR OTHER DEALINGS IN THE SOFTWARE.
12783
12784
12785// a transform stream is a readable/writable stream where you do
12786// something with the data. Sometimes it's called a "filter",
12787// but that's not a great name for it, since that implies a thing where
12788// some bits pass through, and others are simply ignored. (That would
12789// be a valid example of a transform, of course.)
12790//
12791// While the output is causally related to the input, it's not a
12792// necessarily symmetric or synchronous transformation. For example,
12793// a zlib stream might take multiple plain-text writes(), and then
12794// emit a single compressed chunk some time in the future.
12795//
12796// Here's how this works:
12797//
12798// The Transform stream has all the aspects of the readable and writable
12799// stream classes. When you write(chunk), that calls _write(chunk,cb)
12800// internally, and returns false if there's a lot of pending writes
12801// buffered up. When you call read(), that calls _read(n) until
12802// there's enough pending readable data buffered up.
12803//
12804// In a transform stream, the written data is placed in a buffer. When
12805// _read(n) is called, it transforms the queued up data, calling the
12806// buffered _write cb's as it consumes chunks. If consuming a single
12807// written chunk would result in multiple output chunks, then the first
12808// outputted bit calls the readcb, and subsequent chunks just go into
12809// the read buffer, and will cause it to emit 'readable' if necessary.
12810//
12811// This way, back-pressure is actually determined by the reading side,
12812// since _read has to be called to start processing a new chunk. However,
12813// a pathological inflate type of transform can cause excessive buffering
12814// here. For example, imagine a stream where every byte of input is
12815// interpreted as an integer from 0-255, and then results in that many
12816// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
12817// 1kb of data being output. In this case, you could write a very small
12818// amount of input, and end up with a very large amount of output. In
12819// such a pathological inflating mechanism, there'd be no way to tell
12820// the system to stop doing the transform. A single 4MB write could
12821// cause the system to run out of memory.
12822//
12823// However, even in such a pathological case, only a single written chunk
12824// would be consumed, and then the rest would wait (un-transformed) until
12825// the results of the previous transformed chunk were consumed.
12826
12827module.exports = Transform;
12828
12829var Duplex = _dereq_(72);
12830
12831/*<replacement>*/
12832var util = _dereq_(10);
12833util.inherits = _dereq_(18);
12834/*</replacement>*/
12835
12836util.inherits(Transform, Duplex);
12837
12838
12839function TransformState(options, stream) {
12840 this.afterTransform = function(er, data) {
12841 return afterTransform(stream, er, data);
12842 };
12843
12844 this.needTransform = false;
12845 this.transforming = false;
12846 this.writecb = null;
12847 this.writechunk = null;
12848}
12849
12850function afterTransform(stream, er, data) {
12851 var ts = stream._transformState;
12852 ts.transforming = false;
12853
12854 var cb = ts.writecb;
12855
12856 if (!cb)
12857 return stream.emit('error', new Error('no writecb in Transform class'));
12858
12859 ts.writechunk = null;
12860 ts.writecb = null;
12861
12862 if (data !== null && data !== undefined)
12863 stream.push(data);
12864
12865 if (cb)
12866 cb(er);
12867
12868 var rs = stream._readableState;
12869 rs.reading = false;
12870 if (rs.needReadable || rs.length < rs.highWaterMark) {
12871 stream._read(rs.highWaterMark);
12872 }
12873}
12874
12875
12876function Transform(options) {
12877 if (!(this instanceof Transform))
12878 return new Transform(options);
12879
12880 Duplex.call(this, options);
12881
12882 var ts = this._transformState = new TransformState(options, this);
12883
12884 // when the writable side finishes, then flush out anything remaining.
12885 var stream = this;
12886
12887 // start out asking for a readable event once data is transformed.
12888 this._readableState.needReadable = true;
12889
12890 // we have implemented the _read method, and done the other things
12891 // that Readable wants before the first _read call, so unset the
12892 // sync guard flag.
12893 this._readableState.sync = false;
12894
12895 this.once('finish', function() {
12896 if ('function' === typeof this._flush)
12897 this._flush(function(er) {
12898 done(stream, er);
12899 });
12900 else
12901 done(stream);
12902 });
12903}
12904
12905Transform.prototype.push = function(chunk, encoding) {
12906 this._transformState.needTransform = false;
12907 return Duplex.prototype.push.call(this, chunk, encoding);
12908};
12909
12910// This is the part where you do stuff!
12911// override this function in implementation classes.
12912// 'chunk' is an input chunk.
12913//
12914// Call `push(newChunk)` to pass along transformed output
12915// to the readable side. You may call 'push' zero or more times.
12916//
12917// Call `cb(err)` when you are done with this chunk. If you pass
12918// an error, then that'll put the hurt on the whole operation. If you
12919// never call cb(), then you'll never get another chunk.
12920Transform.prototype._transform = function(chunk, encoding, cb) {
12921 throw new Error('not implemented');
12922};
12923
12924Transform.prototype._write = function(chunk, encoding, cb) {
12925 var ts = this._transformState;
12926 ts.writecb = cb;
12927 ts.writechunk = chunk;
12928 ts.writeencoding = encoding;
12929 if (!ts.transforming) {
12930 var rs = this._readableState;
12931 if (ts.needTransform ||
12932 rs.needReadable ||
12933 rs.length < rs.highWaterMark)
12934 this._read(rs.highWaterMark);
12935 }
12936};
12937
12938// Doesn't matter what the args are here.
12939// _transform does all the work.
12940// That we got here means that the readable side wants more data.
12941Transform.prototype._read = function(n) {
12942 var ts = this._transformState;
12943
12944 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
12945 ts.transforming = true;
12946 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
12947 } else {
12948 // mark that we need a transform, so that any data that comes in
12949 // will get processed, now that we've asked for it.
12950 ts.needTransform = true;
12951 }
12952};
12953
12954
12955function done(stream, er) {
12956 if (er)
12957 return stream.emit('error', er);
12958
12959 // if there's nothing in the write buffer, then that means
12960 // that nothing more will ever be provided
12961 var ws = stream._writableState;
12962 var rs = stream._readableState;
12963 var ts = stream._transformState;
12964
12965 if (ws.length)
12966 throw new Error('calling transform done when ws.length != 0');
12967
12968 if (ts.transforming)
12969 throw new Error('calling transform done when still transforming');
12970
12971 return stream.push(null);
12972}
12973
12974},{"10":10,"18":18,"72":72}],76:[function(_dereq_,module,exports){
12975(function (process){
12976// Copyright Joyent, Inc. and other Node contributors.
12977//
12978// Permission is hereby granted, free of charge, to any person obtaining a
12979// copy of this software and associated documentation files (the
12980// "Software"), to deal in the Software without restriction, including
12981// without limitation the rights to use, copy, modify, merge, publish,
12982// distribute, sublicense, and/or sell copies of the Software, and to permit
12983// persons to whom the Software is furnished to do so, subject to the
12984// following conditions:
12985//
12986// The above copyright notice and this permission notice shall be included
12987// in all copies or substantial portions of the Software.
12988//
12989// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12990// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12991// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12992// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12993// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12994// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12995// USE OR OTHER DEALINGS IN THE SOFTWARE.
12996
12997// A bit simpler than readable streams.
12998// Implement an async ._write(chunk, cb), and it'll handle all
12999// the drain event emission and buffering.
13000
13001module.exports = Writable;
13002
13003/*<replacement>*/
13004var Buffer = _dereq_(9).Buffer;
13005/*</replacement>*/
13006
13007Writable.WritableState = WritableState;
13008
13009
13010/*<replacement>*/
13011var util = _dereq_(10);
13012util.inherits = _dereq_(18);
13013/*</replacement>*/
13014
13015var Stream = _dereq_(81);
13016
13017util.inherits(Writable, Stream);
13018
13019function WriteReq(chunk, encoding, cb) {
13020 this.chunk = chunk;
13021 this.encoding = encoding;
13022 this.callback = cb;
13023}
13024
13025function WritableState(options, stream) {
13026 options = options || {};
13027
13028 // the point at which write() starts returning false
13029 // Note: 0 is a valid value, means that we always return false if
13030 // the entire buffer is not flushed immediately on write()
13031 var hwm = options.highWaterMark;
13032 this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
13033
13034 // object stream flag to indicate whether or not this stream
13035 // contains buffers or objects.
13036 this.objectMode = !!options.objectMode;
13037
13038 // cast to ints.
13039 this.highWaterMark = ~~this.highWaterMark;
13040
13041 this.needDrain = false;
13042 // at the start of calling end()
13043 this.ending = false;
13044 // when end() has been called, and returned
13045 this.ended = false;
13046 // when 'finish' is emitted
13047 this.finished = false;
13048
13049 // should we decode strings into buffers before passing to _write?
13050 // this is here so that some node-core streams can optimize string
13051 // handling at a lower level.
13052 var noDecode = options.decodeStrings === false;
13053 this.decodeStrings = !noDecode;
13054
13055 // Crypto is kind of old and crusty. Historically, its default string
13056 // encoding is 'binary' so we have to make this configurable.
13057 // Everything else in the universe uses 'utf8', though.
13058 this.defaultEncoding = options.defaultEncoding || 'utf8';
13059
13060 // not an actual buffer we keep track of, but a measurement
13061 // of how much we're waiting to get pushed to some underlying
13062 // socket or file.
13063 this.length = 0;
13064
13065 // a flag to see when we're in the middle of a write.
13066 this.writing = false;
13067
13068 // a flag to be able to tell if the onwrite cb is called immediately,
13069 // or on a later tick. We set this to true at first, becuase any
13070 // actions that shouldn't happen until "later" should generally also
13071 // not happen before the first write call.
13072 this.sync = true;
13073
13074 // a flag to know if we're processing previously buffered items, which
13075 // may call the _write() callback in the same tick, so that we don't
13076 // end up in an overlapped onwrite situation.
13077 this.bufferProcessing = false;
13078
13079 // the callback that's passed to _write(chunk,cb)
13080 this.onwrite = function(er) {
13081 onwrite(stream, er);
13082 };
13083
13084 // the callback that the user supplies to write(chunk,encoding,cb)
13085 this.writecb = null;
13086
13087 // the amount that is being written when _write is called.
13088 this.writelen = 0;
13089
13090 this.buffer = [];
13091
13092 // True if the error was already emitted and should not be thrown again
13093 this.errorEmitted = false;
13094}
13095
13096function Writable(options) {
13097 var Duplex = _dereq_(72);
13098
13099 // Writable ctor is applied to Duplexes, though they're not
13100 // instanceof Writable, they're instanceof Readable.
13101 if (!(this instanceof Writable) && !(this instanceof Duplex))
13102 return new Writable(options);
13103
13104 this._writableState = new WritableState(options, this);
13105
13106 // legacy.
13107 this.writable = true;
13108
13109 Stream.call(this);
13110}
13111
13112// Otherwise people can pipe Writable streams, which is just wrong.
13113Writable.prototype.pipe = function() {
13114 this.emit('error', new Error('Cannot pipe. Not readable.'));
13115};
13116
13117
13118function writeAfterEnd(stream, state, cb) {
13119 var er = new Error('write after end');
13120 // TODO: defer error events consistently everywhere, not just the cb
13121 stream.emit('error', er);
13122 process.nextTick(function() {
13123 cb(er);
13124 });
13125}
13126
13127// If we get something that is not a buffer, string, null, or undefined,
13128// and we're not in objectMode, then that's an error.
13129// Otherwise stream chunks are all considered to be of length=1, and the
13130// watermarks determine how many objects to keep in the buffer, rather than
13131// how many bytes or characters.
13132function validChunk(stream, state, chunk, cb) {
13133 var valid = true;
13134 if (!Buffer.isBuffer(chunk) &&
13135 'string' !== typeof chunk &&
13136 chunk !== null &&
13137 chunk !== undefined &&
13138 !state.objectMode) {
13139 var er = new TypeError('Invalid non-string/buffer chunk');
13140 stream.emit('error', er);
13141 process.nextTick(function() {
13142 cb(er);
13143 });
13144 valid = false;
13145 }
13146 return valid;
13147}
13148
13149Writable.prototype.write = function(chunk, encoding, cb) {
13150 var state = this._writableState;
13151 var ret = false;
13152
13153 if (typeof encoding === 'function') {
13154 cb = encoding;
13155 encoding = null;
13156 }
13157
13158 if (Buffer.isBuffer(chunk))
13159 encoding = 'buffer';
13160 else if (!encoding)
13161 encoding = state.defaultEncoding;
13162
13163 if (typeof cb !== 'function')
13164 cb = function() {};
13165
13166 if (state.ended)
13167 writeAfterEnd(this, state, cb);
13168 else if (validChunk(this, state, chunk, cb))
13169 ret = writeOrBuffer(this, state, chunk, encoding, cb);
13170
13171 return ret;
13172};
13173
13174function decodeChunk(state, chunk, encoding) {
13175 if (!state.objectMode &&
13176 state.decodeStrings !== false &&
13177 typeof chunk === 'string') {
13178 chunk = new Buffer(chunk, encoding);
13179 }
13180 return chunk;
13181}
13182
13183// if we're already writing something, then just put this
13184// in the queue, and wait our turn. Otherwise, call _write
13185// If we return false, then we need a drain event, so set that flag.
13186function writeOrBuffer(stream, state, chunk, encoding, cb) {
13187 chunk = decodeChunk(state, chunk, encoding);
13188 if (Buffer.isBuffer(chunk))
13189 encoding = 'buffer';
13190 var len = state.objectMode ? 1 : chunk.length;
13191
13192 state.length += len;
13193
13194 var ret = state.length < state.highWaterMark;
13195 // we must ensure that previous needDrain will not be reset to false.
13196 if (!ret)
13197 state.needDrain = true;
13198
13199 if (state.writing)
13200 state.buffer.push(new WriteReq(chunk, encoding, cb));
13201 else
13202 doWrite(stream, state, len, chunk, encoding, cb);
13203
13204 return ret;
13205}
13206
13207function doWrite(stream, state, len, chunk, encoding, cb) {
13208 state.writelen = len;
13209 state.writecb = cb;
13210 state.writing = true;
13211 state.sync = true;
13212 stream._write(chunk, encoding, state.onwrite);
13213 state.sync = false;
13214}
13215
13216function onwriteError(stream, state, sync, er, cb) {
13217 if (sync)
13218 process.nextTick(function() {
13219 cb(er);
13220 });
13221 else
13222 cb(er);
13223
13224 stream._writableState.errorEmitted = true;
13225 stream.emit('error', er);
13226}
13227
13228function onwriteStateUpdate(state) {
13229 state.writing = false;
13230 state.writecb = null;
13231 state.length -= state.writelen;
13232 state.writelen = 0;
13233}
13234
13235function onwrite(stream, er) {
13236 var state = stream._writableState;
13237 var sync = state.sync;
13238 var cb = state.writecb;
13239
13240 onwriteStateUpdate(state);
13241
13242 if (er)
13243 onwriteError(stream, state, sync, er, cb);
13244 else {
13245 // Check if we're actually ready to finish, but don't emit yet
13246 var finished = needFinish(stream, state);
13247
13248 if (!finished && !state.bufferProcessing && state.buffer.length)
13249 clearBuffer(stream, state);
13250
13251 if (sync) {
13252 process.nextTick(function() {
13253 afterWrite(stream, state, finished, cb);
13254 });
13255 } else {
13256 afterWrite(stream, state, finished, cb);
13257 }
13258 }
13259}
13260
13261function afterWrite(stream, state, finished, cb) {
13262 if (!finished)
13263 onwriteDrain(stream, state);
13264 cb();
13265 if (finished)
13266 finishMaybe(stream, state);
13267}
13268
13269// Must force callback to be called on nextTick, so that we don't
13270// emit 'drain' before the write() consumer gets the 'false' return
13271// value, and has a chance to attach a 'drain' listener.
13272function onwriteDrain(stream, state) {
13273 if (state.length === 0 && state.needDrain) {
13274 state.needDrain = false;
13275 stream.emit('drain');
13276 }
13277}
13278
13279
13280// if there's something in the buffer waiting, then process it
13281function clearBuffer(stream, state) {
13282 state.bufferProcessing = true;
13283
13284 for (var c = 0; c < state.buffer.length; c++) {
13285 var entry = state.buffer[c];
13286 var chunk = entry.chunk;
13287 var encoding = entry.encoding;
13288 var cb = entry.callback;
13289 var len = state.objectMode ? 1 : chunk.length;
13290
13291 doWrite(stream, state, len, chunk, encoding, cb);
13292
13293 // if we didn't call the onwrite immediately, then
13294 // it means that we need to wait until it does.
13295 // also, that means that the chunk and cb are currently
13296 // being processed, so move the buffer counter past them.
13297 if (state.writing) {
13298 c++;
13299 break;
13300 }
13301 }
13302
13303 state.bufferProcessing = false;
13304 if (c < state.buffer.length)
13305 state.buffer = state.buffer.slice(c);
13306 else
13307 state.buffer.length = 0;
13308}
13309
13310Writable.prototype._write = function(chunk, encoding, cb) {
13311 cb(new Error('not implemented'));
13312};
13313
13314Writable.prototype.end = function(chunk, encoding, cb) {
13315 var state = this._writableState;
13316
13317 if (typeof chunk === 'function') {
13318 cb = chunk;
13319 chunk = null;
13320 encoding = null;
13321 } else if (typeof encoding === 'function') {
13322 cb = encoding;
13323 encoding = null;
13324 }
13325
13326 if (typeof chunk !== 'undefined' && chunk !== null)
13327 this.write(chunk, encoding);
13328
13329 // ignore unnecessary end() calls.
13330 if (!state.ending && !state.finished)
13331 endWritable(this, state, cb);
13332};
13333
13334
13335function needFinish(stream, state) {
13336 return (state.ending &&
13337 state.length === 0 &&
13338 !state.finished &&
13339 !state.writing);
13340}
13341
13342function finishMaybe(stream, state) {
13343 var need = needFinish(stream, state);
13344 if (need) {
13345 state.finished = true;
13346 stream.emit('finish');
13347 }
13348 return need;
13349}
13350
13351function endWritable(stream, state, cb) {
13352 state.ending = true;
13353 finishMaybe(stream, state);
13354 if (cb) {
13355 if (state.finished)
13356 process.nextTick(cb);
13357 else
13358 stream.once('finish', cb);
13359 }
13360 state.ended = true;
13361}
13362
13363}).call(this,_dereq_(70))
13364},{"10":10,"18":18,"70":70,"72":72,"81":81,"9":9}],77:[function(_dereq_,module,exports){
13365// Copyright Joyent, Inc. and other Node contributors.
13366//
13367// Permission is hereby granted, free of charge, to any person obtaining a
13368// copy of this software and associated documentation files (the
13369// "Software"), to deal in the Software without restriction, including
13370// without limitation the rights to use, copy, modify, merge, publish,
13371// distribute, sublicense, and/or sell copies of the Software, and to permit
13372// persons to whom the Software is furnished to do so, subject to the
13373// following conditions:
13374//
13375// The above copyright notice and this permission notice shall be included
13376// in all copies or substantial portions of the Software.
13377//
13378// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13379// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13380// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13381// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13382// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13383// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13384// USE OR OTHER DEALINGS IN THE SOFTWARE.
13385
13386var Buffer = _dereq_(9).Buffer;
13387
13388var isBufferEncoding = Buffer.isEncoding
13389 || function(encoding) {
13390 switch (encoding && encoding.toLowerCase()) {
13391 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;
13392 default: return false;
13393 }
13394 }
13395
13396
13397function assertEncoding(encoding) {
13398 if (encoding && !isBufferEncoding(encoding)) {
13399 throw new Error('Unknown encoding: ' + encoding);
13400 }
13401}
13402
13403// StringDecoder provides an interface for efficiently splitting a series of
13404// buffers into a series of JS strings without breaking apart multi-byte
13405// characters. CESU-8 is handled as part of the UTF-8 encoding.
13406//
13407// @TODO Handling all encodings inside a single object makes it very difficult
13408// to reason about this code, so it should be split up in the future.
13409// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
13410// points as used by CESU-8.
13411var StringDecoder = exports.StringDecoder = function(encoding) {
13412 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
13413 assertEncoding(encoding);
13414 switch (this.encoding) {
13415 case 'utf8':
13416 // CESU-8 represents each of Surrogate Pair by 3-bytes
13417 this.surrogateSize = 3;
13418 break;
13419 case 'ucs2':
13420 case 'utf16le':
13421 // UTF-16 represents each of Surrogate Pair by 2-bytes
13422 this.surrogateSize = 2;
13423 this.detectIncompleteChar = utf16DetectIncompleteChar;
13424 break;
13425 case 'base64':
13426 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
13427 this.surrogateSize = 3;
13428 this.detectIncompleteChar = base64DetectIncompleteChar;
13429 break;
13430 default:
13431 this.write = passThroughWrite;
13432 return;
13433 }
13434
13435 // Enough space to store all bytes of a single character. UTF-8 needs 4
13436 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
13437 this.charBuffer = new Buffer(6);
13438 // Number of bytes received for the current incomplete multi-byte character.
13439 this.charReceived = 0;
13440 // Number of bytes expected for the current incomplete multi-byte character.
13441 this.charLength = 0;
13442};
13443
13444
13445// write decodes the given buffer and returns it as JS string that is
13446// guaranteed to not contain any partial multi-byte characters. Any partial
13447// character found at the end of the buffer is buffered up, and will be
13448// returned when calling write again with the remaining bytes.
13449//
13450// Note: Converting a Buffer containing an orphan surrogate to a String
13451// currently works, but converting a String to a Buffer (via `new Buffer`, or
13452// Buffer#write) will replace incomplete surrogates with the unicode
13453// replacement character. See https://codereview.chromium.org/121173009/ .
13454StringDecoder.prototype.write = function(buffer) {
13455 var charStr = '';
13456 // if our last write ended with an incomplete multibyte character
13457 while (this.charLength) {
13458 // determine how many remaining bytes this buffer has to offer for this char
13459 var available = (buffer.length >= this.charLength - this.charReceived) ?
13460 this.charLength - this.charReceived :
13461 buffer.length;
13462
13463 // add the new bytes to the char buffer
13464 buffer.copy(this.charBuffer, this.charReceived, 0, available);
13465 this.charReceived += available;
13466
13467 if (this.charReceived < this.charLength) {
13468 // still not enough chars in this buffer? wait for more ...
13469 return '';
13470 }
13471
13472 // remove bytes belonging to the current character from the buffer
13473 buffer = buffer.slice(available, buffer.length);
13474
13475 // get the character that was split
13476 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
13477
13478 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
13479 var charCode = charStr.charCodeAt(charStr.length - 1);
13480 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
13481 this.charLength += this.surrogateSize;
13482 charStr = '';
13483 continue;
13484 }
13485 this.charReceived = this.charLength = 0;
13486
13487 // if there are no more bytes in this buffer, just emit our char
13488 if (buffer.length === 0) {
13489 return charStr;
13490 }
13491 break;
13492 }
13493
13494 // determine and set charLength / charReceived
13495 this.detectIncompleteChar(buffer);
13496
13497 var end = buffer.length;
13498 if (this.charLength) {
13499 // buffer the incomplete character bytes we got
13500 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
13501 end -= this.charReceived;
13502 }
13503
13504 charStr += buffer.toString(this.encoding, 0, end);
13505
13506 var end = charStr.length - 1;
13507 var charCode = charStr.charCodeAt(end);
13508 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
13509 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
13510 var size = this.surrogateSize;
13511 this.charLength += size;
13512 this.charReceived += size;
13513 this.charBuffer.copy(this.charBuffer, size, 0, size);
13514 buffer.copy(this.charBuffer, 0, 0, size);
13515 return charStr.substring(0, end);
13516 }
13517
13518 // or just emit the charStr
13519 return charStr;
13520};
13521
13522// detectIncompleteChar determines if there is an incomplete UTF-8 character at
13523// the end of the given buffer. If so, it sets this.charLength to the byte
13524// length that character, and sets this.charReceived to the number of bytes
13525// that are available for this character.
13526StringDecoder.prototype.detectIncompleteChar = function(buffer) {
13527 // determine how many bytes we have to check at the end of this buffer
13528 var i = (buffer.length >= 3) ? 3 : buffer.length;
13529
13530 // Figure out if one of the last i bytes of our buffer announces an
13531 // incomplete char.
13532 for (; i > 0; i--) {
13533 var c = buffer[buffer.length - i];
13534
13535 // See http://en.wikipedia.org/wiki/UTF-8#Description
13536
13537 // 110XXXXX
13538 if (i == 1 && c >> 5 == 0x06) {
13539 this.charLength = 2;
13540 break;
13541 }
13542
13543 // 1110XXXX
13544 if (i <= 2 && c >> 4 == 0x0E) {
13545 this.charLength = 3;
13546 break;
13547 }
13548
13549 // 11110XXX
13550 if (i <= 3 && c >> 3 == 0x1E) {
13551 this.charLength = 4;
13552 break;
13553 }
13554 }
13555 this.charReceived = i;
13556};
13557
13558StringDecoder.prototype.end = function(buffer) {
13559 var res = '';
13560 if (buffer && buffer.length)
13561 res = this.write(buffer);
13562
13563 if (this.charReceived) {
13564 var cr = this.charReceived;
13565 var buf = this.charBuffer;
13566 var enc = this.encoding;
13567 res += buf.slice(0, cr).toString(enc);
13568 }
13569
13570 return res;
13571};
13572
13573function passThroughWrite(buffer) {
13574 return buffer.toString(this.encoding);
13575}
13576
13577function utf16DetectIncompleteChar(buffer) {
13578 this.charReceived = buffer.length % 2;
13579 this.charLength = this.charReceived ? 2 : 0;
13580}
13581
13582function base64DetectIncompleteChar(buffer) {
13583 this.charReceived = buffer.length % 3;
13584 this.charLength = this.charReceived ? 3 : 0;
13585}
13586
13587},{"9":9}],78:[function(_dereq_,module,exports){
13588var Stream = _dereq_(81); // hack to fix a circular dependency issue when used with browserify
13589exports = module.exports = _dereq_(74);
13590exports.Stream = Stream;
13591exports.Readable = exports;
13592exports.Writable = _dereq_(76);
13593exports.Duplex = _dereq_(72);
13594exports.Transform = _dereq_(75);
13595exports.PassThrough = _dereq_(73);
13596
13597},{"72":72,"73":73,"74":74,"75":75,"76":76,"81":81}],79:[function(_dereq_,module,exports){
13598/* eslint-disable node/no-deprecated-api */
13599var buffer = _dereq_(9)
13600var Buffer = buffer.Buffer
13601
13602// alternative to using Object.keys for old browsers
13603function copyProps (src, dst) {
13604 for (var key in src) {
13605 dst[key] = src[key]
13606 }
13607}
13608if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
13609 module.exports = buffer
13610} else {
13611 // Copy properties from require('buffer')
13612 copyProps(buffer, exports)
13613 exports.Buffer = SafeBuffer
13614}
13615
13616function SafeBuffer (arg, encodingOrOffset, length) {
13617 return Buffer(arg, encodingOrOffset, length)
13618}
13619
13620SafeBuffer.prototype = Object.create(Buffer.prototype)
13621
13622// Copy static methods from Buffer
13623copyProps(Buffer, SafeBuffer)
13624
13625SafeBuffer.from = function (arg, encodingOrOffset, length) {
13626 if (typeof arg === 'number') {
13627 throw new TypeError('Argument must not be a number')
13628 }
13629 return Buffer(arg, encodingOrOffset, length)
13630}
13631
13632SafeBuffer.alloc = function (size, fill, encoding) {
13633 if (typeof size !== 'number') {
13634 throw new TypeError('Argument must be a number')
13635 }
13636 var buf = Buffer(size)
13637 if (fill !== undefined) {
13638 if (typeof encoding === 'string') {
13639 buf.fill(fill, encoding)
13640 } else {
13641 buf.fill(fill)
13642 }
13643 } else {
13644 buf.fill(0)
13645 }
13646 return buf
13647}
13648
13649SafeBuffer.allocUnsafe = function (size) {
13650 if (typeof size !== 'number') {
13651 throw new TypeError('Argument must be a number')
13652 }
13653 return Buffer(size)
13654}
13655
13656SafeBuffer.allocUnsafeSlow = function (size) {
13657 if (typeof size !== 'number') {
13658 throw new TypeError('Argument must be a number')
13659 }
13660 return buffer.SlowBuffer(size)
13661}
13662
13663},{"9":9}],80:[function(_dereq_,module,exports){
13664(function (factory) {
13665 if (typeof exports === 'object') {
13666 // Node/CommonJS
13667 module.exports = factory();
13668 } else if (typeof define === 'function' && define.amd) {
13669 // AMD
13670 define(factory);
13671 } else {
13672 // Browser globals (with support for web workers)
13673 var glob;
13674
13675 try {
13676 glob = window;
13677 } catch (e) {
13678 glob = self;
13679 }
13680
13681 glob.SparkMD5 = factory();
13682 }
13683}(function (undefined) {
13684
13685 'use strict';
13686
13687 /*
13688 * Fastest md5 implementation around (JKM md5).
13689 * Credits: Joseph Myers
13690 *
13691 * @see http://www.myersdaily.org/joseph/javascript/md5-text.html
13692 * @see http://jsperf.com/md5-shootout/7
13693 */
13694
13695 /* this function is much faster,
13696 so if possible we use it. Some IEs
13697 are the only ones I know of that
13698 need the idiotic second function,
13699 generated by an if clause. */
13700 var add32 = function (a, b) {
13701 return (a + b) & 0xFFFFFFFF;
13702 },
13703 hex_chr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
13704
13705
13706 function cmn(q, a, b, x, s, t) {
13707 a = add32(add32(a, q), add32(x, t));
13708 return add32((a << s) | (a >>> (32 - s)), b);
13709 }
13710
13711 function md5cycle(x, k) {
13712 var a = x[0],
13713 b = x[1],
13714 c = x[2],
13715 d = x[3];
13716
13717 a += (b & c | ~b & d) + k[0] - 680876936 | 0;
13718 a = (a << 7 | a >>> 25) + b | 0;
13719 d += (a & b | ~a & c) + k[1] - 389564586 | 0;
13720 d = (d << 12 | d >>> 20) + a | 0;
13721 c += (d & a | ~d & b) + k[2] + 606105819 | 0;
13722 c = (c << 17 | c >>> 15) + d | 0;
13723 b += (c & d | ~c & a) + k[3] - 1044525330 | 0;
13724 b = (b << 22 | b >>> 10) + c | 0;
13725 a += (b & c | ~b & d) + k[4] - 176418897 | 0;
13726 a = (a << 7 | a >>> 25) + b | 0;
13727 d += (a & b | ~a & c) + k[5] + 1200080426 | 0;
13728 d = (d << 12 | d >>> 20) + a | 0;
13729 c += (d & a | ~d & b) + k[6] - 1473231341 | 0;
13730 c = (c << 17 | c >>> 15) + d | 0;
13731 b += (c & d | ~c & a) + k[7] - 45705983 | 0;
13732 b = (b << 22 | b >>> 10) + c | 0;
13733 a += (b & c | ~b & d) + k[8] + 1770035416 | 0;
13734 a = (a << 7 | a >>> 25) + b | 0;
13735 d += (a & b | ~a & c) + k[9] - 1958414417 | 0;
13736 d = (d << 12 | d >>> 20) + a | 0;
13737 c += (d & a | ~d & b) + k[10] - 42063 | 0;
13738 c = (c << 17 | c >>> 15) + d | 0;
13739 b += (c & d | ~c & a) + k[11] - 1990404162 | 0;
13740 b = (b << 22 | b >>> 10) + c | 0;
13741 a += (b & c | ~b & d) + k[12] + 1804603682 | 0;
13742 a = (a << 7 | a >>> 25) + b | 0;
13743 d += (a & b | ~a & c) + k[13] - 40341101 | 0;
13744 d = (d << 12 | d >>> 20) + a | 0;
13745 c += (d & a | ~d & b) + k[14] - 1502002290 | 0;
13746 c = (c << 17 | c >>> 15) + d | 0;
13747 b += (c & d | ~c & a) + k[15] + 1236535329 | 0;
13748 b = (b << 22 | b >>> 10) + c | 0;
13749
13750 a += (b & d | c & ~d) + k[1] - 165796510 | 0;
13751 a = (a << 5 | a >>> 27) + b | 0;
13752 d += (a & c | b & ~c) + k[6] - 1069501632 | 0;
13753 d = (d << 9 | d >>> 23) + a | 0;
13754 c += (d & b | a & ~b) + k[11] + 643717713 | 0;
13755 c = (c << 14 | c >>> 18) + d | 0;
13756 b += (c & a | d & ~a) + k[0] - 373897302 | 0;
13757 b = (b << 20 | b >>> 12) + c | 0;
13758 a += (b & d | c & ~d) + k[5] - 701558691 | 0;
13759 a = (a << 5 | a >>> 27) + b | 0;
13760 d += (a & c | b & ~c) + k[10] + 38016083 | 0;
13761 d = (d << 9 | d >>> 23) + a | 0;
13762 c += (d & b | a & ~b) + k[15] - 660478335 | 0;
13763 c = (c << 14 | c >>> 18) + d | 0;
13764 b += (c & a | d & ~a) + k[4] - 405537848 | 0;
13765 b = (b << 20 | b >>> 12) + c | 0;
13766 a += (b & d | c & ~d) + k[9] + 568446438 | 0;
13767 a = (a << 5 | a >>> 27) + b | 0;
13768 d += (a & c | b & ~c) + k[14] - 1019803690 | 0;
13769 d = (d << 9 | d >>> 23) + a | 0;
13770 c += (d & b | a & ~b) + k[3] - 187363961 | 0;
13771 c = (c << 14 | c >>> 18) + d | 0;
13772 b += (c & a | d & ~a) + k[8] + 1163531501 | 0;
13773 b = (b << 20 | b >>> 12) + c | 0;
13774 a += (b & d | c & ~d) + k[13] - 1444681467 | 0;
13775 a = (a << 5 | a >>> 27) + b | 0;
13776 d += (a & c | b & ~c) + k[2] - 51403784 | 0;
13777 d = (d << 9 | d >>> 23) + a | 0;
13778 c += (d & b | a & ~b) + k[7] + 1735328473 | 0;
13779 c = (c << 14 | c >>> 18) + d | 0;
13780 b += (c & a | d & ~a) + k[12] - 1926607734 | 0;
13781 b = (b << 20 | b >>> 12) + c | 0;
13782
13783 a += (b ^ c ^ d) + k[5] - 378558 | 0;
13784 a = (a << 4 | a >>> 28) + b | 0;
13785 d += (a ^ b ^ c) + k[8] - 2022574463 | 0;
13786 d = (d << 11 | d >>> 21) + a | 0;
13787 c += (d ^ a ^ b) + k[11] + 1839030562 | 0;
13788 c = (c << 16 | c >>> 16) + d | 0;
13789 b += (c ^ d ^ a) + k[14] - 35309556 | 0;
13790 b = (b << 23 | b >>> 9) + c | 0;
13791 a += (b ^ c ^ d) + k[1] - 1530992060 | 0;
13792 a = (a << 4 | a >>> 28) + b | 0;
13793 d += (a ^ b ^ c) + k[4] + 1272893353 | 0;
13794 d = (d << 11 | d >>> 21) + a | 0;
13795 c += (d ^ a ^ b) + k[7] - 155497632 | 0;
13796 c = (c << 16 | c >>> 16) + d | 0;
13797 b += (c ^ d ^ a) + k[10] - 1094730640 | 0;
13798 b = (b << 23 | b >>> 9) + c | 0;
13799 a += (b ^ c ^ d) + k[13] + 681279174 | 0;
13800 a = (a << 4 | a >>> 28) + b | 0;
13801 d += (a ^ b ^ c) + k[0] - 358537222 | 0;
13802 d = (d << 11 | d >>> 21) + a | 0;
13803 c += (d ^ a ^ b) + k[3] - 722521979 | 0;
13804 c = (c << 16 | c >>> 16) + d | 0;
13805 b += (c ^ d ^ a) + k[6] + 76029189 | 0;
13806 b = (b << 23 | b >>> 9) + c | 0;
13807 a += (b ^ c ^ d) + k[9] - 640364487 | 0;
13808 a = (a << 4 | a >>> 28) + b | 0;
13809 d += (a ^ b ^ c) + k[12] - 421815835 | 0;
13810 d = (d << 11 | d >>> 21) + a | 0;
13811 c += (d ^ a ^ b) + k[15] + 530742520 | 0;
13812 c = (c << 16 | c >>> 16) + d | 0;
13813 b += (c ^ d ^ a) + k[2] - 995338651 | 0;
13814 b = (b << 23 | b >>> 9) + c | 0;
13815
13816 a += (c ^ (b | ~d)) + k[0] - 198630844 | 0;
13817 a = (a << 6 | a >>> 26) + b | 0;
13818 d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0;
13819 d = (d << 10 | d >>> 22) + a | 0;
13820 c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0;
13821 c = (c << 15 | c >>> 17) + d | 0;
13822 b += (d ^ (c | ~a)) + k[5] - 57434055 | 0;
13823 b = (b << 21 |b >>> 11) + c | 0;
13824 a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0;
13825 a = (a << 6 | a >>> 26) + b | 0;
13826 d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0;
13827 d = (d << 10 | d >>> 22) + a | 0;
13828 c += (a ^ (d | ~b)) + k[10] - 1051523 | 0;
13829 c = (c << 15 | c >>> 17) + d | 0;
13830 b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0;
13831 b = (b << 21 |b >>> 11) + c | 0;
13832 a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0;
13833 a = (a << 6 | a >>> 26) + b | 0;
13834 d += (b ^ (a | ~c)) + k[15] - 30611744 | 0;
13835 d = (d << 10 | d >>> 22) + a | 0;
13836 c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0;
13837 c = (c << 15 | c >>> 17) + d | 0;
13838 b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0;
13839 b = (b << 21 |b >>> 11) + c | 0;
13840 a += (c ^ (b | ~d)) + k[4] - 145523070 | 0;
13841 a = (a << 6 | a >>> 26) + b | 0;
13842 d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0;
13843 d = (d << 10 | d >>> 22) + a | 0;
13844 c += (a ^ (d | ~b)) + k[2] + 718787259 | 0;
13845 c = (c << 15 | c >>> 17) + d | 0;
13846 b += (d ^ (c | ~a)) + k[9] - 343485551 | 0;
13847 b = (b << 21 | b >>> 11) + c | 0;
13848
13849 x[0] = a + x[0] | 0;
13850 x[1] = b + x[1] | 0;
13851 x[2] = c + x[2] | 0;
13852 x[3] = d + x[3] | 0;
13853 }
13854
13855 function md5blk(s) {
13856 var md5blks = [],
13857 i; /* Andy King said do it this way. */
13858
13859 for (i = 0; i < 64; i += 4) {
13860 md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
13861 }
13862 return md5blks;
13863 }
13864
13865 function md5blk_array(a) {
13866 var md5blks = [],
13867 i; /* Andy King said do it this way. */
13868
13869 for (i = 0; i < 64; i += 4) {
13870 md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);
13871 }
13872 return md5blks;
13873 }
13874
13875 function md51(s) {
13876 var n = s.length,
13877 state = [1732584193, -271733879, -1732584194, 271733878],
13878 i,
13879 length,
13880 tail,
13881 tmp,
13882 lo,
13883 hi;
13884
13885 for (i = 64; i <= n; i += 64) {
13886 md5cycle(state, md5blk(s.substring(i - 64, i)));
13887 }
13888 s = s.substring(i - 64);
13889 length = s.length;
13890 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
13891 for (i = 0; i < length; i += 1) {
13892 tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
13893 }
13894 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13895 if (i > 55) {
13896 md5cycle(state, tail);
13897 for (i = 0; i < 16; i += 1) {
13898 tail[i] = 0;
13899 }
13900 }
13901
13902 // Beware that the final length might not fit in 32 bits so we take care of that
13903 tmp = n * 8;
13904 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
13905 lo = parseInt(tmp[2], 16);
13906 hi = parseInt(tmp[1], 16) || 0;
13907
13908 tail[14] = lo;
13909 tail[15] = hi;
13910
13911 md5cycle(state, tail);
13912 return state;
13913 }
13914
13915 function md51_array(a) {
13916 var n = a.length,
13917 state = [1732584193, -271733879, -1732584194, 271733878],
13918 i,
13919 length,
13920 tail,
13921 tmp,
13922 lo,
13923 hi;
13924
13925 for (i = 64; i <= n; i += 64) {
13926 md5cycle(state, md5blk_array(a.subarray(i - 64, i)));
13927 }
13928
13929 // Not sure if it is a bug, however IE10 will always produce a sub array of length 1
13930 // containing the last element of the parent array if the sub array specified starts
13931 // beyond the length of the parent array - weird.
13932 // https://connect.microsoft.com/IE/feedback/details/771452/typed-array-subarray-issue
13933 a = (i - 64) < n ? a.subarray(i - 64) : new Uint8Array(0);
13934
13935 length = a.length;
13936 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
13937 for (i = 0; i < length; i += 1) {
13938 tail[i >> 2] |= a[i] << ((i % 4) << 3);
13939 }
13940
13941 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13942 if (i > 55) {
13943 md5cycle(state, tail);
13944 for (i = 0; i < 16; i += 1) {
13945 tail[i] = 0;
13946 }
13947 }
13948
13949 // Beware that the final length might not fit in 32 bits so we take care of that
13950 tmp = n * 8;
13951 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
13952 lo = parseInt(tmp[2], 16);
13953 hi = parseInt(tmp[1], 16) || 0;
13954
13955 tail[14] = lo;
13956 tail[15] = hi;
13957
13958 md5cycle(state, tail);
13959
13960 return state;
13961 }
13962
13963 function rhex(n) {
13964 var s = '',
13965 j;
13966 for (j = 0; j < 4; j += 1) {
13967 s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
13968 }
13969 return s;
13970 }
13971
13972 function hex(x) {
13973 var i;
13974 for (i = 0; i < x.length; i += 1) {
13975 x[i] = rhex(x[i]);
13976 }
13977 return x.join('');
13978 }
13979
13980 // In some cases the fast add32 function cannot be used..
13981 if (hex(md51('hello')) !== '5d41402abc4b2a76b9719d911017c592') {
13982 add32 = function (x, y) {
13983 var lsw = (x & 0xFFFF) + (y & 0xFFFF),
13984 msw = (x >> 16) + (y >> 16) + (lsw >> 16);
13985 return (msw << 16) | (lsw & 0xFFFF);
13986 };
13987 }
13988
13989 // ---------------------------------------------------
13990
13991 /**
13992 * ArrayBuffer slice polyfill.
13993 *
13994 * @see https://github.com/ttaubert/node-arraybuffer-slice
13995 */
13996
13997 if (typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.prototype.slice) {
13998 (function () {
13999 function clamp(val, length) {
14000 val = (val | 0) || 0;
14001
14002 if (val < 0) {
14003 return Math.max(val + length, 0);
14004 }
14005
14006 return Math.min(val, length);
14007 }
14008
14009 ArrayBuffer.prototype.slice = function (from, to) {
14010 var length = this.byteLength,
14011 begin = clamp(from, length),
14012 end = length,
14013 num,
14014 target,
14015 targetArray,
14016 sourceArray;
14017
14018 if (to !== undefined) {
14019 end = clamp(to, length);
14020 }
14021
14022 if (begin > end) {
14023 return new ArrayBuffer(0);
14024 }
14025
14026 num = end - begin;
14027 target = new ArrayBuffer(num);
14028 targetArray = new Uint8Array(target);
14029
14030 sourceArray = new Uint8Array(this, begin, num);
14031 targetArray.set(sourceArray);
14032
14033 return target;
14034 };
14035 })();
14036 }
14037
14038 // ---------------------------------------------------
14039
14040 /**
14041 * Helpers.
14042 */
14043
14044 function toUtf8(str) {
14045 if (/[\u0080-\uFFFF]/.test(str)) {
14046 str = unescape(encodeURIComponent(str));
14047 }
14048
14049 return str;
14050 }
14051
14052 function utf8Str2ArrayBuffer(str, returnUInt8Array) {
14053 var length = str.length,
14054 buff = new ArrayBuffer(length),
14055 arr = new Uint8Array(buff),
14056 i;
14057
14058 for (i = 0; i < length; i += 1) {
14059 arr[i] = str.charCodeAt(i);
14060 }
14061
14062 return returnUInt8Array ? arr : buff;
14063 }
14064
14065 function arrayBuffer2Utf8Str(buff) {
14066 return String.fromCharCode.apply(null, new Uint8Array(buff));
14067 }
14068
14069 function concatenateArrayBuffers(first, second, returnUInt8Array) {
14070 var result = new Uint8Array(first.byteLength + second.byteLength);
14071
14072 result.set(new Uint8Array(first));
14073 result.set(new Uint8Array(second), first.byteLength);
14074
14075 return returnUInt8Array ? result : result.buffer;
14076 }
14077
14078 function hexToBinaryString(hex) {
14079 var bytes = [],
14080 length = hex.length,
14081 x;
14082
14083 for (x = 0; x < length - 1; x += 2) {
14084 bytes.push(parseInt(hex.substr(x, 2), 16));
14085 }
14086
14087 return String.fromCharCode.apply(String, bytes);
14088 }
14089
14090 // ---------------------------------------------------
14091
14092 /**
14093 * SparkMD5 OOP implementation.
14094 *
14095 * Use this class to perform an incremental md5, otherwise use the
14096 * static methods instead.
14097 */
14098
14099 function SparkMD5() {
14100 // call reset to init the instance
14101 this.reset();
14102 }
14103
14104 /**
14105 * Appends a string.
14106 * A conversion will be applied if an utf8 string is detected.
14107 *
14108 * @param {String} str The string to be appended
14109 *
14110 * @return {SparkMD5} The instance itself
14111 */
14112 SparkMD5.prototype.append = function (str) {
14113 // Converts the string to utf8 bytes if necessary
14114 // Then append as binary
14115 this.appendBinary(toUtf8(str));
14116
14117 return this;
14118 };
14119
14120 /**
14121 * Appends a binary string.
14122 *
14123 * @param {String} contents The binary string to be appended
14124 *
14125 * @return {SparkMD5} The instance itself
14126 */
14127 SparkMD5.prototype.appendBinary = function (contents) {
14128 this._buff += contents;
14129 this._length += contents.length;
14130
14131 var length = this._buff.length,
14132 i;
14133
14134 for (i = 64; i <= length; i += 64) {
14135 md5cycle(this._hash, md5blk(this._buff.substring(i - 64, i)));
14136 }
14137
14138 this._buff = this._buff.substring(i - 64);
14139
14140 return this;
14141 };
14142
14143 /**
14144 * Finishes the incremental computation, reseting the internal state and
14145 * returning the result.
14146 *
14147 * @param {Boolean} raw True to get the raw string, false to get the hex string
14148 *
14149 * @return {String} The result
14150 */
14151 SparkMD5.prototype.end = function (raw) {
14152 var buff = this._buff,
14153 length = buff.length,
14154 i,
14155 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
14156 ret;
14157
14158 for (i = 0; i < length; i += 1) {
14159 tail[i >> 2] |= buff.charCodeAt(i) << ((i % 4) << 3);
14160 }
14161
14162 this._finish(tail, length);
14163 ret = hex(this._hash);
14164
14165 if (raw) {
14166 ret = hexToBinaryString(ret);
14167 }
14168
14169 this.reset();
14170
14171 return ret;
14172 };
14173
14174 /**
14175 * Resets the internal state of the computation.
14176 *
14177 * @return {SparkMD5} The instance itself
14178 */
14179 SparkMD5.prototype.reset = function () {
14180 this._buff = '';
14181 this._length = 0;
14182 this._hash = [1732584193, -271733879, -1732584194, 271733878];
14183
14184 return this;
14185 };
14186
14187 /**
14188 * Gets the internal state of the computation.
14189 *
14190 * @return {Object} The state
14191 */
14192 SparkMD5.prototype.getState = function () {
14193 return {
14194 buff: this._buff,
14195 length: this._length,
14196 hash: this._hash
14197 };
14198 };
14199
14200 /**
14201 * Gets the internal state of the computation.
14202 *
14203 * @param {Object} state The state
14204 *
14205 * @return {SparkMD5} The instance itself
14206 */
14207 SparkMD5.prototype.setState = function (state) {
14208 this._buff = state.buff;
14209 this._length = state.length;
14210 this._hash = state.hash;
14211
14212 return this;
14213 };
14214
14215 /**
14216 * Releases memory used by the incremental buffer and other additional
14217 * resources. If you plan to use the instance again, use reset instead.
14218 */
14219 SparkMD5.prototype.destroy = function () {
14220 delete this._hash;
14221 delete this._buff;
14222 delete this._length;
14223 };
14224
14225 /**
14226 * Finish the final calculation based on the tail.
14227 *
14228 * @param {Array} tail The tail (will be modified)
14229 * @param {Number} length The length of the remaining buffer
14230 */
14231 SparkMD5.prototype._finish = function (tail, length) {
14232 var i = length,
14233 tmp,
14234 lo,
14235 hi;
14236
14237 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
14238 if (i > 55) {
14239 md5cycle(this._hash, tail);
14240 for (i = 0; i < 16; i += 1) {
14241 tail[i] = 0;
14242 }
14243 }
14244
14245 // Do the final computation based on the tail and length
14246 // Beware that the final length may not fit in 32 bits so we take care of that
14247 tmp = this._length * 8;
14248 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
14249 lo = parseInt(tmp[2], 16);
14250 hi = parseInt(tmp[1], 16) || 0;
14251
14252 tail[14] = lo;
14253 tail[15] = hi;
14254 md5cycle(this._hash, tail);
14255 };
14256
14257 /**
14258 * Performs the md5 hash on a string.
14259 * A conversion will be applied if utf8 string is detected.
14260 *
14261 * @param {String} str The string
14262 * @param {Boolean} raw True to get the raw string, false to get the hex string
14263 *
14264 * @return {String} The result
14265 */
14266 SparkMD5.hash = function (str, raw) {
14267 // Converts the string to utf8 bytes if necessary
14268 // Then compute it using the binary function
14269 return SparkMD5.hashBinary(toUtf8(str), raw);
14270 };
14271
14272 /**
14273 * Performs the md5 hash on a binary string.
14274 *
14275 * @param {String} content The binary string
14276 * @param {Boolean} raw True to get the raw string, false to get the hex string
14277 *
14278 * @return {String} The result
14279 */
14280 SparkMD5.hashBinary = function (content, raw) {
14281 var hash = md51(content),
14282 ret = hex(hash);
14283
14284 return raw ? hexToBinaryString(ret) : ret;
14285 };
14286
14287 // ---------------------------------------------------
14288
14289 /**
14290 * SparkMD5 OOP implementation for array buffers.
14291 *
14292 * Use this class to perform an incremental md5 ONLY for array buffers.
14293 */
14294 SparkMD5.ArrayBuffer = function () {
14295 // call reset to init the instance
14296 this.reset();
14297 };
14298
14299 /**
14300 * Appends an array buffer.
14301 *
14302 * @param {ArrayBuffer} arr The array to be appended
14303 *
14304 * @return {SparkMD5.ArrayBuffer} The instance itself
14305 */
14306 SparkMD5.ArrayBuffer.prototype.append = function (arr) {
14307 var buff = concatenateArrayBuffers(this._buff.buffer, arr, true),
14308 length = buff.length,
14309 i;
14310
14311 this._length += arr.byteLength;
14312
14313 for (i = 64; i <= length; i += 64) {
14314 md5cycle(this._hash, md5blk_array(buff.subarray(i - 64, i)));
14315 }
14316
14317 this._buff = (i - 64) < length ? new Uint8Array(buff.buffer.slice(i - 64)) : new Uint8Array(0);
14318
14319 return this;
14320 };
14321
14322 /**
14323 * Finishes the incremental computation, reseting the internal state and
14324 * returning the result.
14325 *
14326 * @param {Boolean} raw True to get the raw string, false to get the hex string
14327 *
14328 * @return {String} The result
14329 */
14330 SparkMD5.ArrayBuffer.prototype.end = function (raw) {
14331 var buff = this._buff,
14332 length = buff.length,
14333 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
14334 i,
14335 ret;
14336
14337 for (i = 0; i < length; i += 1) {
14338 tail[i >> 2] |= buff[i] << ((i % 4) << 3);
14339 }
14340
14341 this._finish(tail, length);
14342 ret = hex(this._hash);
14343
14344 if (raw) {
14345 ret = hexToBinaryString(ret);
14346 }
14347
14348 this.reset();
14349
14350 return ret;
14351 };
14352
14353 /**
14354 * Resets the internal state of the computation.
14355 *
14356 * @return {SparkMD5.ArrayBuffer} The instance itself
14357 */
14358 SparkMD5.ArrayBuffer.prototype.reset = function () {
14359 this._buff = new Uint8Array(0);
14360 this._length = 0;
14361 this._hash = [1732584193, -271733879, -1732584194, 271733878];
14362
14363 return this;
14364 };
14365
14366 /**
14367 * Gets the internal state of the computation.
14368 *
14369 * @return {Object} The state
14370 */
14371 SparkMD5.ArrayBuffer.prototype.getState = function () {
14372 var state = SparkMD5.prototype.getState.call(this);
14373
14374 // Convert buffer to a string
14375 state.buff = arrayBuffer2Utf8Str(state.buff);
14376
14377 return state;
14378 };
14379
14380 /**
14381 * Gets the internal state of the computation.
14382 *
14383 * @param {Object} state The state
14384 *
14385 * @return {SparkMD5.ArrayBuffer} The instance itself
14386 */
14387 SparkMD5.ArrayBuffer.prototype.setState = function (state) {
14388 // Convert string to buffer
14389 state.buff = utf8Str2ArrayBuffer(state.buff, true);
14390
14391 return SparkMD5.prototype.setState.call(this, state);
14392 };
14393
14394 SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
14395
14396 SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
14397
14398 /**
14399 * Performs the md5 hash on an array buffer.
14400 *
14401 * @param {ArrayBuffer} arr The array buffer
14402 * @param {Boolean} raw True to get the raw string, false to get the hex one
14403 *
14404 * @return {String} The result
14405 */
14406 SparkMD5.ArrayBuffer.hash = function (arr, raw) {
14407 var hash = md51_array(new Uint8Array(arr)),
14408 ret = hex(hash);
14409
14410 return raw ? hexToBinaryString(ret) : ret;
14411 };
14412
14413 return SparkMD5;
14414}));
14415
14416},{}],81:[function(_dereq_,module,exports){
14417// Copyright Joyent, Inc. and other Node contributors.
14418//
14419// Permission is hereby granted, free of charge, to any person obtaining a
14420// copy of this software and associated documentation files (the
14421// "Software"), to deal in the Software without restriction, including
14422// without limitation the rights to use, copy, modify, merge, publish,
14423// distribute, sublicense, and/or sell copies of the Software, and to permit
14424// persons to whom the Software is furnished to do so, subject to the
14425// following conditions:
14426//
14427// The above copyright notice and this permission notice shall be included
14428// in all copies or substantial portions of the Software.
14429//
14430// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14431// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14432// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14433// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14434// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14435// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14436// USE OR OTHER DEALINGS IN THE SOFTWARE.
14437
14438module.exports = Stream;
14439
14440var EE = _dereq_(14).EventEmitter;
14441var inherits = _dereq_(18);
14442
14443inherits(Stream, EE);
14444Stream.Readable = _dereq_(93);
14445Stream.Writable = _dereq_(95);
14446Stream.Duplex = _dereq_(83);
14447Stream.Transform = _dereq_(94);
14448Stream.PassThrough = _dereq_(92);
14449
14450// Backwards-compat with node 0.4.x
14451Stream.Stream = Stream;
14452
14453
14454
14455// old-style streams. Note that the pipe method (the only relevant
14456// part of this class) is overridden in the Readable class.
14457
14458function Stream() {
14459 EE.call(this);
14460}
14461
14462Stream.prototype.pipe = function(dest, options) {
14463 var source = this;
14464
14465 function ondata(chunk) {
14466 if (dest.writable) {
14467 if (false === dest.write(chunk) && source.pause) {
14468 source.pause();
14469 }
14470 }
14471 }
14472
14473 source.on('data', ondata);
14474
14475 function ondrain() {
14476 if (source.readable && source.resume) {
14477 source.resume();
14478 }
14479 }
14480
14481 dest.on('drain', ondrain);
14482
14483 // If the 'end' option is not supplied, dest.end() will be called when
14484 // source gets the 'end' or 'close' events. Only dest.end() once.
14485 if (!dest._isStdio && (!options || options.end !== false)) {
14486 source.on('end', onend);
14487 source.on('close', onclose);
14488 }
14489
14490 var didOnEnd = false;
14491 function onend() {
14492 if (didOnEnd) return;
14493 didOnEnd = true;
14494
14495 dest.end();
14496 }
14497
14498
14499 function onclose() {
14500 if (didOnEnd) return;
14501 didOnEnd = true;
14502
14503 if (typeof dest.destroy === 'function') dest.destroy();
14504 }
14505
14506 // don't leave dangling pipes when there are errors.
14507 function onerror(er) {
14508 cleanup();
14509 if (EE.listenerCount(this, 'error') === 0) {
14510 throw er; // Unhandled stream error in pipe.
14511 }
14512 }
14513
14514 source.on('error', onerror);
14515 dest.on('error', onerror);
14516
14517 // remove all the event listeners that were added.
14518 function cleanup() {
14519 source.removeListener('data', ondata);
14520 dest.removeListener('drain', ondrain);
14521
14522 source.removeListener('end', onend);
14523 source.removeListener('close', onclose);
14524
14525 source.removeListener('error', onerror);
14526 dest.removeListener('error', onerror);
14527
14528 source.removeListener('end', cleanup);
14529 source.removeListener('close', cleanup);
14530
14531 dest.removeListener('close', cleanup);
14532 }
14533
14534 source.on('end', cleanup);
14535 source.on('close', cleanup);
14536
14537 dest.on('close', cleanup);
14538
14539 dest.emit('pipe', source);
14540
14541 // Allow for unix-like usage: A.pipe(B).pipe(C)
14542 return dest;
14543};
14544
14545},{"14":14,"18":18,"83":83,"92":92,"93":93,"94":94,"95":95}],82:[function(_dereq_,module,exports){
14546var toString = {}.toString;
14547
14548module.exports = Array.isArray || function (arr) {
14549 return toString.call(arr) == '[object Array]';
14550};
14551
14552},{}],83:[function(_dereq_,module,exports){
14553module.exports = _dereq_(84);
14554
14555},{"84":84}],84:[function(_dereq_,module,exports){
14556// Copyright Joyent, Inc. and other Node contributors.
14557//
14558// Permission is hereby granted, free of charge, to any person obtaining a
14559// copy of this software and associated documentation files (the
14560// "Software"), to deal in the Software without restriction, including
14561// without limitation the rights to use, copy, modify, merge, publish,
14562// distribute, sublicense, and/or sell copies of the Software, and to permit
14563// persons to whom the Software is furnished to do so, subject to the
14564// following conditions:
14565//
14566// The above copyright notice and this permission notice shall be included
14567// in all copies or substantial portions of the Software.
14568//
14569// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14570// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14571// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14572// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14573// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14574// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14575// USE OR OTHER DEALINGS IN THE SOFTWARE.
14576
14577// a duplex stream is just a stream that is both readable and writable.
14578// Since JS doesn't have multiple prototypal inheritance, this class
14579// prototypally inherits from Readable, and then parasitically from
14580// Writable.
14581
14582'use strict';
14583
14584/*<replacement>*/
14585
14586var pna = _dereq_(69);
14587/*</replacement>*/
14588
14589/*<replacement>*/
14590var objectKeys = Object.keys || function (obj) {
14591 var keys = [];
14592 for (var key in obj) {
14593 keys.push(key);
14594 }return keys;
14595};
14596/*</replacement>*/
14597
14598module.exports = Duplex;
14599
14600/*<replacement>*/
14601var util = Object.create(_dereq_(10));
14602util.inherits = _dereq_(18);
14603/*</replacement>*/
14604
14605var Readable = _dereq_(86);
14606var Writable = _dereq_(88);
14607
14608util.inherits(Duplex, Readable);
14609
14610{
14611 // avoid scope creep, the keys array can then be collected
14612 var keys = objectKeys(Writable.prototype);
14613 for (var v = 0; v < keys.length; v++) {
14614 var method = keys[v];
14615 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
14616 }
14617}
14618
14619function Duplex(options) {
14620 if (!(this instanceof Duplex)) return new Duplex(options);
14621
14622 Readable.call(this, options);
14623 Writable.call(this, options);
14624
14625 if (options && options.readable === false) this.readable = false;
14626
14627 if (options && options.writable === false) this.writable = false;
14628
14629 this.allowHalfOpen = true;
14630 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
14631
14632 this.once('end', onend);
14633}
14634
14635Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
14636 // making it explicit this property is not enumerable
14637 // because otherwise some prototype manipulation in
14638 // userland will fail
14639 enumerable: false,
14640 get: function () {
14641 return this._writableState.highWaterMark;
14642 }
14643});
14644
14645// the no-half-open enforcer
14646function onend() {
14647 // if we allow half-open state, or if the writable side ended,
14648 // then we're ok.
14649 if (this.allowHalfOpen || this._writableState.ended) return;
14650
14651 // no more data can be written.
14652 // But allow more writes to happen in this tick.
14653 pna.nextTick(onEndNT, this);
14654}
14655
14656function onEndNT(self) {
14657 self.end();
14658}
14659
14660Object.defineProperty(Duplex.prototype, 'destroyed', {
14661 get: function () {
14662 if (this._readableState === undefined || this._writableState === undefined) {
14663 return false;
14664 }
14665 return this._readableState.destroyed && this._writableState.destroyed;
14666 },
14667 set: function (value) {
14668 // we ignore the value if the stream
14669 // has not been initialized yet
14670 if (this._readableState === undefined || this._writableState === undefined) {
14671 return;
14672 }
14673
14674 // backward compatibility, the user is explicitly
14675 // managing destroyed
14676 this._readableState.destroyed = value;
14677 this._writableState.destroyed = value;
14678 }
14679});
14680
14681Duplex.prototype._destroy = function (err, cb) {
14682 this.push(null);
14683 this.end();
14684
14685 pna.nextTick(cb, err);
14686};
14687},{"10":10,"18":18,"69":69,"86":86,"88":88}],85:[function(_dereq_,module,exports){
14688// Copyright Joyent, Inc. and other Node contributors.
14689//
14690// Permission is hereby granted, free of charge, to any person obtaining a
14691// copy of this software and associated documentation files (the
14692// "Software"), to deal in the Software without restriction, including
14693// without limitation the rights to use, copy, modify, merge, publish,
14694// distribute, sublicense, and/or sell copies of the Software, and to permit
14695// persons to whom the Software is furnished to do so, subject to the
14696// following conditions:
14697//
14698// The above copyright notice and this permission notice shall be included
14699// in all copies or substantial portions of the Software.
14700//
14701// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14702// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14703// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14704// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14705// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14706// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14707// USE OR OTHER DEALINGS IN THE SOFTWARE.
14708
14709// a passthrough stream.
14710// basically just the most minimal sort of Transform stream.
14711// Every written chunk gets output as-is.
14712
14713'use strict';
14714
14715module.exports = PassThrough;
14716
14717var Transform = _dereq_(87);
14718
14719/*<replacement>*/
14720var util = Object.create(_dereq_(10));
14721util.inherits = _dereq_(18);
14722/*</replacement>*/
14723
14724util.inherits(PassThrough, Transform);
14725
14726function PassThrough(options) {
14727 if (!(this instanceof PassThrough)) return new PassThrough(options);
14728
14729 Transform.call(this, options);
14730}
14731
14732PassThrough.prototype._transform = function (chunk, encoding, cb) {
14733 cb(null, chunk);
14734};
14735},{"10":10,"18":18,"87":87}],86:[function(_dereq_,module,exports){
14736(function (process,global){
14737// Copyright Joyent, Inc. and other Node contributors.
14738//
14739// Permission is hereby granted, free of charge, to any person obtaining a
14740// copy of this software and associated documentation files (the
14741// "Software"), to deal in the Software without restriction, including
14742// without limitation the rights to use, copy, modify, merge, publish,
14743// distribute, sublicense, and/or sell copies of the Software, and to permit
14744// persons to whom the Software is furnished to do so, subject to the
14745// following conditions:
14746//
14747// The above copyright notice and this permission notice shall be included
14748// in all copies or substantial portions of the Software.
14749//
14750// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14751// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14752// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14753// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14754// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14755// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14756// USE OR OTHER DEALINGS IN THE SOFTWARE.
14757
14758'use strict';
14759
14760/*<replacement>*/
14761
14762var pna = _dereq_(69);
14763/*</replacement>*/
14764
14765module.exports = Readable;
14766
14767/*<replacement>*/
14768var isArray = _dereq_(82);
14769/*</replacement>*/
14770
14771/*<replacement>*/
14772var Duplex;
14773/*</replacement>*/
14774
14775Readable.ReadableState = ReadableState;
14776
14777/*<replacement>*/
14778var EE = _dereq_(14).EventEmitter;
14779
14780var EElistenerCount = function (emitter, type) {
14781 return emitter.listeners(type).length;
14782};
14783/*</replacement>*/
14784
14785/*<replacement>*/
14786var Stream = _dereq_(91);
14787/*</replacement>*/
14788
14789/*<replacement>*/
14790
14791var Buffer = _dereq_(96).Buffer;
14792var OurUint8Array = global.Uint8Array || function () {};
14793function _uint8ArrayToBuffer(chunk) {
14794 return Buffer.from(chunk);
14795}
14796function _isUint8Array(obj) {
14797 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
14798}
14799
14800/*</replacement>*/
14801
14802/*<replacement>*/
14803var util = Object.create(_dereq_(10));
14804util.inherits = _dereq_(18);
14805/*</replacement>*/
14806
14807/*<replacement>*/
14808var debugUtil = _dereq_(7);
14809var debug = void 0;
14810if (debugUtil && debugUtil.debuglog) {
14811 debug = debugUtil.debuglog('stream');
14812} else {
14813 debug = function () {};
14814}
14815/*</replacement>*/
14816
14817var BufferList = _dereq_(89);
14818var destroyImpl = _dereq_(90);
14819var StringDecoder;
14820
14821util.inherits(Readable, Stream);
14822
14823var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
14824
14825function prependListener(emitter, event, fn) {
14826 // Sadly this is not cacheable as some libraries bundle their own
14827 // event emitter implementation with them.
14828 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
14829
14830 // This is a hack to make sure that our error handler is attached before any
14831 // userland ones. NEVER DO THIS. This is here only because this code needs
14832 // to continue to work with older versions of Node.js that do not include
14833 // the prependListener() method. The goal is to eventually remove this hack.
14834 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]];
14835}
14836
14837function ReadableState(options, stream) {
14838 Duplex = Duplex || _dereq_(84);
14839
14840 options = options || {};
14841
14842 // Duplex streams are both readable and writable, but share
14843 // the same options object.
14844 // However, some cases require setting options to different
14845 // values for the readable and the writable sides of the duplex stream.
14846 // These options can be provided separately as readableXXX and writableXXX.
14847 var isDuplex = stream instanceof Duplex;
14848
14849 // object stream flag. Used to make read(n) ignore n and to
14850 // make all the buffer merging and length checks go away
14851 this.objectMode = !!options.objectMode;
14852
14853 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
14854
14855 // the point at which it stops calling _read() to fill the buffer
14856 // Note: 0 is a valid value, means "don't call _read preemptively ever"
14857 var hwm = options.highWaterMark;
14858 var readableHwm = options.readableHighWaterMark;
14859 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
14860
14861 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
14862
14863 // cast to ints.
14864 this.highWaterMark = Math.floor(this.highWaterMark);
14865
14866 // A linked list is used to store data chunks instead of an array because the
14867 // linked list can remove elements from the beginning faster than
14868 // array.shift()
14869 this.buffer = new BufferList();
14870 this.length = 0;
14871 this.pipes = null;
14872 this.pipesCount = 0;
14873 this.flowing = null;
14874 this.ended = false;
14875 this.endEmitted = false;
14876 this.reading = false;
14877
14878 // a flag to be able to tell if the event 'readable'/'data' is emitted
14879 // immediately, or on a later tick. We set this to true at first, because
14880 // any actions that shouldn't happen until "later" should generally also
14881 // not happen before the first read call.
14882 this.sync = true;
14883
14884 // whenever we return null, then we set a flag to say
14885 // that we're awaiting a 'readable' event emission.
14886 this.needReadable = false;
14887 this.emittedReadable = false;
14888 this.readableListening = false;
14889 this.resumeScheduled = false;
14890
14891 // has it been destroyed
14892 this.destroyed = false;
14893
14894 // Crypto is kind of old and crusty. Historically, its default string
14895 // encoding is 'binary' so we have to make this configurable.
14896 // Everything else in the universe uses 'utf8', though.
14897 this.defaultEncoding = options.defaultEncoding || 'utf8';
14898
14899 // the number of writers that are awaiting a drain event in .pipe()s
14900 this.awaitDrain = 0;
14901
14902 // if true, a maybeReadMore has been scheduled
14903 this.readingMore = false;
14904
14905 this.decoder = null;
14906 this.encoding = null;
14907 if (options.encoding) {
14908 if (!StringDecoder) StringDecoder = _dereq_(97).StringDecoder;
14909 this.decoder = new StringDecoder(options.encoding);
14910 this.encoding = options.encoding;
14911 }
14912}
14913
14914function Readable(options) {
14915 Duplex = Duplex || _dereq_(84);
14916
14917 if (!(this instanceof Readable)) return new Readable(options);
14918
14919 this._readableState = new ReadableState(options, this);
14920
14921 // legacy
14922 this.readable = true;
14923
14924 if (options) {
14925 if (typeof options.read === 'function') this._read = options.read;
14926
14927 if (typeof options.destroy === 'function') this._destroy = options.destroy;
14928 }
14929
14930 Stream.call(this);
14931}
14932
14933Object.defineProperty(Readable.prototype, 'destroyed', {
14934 get: function () {
14935 if (this._readableState === undefined) {
14936 return false;
14937 }
14938 return this._readableState.destroyed;
14939 },
14940 set: function (value) {
14941 // we ignore the value if the stream
14942 // has not been initialized yet
14943 if (!this._readableState) {
14944 return;
14945 }
14946
14947 // backward compatibility, the user is explicitly
14948 // managing destroyed
14949 this._readableState.destroyed = value;
14950 }
14951});
14952
14953Readable.prototype.destroy = destroyImpl.destroy;
14954Readable.prototype._undestroy = destroyImpl.undestroy;
14955Readable.prototype._destroy = function (err, cb) {
14956 this.push(null);
14957 cb(err);
14958};
14959
14960// Manually shove something into the read() buffer.
14961// This returns true if the highWaterMark has not been hit yet,
14962// similar to how Writable.write() returns true if you should
14963// write() some more.
14964Readable.prototype.push = function (chunk, encoding) {
14965 var state = this._readableState;
14966 var skipChunkCheck;
14967
14968 if (!state.objectMode) {
14969 if (typeof chunk === 'string') {
14970 encoding = encoding || state.defaultEncoding;
14971 if (encoding !== state.encoding) {
14972 chunk = Buffer.from(chunk, encoding);
14973 encoding = '';
14974 }
14975 skipChunkCheck = true;
14976 }
14977 } else {
14978 skipChunkCheck = true;
14979 }
14980
14981 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
14982};
14983
14984// Unshift should *always* be something directly out of read()
14985Readable.prototype.unshift = function (chunk) {
14986 return readableAddChunk(this, chunk, null, true, false);
14987};
14988
14989function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
14990 var state = stream._readableState;
14991 if (chunk === null) {
14992 state.reading = false;
14993 onEofChunk(stream, state);
14994 } else {
14995 var er;
14996 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
14997 if (er) {
14998 stream.emit('error', er);
14999 } else if (state.objectMode || chunk && chunk.length > 0) {
15000 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
15001 chunk = _uint8ArrayToBuffer(chunk);
15002 }
15003
15004 if (addToFront) {
15005 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
15006 } else if (state.ended) {
15007 stream.emit('error', new Error('stream.push() after EOF'));
15008 } else {
15009 state.reading = false;
15010 if (state.decoder && !encoding) {
15011 chunk = state.decoder.write(chunk);
15012 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
15013 } else {
15014 addChunk(stream, state, chunk, false);
15015 }
15016 }
15017 } else if (!addToFront) {
15018 state.reading = false;
15019 }
15020 }
15021
15022 return needMoreData(state);
15023}
15024
15025function addChunk(stream, state, chunk, addToFront) {
15026 if (state.flowing && state.length === 0 && !state.sync) {
15027 stream.emit('data', chunk);
15028 stream.read(0);
15029 } else {
15030 // update the buffer info.
15031 state.length += state.objectMode ? 1 : chunk.length;
15032 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
15033
15034 if (state.needReadable) emitReadable(stream);
15035 }
15036 maybeReadMore(stream, state);
15037}
15038
15039function chunkInvalid(state, chunk) {
15040 var er;
15041 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
15042 er = new TypeError('Invalid non-string/buffer chunk');
15043 }
15044 return er;
15045}
15046
15047// if it's past the high water mark, we can push in some more.
15048// Also, if we have no data yet, we can stand some
15049// more bytes. This is to work around cases where hwm=0,
15050// such as the repl. Also, if the push() triggered a
15051// readable event, and the user called read(largeNumber) such that
15052// needReadable was set, then we ought to push more, so that another
15053// 'readable' event will be triggered.
15054function needMoreData(state) {
15055 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
15056}
15057
15058Readable.prototype.isPaused = function () {
15059 return this._readableState.flowing === false;
15060};
15061
15062// backwards compatibility.
15063Readable.prototype.setEncoding = function (enc) {
15064 if (!StringDecoder) StringDecoder = _dereq_(97).StringDecoder;
15065 this._readableState.decoder = new StringDecoder(enc);
15066 this._readableState.encoding = enc;
15067 return this;
15068};
15069
15070// Don't raise the hwm > 8MB
15071var MAX_HWM = 0x800000;
15072function computeNewHighWaterMark(n) {
15073 if (n >= MAX_HWM) {
15074 n = MAX_HWM;
15075 } else {
15076 // Get the next highest power of 2 to prevent increasing hwm excessively in
15077 // tiny amounts
15078 n--;
15079 n |= n >>> 1;
15080 n |= n >>> 2;
15081 n |= n >>> 4;
15082 n |= n >>> 8;
15083 n |= n >>> 16;
15084 n++;
15085 }
15086 return n;
15087}
15088
15089// This function is designed to be inlinable, so please take care when making
15090// changes to the function body.
15091function howMuchToRead(n, state) {
15092 if (n <= 0 || state.length === 0 && state.ended) return 0;
15093 if (state.objectMode) return 1;
15094 if (n !== n) {
15095 // Only flow one buffer at a time
15096 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
15097 }
15098 // If we're asking for more than the current hwm, then raise the hwm.
15099 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
15100 if (n <= state.length) return n;
15101 // Don't have enough
15102 if (!state.ended) {
15103 state.needReadable = true;
15104 return 0;
15105 }
15106 return state.length;
15107}
15108
15109// you can override either this method, or the async _read(n) below.
15110Readable.prototype.read = function (n) {
15111 debug('read', n);
15112 n = parseInt(n, 10);
15113 var state = this._readableState;
15114 var nOrig = n;
15115
15116 if (n !== 0) state.emittedReadable = false;
15117
15118 // if we're doing read(0) to trigger a readable event, but we
15119 // already have a bunch of data in the buffer, then just trigger
15120 // the 'readable' event and move on.
15121 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
15122 debug('read: emitReadable', state.length, state.ended);
15123 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
15124 return null;
15125 }
15126
15127 n = howMuchToRead(n, state);
15128
15129 // if we've ended, and we're now clear, then finish it up.
15130 if (n === 0 && state.ended) {
15131 if (state.length === 0) endReadable(this);
15132 return null;
15133 }
15134
15135 // All the actual chunk generation logic needs to be
15136 // *below* the call to _read. The reason is that in certain
15137 // synthetic stream cases, such as passthrough streams, _read
15138 // may be a completely synchronous operation which may change
15139 // the state of the read buffer, providing enough data when
15140 // before there was *not* enough.
15141 //
15142 // So, the steps are:
15143 // 1. Figure out what the state of things will be after we do
15144 // a read from the buffer.
15145 //
15146 // 2. If that resulting state will trigger a _read, then call _read.
15147 // Note that this may be asynchronous, or synchronous. Yes, it is
15148 // deeply ugly to write APIs this way, but that still doesn't mean
15149 // that the Readable class should behave improperly, as streams are
15150 // designed to be sync/async agnostic.
15151 // Take note if the _read call is sync or async (ie, if the read call
15152 // has returned yet), so that we know whether or not it's safe to emit
15153 // 'readable' etc.
15154 //
15155 // 3. Actually pull the requested chunks out of the buffer and return.
15156
15157 // if we need a readable event, then we need to do some reading.
15158 var doRead = state.needReadable;
15159 debug('need readable', doRead);
15160
15161 // if we currently have less than the highWaterMark, then also read some
15162 if (state.length === 0 || state.length - n < state.highWaterMark) {
15163 doRead = true;
15164 debug('length less than watermark', doRead);
15165 }
15166
15167 // however, if we've ended, then there's no point, and if we're already
15168 // reading, then it's unnecessary.
15169 if (state.ended || state.reading) {
15170 doRead = false;
15171 debug('reading or ended', doRead);
15172 } else if (doRead) {
15173 debug('do read');
15174 state.reading = true;
15175 state.sync = true;
15176 // if the length is currently zero, then we *need* a readable event.
15177 if (state.length === 0) state.needReadable = true;
15178 // call internal read method
15179 this._read(state.highWaterMark);
15180 state.sync = false;
15181 // If _read pushed data synchronously, then `reading` will be false,
15182 // and we need to re-evaluate how much data we can return to the user.
15183 if (!state.reading) n = howMuchToRead(nOrig, state);
15184 }
15185
15186 var ret;
15187 if (n > 0) ret = fromList(n, state);else ret = null;
15188
15189 if (ret === null) {
15190 state.needReadable = true;
15191 n = 0;
15192 } else {
15193 state.length -= n;
15194 }
15195
15196 if (state.length === 0) {
15197 // If we have nothing in the buffer, then we want to know
15198 // as soon as we *do* get something into the buffer.
15199 if (!state.ended) state.needReadable = true;
15200
15201 // If we tried to read() past the EOF, then emit end on the next tick.
15202 if (nOrig !== n && state.ended) endReadable(this);
15203 }
15204
15205 if (ret !== null) this.emit('data', ret);
15206
15207 return ret;
15208};
15209
15210function onEofChunk(stream, state) {
15211 if (state.ended) return;
15212 if (state.decoder) {
15213 var chunk = state.decoder.end();
15214 if (chunk && chunk.length) {
15215 state.buffer.push(chunk);
15216 state.length += state.objectMode ? 1 : chunk.length;
15217 }
15218 }
15219 state.ended = true;
15220
15221 // emit 'readable' now to make sure it gets picked up.
15222 emitReadable(stream);
15223}
15224
15225// Don't emit readable right away in sync mode, because this can trigger
15226// another read() call => stack overflow. This way, it might trigger
15227// a nextTick recursion warning, but that's not so bad.
15228function emitReadable(stream) {
15229 var state = stream._readableState;
15230 state.needReadable = false;
15231 if (!state.emittedReadable) {
15232 debug('emitReadable', state.flowing);
15233 state.emittedReadable = true;
15234 if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
15235 }
15236}
15237
15238function emitReadable_(stream) {
15239 debug('emit readable');
15240 stream.emit('readable');
15241 flow(stream);
15242}
15243
15244// at this point, the user has presumably seen the 'readable' event,
15245// and called read() to consume some data. that may have triggered
15246// in turn another _read(n) call, in which case reading = true if
15247// it's in progress.
15248// However, if we're not ended, or reading, and the length < hwm,
15249// then go ahead and try to read some more preemptively.
15250function maybeReadMore(stream, state) {
15251 if (!state.readingMore) {
15252 state.readingMore = true;
15253 pna.nextTick(maybeReadMore_, stream, state);
15254 }
15255}
15256
15257function maybeReadMore_(stream, state) {
15258 var len = state.length;
15259 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
15260 debug('maybeReadMore read 0');
15261 stream.read(0);
15262 if (len === state.length)
15263 // didn't get any data, stop spinning.
15264 break;else len = state.length;
15265 }
15266 state.readingMore = false;
15267}
15268
15269// abstract method. to be overridden in specific implementation classes.
15270// call cb(er, data) where data is <= n in length.
15271// for virtual (non-string, non-buffer) streams, "length" is somewhat
15272// arbitrary, and perhaps not very meaningful.
15273Readable.prototype._read = function (n) {
15274 this.emit('error', new Error('_read() is not implemented'));
15275};
15276
15277Readable.prototype.pipe = function (dest, pipeOpts) {
15278 var src = this;
15279 var state = this._readableState;
15280
15281 switch (state.pipesCount) {
15282 case 0:
15283 state.pipes = dest;
15284 break;
15285 case 1:
15286 state.pipes = [state.pipes, dest];
15287 break;
15288 default:
15289 state.pipes.push(dest);
15290 break;
15291 }
15292 state.pipesCount += 1;
15293 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
15294
15295 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
15296
15297 var endFn = doEnd ? onend : unpipe;
15298 if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
15299
15300 dest.on('unpipe', onunpipe);
15301 function onunpipe(readable, unpipeInfo) {
15302 debug('onunpipe');
15303 if (readable === src) {
15304 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
15305 unpipeInfo.hasUnpiped = true;
15306 cleanup();
15307 }
15308 }
15309 }
15310
15311 function onend() {
15312 debug('onend');
15313 dest.end();
15314 }
15315
15316 // when the dest drains, it reduces the awaitDrain counter
15317 // on the source. This would be more elegant with a .once()
15318 // handler in flow(), but adding and removing repeatedly is
15319 // too slow.
15320 var ondrain = pipeOnDrain(src);
15321 dest.on('drain', ondrain);
15322
15323 var cleanedUp = false;
15324 function cleanup() {
15325 debug('cleanup');
15326 // cleanup event handlers once the pipe is broken
15327 dest.removeListener('close', onclose);
15328 dest.removeListener('finish', onfinish);
15329 dest.removeListener('drain', ondrain);
15330 dest.removeListener('error', onerror);
15331 dest.removeListener('unpipe', onunpipe);
15332 src.removeListener('end', onend);
15333 src.removeListener('end', unpipe);
15334 src.removeListener('data', ondata);
15335
15336 cleanedUp = true;
15337
15338 // if the reader is waiting for a drain event from this
15339 // specific writer, then it would cause it to never start
15340 // flowing again.
15341 // So, if this is awaiting a drain, then we just call it now.
15342 // If we don't know, then assume that we are waiting for one.
15343 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
15344 }
15345
15346 // If the user pushes more data while we're writing to dest then we'll end up
15347 // in ondata again. However, we only want to increase awaitDrain once because
15348 // dest will only emit one 'drain' event for the multiple writes.
15349 // => Introduce a guard on increasing awaitDrain.
15350 var increasedAwaitDrain = false;
15351 src.on('data', ondata);
15352 function ondata(chunk) {
15353 debug('ondata');
15354 increasedAwaitDrain = false;
15355 var ret = dest.write(chunk);
15356 if (false === ret && !increasedAwaitDrain) {
15357 // If the user unpiped during `dest.write()`, it is possible
15358 // to get stuck in a permanently paused state if that write
15359 // also returned false.
15360 // => Check whether `dest` is still a piping destination.
15361 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
15362 debug('false write response, pause', src._readableState.awaitDrain);
15363 src._readableState.awaitDrain++;
15364 increasedAwaitDrain = true;
15365 }
15366 src.pause();
15367 }
15368 }
15369
15370 // if the dest has an error, then stop piping into it.
15371 // however, don't suppress the throwing behavior for this.
15372 function onerror(er) {
15373 debug('onerror', er);
15374 unpipe();
15375 dest.removeListener('error', onerror);
15376 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
15377 }
15378
15379 // Make sure our error handler is attached before userland ones.
15380 prependListener(dest, 'error', onerror);
15381
15382 // Both close and finish should trigger unpipe, but only once.
15383 function onclose() {
15384 dest.removeListener('finish', onfinish);
15385 unpipe();
15386 }
15387 dest.once('close', onclose);
15388 function onfinish() {
15389 debug('onfinish');
15390 dest.removeListener('close', onclose);
15391 unpipe();
15392 }
15393 dest.once('finish', onfinish);
15394
15395 function unpipe() {
15396 debug('unpipe');
15397 src.unpipe(dest);
15398 }
15399
15400 // tell the dest that it's being piped to
15401 dest.emit('pipe', src);
15402
15403 // start the flow if it hasn't been started already.
15404 if (!state.flowing) {
15405 debug('pipe resume');
15406 src.resume();
15407 }
15408
15409 return dest;
15410};
15411
15412function pipeOnDrain(src) {
15413 return function () {
15414 var state = src._readableState;
15415 debug('pipeOnDrain', state.awaitDrain);
15416 if (state.awaitDrain) state.awaitDrain--;
15417 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
15418 state.flowing = true;
15419 flow(src);
15420 }
15421 };
15422}
15423
15424Readable.prototype.unpipe = function (dest) {
15425 var state = this._readableState;
15426 var unpipeInfo = { hasUnpiped: false };
15427
15428 // if we're not piping anywhere, then do nothing.
15429 if (state.pipesCount === 0) return this;
15430
15431 // just one destination. most common case.
15432 if (state.pipesCount === 1) {
15433 // passed in one, but it's not the right one.
15434 if (dest && dest !== state.pipes) return this;
15435
15436 if (!dest) dest = state.pipes;
15437
15438 // got a match.
15439 state.pipes = null;
15440 state.pipesCount = 0;
15441 state.flowing = false;
15442 if (dest) dest.emit('unpipe', this, unpipeInfo);
15443 return this;
15444 }
15445
15446 // slow case. multiple pipe destinations.
15447
15448 if (!dest) {
15449 // remove all.
15450 var dests = state.pipes;
15451 var len = state.pipesCount;
15452 state.pipes = null;
15453 state.pipesCount = 0;
15454 state.flowing = false;
15455
15456 for (var i = 0; i < len; i++) {
15457 dests[i].emit('unpipe', this, unpipeInfo);
15458 }return this;
15459 }
15460
15461 // try to find the right one.
15462 var index = indexOf(state.pipes, dest);
15463 if (index === -1) return this;
15464
15465 state.pipes.splice(index, 1);
15466 state.pipesCount -= 1;
15467 if (state.pipesCount === 1) state.pipes = state.pipes[0];
15468
15469 dest.emit('unpipe', this, unpipeInfo);
15470
15471 return this;
15472};
15473
15474// set up data events if they are asked for
15475// Ensure readable listeners eventually get something
15476Readable.prototype.on = function (ev, fn) {
15477 var res = Stream.prototype.on.call(this, ev, fn);
15478
15479 if (ev === 'data') {
15480 // Start flowing on next tick if stream isn't explicitly paused
15481 if (this._readableState.flowing !== false) this.resume();
15482 } else if (ev === 'readable') {
15483 var state = this._readableState;
15484 if (!state.endEmitted && !state.readableListening) {
15485 state.readableListening = state.needReadable = true;
15486 state.emittedReadable = false;
15487 if (!state.reading) {
15488 pna.nextTick(nReadingNextTick, this);
15489 } else if (state.length) {
15490 emitReadable(this);
15491 }
15492 }
15493 }
15494
15495 return res;
15496};
15497Readable.prototype.addListener = Readable.prototype.on;
15498
15499function nReadingNextTick(self) {
15500 debug('readable nexttick read 0');
15501 self.read(0);
15502}
15503
15504// pause() and resume() are remnants of the legacy readable stream API
15505// If the user uses them, then switch into old mode.
15506Readable.prototype.resume = function () {
15507 var state = this._readableState;
15508 if (!state.flowing) {
15509 debug('resume');
15510 state.flowing = true;
15511 resume(this, state);
15512 }
15513 return this;
15514};
15515
15516function resume(stream, state) {
15517 if (!state.resumeScheduled) {
15518 state.resumeScheduled = true;
15519 pna.nextTick(resume_, stream, state);
15520 }
15521}
15522
15523function resume_(stream, state) {
15524 if (!state.reading) {
15525 debug('resume read 0');
15526 stream.read(0);
15527 }
15528
15529 state.resumeScheduled = false;
15530 state.awaitDrain = 0;
15531 stream.emit('resume');
15532 flow(stream);
15533 if (state.flowing && !state.reading) stream.read(0);
15534}
15535
15536Readable.prototype.pause = function () {
15537 debug('call pause flowing=%j', this._readableState.flowing);
15538 if (false !== this._readableState.flowing) {
15539 debug('pause');
15540 this._readableState.flowing = false;
15541 this.emit('pause');
15542 }
15543 return this;
15544};
15545
15546function flow(stream) {
15547 var state = stream._readableState;
15548 debug('flow', state.flowing);
15549 while (state.flowing && stream.read() !== null) {}
15550}
15551
15552// wrap an old-style stream as the async data source.
15553// This is *not* part of the readable stream interface.
15554// It is an ugly unfortunate mess of history.
15555Readable.prototype.wrap = function (stream) {
15556 var _this = this;
15557
15558 var state = this._readableState;
15559 var paused = false;
15560
15561 stream.on('end', function () {
15562 debug('wrapped end');
15563 if (state.decoder && !state.ended) {
15564 var chunk = state.decoder.end();
15565 if (chunk && chunk.length) _this.push(chunk);
15566 }
15567
15568 _this.push(null);
15569 });
15570
15571 stream.on('data', function (chunk) {
15572 debug('wrapped data');
15573 if (state.decoder) chunk = state.decoder.write(chunk);
15574
15575 // don't skip over falsy values in objectMode
15576 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
15577
15578 var ret = _this.push(chunk);
15579 if (!ret) {
15580 paused = true;
15581 stream.pause();
15582 }
15583 });
15584
15585 // proxy all the other methods.
15586 // important when wrapping filters and duplexes.
15587 for (var i in stream) {
15588 if (this[i] === undefined && typeof stream[i] === 'function') {
15589 this[i] = function (method) {
15590 return function () {
15591 return stream[method].apply(stream, arguments);
15592 };
15593 }(i);
15594 }
15595 }
15596
15597 // proxy certain important events.
15598 for (var n = 0; n < kProxyEvents.length; n++) {
15599 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
15600 }
15601
15602 // when we try to consume some more bytes, simply unpause the
15603 // underlying stream.
15604 this._read = function (n) {
15605 debug('wrapped _read', n);
15606 if (paused) {
15607 paused = false;
15608 stream.resume();
15609 }
15610 };
15611
15612 return this;
15613};
15614
15615Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
15616 // making it explicit this property is not enumerable
15617 // because otherwise some prototype manipulation in
15618 // userland will fail
15619 enumerable: false,
15620 get: function () {
15621 return this._readableState.highWaterMark;
15622 }
15623});
15624
15625// exposed for testing purposes only.
15626Readable._fromList = fromList;
15627
15628// Pluck off n bytes from an array of buffers.
15629// Length is the combined lengths of all the buffers in the list.
15630// This function is designed to be inlinable, so please take care when making
15631// changes to the function body.
15632function fromList(n, state) {
15633 // nothing buffered
15634 if (state.length === 0) return null;
15635
15636 var ret;
15637 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
15638 // read it all, truncate the list
15639 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);
15640 state.buffer.clear();
15641 } else {
15642 // read part of list
15643 ret = fromListPartial(n, state.buffer, state.decoder);
15644 }
15645
15646 return ret;
15647}
15648
15649// Extracts only enough buffered data to satisfy the amount requested.
15650// This function is designed to be inlinable, so please take care when making
15651// changes to the function body.
15652function fromListPartial(n, list, hasStrings) {
15653 var ret;
15654 if (n < list.head.data.length) {
15655 // slice is the same for buffers and strings
15656 ret = list.head.data.slice(0, n);
15657 list.head.data = list.head.data.slice(n);
15658 } else if (n === list.head.data.length) {
15659 // first chunk is a perfect match
15660 ret = list.shift();
15661 } else {
15662 // result spans more than one buffer
15663 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
15664 }
15665 return ret;
15666}
15667
15668// Copies a specified amount of characters from the list of buffered data
15669// chunks.
15670// This function is designed to be inlinable, so please take care when making
15671// changes to the function body.
15672function copyFromBufferString(n, list) {
15673 var p = list.head;
15674 var c = 1;
15675 var ret = p.data;
15676 n -= ret.length;
15677 while (p = p.next) {
15678 var str = p.data;
15679 var nb = n > str.length ? str.length : n;
15680 if (nb === str.length) ret += str;else ret += str.slice(0, n);
15681 n -= nb;
15682 if (n === 0) {
15683 if (nb === str.length) {
15684 ++c;
15685 if (p.next) list.head = p.next;else list.head = list.tail = null;
15686 } else {
15687 list.head = p;
15688 p.data = str.slice(nb);
15689 }
15690 break;
15691 }
15692 ++c;
15693 }
15694 list.length -= c;
15695 return ret;
15696}
15697
15698// Copies a specified amount of bytes from the list of buffered data chunks.
15699// This function is designed to be inlinable, so please take care when making
15700// changes to the function body.
15701function copyFromBuffer(n, list) {
15702 var ret = Buffer.allocUnsafe(n);
15703 var p = list.head;
15704 var c = 1;
15705 p.data.copy(ret);
15706 n -= p.data.length;
15707 while (p = p.next) {
15708 var buf = p.data;
15709 var nb = n > buf.length ? buf.length : n;
15710 buf.copy(ret, ret.length - n, 0, nb);
15711 n -= nb;
15712 if (n === 0) {
15713 if (nb === buf.length) {
15714 ++c;
15715 if (p.next) list.head = p.next;else list.head = list.tail = null;
15716 } else {
15717 list.head = p;
15718 p.data = buf.slice(nb);
15719 }
15720 break;
15721 }
15722 ++c;
15723 }
15724 list.length -= c;
15725 return ret;
15726}
15727
15728function endReadable(stream) {
15729 var state = stream._readableState;
15730
15731 // If we get here before consuming all the bytes, then that is a
15732 // bug in node. Should never happen.
15733 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
15734
15735 if (!state.endEmitted) {
15736 state.ended = true;
15737 pna.nextTick(endReadableNT, state, stream);
15738 }
15739}
15740
15741function endReadableNT(state, stream) {
15742 // Check that we didn't get one last unshift.
15743 if (!state.endEmitted && state.length === 0) {
15744 state.endEmitted = true;
15745 stream.readable = false;
15746 stream.emit('end');
15747 }
15748}
15749
15750function indexOf(xs, x) {
15751 for (var i = 0, l = xs.length; i < l; i++) {
15752 if (xs[i] === x) return i;
15753 }
15754 return -1;
15755}
15756}).call(this,_dereq_(70),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
15757},{"10":10,"14":14,"18":18,"69":69,"7":7,"70":70,"82":82,"84":84,"89":89,"90":90,"91":91,"96":96,"97":97}],87:[function(_dereq_,module,exports){
15758// Copyright Joyent, Inc. and other Node contributors.
15759//
15760// Permission is hereby granted, free of charge, to any person obtaining a
15761// copy of this software and associated documentation files (the
15762// "Software"), to deal in the Software without restriction, including
15763// without limitation the rights to use, copy, modify, merge, publish,
15764// distribute, sublicense, and/or sell copies of the Software, and to permit
15765// persons to whom the Software is furnished to do so, subject to the
15766// following conditions:
15767//
15768// The above copyright notice and this permission notice shall be included
15769// in all copies or substantial portions of the Software.
15770//
15771// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15772// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15773// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15774// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15775// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15776// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15777// USE OR OTHER DEALINGS IN THE SOFTWARE.
15778
15779// a transform stream is a readable/writable stream where you do
15780// something with the data. Sometimes it's called a "filter",
15781// but that's not a great name for it, since that implies a thing where
15782// some bits pass through, and others are simply ignored. (That would
15783// be a valid example of a transform, of course.)
15784//
15785// While the output is causally related to the input, it's not a
15786// necessarily symmetric or synchronous transformation. For example,
15787// a zlib stream might take multiple plain-text writes(), and then
15788// emit a single compressed chunk some time in the future.
15789//
15790// Here's how this works:
15791//
15792// The Transform stream has all the aspects of the readable and writable
15793// stream classes. When you write(chunk), that calls _write(chunk,cb)
15794// internally, and returns false if there's a lot of pending writes
15795// buffered up. When you call read(), that calls _read(n) until
15796// there's enough pending readable data buffered up.
15797//
15798// In a transform stream, the written data is placed in a buffer. When
15799// _read(n) is called, it transforms the queued up data, calling the
15800// buffered _write cb's as it consumes chunks. If consuming a single
15801// written chunk would result in multiple output chunks, then the first
15802// outputted bit calls the readcb, and subsequent chunks just go into
15803// the read buffer, and will cause it to emit 'readable' if necessary.
15804//
15805// This way, back-pressure is actually determined by the reading side,
15806// since _read has to be called to start processing a new chunk. However,
15807// a pathological inflate type of transform can cause excessive buffering
15808// here. For example, imagine a stream where every byte of input is
15809// interpreted as an integer from 0-255, and then results in that many
15810// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
15811// 1kb of data being output. In this case, you could write a very small
15812// amount of input, and end up with a very large amount of output. In
15813// such a pathological inflating mechanism, there'd be no way to tell
15814// the system to stop doing the transform. A single 4MB write could
15815// cause the system to run out of memory.
15816//
15817// However, even in such a pathological case, only a single written chunk
15818// would be consumed, and then the rest would wait (un-transformed) until
15819// the results of the previous transformed chunk were consumed.
15820
15821'use strict';
15822
15823module.exports = Transform;
15824
15825var Duplex = _dereq_(84);
15826
15827/*<replacement>*/
15828var util = Object.create(_dereq_(10));
15829util.inherits = _dereq_(18);
15830/*</replacement>*/
15831
15832util.inherits(Transform, Duplex);
15833
15834function afterTransform(er, data) {
15835 var ts = this._transformState;
15836 ts.transforming = false;
15837
15838 var cb = ts.writecb;
15839
15840 if (!cb) {
15841 return this.emit('error', new Error('write callback called multiple times'));
15842 }
15843
15844 ts.writechunk = null;
15845 ts.writecb = null;
15846
15847 if (data != null) // single equals check for both `null` and `undefined`
15848 this.push(data);
15849
15850 cb(er);
15851
15852 var rs = this._readableState;
15853 rs.reading = false;
15854 if (rs.needReadable || rs.length < rs.highWaterMark) {
15855 this._read(rs.highWaterMark);
15856 }
15857}
15858
15859function Transform(options) {
15860 if (!(this instanceof Transform)) return new Transform(options);
15861
15862 Duplex.call(this, options);
15863
15864 this._transformState = {
15865 afterTransform: afterTransform.bind(this),
15866 needTransform: false,
15867 transforming: false,
15868 writecb: null,
15869 writechunk: null,
15870 writeencoding: null
15871 };
15872
15873 // start out asking for a readable event once data is transformed.
15874 this._readableState.needReadable = true;
15875
15876 // we have implemented the _read method, and done the other things
15877 // that Readable wants before the first _read call, so unset the
15878 // sync guard flag.
15879 this._readableState.sync = false;
15880
15881 if (options) {
15882 if (typeof options.transform === 'function') this._transform = options.transform;
15883
15884 if (typeof options.flush === 'function') this._flush = options.flush;
15885 }
15886
15887 // When the writable side finishes, then flush out anything remaining.
15888 this.on('prefinish', prefinish);
15889}
15890
15891function prefinish() {
15892 var _this = this;
15893
15894 if (typeof this._flush === 'function') {
15895 this._flush(function (er, data) {
15896 done(_this, er, data);
15897 });
15898 } else {
15899 done(this, null, null);
15900 }
15901}
15902
15903Transform.prototype.push = function (chunk, encoding) {
15904 this._transformState.needTransform = false;
15905 return Duplex.prototype.push.call(this, chunk, encoding);
15906};
15907
15908// This is the part where you do stuff!
15909// override this function in implementation classes.
15910// 'chunk' is an input chunk.
15911//
15912// Call `push(newChunk)` to pass along transformed output
15913// to the readable side. You may call 'push' zero or more times.
15914//
15915// Call `cb(err)` when you are done with this chunk. If you pass
15916// an error, then that'll put the hurt on the whole operation. If you
15917// never call cb(), then you'll never get another chunk.
15918Transform.prototype._transform = function (chunk, encoding, cb) {
15919 throw new Error('_transform() is not implemented');
15920};
15921
15922Transform.prototype._write = function (chunk, encoding, cb) {
15923 var ts = this._transformState;
15924 ts.writecb = cb;
15925 ts.writechunk = chunk;
15926 ts.writeencoding = encoding;
15927 if (!ts.transforming) {
15928 var rs = this._readableState;
15929 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
15930 }
15931};
15932
15933// Doesn't matter what the args are here.
15934// _transform does all the work.
15935// That we got here means that the readable side wants more data.
15936Transform.prototype._read = function (n) {
15937 var ts = this._transformState;
15938
15939 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
15940 ts.transforming = true;
15941 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
15942 } else {
15943 // mark that we need a transform, so that any data that comes in
15944 // will get processed, now that we've asked for it.
15945 ts.needTransform = true;
15946 }
15947};
15948
15949Transform.prototype._destroy = function (err, cb) {
15950 var _this2 = this;
15951
15952 Duplex.prototype._destroy.call(this, err, function (err2) {
15953 cb(err2);
15954 _this2.emit('close');
15955 });
15956};
15957
15958function done(stream, er, data) {
15959 if (er) return stream.emit('error', er);
15960
15961 if (data != null) // single equals check for both `null` and `undefined`
15962 stream.push(data);
15963
15964 // if there's nothing in the write buffer, then that means
15965 // that nothing more will ever be provided
15966 if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
15967
15968 if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
15969
15970 return stream.push(null);
15971}
15972},{"10":10,"18":18,"84":84}],88:[function(_dereq_,module,exports){
15973(function (process,global,setImmediate){
15974// Copyright Joyent, Inc. and other Node contributors.
15975//
15976// Permission is hereby granted, free of charge, to any person obtaining a
15977// copy of this software and associated documentation files (the
15978// "Software"), to deal in the Software without restriction, including
15979// without limitation the rights to use, copy, modify, merge, publish,
15980// distribute, sublicense, and/or sell copies of the Software, and to permit
15981// persons to whom the Software is furnished to do so, subject to the
15982// following conditions:
15983//
15984// The above copyright notice and this permission notice shall be included
15985// in all copies or substantial portions of the Software.
15986//
15987// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15988// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15989// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15990// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15991// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15992// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15993// USE OR OTHER DEALINGS IN THE SOFTWARE.
15994
15995// A bit simpler than readable streams.
15996// Implement an async ._write(chunk, encoding, cb), and it'll handle all
15997// the drain event emission and buffering.
15998
15999'use strict';
16000
16001/*<replacement>*/
16002
16003var pna = _dereq_(69);
16004/*</replacement>*/
16005
16006module.exports = Writable;
16007
16008/* <replacement> */
16009function WriteReq(chunk, encoding, cb) {
16010 this.chunk = chunk;
16011 this.encoding = encoding;
16012 this.callback = cb;
16013 this.next = null;
16014}
16015
16016// It seems a linked list but it is not
16017// there will be only 2 of these for each stream
16018function CorkedRequest(state) {
16019 var _this = this;
16020
16021 this.next = null;
16022 this.entry = null;
16023 this.finish = function () {
16024 onCorkedFinish(_this, state);
16025 };
16026}
16027/* </replacement> */
16028
16029/*<replacement>*/
16030var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
16031/*</replacement>*/
16032
16033/*<replacement>*/
16034var Duplex;
16035/*</replacement>*/
16036
16037Writable.WritableState = WritableState;
16038
16039/*<replacement>*/
16040var util = Object.create(_dereq_(10));
16041util.inherits = _dereq_(18);
16042/*</replacement>*/
16043
16044/*<replacement>*/
16045var internalUtil = {
16046 deprecate: _dereq_(116)
16047};
16048/*</replacement>*/
16049
16050/*<replacement>*/
16051var Stream = _dereq_(91);
16052/*</replacement>*/
16053
16054/*<replacement>*/
16055
16056var Buffer = _dereq_(96).Buffer;
16057var OurUint8Array = global.Uint8Array || function () {};
16058function _uint8ArrayToBuffer(chunk) {
16059 return Buffer.from(chunk);
16060}
16061function _isUint8Array(obj) {
16062 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
16063}
16064
16065/*</replacement>*/
16066
16067var destroyImpl = _dereq_(90);
16068
16069util.inherits(Writable, Stream);
16070
16071function nop() {}
16072
16073function WritableState(options, stream) {
16074 Duplex = Duplex || _dereq_(84);
16075
16076 options = options || {};
16077
16078 // Duplex streams are both readable and writable, but share
16079 // the same options object.
16080 // However, some cases require setting options to different
16081 // values for the readable and the writable sides of the duplex stream.
16082 // These options can be provided separately as readableXXX and writableXXX.
16083 var isDuplex = stream instanceof Duplex;
16084
16085 // object stream flag to indicate whether or not this stream
16086 // contains buffers or objects.
16087 this.objectMode = !!options.objectMode;
16088
16089 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
16090
16091 // the point at which write() starts returning false
16092 // Note: 0 is a valid value, means that we always return false if
16093 // the entire buffer is not flushed immediately on write()
16094 var hwm = options.highWaterMark;
16095 var writableHwm = options.writableHighWaterMark;
16096 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
16097
16098 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
16099
16100 // cast to ints.
16101 this.highWaterMark = Math.floor(this.highWaterMark);
16102
16103 // if _final has been called
16104 this.finalCalled = false;
16105
16106 // drain event flag.
16107 this.needDrain = false;
16108 // at the start of calling end()
16109 this.ending = false;
16110 // when end() has been called, and returned
16111 this.ended = false;
16112 // when 'finish' is emitted
16113 this.finished = false;
16114
16115 // has it been destroyed
16116 this.destroyed = false;
16117
16118 // should we decode strings into buffers before passing to _write?
16119 // this is here so that some node-core streams can optimize string
16120 // handling at a lower level.
16121 var noDecode = options.decodeStrings === false;
16122 this.decodeStrings = !noDecode;
16123
16124 // Crypto is kind of old and crusty. Historically, its default string
16125 // encoding is 'binary' so we have to make this configurable.
16126 // Everything else in the universe uses 'utf8', though.
16127 this.defaultEncoding = options.defaultEncoding || 'utf8';
16128
16129 // not an actual buffer we keep track of, but a measurement
16130 // of how much we're waiting to get pushed to some underlying
16131 // socket or file.
16132 this.length = 0;
16133
16134 // a flag to see when we're in the middle of a write.
16135 this.writing = false;
16136
16137 // when true all writes will be buffered until .uncork() call
16138 this.corked = 0;
16139
16140 // a flag to be able to tell if the onwrite cb is called immediately,
16141 // or on a later tick. We set this to true at first, because any
16142 // actions that shouldn't happen until "later" should generally also
16143 // not happen before the first write call.
16144 this.sync = true;
16145
16146 // a flag to know if we're processing previously buffered items, which
16147 // may call the _write() callback in the same tick, so that we don't
16148 // end up in an overlapped onwrite situation.
16149 this.bufferProcessing = false;
16150
16151 // the callback that's passed to _write(chunk,cb)
16152 this.onwrite = function (er) {
16153 onwrite(stream, er);
16154 };
16155
16156 // the callback that the user supplies to write(chunk,encoding,cb)
16157 this.writecb = null;
16158
16159 // the amount that is being written when _write is called.
16160 this.writelen = 0;
16161
16162 this.bufferedRequest = null;
16163 this.lastBufferedRequest = null;
16164
16165 // number of pending user-supplied write callbacks
16166 // this must be 0 before 'finish' can be emitted
16167 this.pendingcb = 0;
16168
16169 // emit prefinish if the only thing we're waiting for is _write cbs
16170 // This is relevant for synchronous Transform streams
16171 this.prefinished = false;
16172
16173 // True if the error was already emitted and should not be thrown again
16174 this.errorEmitted = false;
16175
16176 // count buffered requests
16177 this.bufferedRequestCount = 0;
16178
16179 // allocate the first CorkedRequest, there is always
16180 // one allocated and free to use, and we maintain at most two
16181 this.corkedRequestsFree = new CorkedRequest(this);
16182}
16183
16184WritableState.prototype.getBuffer = function getBuffer() {
16185 var current = this.bufferedRequest;
16186 var out = [];
16187 while (current) {
16188 out.push(current);
16189 current = current.next;
16190 }
16191 return out;
16192};
16193
16194(function () {
16195 try {
16196 Object.defineProperty(WritableState.prototype, 'buffer', {
16197 get: internalUtil.deprecate(function () {
16198 return this.getBuffer();
16199 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
16200 });
16201 } catch (_) {}
16202})();
16203
16204// Test _writableState for inheritance to account for Duplex streams,
16205// whose prototype chain only points to Readable.
16206var realHasInstance;
16207if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
16208 realHasInstance = Function.prototype[Symbol.hasInstance];
16209 Object.defineProperty(Writable, Symbol.hasInstance, {
16210 value: function (object) {
16211 if (realHasInstance.call(this, object)) return true;
16212 if (this !== Writable) return false;
16213
16214 return object && object._writableState instanceof WritableState;
16215 }
16216 });
16217} else {
16218 realHasInstance = function (object) {
16219 return object instanceof this;
16220 };
16221}
16222
16223function Writable(options) {
16224 Duplex = Duplex || _dereq_(84);
16225
16226 // Writable ctor is applied to Duplexes, too.
16227 // `realHasInstance` is necessary because using plain `instanceof`
16228 // would return false, as no `_writableState` property is attached.
16229
16230 // Trying to use the custom `instanceof` for Writable here will also break the
16231 // Node.js LazyTransform implementation, which has a non-trivial getter for
16232 // `_writableState` that would lead to infinite recursion.
16233 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
16234 return new Writable(options);
16235 }
16236
16237 this._writableState = new WritableState(options, this);
16238
16239 // legacy.
16240 this.writable = true;
16241
16242 if (options) {
16243 if (typeof options.write === 'function') this._write = options.write;
16244
16245 if (typeof options.writev === 'function') this._writev = options.writev;
16246
16247 if (typeof options.destroy === 'function') this._destroy = options.destroy;
16248
16249 if (typeof options.final === 'function') this._final = options.final;
16250 }
16251
16252 Stream.call(this);
16253}
16254
16255// Otherwise people can pipe Writable streams, which is just wrong.
16256Writable.prototype.pipe = function () {
16257 this.emit('error', new Error('Cannot pipe, not readable'));
16258};
16259
16260function writeAfterEnd(stream, cb) {
16261 var er = new Error('write after end');
16262 // TODO: defer error events consistently everywhere, not just the cb
16263 stream.emit('error', er);
16264 pna.nextTick(cb, er);
16265}
16266
16267// Checks that a user-supplied chunk is valid, especially for the particular
16268// mode the stream is in. Currently this means that `null` is never accepted
16269// and undefined/non-string values are only allowed in object mode.
16270function validChunk(stream, state, chunk, cb) {
16271 var valid = true;
16272 var er = false;
16273
16274 if (chunk === null) {
16275 er = new TypeError('May not write null values to stream');
16276 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
16277 er = new TypeError('Invalid non-string/buffer chunk');
16278 }
16279 if (er) {
16280 stream.emit('error', er);
16281 pna.nextTick(cb, er);
16282 valid = false;
16283 }
16284 return valid;
16285}
16286
16287Writable.prototype.write = function (chunk, encoding, cb) {
16288 var state = this._writableState;
16289 var ret = false;
16290 var isBuf = !state.objectMode && _isUint8Array(chunk);
16291
16292 if (isBuf && !Buffer.isBuffer(chunk)) {
16293 chunk = _uint8ArrayToBuffer(chunk);
16294 }
16295
16296 if (typeof encoding === 'function') {
16297 cb = encoding;
16298 encoding = null;
16299 }
16300
16301 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
16302
16303 if (typeof cb !== 'function') cb = nop;
16304
16305 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
16306 state.pendingcb++;
16307 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
16308 }
16309
16310 return ret;
16311};
16312
16313Writable.prototype.cork = function () {
16314 var state = this._writableState;
16315
16316 state.corked++;
16317};
16318
16319Writable.prototype.uncork = function () {
16320 var state = this._writableState;
16321
16322 if (state.corked) {
16323 state.corked--;
16324
16325 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
16326 }
16327};
16328
16329Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
16330 // node::ParseEncoding() requires lower case.
16331 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
16332 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);
16333 this._writableState.defaultEncoding = encoding;
16334 return this;
16335};
16336
16337function decodeChunk(state, chunk, encoding) {
16338 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
16339 chunk = Buffer.from(chunk, encoding);
16340 }
16341 return chunk;
16342}
16343
16344Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
16345 // making it explicit this property is not enumerable
16346 // because otherwise some prototype manipulation in
16347 // userland will fail
16348 enumerable: false,
16349 get: function () {
16350 return this._writableState.highWaterMark;
16351 }
16352});
16353
16354// if we're already writing something, then just put this
16355// in the queue, and wait our turn. Otherwise, call _write
16356// If we return false, then we need a drain event, so set that flag.
16357function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
16358 if (!isBuf) {
16359 var newChunk = decodeChunk(state, chunk, encoding);
16360 if (chunk !== newChunk) {
16361 isBuf = true;
16362 encoding = 'buffer';
16363 chunk = newChunk;
16364 }
16365 }
16366 var len = state.objectMode ? 1 : chunk.length;
16367
16368 state.length += len;
16369
16370 var ret = state.length < state.highWaterMark;
16371 // we must ensure that previous needDrain will not be reset to false.
16372 if (!ret) state.needDrain = true;
16373
16374 if (state.writing || state.corked) {
16375 var last = state.lastBufferedRequest;
16376 state.lastBufferedRequest = {
16377 chunk: chunk,
16378 encoding: encoding,
16379 isBuf: isBuf,
16380 callback: cb,
16381 next: null
16382 };
16383 if (last) {
16384 last.next = state.lastBufferedRequest;
16385 } else {
16386 state.bufferedRequest = state.lastBufferedRequest;
16387 }
16388 state.bufferedRequestCount += 1;
16389 } else {
16390 doWrite(stream, state, false, len, chunk, encoding, cb);
16391 }
16392
16393 return ret;
16394}
16395
16396function doWrite(stream, state, writev, len, chunk, encoding, cb) {
16397 state.writelen = len;
16398 state.writecb = cb;
16399 state.writing = true;
16400 state.sync = true;
16401 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
16402 state.sync = false;
16403}
16404
16405function onwriteError(stream, state, sync, er, cb) {
16406 --state.pendingcb;
16407
16408 if (sync) {
16409 // defer the callback if we are being called synchronously
16410 // to avoid piling up things on the stack
16411 pna.nextTick(cb, er);
16412 // this can emit finish, and it will always happen
16413 // after error
16414 pna.nextTick(finishMaybe, stream, state);
16415 stream._writableState.errorEmitted = true;
16416 stream.emit('error', er);
16417 } else {
16418 // the caller expect this to happen before if
16419 // it is async
16420 cb(er);
16421 stream._writableState.errorEmitted = true;
16422 stream.emit('error', er);
16423 // this can emit finish, but finish must
16424 // always follow error
16425 finishMaybe(stream, state);
16426 }
16427}
16428
16429function onwriteStateUpdate(state) {
16430 state.writing = false;
16431 state.writecb = null;
16432 state.length -= state.writelen;
16433 state.writelen = 0;
16434}
16435
16436function onwrite(stream, er) {
16437 var state = stream._writableState;
16438 var sync = state.sync;
16439 var cb = state.writecb;
16440
16441 onwriteStateUpdate(state);
16442
16443 if (er) onwriteError(stream, state, sync, er, cb);else {
16444 // Check if we're actually ready to finish, but don't emit yet
16445 var finished = needFinish(state);
16446
16447 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
16448 clearBuffer(stream, state);
16449 }
16450
16451 if (sync) {
16452 /*<replacement>*/
16453 asyncWrite(afterWrite, stream, state, finished, cb);
16454 /*</replacement>*/
16455 } else {
16456 afterWrite(stream, state, finished, cb);
16457 }
16458 }
16459}
16460
16461function afterWrite(stream, state, finished, cb) {
16462 if (!finished) onwriteDrain(stream, state);
16463 state.pendingcb--;
16464 cb();
16465 finishMaybe(stream, state);
16466}
16467
16468// Must force callback to be called on nextTick, so that we don't
16469// emit 'drain' before the write() consumer gets the 'false' return
16470// value, and has a chance to attach a 'drain' listener.
16471function onwriteDrain(stream, state) {
16472 if (state.length === 0 && state.needDrain) {
16473 state.needDrain = false;
16474 stream.emit('drain');
16475 }
16476}
16477
16478// if there's something in the buffer waiting, then process it
16479function clearBuffer(stream, state) {
16480 state.bufferProcessing = true;
16481 var entry = state.bufferedRequest;
16482
16483 if (stream._writev && entry && entry.next) {
16484 // Fast case, write everything using _writev()
16485 var l = state.bufferedRequestCount;
16486 var buffer = new Array(l);
16487 var holder = state.corkedRequestsFree;
16488 holder.entry = entry;
16489
16490 var count = 0;
16491 var allBuffers = true;
16492 while (entry) {
16493 buffer[count] = entry;
16494 if (!entry.isBuf) allBuffers = false;
16495 entry = entry.next;
16496 count += 1;
16497 }
16498 buffer.allBuffers = allBuffers;
16499
16500 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
16501
16502 // doWrite is almost always async, defer these to save a bit of time
16503 // as the hot path ends with doWrite
16504 state.pendingcb++;
16505 state.lastBufferedRequest = null;
16506 if (holder.next) {
16507 state.corkedRequestsFree = holder.next;
16508 holder.next = null;
16509 } else {
16510 state.corkedRequestsFree = new CorkedRequest(state);
16511 }
16512 state.bufferedRequestCount = 0;
16513 } else {
16514 // Slow case, write chunks one-by-one
16515 while (entry) {
16516 var chunk = entry.chunk;
16517 var encoding = entry.encoding;
16518 var cb = entry.callback;
16519 var len = state.objectMode ? 1 : chunk.length;
16520
16521 doWrite(stream, state, false, len, chunk, encoding, cb);
16522 entry = entry.next;
16523 state.bufferedRequestCount--;
16524 // if we didn't call the onwrite immediately, then
16525 // it means that we need to wait until it does.
16526 // also, that means that the chunk and cb are currently
16527 // being processed, so move the buffer counter past them.
16528 if (state.writing) {
16529 break;
16530 }
16531 }
16532
16533 if (entry === null) state.lastBufferedRequest = null;
16534 }
16535
16536 state.bufferedRequest = entry;
16537 state.bufferProcessing = false;
16538}
16539
16540Writable.prototype._write = function (chunk, encoding, cb) {
16541 cb(new Error('_write() is not implemented'));
16542};
16543
16544Writable.prototype._writev = null;
16545
16546Writable.prototype.end = function (chunk, encoding, cb) {
16547 var state = this._writableState;
16548
16549 if (typeof chunk === 'function') {
16550 cb = chunk;
16551 chunk = null;
16552 encoding = null;
16553 } else if (typeof encoding === 'function') {
16554 cb = encoding;
16555 encoding = null;
16556 }
16557
16558 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
16559
16560 // .end() fully uncorks
16561 if (state.corked) {
16562 state.corked = 1;
16563 this.uncork();
16564 }
16565
16566 // ignore unnecessary end() calls.
16567 if (!state.ending && !state.finished) endWritable(this, state, cb);
16568};
16569
16570function needFinish(state) {
16571 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
16572}
16573function callFinal(stream, state) {
16574 stream._final(function (err) {
16575 state.pendingcb--;
16576 if (err) {
16577 stream.emit('error', err);
16578 }
16579 state.prefinished = true;
16580 stream.emit('prefinish');
16581 finishMaybe(stream, state);
16582 });
16583}
16584function prefinish(stream, state) {
16585 if (!state.prefinished && !state.finalCalled) {
16586 if (typeof stream._final === 'function') {
16587 state.pendingcb++;
16588 state.finalCalled = true;
16589 pna.nextTick(callFinal, stream, state);
16590 } else {
16591 state.prefinished = true;
16592 stream.emit('prefinish');
16593 }
16594 }
16595}
16596
16597function finishMaybe(stream, state) {
16598 var need = needFinish(state);
16599 if (need) {
16600 prefinish(stream, state);
16601 if (state.pendingcb === 0) {
16602 state.finished = true;
16603 stream.emit('finish');
16604 }
16605 }
16606 return need;
16607}
16608
16609function endWritable(stream, state, cb) {
16610 state.ending = true;
16611 finishMaybe(stream, state);
16612 if (cb) {
16613 if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
16614 }
16615 state.ended = true;
16616 stream.writable = false;
16617}
16618
16619function onCorkedFinish(corkReq, state, err) {
16620 var entry = corkReq.entry;
16621 corkReq.entry = null;
16622 while (entry) {
16623 var cb = entry.callback;
16624 state.pendingcb--;
16625 cb(err);
16626 entry = entry.next;
16627 }
16628 if (state.corkedRequestsFree) {
16629 state.corkedRequestsFree.next = corkReq;
16630 } else {
16631 state.corkedRequestsFree = corkReq;
16632 }
16633}
16634
16635Object.defineProperty(Writable.prototype, 'destroyed', {
16636 get: function () {
16637 if (this._writableState === undefined) {
16638 return false;
16639 }
16640 return this._writableState.destroyed;
16641 },
16642 set: function (value) {
16643 // we ignore the value if the stream
16644 // has not been initialized yet
16645 if (!this._writableState) {
16646 return;
16647 }
16648
16649 // backward compatibility, the user is explicitly
16650 // managing destroyed
16651 this._writableState.destroyed = value;
16652 }
16653});
16654
16655Writable.prototype.destroy = destroyImpl.destroy;
16656Writable.prototype._undestroy = destroyImpl.undestroy;
16657Writable.prototype._destroy = function (err, cb) {
16658 this.end();
16659 cb(err);
16660};
16661}).call(this,_dereq_(70),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_(115).setImmediate)
16662},{"10":10,"115":115,"116":116,"18":18,"69":69,"70":70,"84":84,"90":90,"91":91,"96":96}],89:[function(_dereq_,module,exports){
16663'use strict';
16664
16665function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
16666
16667var Buffer = _dereq_(96).Buffer;
16668var util = _dereq_(7);
16669
16670function copyBuffer(src, target, offset) {
16671 src.copy(target, offset);
16672}
16673
16674module.exports = function () {
16675 function BufferList() {
16676 _classCallCheck(this, BufferList);
16677
16678 this.head = null;
16679 this.tail = null;
16680 this.length = 0;
16681 }
16682
16683 BufferList.prototype.push = function push(v) {
16684 var entry = { data: v, next: null };
16685 if (this.length > 0) this.tail.next = entry;else this.head = entry;
16686 this.tail = entry;
16687 ++this.length;
16688 };
16689
16690 BufferList.prototype.unshift = function unshift(v) {
16691 var entry = { data: v, next: this.head };
16692 if (this.length === 0) this.tail = entry;
16693 this.head = entry;
16694 ++this.length;
16695 };
16696
16697 BufferList.prototype.shift = function shift() {
16698 if (this.length === 0) return;
16699 var ret = this.head.data;
16700 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
16701 --this.length;
16702 return ret;
16703 };
16704
16705 BufferList.prototype.clear = function clear() {
16706 this.head = this.tail = null;
16707 this.length = 0;
16708 };
16709
16710 BufferList.prototype.join = function join(s) {
16711 if (this.length === 0) return '';
16712 var p = this.head;
16713 var ret = '' + p.data;
16714 while (p = p.next) {
16715 ret += s + p.data;
16716 }return ret;
16717 };
16718
16719 BufferList.prototype.concat = function concat(n) {
16720 if (this.length === 0) return Buffer.alloc(0);
16721 if (this.length === 1) return this.head.data;
16722 var ret = Buffer.allocUnsafe(n >>> 0);
16723 var p = this.head;
16724 var i = 0;
16725 while (p) {
16726 copyBuffer(p.data, ret, i);
16727 i += p.data.length;
16728 p = p.next;
16729 }
16730 return ret;
16731 };
16732
16733 return BufferList;
16734}();
16735
16736if (util && util.inspect && util.inspect.custom) {
16737 module.exports.prototype[util.inspect.custom] = function () {
16738 var obj = util.inspect({ length: this.length });
16739 return this.constructor.name + ' ' + obj;
16740 };
16741}
16742},{"7":7,"96":96}],90:[function(_dereq_,module,exports){
16743'use strict';
16744
16745/*<replacement>*/
16746
16747var pna = _dereq_(69);
16748/*</replacement>*/
16749
16750// undocumented cb() API, needed for core, not for public API
16751function destroy(err, cb) {
16752 var _this = this;
16753
16754 var readableDestroyed = this._readableState && this._readableState.destroyed;
16755 var writableDestroyed = this._writableState && this._writableState.destroyed;
16756
16757 if (readableDestroyed || writableDestroyed) {
16758 if (cb) {
16759 cb(err);
16760 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
16761 pna.nextTick(emitErrorNT, this, err);
16762 }
16763 return this;
16764 }
16765
16766 // we set destroyed to true before firing error callbacks in order
16767 // to make it re-entrance safe in case destroy() is called within callbacks
16768
16769 if (this._readableState) {
16770 this._readableState.destroyed = true;
16771 }
16772
16773 // if this is a duplex stream mark the writable part as destroyed as well
16774 if (this._writableState) {
16775 this._writableState.destroyed = true;
16776 }
16777
16778 this._destroy(err || null, function (err) {
16779 if (!cb && err) {
16780 pna.nextTick(emitErrorNT, _this, err);
16781 if (_this._writableState) {
16782 _this._writableState.errorEmitted = true;
16783 }
16784 } else if (cb) {
16785 cb(err);
16786 }
16787 });
16788
16789 return this;
16790}
16791
16792function undestroy() {
16793 if (this._readableState) {
16794 this._readableState.destroyed = false;
16795 this._readableState.reading = false;
16796 this._readableState.ended = false;
16797 this._readableState.endEmitted = false;
16798 }
16799
16800 if (this._writableState) {
16801 this._writableState.destroyed = false;
16802 this._writableState.ended = false;
16803 this._writableState.ending = false;
16804 this._writableState.finished = false;
16805 this._writableState.errorEmitted = false;
16806 }
16807}
16808
16809function emitErrorNT(self, err) {
16810 self.emit('error', err);
16811}
16812
16813module.exports = {
16814 destroy: destroy,
16815 undestroy: undestroy
16816};
16817},{"69":69}],91:[function(_dereq_,module,exports){
16818arguments[4][38][0].apply(exports,arguments)
16819},{"14":14,"38":38}],92:[function(_dereq_,module,exports){
16820module.exports = _dereq_(93).PassThrough
16821
16822},{"93":93}],93:[function(_dereq_,module,exports){
16823exports = module.exports = _dereq_(86);
16824exports.Stream = exports;
16825exports.Readable = exports;
16826exports.Writable = _dereq_(88);
16827exports.Duplex = _dereq_(84);
16828exports.Transform = _dereq_(87);
16829exports.PassThrough = _dereq_(85);
16830
16831},{"84":84,"85":85,"86":86,"87":87,"88":88}],94:[function(_dereq_,module,exports){
16832module.exports = _dereq_(93).Transform
16833
16834},{"93":93}],95:[function(_dereq_,module,exports){
16835module.exports = _dereq_(88);
16836
16837},{"88":88}],96:[function(_dereq_,module,exports){
16838/* eslint-disable node/no-deprecated-api */
16839var buffer = _dereq_(9)
16840var Buffer = buffer.Buffer
16841
16842// alternative to using Object.keys for old browsers
16843function copyProps (src, dst) {
16844 for (var key in src) {
16845 dst[key] = src[key]
16846 }
16847}
16848if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
16849 module.exports = buffer
16850} else {
16851 // Copy properties from require('buffer')
16852 copyProps(buffer, exports)
16853 exports.Buffer = SafeBuffer
16854}
16855
16856function SafeBuffer (arg, encodingOrOffset, length) {
16857 return Buffer(arg, encodingOrOffset, length)
16858}
16859
16860// Copy static methods from Buffer
16861copyProps(Buffer, SafeBuffer)
16862
16863SafeBuffer.from = function (arg, encodingOrOffset, length) {
16864 if (typeof arg === 'number') {
16865 throw new TypeError('Argument must not be a number')
16866 }
16867 return Buffer(arg, encodingOrOffset, length)
16868}
16869
16870SafeBuffer.alloc = function (size, fill, encoding) {
16871 if (typeof size !== 'number') {
16872 throw new TypeError('Argument must be a number')
16873 }
16874 var buf = Buffer(size)
16875 if (fill !== undefined) {
16876 if (typeof encoding === 'string') {
16877 buf.fill(fill, encoding)
16878 } else {
16879 buf.fill(fill)
16880 }
16881 } else {
16882 buf.fill(0)
16883 }
16884 return buf
16885}
16886
16887SafeBuffer.allocUnsafe = function (size) {
16888 if (typeof size !== 'number') {
16889 throw new TypeError('Argument must be a number')
16890 }
16891 return Buffer(size)
16892}
16893
16894SafeBuffer.allocUnsafeSlow = function (size) {
16895 if (typeof size !== 'number') {
16896 throw new TypeError('Argument must be a number')
16897 }
16898 return buffer.SlowBuffer(size)
16899}
16900
16901},{"9":9}],97:[function(_dereq_,module,exports){
16902// Copyright Joyent, Inc. and other Node contributors.
16903//
16904// Permission is hereby granted, free of charge, to any person obtaining a
16905// copy of this software and associated documentation files (the
16906// "Software"), to deal in the Software without restriction, including
16907// without limitation the rights to use, copy, modify, merge, publish,
16908// distribute, sublicense, and/or sell copies of the Software, and to permit
16909// persons to whom the Software is furnished to do so, subject to the
16910// following conditions:
16911//
16912// The above copyright notice and this permission notice shall be included
16913// in all copies or substantial portions of the Software.
16914//
16915// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16916// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16917// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
16918// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
16919// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16920// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
16921// USE OR OTHER DEALINGS IN THE SOFTWARE.
16922
16923'use strict';
16924
16925/*<replacement>*/
16926
16927var Buffer = _dereq_(96).Buffer;
16928/*</replacement>*/
16929
16930var isEncoding = Buffer.isEncoding || function (encoding) {
16931 encoding = '' + encoding;
16932 switch (encoding && encoding.toLowerCase()) {
16933 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':
16934 return true;
16935 default:
16936 return false;
16937 }
16938};
16939
16940function _normalizeEncoding(enc) {
16941 if (!enc) return 'utf8';
16942 var retried;
16943 while (true) {
16944 switch (enc) {
16945 case 'utf8':
16946 case 'utf-8':
16947 return 'utf8';
16948 case 'ucs2':
16949 case 'ucs-2':
16950 case 'utf16le':
16951 case 'utf-16le':
16952 return 'utf16le';
16953 case 'latin1':
16954 case 'binary':
16955 return 'latin1';
16956 case 'base64':
16957 case 'ascii':
16958 case 'hex':
16959 return enc;
16960 default:
16961 if (retried) return; // undefined
16962 enc = ('' + enc).toLowerCase();
16963 retried = true;
16964 }
16965 }
16966};
16967
16968// Do not cache `Buffer.isEncoding` when checking encoding names as some
16969// modules monkey-patch it to support additional encodings
16970function normalizeEncoding(enc) {
16971 var nenc = _normalizeEncoding(enc);
16972 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
16973 return nenc || enc;
16974}
16975
16976// StringDecoder provides an interface for efficiently splitting a series of
16977// buffers into a series of JS strings without breaking apart multi-byte
16978// characters.
16979exports.StringDecoder = StringDecoder;
16980function StringDecoder(encoding) {
16981 this.encoding = normalizeEncoding(encoding);
16982 var nb;
16983 switch (this.encoding) {
16984 case 'utf16le':
16985 this.text = utf16Text;
16986 this.end = utf16End;
16987 nb = 4;
16988 break;
16989 case 'utf8':
16990 this.fillLast = utf8FillLast;
16991 nb = 4;
16992 break;
16993 case 'base64':
16994 this.text = base64Text;
16995 this.end = base64End;
16996 nb = 3;
16997 break;
16998 default:
16999 this.write = simpleWrite;
17000 this.end = simpleEnd;
17001 return;
17002 }
17003 this.lastNeed = 0;
17004 this.lastTotal = 0;
17005 this.lastChar = Buffer.allocUnsafe(nb);
17006}
17007
17008StringDecoder.prototype.write = function (buf) {
17009 if (buf.length === 0) return '';
17010 var r;
17011 var i;
17012 if (this.lastNeed) {
17013 r = this.fillLast(buf);
17014 if (r === undefined) return '';
17015 i = this.lastNeed;
17016 this.lastNeed = 0;
17017 } else {
17018 i = 0;
17019 }
17020 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
17021 return r || '';
17022};
17023
17024StringDecoder.prototype.end = utf8End;
17025
17026// Returns only complete characters in a Buffer
17027StringDecoder.prototype.text = utf8Text;
17028
17029// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
17030StringDecoder.prototype.fillLast = function (buf) {
17031 if (this.lastNeed <= buf.length) {
17032 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
17033 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
17034 }
17035 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
17036 this.lastNeed -= buf.length;
17037};
17038
17039// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
17040// continuation byte. If an invalid byte is detected, -2 is returned.
17041function utf8CheckByte(byte) {
17042 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;
17043 return byte >> 6 === 0x02 ? -1 : -2;
17044}
17045
17046// Checks at most 3 bytes at the end of a Buffer in order to detect an
17047// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
17048// needed to complete the UTF-8 character (if applicable) are returned.
17049function utf8CheckIncomplete(self, buf, i) {
17050 var j = buf.length - 1;
17051 if (j < i) return 0;
17052 var nb = utf8CheckByte(buf[j]);
17053 if (nb >= 0) {
17054 if (nb > 0) self.lastNeed = nb - 1;
17055 return nb;
17056 }
17057 if (--j < i || nb === -2) return 0;
17058 nb = utf8CheckByte(buf[j]);
17059 if (nb >= 0) {
17060 if (nb > 0) self.lastNeed = nb - 2;
17061 return nb;
17062 }
17063 if (--j < i || nb === -2) return 0;
17064 nb = utf8CheckByte(buf[j]);
17065 if (nb >= 0) {
17066 if (nb > 0) {
17067 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
17068 }
17069 return nb;
17070 }
17071 return 0;
17072}
17073
17074// Validates as many continuation bytes for a multi-byte UTF-8 character as
17075// needed or are available. If we see a non-continuation byte where we expect
17076// one, we "replace" the validated continuation bytes we've seen so far with
17077// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
17078// behavior. The continuation byte check is included three times in the case
17079// where all of the continuation bytes for a character exist in the same buffer.
17080// It is also done this way as a slight performance increase instead of using a
17081// loop.
17082function utf8CheckExtraBytes(self, buf, p) {
17083 if ((buf[0] & 0xC0) !== 0x80) {
17084 self.lastNeed = 0;
17085 return '\ufffd';
17086 }
17087 if (self.lastNeed > 1 && buf.length > 1) {
17088 if ((buf[1] & 0xC0) !== 0x80) {
17089 self.lastNeed = 1;
17090 return '\ufffd';
17091 }
17092 if (self.lastNeed > 2 && buf.length > 2) {
17093 if ((buf[2] & 0xC0) !== 0x80) {
17094 self.lastNeed = 2;
17095 return '\ufffd';
17096 }
17097 }
17098 }
17099}
17100
17101// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
17102function utf8FillLast(buf) {
17103 var p = this.lastTotal - this.lastNeed;
17104 var r = utf8CheckExtraBytes(this, buf, p);
17105 if (r !== undefined) return r;
17106 if (this.lastNeed <= buf.length) {
17107 buf.copy(this.lastChar, p, 0, this.lastNeed);
17108 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
17109 }
17110 buf.copy(this.lastChar, p, 0, buf.length);
17111 this.lastNeed -= buf.length;
17112}
17113
17114// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
17115// partial character, the character's bytes are buffered until the required
17116// number of bytes are available.
17117function utf8Text(buf, i) {
17118 var total = utf8CheckIncomplete(this, buf, i);
17119 if (!this.lastNeed) return buf.toString('utf8', i);
17120 this.lastTotal = total;
17121 var end = buf.length - (total - this.lastNeed);
17122 buf.copy(this.lastChar, 0, end);
17123 return buf.toString('utf8', i, end);
17124}
17125
17126// For UTF-8, a replacement character is added when ending on a partial
17127// character.
17128function utf8End(buf) {
17129 var r = buf && buf.length ? this.write(buf) : '';
17130 if (this.lastNeed) return r + '\ufffd';
17131 return r;
17132}
17133
17134// UTF-16LE typically needs two bytes per character, but even if we have an even
17135// number of bytes available, we need to check if we end on a leading/high
17136// surrogate. In that case, we need to wait for the next two bytes in order to
17137// decode the last character properly.
17138function utf16Text(buf, i) {
17139 if ((buf.length - i) % 2 === 0) {
17140 var r = buf.toString('utf16le', i);
17141 if (r) {
17142 var c = r.charCodeAt(r.length - 1);
17143 if (c >= 0xD800 && c <= 0xDBFF) {
17144 this.lastNeed = 2;
17145 this.lastTotal = 4;
17146 this.lastChar[0] = buf[buf.length - 2];
17147 this.lastChar[1] = buf[buf.length - 1];
17148 return r.slice(0, -1);
17149 }
17150 }
17151 return r;
17152 }
17153 this.lastNeed = 1;
17154 this.lastTotal = 2;
17155 this.lastChar[0] = buf[buf.length - 1];
17156 return buf.toString('utf16le', i, buf.length - 1);
17157}
17158
17159// For UTF-16LE we do not explicitly append special replacement characters if we
17160// end on a partial character, we simply let v8 handle that.
17161function utf16End(buf) {
17162 var r = buf && buf.length ? this.write(buf) : '';
17163 if (this.lastNeed) {
17164 var end = this.lastTotal - this.lastNeed;
17165 return r + this.lastChar.toString('utf16le', 0, end);
17166 }
17167 return r;
17168}
17169
17170function base64Text(buf, i) {
17171 var n = (buf.length - i) % 3;
17172 if (n === 0) return buf.toString('base64', i);
17173 this.lastNeed = 3 - n;
17174 this.lastTotal = 3;
17175 if (n === 1) {
17176 this.lastChar[0] = buf[buf.length - 1];
17177 } else {
17178 this.lastChar[0] = buf[buf.length - 2];
17179 this.lastChar[1] = buf[buf.length - 1];
17180 }
17181 return buf.toString('base64', i, buf.length - n);
17182}
17183
17184function base64End(buf) {
17185 var r = buf && buf.length ? this.write(buf) : '';
17186 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
17187 return r;
17188}
17189
17190// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
17191function simpleWrite(buf) {
17192 return buf.toString(this.encoding);
17193}
17194
17195function simpleEnd(buf) {
17196 return buf && buf.length ? this.write(buf) : '';
17197}
17198},{"96":96}],98:[function(_dereq_,module,exports){
17199arguments[4][97][0].apply(exports,arguments)
17200},{"79":79,"97":97}],99:[function(_dereq_,module,exports){
17201arguments[4][25][0].apply(exports,arguments)
17202},{"25":25}],100:[function(_dereq_,module,exports){
17203arguments[4][26][0].apply(exports,arguments)
17204},{"102":102,"104":104,"18":18,"26":26,"70":70}],101:[function(_dereq_,module,exports){
17205arguments[4][27][0].apply(exports,arguments)
17206},{"103":103,"18":18,"27":27}],102:[function(_dereq_,module,exports){
17207arguments[4][28][0].apply(exports,arguments)
17208},{"100":100,"105":105,"106":106,"107":107,"109":109,"111":111,"112":112,"14":14,"18":18,"28":28,"7":7,"70":70,"9":9,"98":98,"99":99}],103:[function(_dereq_,module,exports){
17209arguments[4][29][0].apply(exports,arguments)
17210},{"100":100,"18":18,"29":29,"99":99}],104:[function(_dereq_,module,exports){
17211arguments[4][30][0].apply(exports,arguments)
17212},{"100":100,"107":107,"111":111,"112":112,"116":116,"18":18,"30":30,"70":70,"9":9,"99":99}],105:[function(_dereq_,module,exports){
17213arguments[4][31][0].apply(exports,arguments)
17214},{"108":108,"31":31,"70":70}],106:[function(_dereq_,module,exports){
17215arguments[4][32][0].apply(exports,arguments)
17216},{"32":32,"7":7,"9":9}],107:[function(_dereq_,module,exports){
17217arguments[4][33][0].apply(exports,arguments)
17218},{"33":33,"70":70}],108:[function(_dereq_,module,exports){
17219arguments[4][34][0].apply(exports,arguments)
17220},{"34":34,"99":99}],109:[function(_dereq_,module,exports){
17221arguments[4][35][0].apply(exports,arguments)
17222},{"35":35}],110:[function(_dereq_,module,exports){
17223arguments[4][36][0].apply(exports,arguments)
17224},{"108":108,"36":36,"99":99}],111:[function(_dereq_,module,exports){
17225arguments[4][37][0].apply(exports,arguments)
17226},{"37":37,"99":99}],112:[function(_dereq_,module,exports){
17227arguments[4][38][0].apply(exports,arguments)
17228},{"14":14,"38":38}],113:[function(_dereq_,module,exports){
17229arguments[4][39][0].apply(exports,arguments)
17230},{"100":100,"101":101,"102":102,"103":103,"104":104,"108":108,"110":110,"39":39}],114:[function(_dereq_,module,exports){
17231(function (process){
17232var Transform = _dereq_(113).Transform
17233 , inherits = _dereq_(119).inherits
17234
17235function DestroyableTransform(opts) {
17236 Transform.call(this, opts)
17237 this._destroyed = false
17238}
17239
17240inherits(DestroyableTransform, Transform)
17241
17242DestroyableTransform.prototype.destroy = function(err) {
17243 if (this._destroyed) return
17244 this._destroyed = true
17245
17246 var self = this
17247 process.nextTick(function() {
17248 if (err)
17249 self.emit('error', err)
17250 self.emit('close')
17251 })
17252}
17253
17254// a noop _transform function
17255function noop (chunk, enc, callback) {
17256 callback(null, chunk)
17257}
17258
17259
17260// create a new export function, used by both the main export and
17261// the .ctor export, contains common logic for dealing with arguments
17262function through2 (construct) {
17263 return function (options, transform, flush) {
17264 if (typeof options == 'function') {
17265 flush = transform
17266 transform = options
17267 options = {}
17268 }
17269
17270 if (typeof transform != 'function')
17271 transform = noop
17272
17273 if (typeof flush != 'function')
17274 flush = null
17275
17276 return construct(options, transform, flush)
17277 }
17278}
17279
17280
17281// main export, just make me a transform stream!
17282module.exports = through2(function (options, transform, flush) {
17283 var t2 = new DestroyableTransform(options)
17284
17285 t2._transform = transform
17286
17287 if (flush)
17288 t2._flush = flush
17289
17290 return t2
17291})
17292
17293
17294// make me a reusable prototype that I can `new`, or implicitly `new`
17295// with a constructor call
17296module.exports.ctor = through2(function (options, transform, flush) {
17297 function Through2 (override) {
17298 if (!(this instanceof Through2))
17299 return new Through2(override)
17300
17301 this.options = Object.assign({}, options, override)
17302
17303 DestroyableTransform.call(this, this.options)
17304 }
17305
17306 inherits(Through2, DestroyableTransform)
17307
17308 Through2.prototype._transform = transform
17309
17310 if (flush)
17311 Through2.prototype._flush = flush
17312
17313 return Through2
17314})
17315
17316
17317module.exports.obj = through2(function (options, transform, flush) {
17318 var t2 = new DestroyableTransform(Object.assign({ objectMode: true, highWaterMark: 16 }, options))
17319
17320 t2._transform = transform
17321
17322 if (flush)
17323 t2._flush = flush
17324
17325 return t2
17326})
17327
17328}).call(this,_dereq_(70))
17329},{"113":113,"119":119,"70":70}],115:[function(_dereq_,module,exports){
17330(function (setImmediate,clearImmediate){
17331var nextTick = _dereq_(70).nextTick;
17332var apply = Function.prototype.apply;
17333var slice = Array.prototype.slice;
17334var immediateIds = {};
17335var nextImmediateId = 0;
17336
17337// DOM APIs, for completeness
17338
17339exports.setTimeout = function() {
17340 return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
17341};
17342exports.setInterval = function() {
17343 return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
17344};
17345exports.clearTimeout =
17346exports.clearInterval = function(timeout) { timeout.close(); };
17347
17348function Timeout(id, clearFn) {
17349 this._id = id;
17350 this._clearFn = clearFn;
17351}
17352Timeout.prototype.unref = Timeout.prototype.ref = function() {};
17353Timeout.prototype.close = function() {
17354 this._clearFn.call(window, this._id);
17355};
17356
17357// Does not start the time, just sets up the members needed.
17358exports.enroll = function(item, msecs) {
17359 clearTimeout(item._idleTimeoutId);
17360 item._idleTimeout = msecs;
17361};
17362
17363exports.unenroll = function(item) {
17364 clearTimeout(item._idleTimeoutId);
17365 item._idleTimeout = -1;
17366};
17367
17368exports._unrefActive = exports.active = function(item) {
17369 clearTimeout(item._idleTimeoutId);
17370
17371 var msecs = item._idleTimeout;
17372 if (msecs >= 0) {
17373 item._idleTimeoutId = setTimeout(function onTimeout() {
17374 if (item._onTimeout)
17375 item._onTimeout();
17376 }, msecs);
17377 }
17378};
17379
17380// That's not how node.js implements it but the exposed api is the same.
17381exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
17382 var id = nextImmediateId++;
17383 var args = arguments.length < 2 ? false : slice.call(arguments, 1);
17384
17385 immediateIds[id] = true;
17386
17387 nextTick(function onNextTick() {
17388 if (immediateIds[id]) {
17389 // fn.call() is faster so we optimize for the common use-case
17390 // @see http://jsperf.com/call-apply-segu
17391 if (args) {
17392 fn.apply(null, args);
17393 } else {
17394 fn.call(null);
17395 }
17396 // Prevent ids from leaking
17397 exports.clearImmediate(id);
17398 }
17399 });
17400
17401 return id;
17402};
17403
17404exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
17405 delete immediateIds[id];
17406};
17407}).call(this,_dereq_(115).setImmediate,_dereq_(115).clearImmediate)
17408},{"115":115,"70":70}],116:[function(_dereq_,module,exports){
17409(function (global){
17410
17411/**
17412 * Module exports.
17413 */
17414
17415module.exports = deprecate;
17416
17417/**
17418 * Mark that a method should not be used.
17419 * Returns a modified function which warns once by default.
17420 *
17421 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
17422 *
17423 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
17424 * will throw an Error when invoked.
17425 *
17426 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
17427 * will invoke `console.trace()` instead of `console.error()`.
17428 *
17429 * @param {Function} fn - the function to deprecate
17430 * @param {String} msg - the string to print to the console when `fn` is invoked
17431 * @returns {Function} a new "deprecated" version of `fn`
17432 * @api public
17433 */
17434
17435function deprecate (fn, msg) {
17436 if (config('noDeprecation')) {
17437 return fn;
17438 }
17439
17440 var warned = false;
17441 function deprecated() {
17442 if (!warned) {
17443 if (config('throwDeprecation')) {
17444 throw new Error(msg);
17445 } else if (config('traceDeprecation')) {
17446 console.trace(msg);
17447 } else {
17448 console.warn(msg);
17449 }
17450 warned = true;
17451 }
17452 return fn.apply(this, arguments);
17453 }
17454
17455 return deprecated;
17456}
17457
17458/**
17459 * Checks `localStorage` for boolean values for the given `name`.
17460 *
17461 * @param {String} name
17462 * @returns {Boolean}
17463 * @api private
17464 */
17465
17466function config (name) {
17467 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
17468 try {
17469 if (!global.localStorage) return false;
17470 } catch (_) {
17471 return false;
17472 }
17473 var val = global.localStorage[name];
17474 if (null == val) return false;
17475 return String(val).toLowerCase() === 'true';
17476}
17477
17478}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
17479},{}],117:[function(_dereq_,module,exports){
17480arguments[4][3][0].apply(exports,arguments)
17481},{"3":3}],118:[function(_dereq_,module,exports){
17482arguments[4][4][0].apply(exports,arguments)
17483},{"4":4}],119:[function(_dereq_,module,exports){
17484arguments[4][5][0].apply(exports,arguments)
17485},{"117":117,"118":118,"5":5,"70":70}],120:[function(_dereq_,module,exports){
17486var v1 = _dereq_(123);
17487var v4 = _dereq_(124);
17488
17489var uuid = v4;
17490uuid.v1 = v1;
17491uuid.v4 = v4;
17492
17493module.exports = uuid;
17494
17495},{"123":123,"124":124}],121:[function(_dereq_,module,exports){
17496/**
17497 * Convert array of 16 byte values to UUID string format of the form:
17498 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
17499 */
17500var byteToHex = [];
17501for (var i = 0; i < 256; ++i) {
17502 byteToHex[i] = (i + 0x100).toString(16).substr(1);
17503}
17504
17505function bytesToUuid(buf, offset) {
17506 var i = offset || 0;
17507 var bth = byteToHex;
17508 // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
17509 return ([bth[buf[i++]], bth[buf[i++]],
17510 bth[buf[i++]], bth[buf[i++]], '-',
17511 bth[buf[i++]], bth[buf[i++]], '-',
17512 bth[buf[i++]], bth[buf[i++]], '-',
17513 bth[buf[i++]], bth[buf[i++]], '-',
17514 bth[buf[i++]], bth[buf[i++]],
17515 bth[buf[i++]], bth[buf[i++]],
17516 bth[buf[i++]], bth[buf[i++]]]).join('');
17517}
17518
17519module.exports = bytesToUuid;
17520
17521},{}],122:[function(_dereq_,module,exports){
17522// Unique ID creation requires a high quality random # generator. In the
17523// browser this is a little complicated due to unknown quality of Math.random()
17524// and inconsistent support for the `crypto` API. We do the best we can via
17525// feature-detection
17526
17527// getRandomValues needs to be invoked in a context where "this" is a Crypto
17528// implementation. Also, find the complete implementation of crypto on IE11.
17529var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
17530 (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));
17531
17532if (getRandomValues) {
17533 // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
17534 var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
17535
17536 module.exports = function whatwgRNG() {
17537 getRandomValues(rnds8);
17538 return rnds8;
17539 };
17540} else {
17541 // Math.random()-based (RNG)
17542 //
17543 // If all else fails, use Math.random(). It's fast, but is of unspecified
17544 // quality.
17545 var rnds = new Array(16);
17546
17547 module.exports = function mathRNG() {
17548 for (var i = 0, r; i < 16; i++) {
17549 if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
17550 rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
17551 }
17552
17553 return rnds;
17554 };
17555}
17556
17557},{}],123:[function(_dereq_,module,exports){
17558var rng = _dereq_(122);
17559var bytesToUuid = _dereq_(121);
17560
17561// **`v1()` - Generate time-based UUID**
17562//
17563// Inspired by https://github.com/LiosK/UUID.js
17564// and http://docs.python.org/library/uuid.html
17565
17566var _nodeId;
17567var _clockseq;
17568
17569// Previous uuid creation time
17570var _lastMSecs = 0;
17571var _lastNSecs = 0;
17572
17573// See https://github.com/broofa/node-uuid for API details
17574function v1(options, buf, offset) {
17575 var i = buf && offset || 0;
17576 var b = buf || [];
17577
17578 options = options || {};
17579 var node = options.node || _nodeId;
17580 var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
17581
17582 // node and clockseq need to be initialized to random values if they're not
17583 // specified. We do this lazily to minimize issues related to insufficient
17584 // system entropy. See #189
17585 if (node == null || clockseq == null) {
17586 var seedBytes = rng();
17587 if (node == null) {
17588 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
17589 node = _nodeId = [
17590 seedBytes[0] | 0x01,
17591 seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]
17592 ];
17593 }
17594 if (clockseq == null) {
17595 // Per 4.2.2, randomize (14 bit) clockseq
17596 clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
17597 }
17598 }
17599
17600 // UUID timestamps are 100 nano-second units since the Gregorian epoch,
17601 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
17602 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
17603 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
17604 var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
17605
17606 // Per 4.2.1.2, use count of uuid's generated during the current clock
17607 // cycle to simulate higher resolution clock
17608 var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
17609
17610 // Time since last uuid creation (in msecs)
17611 var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
17612
17613 // Per 4.2.1.2, Bump clockseq on clock regression
17614 if (dt < 0 && options.clockseq === undefined) {
17615 clockseq = clockseq + 1 & 0x3fff;
17616 }
17617
17618 // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
17619 // time interval
17620 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
17621 nsecs = 0;
17622 }
17623
17624 // Per 4.2.1.2 Throw error if too many uuids are requested
17625 if (nsecs >= 10000) {
17626 throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
17627 }
17628
17629 _lastMSecs = msecs;
17630 _lastNSecs = nsecs;
17631 _clockseq = clockseq;
17632
17633 // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
17634 msecs += 12219292800000;
17635
17636 // `time_low`
17637 var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
17638 b[i++] = tl >>> 24 & 0xff;
17639 b[i++] = tl >>> 16 & 0xff;
17640 b[i++] = tl >>> 8 & 0xff;
17641 b[i++] = tl & 0xff;
17642
17643 // `time_mid`
17644 var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
17645 b[i++] = tmh >>> 8 & 0xff;
17646 b[i++] = tmh & 0xff;
17647
17648 // `time_high_and_version`
17649 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
17650 b[i++] = tmh >>> 16 & 0xff;
17651
17652 // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
17653 b[i++] = clockseq >>> 8 | 0x80;
17654
17655 // `clock_seq_low`
17656 b[i++] = clockseq & 0xff;
17657
17658 // `node`
17659 for (var n = 0; n < 6; ++n) {
17660 b[i + n] = node[n];
17661 }
17662
17663 return buf ? buf : bytesToUuid(b);
17664}
17665
17666module.exports = v1;
17667
17668},{"121":121,"122":122}],124:[function(_dereq_,module,exports){
17669var rng = _dereq_(122);
17670var bytesToUuid = _dereq_(121);
17671
17672function v4(options, buf, offset) {
17673 var i = buf && offset || 0;
17674
17675 if (typeof(options) == 'string') {
17676 buf = options === 'binary' ? new Array(16) : null;
17677 options = null;
17678 }
17679 options = options || {};
17680
17681 var rnds = options.random || (options.rng || rng)();
17682
17683 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
17684 rnds[6] = (rnds[6] & 0x0f) | 0x40;
17685 rnds[8] = (rnds[8] & 0x3f) | 0x80;
17686
17687 // Copy bytes to buffer, if provided
17688 if (buf) {
17689 for (var ii = 0; ii < 16; ++ii) {
17690 buf[i + ii] = rnds[ii];
17691 }
17692 }
17693
17694 return buf || bytesToUuid(rnds);
17695}
17696
17697module.exports = v4;
17698
17699},{"121":121,"122":122}],125:[function(_dereq_,module,exports){
17700'use strict';
17701
17702/**
17703 * Stringify/parse functions that don't operate
17704 * recursively, so they avoid call stack exceeded
17705 * errors.
17706 */
17707exports.stringify = function stringify(input) {
17708 var queue = [];
17709 queue.push({obj: input});
17710
17711 var res = '';
17712 var next, obj, prefix, val, i, arrayPrefix, keys, k, key, value, objPrefix;
17713 while ((next = queue.pop())) {
17714 obj = next.obj;
17715 prefix = next.prefix || '';
17716 val = next.val || '';
17717 res += prefix;
17718 if (val) {
17719 res += val;
17720 } else if (typeof obj !== 'object') {
17721 res += typeof obj === 'undefined' ? null : JSON.stringify(obj);
17722 } else if (obj === null) {
17723 res += 'null';
17724 } else if (Array.isArray(obj)) {
17725 queue.push({val: ']'});
17726 for (i = obj.length - 1; i >= 0; i--) {
17727 arrayPrefix = i === 0 ? '' : ',';
17728 queue.push({obj: obj[i], prefix: arrayPrefix});
17729 }
17730 queue.push({val: '['});
17731 } else { // object
17732 keys = [];
17733 for (k in obj) {
17734 if (obj.hasOwnProperty(k)) {
17735 keys.push(k);
17736 }
17737 }
17738 queue.push({val: '}'});
17739 for (i = keys.length - 1; i >= 0; i--) {
17740 key = keys[i];
17741 value = obj[key];
17742 objPrefix = (i > 0 ? ',' : '');
17743 objPrefix += JSON.stringify(key) + ':';
17744 queue.push({obj: value, prefix: objPrefix});
17745 }
17746 queue.push({val: '{'});
17747 }
17748 }
17749 return res;
17750};
17751
17752// Convenience function for the parse function.
17753// This pop function is basically copied from
17754// pouchCollate.parseIndexableString
17755function pop(obj, stack, metaStack) {
17756 var lastMetaElement = metaStack[metaStack.length - 1];
17757 if (obj === lastMetaElement.element) {
17758 // popping a meta-element, e.g. an object whose value is another object
17759 metaStack.pop();
17760 lastMetaElement = metaStack[metaStack.length - 1];
17761 }
17762 var element = lastMetaElement.element;
17763 var lastElementIndex = lastMetaElement.index;
17764 if (Array.isArray(element)) {
17765 element.push(obj);
17766 } else if (lastElementIndex === stack.length - 2) { // obj with key+value
17767 var key = stack.pop();
17768 element[key] = obj;
17769 } else {
17770 stack.push(obj); // obj with key only
17771 }
17772}
17773
17774exports.parse = function (str) {
17775 var stack = [];
17776 var metaStack = []; // stack for arrays and objects
17777 var i = 0;
17778 var collationIndex,parsedNum,numChar;
17779 var parsedString,lastCh,numConsecutiveSlashes,ch;
17780 var arrayElement, objElement;
17781 while (true) {
17782 collationIndex = str[i++];
17783 if (collationIndex === '}' ||
17784 collationIndex === ']' ||
17785 typeof collationIndex === 'undefined') {
17786 if (stack.length === 1) {
17787 return stack.pop();
17788 } else {
17789 pop(stack.pop(), stack, metaStack);
17790 continue;
17791 }
17792 }
17793 switch (collationIndex) {
17794 case ' ':
17795 case '\t':
17796 case '\n':
17797 case ':':
17798 case ',':
17799 break;
17800 case 'n':
17801 i += 3; // 'ull'
17802 pop(null, stack, metaStack);
17803 break;
17804 case 't':
17805 i += 3; // 'rue'
17806 pop(true, stack, metaStack);
17807 break;
17808 case 'f':
17809 i += 4; // 'alse'
17810 pop(false, stack, metaStack);
17811 break;
17812 case '0':
17813 case '1':
17814 case '2':
17815 case '3':
17816 case '4':
17817 case '5':
17818 case '6':
17819 case '7':
17820 case '8':
17821 case '9':
17822 case '-':
17823 parsedNum = '';
17824 i--;
17825 while (true) {
17826 numChar = str[i++];
17827 if (/[\d\.\-e\+]/.test(numChar)) {
17828 parsedNum += numChar;
17829 } else {
17830 i--;
17831 break;
17832 }
17833 }
17834 pop(parseFloat(parsedNum), stack, metaStack);
17835 break;
17836 case '"':
17837 parsedString = '';
17838 lastCh = void 0;
17839 numConsecutiveSlashes = 0;
17840 while (true) {
17841 ch = str[i++];
17842 if (ch !== '"' || (lastCh === '\\' &&
17843 numConsecutiveSlashes % 2 === 1)) {
17844 parsedString += ch;
17845 lastCh = ch;
17846 if (lastCh === '\\') {
17847 numConsecutiveSlashes++;
17848 } else {
17849 numConsecutiveSlashes = 0;
17850 }
17851 } else {
17852 break;
17853 }
17854 }
17855 pop(JSON.parse('"' + parsedString + '"'), stack, metaStack);
17856 break;
17857 case '[':
17858 arrayElement = { element: [], index: stack.length };
17859 stack.push(arrayElement.element);
17860 metaStack.push(arrayElement);
17861 break;
17862 case '{':
17863 objElement = { element: {}, index: stack.length };
17864 stack.push(objElement.element);
17865 metaStack.push(objElement);
17866 break;
17867 default:
17868 throw new Error(
17869 'unexpectedly reached end of input: ' + collationIndex);
17870 }
17871 }
17872};
17873
17874},{}],126:[function(_dereq_,module,exports){
17875(function (global){
17876'use strict';
17877
17878function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
17879
17880var immediate = _interopDefault(_dereq_(17));
17881var uuidV4 = _interopDefault(_dereq_(120));
17882var Md5 = _interopDefault(_dereq_(80));
17883var levelup = _interopDefault(_dereq_(43));
17884var ltgt = _interopDefault(_dereq_(52));
17885var events = _dereq_(14);
17886var events__default = _interopDefault(events);
17887var Codec = _interopDefault(_dereq_(21));
17888var ReadableStreamCore = _interopDefault(_dereq_(78));
17889var inherits = _interopDefault(_dereq_(18));
17890var through2 = _dereq_(114);
17891var getArguments = _interopDefault(_dereq_(1));
17892var Deque = _interopDefault(_dereq_(11));
17893var bufferFrom = _interopDefault(_dereq_(8));
17894var vuvuzela = _interopDefault(_dereq_(125));
17895var memdown = _interopDefault(_dereq_(54));
17896
17897function isBinaryObject(object) {
17898 return (typeof ArrayBuffer !== 'undefined' && object instanceof ArrayBuffer) ||
17899 (typeof Blob !== 'undefined' && object instanceof Blob);
17900}
17901
17902function cloneArrayBuffer(buff) {
17903 if (typeof buff.slice === 'function') {
17904 return buff.slice(0);
17905 }
17906 // IE10-11 slice() polyfill
17907 var target = new ArrayBuffer(buff.byteLength);
17908 var targetArray = new Uint8Array(target);
17909 var sourceArray = new Uint8Array(buff);
17910 targetArray.set(sourceArray);
17911 return target;
17912}
17913
17914function cloneBinaryObject(object) {
17915 if (object instanceof ArrayBuffer) {
17916 return cloneArrayBuffer(object);
17917 }
17918 var size = object.size;
17919 var type = object.type;
17920 // Blob
17921 if (typeof object.slice === 'function') {
17922 return object.slice(0, size, type);
17923 }
17924 // PhantomJS slice() replacement
17925 return object.webkitSlice(0, size, type);
17926}
17927
17928// most of this is borrowed from lodash.isPlainObject:
17929// https://github.com/fis-components/lodash.isplainobject/
17930// blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js
17931
17932var funcToString = Function.prototype.toString;
17933var objectCtorString = funcToString.call(Object);
17934
17935function isPlainObject(value) {
17936 var proto = Object.getPrototypeOf(value);
17937 /* istanbul ignore if */
17938 if (proto === null) { // not sure when this happens, but I guess it can
17939 return true;
17940 }
17941 var Ctor = proto.constructor;
17942 return (typeof Ctor == 'function' &&
17943 Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
17944}
17945
17946function clone(object) {
17947 var newObject;
17948 var i;
17949 var len;
17950
17951 if (!object || typeof object !== 'object') {
17952 return object;
17953 }
17954
17955 if (Array.isArray(object)) {
17956 newObject = [];
17957 for (i = 0, len = object.length; i < len; i++) {
17958 newObject[i] = clone(object[i]);
17959 }
17960 return newObject;
17961 }
17962
17963 // special case: to avoid inconsistencies between IndexedDB
17964 // and other backends, we automatically stringify Dates
17965 if (object instanceof Date) {
17966 return object.toISOString();
17967 }
17968
17969 if (isBinaryObject(object)) {
17970 return cloneBinaryObject(object);
17971 }
17972
17973 if (!isPlainObject(object)) {
17974 return object; // don't clone objects like Workers
17975 }
17976
17977 newObject = {};
17978 for (i in object) {
17979 /* istanbul ignore else */
17980 if (Object.prototype.hasOwnProperty.call(object, i)) {
17981 var value = clone(object[i]);
17982 if (typeof value !== 'undefined') {
17983 newObject[i] = value;
17984 }
17985 }
17986 }
17987 return newObject;
17988}
17989
17990function mangle(key) {
17991 return '$' + key;
17992}
17993function unmangle(key) {
17994 return key.substring(1);
17995}
17996function Map$1() {
17997 this._store = {};
17998}
17999Map$1.prototype.get = function (key) {
18000 var mangled = mangle(key);
18001 return this._store[mangled];
18002};
18003Map$1.prototype.set = function (key, value) {
18004 var mangled = mangle(key);
18005 this._store[mangled] = value;
18006 return true;
18007};
18008Map$1.prototype.has = function (key) {
18009 var mangled = mangle(key);
18010 return mangled in this._store;
18011};
18012Map$1.prototype["delete"] = function (key) {
18013 var mangled = mangle(key);
18014 var res = mangled in this._store;
18015 delete this._store[mangled];
18016 return res;
18017};
18018Map$1.prototype.forEach = function (cb) {
18019 var keys = Object.keys(this._store);
18020 for (var i = 0, len = keys.length; i < len; i++) {
18021 var key = keys[i];
18022 var value = this._store[key];
18023 key = unmangle(key);
18024 cb(value, key);
18025 }
18026};
18027Object.defineProperty(Map$1.prototype, 'size', {
18028 get: function () {
18029 return Object.keys(this._store).length;
18030 }
18031});
18032
18033function Set$1(array) {
18034 this._store = new Map$1();
18035
18036 // init with an array
18037 if (array && Array.isArray(array)) {
18038 for (var i = 0, len = array.length; i < len; i++) {
18039 this.add(array[i]);
18040 }
18041 }
18042}
18043Set$1.prototype.add = function (key) {
18044 return this._store.set(key, true);
18045};
18046Set$1.prototype.has = function (key) {
18047 return this._store.has(key);
18048};
18049Set$1.prototype.forEach = function (cb) {
18050 this._store.forEach(function (value, key) {
18051 cb(key);
18052 });
18053};
18054Object.defineProperty(Set$1.prototype, 'size', {
18055 get: function () {
18056 return this._store.size;
18057 }
18058});
18059
18060/* global Map,Set,Symbol */
18061// Based on https://kangax.github.io/compat-table/es6/ we can sniff out
18062// incomplete Map/Set implementations which would otherwise cause our tests to fail.
18063// Notably they fail in IE11 and iOS 8.4, which this prevents.
18064function supportsMapAndSet() {
18065 if (typeof Symbol === 'undefined' || typeof Map === 'undefined' || typeof Set === 'undefined') {
18066 return false;
18067 }
18068 var prop = Object.getOwnPropertyDescriptor(Map, Symbol.species);
18069 return prop && 'get' in prop && Map[Symbol.species] === Map;
18070}
18071
18072// based on https://github.com/montagejs/collections
18073
18074var ExportedSet;
18075var ExportedMap;
18076
18077{
18078 if (supportsMapAndSet()) { // prefer built-in Map/Set
18079 ExportedSet = Set;
18080 ExportedMap = Map;
18081 } else { // fall back to our polyfill
18082 ExportedSet = Set$1;
18083 ExportedMap = Map$1;
18084 }
18085}
18086
18087// like underscore/lodash _.pick()
18088function pick(obj, arr) {
18089 var res = {};
18090 for (var i = 0, len = arr.length; i < len; i++) {
18091 var prop = arr[i];
18092 if (prop in obj) {
18093 res[prop] = obj[prop];
18094 }
18095 }
18096 return res;
18097}
18098
18099var hasLocal;
18100
18101try {
18102 localStorage.setItem('_pouch_check_localstorage', 1);
18103 hasLocal = !!localStorage.getItem('_pouch_check_localstorage');
18104} catch (e) {
18105 hasLocal = false;
18106}
18107
18108function hasLocalStorage() {
18109 return hasLocal;
18110}
18111
18112// Custom nextTick() shim for browsers. In node, this will just be process.nextTick(). We
18113
18114inherits(Changes, events.EventEmitter);
18115
18116/* istanbul ignore next */
18117function attachBrowserEvents(self) {
18118 if (hasLocalStorage()) {
18119 addEventListener("storage", function (e) {
18120 self.emit(e.key);
18121 });
18122 }
18123}
18124
18125function Changes() {
18126 events.EventEmitter.call(this);
18127 this._listeners = {};
18128
18129 attachBrowserEvents(this);
18130}
18131Changes.prototype.addListener = function (dbName, id, db, opts) {
18132 /* istanbul ignore if */
18133 if (this._listeners[id]) {
18134 return;
18135 }
18136 var self = this;
18137 var inprogress = false;
18138 function eventFunction() {
18139 /* istanbul ignore if */
18140 if (!self._listeners[id]) {
18141 return;
18142 }
18143 if (inprogress) {
18144 inprogress = 'waiting';
18145 return;
18146 }
18147 inprogress = true;
18148 var changesOpts = pick(opts, [
18149 'style', 'include_docs', 'attachments', 'conflicts', 'filter',
18150 'doc_ids', 'view', 'since', 'query_params', 'binary', 'return_docs'
18151 ]);
18152
18153 /* istanbul ignore next */
18154 function onError() {
18155 inprogress = false;
18156 }
18157
18158 db.changes(changesOpts).on('change', function (c) {
18159 if (c.seq > opts.since && !opts.cancelled) {
18160 opts.since = c.seq;
18161 opts.onChange(c);
18162 }
18163 }).on('complete', function () {
18164 if (inprogress === 'waiting') {
18165 immediate(eventFunction);
18166 }
18167 inprogress = false;
18168 }).on('error', onError);
18169 }
18170 this._listeners[id] = eventFunction;
18171 this.on(dbName, eventFunction);
18172};
18173
18174Changes.prototype.removeListener = function (dbName, id) {
18175 /* istanbul ignore if */
18176 if (!(id in this._listeners)) {
18177 return;
18178 }
18179 events.EventEmitter.prototype.removeListener.call(this, dbName,
18180 this._listeners[id]);
18181 delete this._listeners[id];
18182};
18183
18184
18185/* istanbul ignore next */
18186Changes.prototype.notifyLocalWindows = function (dbName) {
18187 //do a useless change on a storage thing
18188 //in order to get other windows's listeners to activate
18189 if (hasLocalStorage()) {
18190 localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a";
18191 }
18192};
18193
18194Changes.prototype.notify = function (dbName) {
18195 this.emit(dbName);
18196 this.notifyLocalWindows(dbName);
18197};
18198
18199function guardedConsole(method) {
18200 /* istanbul ignore else */
18201 if (typeof console !== 'undefined' && typeof console[method] === 'function') {
18202 var args = Array.prototype.slice.call(arguments, 1);
18203 console[method].apply(console, args);
18204 }
18205}
18206
18207var assign;
18208{
18209 if (typeof Object.assign === 'function') {
18210 assign = Object.assign;
18211 } else {
18212 // lite Object.assign polyfill based on
18213 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
18214 assign = function (target) {
18215 var to = Object(target);
18216
18217 for (var index = 1; index < arguments.length; index++) {
18218 var nextSource = arguments[index];
18219
18220 if (nextSource != null) { // Skip over if undefined or null
18221 for (var nextKey in nextSource) {
18222 // Avoid bugs when hasOwnProperty is shadowed
18223 if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
18224 to[nextKey] = nextSource[nextKey];
18225 }
18226 }
18227 }
18228 }
18229 return to;
18230 };
18231 }
18232}
18233
18234var $inject_Object_assign = assign;
18235
18236inherits(PouchError, Error);
18237
18238function PouchError(status, error, reason) {
18239 Error.call(this, reason);
18240 this.status = status;
18241 this.name = error;
18242 this.message = reason;
18243 this.error = true;
18244}
18245
18246PouchError.prototype.toString = function () {
18247 return JSON.stringify({
18248 status: this.status,
18249 name: this.name,
18250 message: this.message,
18251 reason: this.reason
18252 });
18253};
18254
18255var UNAUTHORIZED = new PouchError(401, 'unauthorized', "Name or password is incorrect.");
18256var MISSING_BULK_DOCS = new PouchError(400, 'bad_request', "Missing JSON list of 'docs'");
18257var MISSING_DOC = new PouchError(404, 'not_found', 'missing');
18258var REV_CONFLICT = new PouchError(409, 'conflict', 'Document update conflict');
18259var INVALID_ID = new PouchError(400, 'bad_request', '_id field must contain a string');
18260var MISSING_ID = new PouchError(412, 'missing_id', '_id is required for puts');
18261var RESERVED_ID = new PouchError(400, 'bad_request', 'Only reserved document ids may start with underscore.');
18262var NOT_OPEN = new PouchError(412, 'precondition_failed', 'Database not open');
18263var UNKNOWN_ERROR = new PouchError(500, 'unknown_error', 'Database encountered an unknown error');
18264var BAD_ARG = new PouchError(500, 'badarg', 'Some query argument is invalid');
18265var INVALID_REQUEST = new PouchError(400, 'invalid_request', 'Request was invalid');
18266var QUERY_PARSE_ERROR = new PouchError(400, 'query_parse_error', 'Some query parameter is invalid');
18267var DOC_VALIDATION = new PouchError(500, 'doc_validation', 'Bad special document member');
18268var BAD_REQUEST = new PouchError(400, 'bad_request', 'Something wrong with the request');
18269var NOT_AN_OBJECT = new PouchError(400, 'bad_request', 'Document must be a JSON object');
18270var DB_MISSING = new PouchError(404, 'not_found', 'Database not found');
18271var IDB_ERROR = new PouchError(500, 'indexed_db_went_bad', 'unknown');
18272var WSQ_ERROR = new PouchError(500, 'web_sql_went_bad', 'unknown');
18273var LDB_ERROR = new PouchError(500, 'levelDB_went_went_bad', 'unknown');
18274var FORBIDDEN = new PouchError(403, 'forbidden', 'Forbidden by design doc validate_doc_update function');
18275var INVALID_REV = new PouchError(400, 'bad_request', 'Invalid rev format');
18276var FILE_EXISTS = new PouchError(412, 'file_exists', 'The database could not be created, the file already exists.');
18277var MISSING_STUB = new PouchError(412, 'missing_stub', 'A pre-existing attachment stub wasn\'t found');
18278var INVALID_URL = new PouchError(413, 'invalid_url', 'Provided URL is invalid');
18279
18280function createError(error, reason) {
18281 function CustomPouchError(reason) {
18282 // inherit error properties from our parent error manually
18283 // so as to allow proper JSON parsing.
18284 /* jshint ignore:start */
18285 for (var p in error) {
18286 if (typeof error[p] !== 'function') {
18287 this[p] = error[p];
18288 }
18289 }
18290 /* jshint ignore:end */
18291 if (reason !== undefined) {
18292 this.reason = reason;
18293 }
18294 }
18295 CustomPouchError.prototype = PouchError.prototype;
18296 return new CustomPouchError(reason);
18297}
18298
18299function tryFilter(filter, doc, req) {
18300 try {
18301 return !filter(doc, req);
18302 } catch (err) {
18303 var msg = 'Filter function threw: ' + err.toString();
18304 return createError(BAD_REQUEST, msg);
18305 }
18306}
18307
18308function filterChange(opts) {
18309 var req = {};
18310 var hasFilter = opts.filter && typeof opts.filter === 'function';
18311 req.query = opts.query_params;
18312
18313 return function filter(change) {
18314 if (!change.doc) {
18315 // CSG sends events on the changes feed that don't have documents,
18316 // this hack makes a whole lot of existing code robust.
18317 change.doc = {};
18318 }
18319
18320 var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req);
18321
18322 if (typeof filterReturn === 'object') {
18323 return filterReturn;
18324 }
18325
18326 if (filterReturn) {
18327 return false;
18328 }
18329
18330 if (!opts.include_docs) {
18331 delete change.doc;
18332 } else if (!opts.attachments) {
18333 for (var att in change.doc._attachments) {
18334 /* istanbul ignore else */
18335 if (change.doc._attachments.hasOwnProperty(att)) {
18336 change.doc._attachments[att].stub = true;
18337 }
18338 }
18339 }
18340 return true;
18341 };
18342}
18343
18344// shim for Function.prototype.name,
18345// for browsers that don't support it like IE
18346
18347/* istanbul ignore next */
18348function f() {}
18349
18350var hasName = f.name;
18351var res;
18352
18353// We dont run coverage in IE
18354/* istanbul ignore else */
18355if (hasName) {
18356 res = function (fun) {
18357 return fun.name;
18358 };
18359} else {
18360 res = function (fun) {
18361 var match = fun.toString().match(/^\s*function\s*(?:(\S+)\s*)?\(/);
18362 if (match && match[1]) {
18363 return match[1];
18364 }
18365 else {
18366 return '';
18367 }
18368 };
18369}
18370
18371var functionName = res;
18372
18373// Determine id an ID is valid
18374// - invalid IDs begin with an underescore that does not begin '_design' or
18375// '_local'
18376// - any other string value is a valid id
18377// Returns the specific error object for each case
18378function invalidIdError(id) {
18379 var err;
18380 if (!id) {
18381 err = createError(MISSING_ID);
18382 } else if (typeof id !== 'string') {
18383 err = createError(INVALID_ID);
18384 } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {
18385 err = createError(RESERVED_ID);
18386 }
18387 if (err) {
18388 throw err;
18389 }
18390}
18391
18392// Checks if a PouchDB object is "remote" or not. This is
18393
18394// originally parseUri 1.2.2, now patched by us
18395
18396// Based on https://github.com/alexdavid/scope-eval v0.0.3
18397
18398var thisAtob = function (str) {
18399 return atob(str);
18400};
18401
18402var thisBtoa = function (str) {
18403 return btoa(str);
18404};
18405
18406// Abstracts constructing a Blob object, so it also works in older
18407// browsers that don't support the native Blob constructor (e.g.
18408// old QtWebKit versions, Android < 4.4).
18409function createBlob(parts, properties) {
18410 /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
18411 parts = parts || [];
18412 properties = properties || {};
18413 try {
18414 return new Blob(parts, properties);
18415 } catch (e) {
18416 if (e.name !== "TypeError") {
18417 throw e;
18418 }
18419 var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
18420 typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
18421 typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
18422 WebKitBlobBuilder;
18423 var builder = new Builder();
18424 for (var i = 0; i < parts.length; i += 1) {
18425 builder.append(parts[i]);
18426 }
18427 return builder.getBlob(properties.type);
18428 }
18429}
18430
18431// From http://stackoverflow.com/questions/14967647/ (continues on next line)
18432// encode-decode-image-with-base64-breaks-image (2013-04-21)
18433function binaryStringToArrayBuffer(bin) {
18434 var length = bin.length;
18435 var buf = new ArrayBuffer(length);
18436 var arr = new Uint8Array(buf);
18437 for (var i = 0; i < length; i++) {
18438 arr[i] = bin.charCodeAt(i);
18439 }
18440 return buf;
18441}
18442
18443function binStringToBluffer(binString, type) {
18444 return createBlob([binaryStringToArrayBuffer(binString)], {type: type});
18445}
18446
18447//Can't find original post, but this is close
18448//http://stackoverflow.com/questions/6965107/ (continues on next line)
18449//converting-between-strings-and-arraybuffers
18450function arrayBufferToBinaryString(buffer) {
18451 var binary = '';
18452 var bytes = new Uint8Array(buffer);
18453 var length = bytes.byteLength;
18454 for (var i = 0; i < length; i++) {
18455 binary += String.fromCharCode(bytes[i]);
18456 }
18457 return binary;
18458}
18459
18460// shim for browsers that don't support it
18461function readAsBinaryString(blob, callback) {
18462 var reader = new FileReader();
18463 var hasBinaryString = typeof reader.readAsBinaryString === 'function';
18464 reader.onloadend = function (e) {
18465 var result = e.target.result || '';
18466 if (hasBinaryString) {
18467 return callback(result);
18468 }
18469 callback(arrayBufferToBinaryString(result));
18470 };
18471 if (hasBinaryString) {
18472 reader.readAsBinaryString(blob);
18473 } else {
18474 reader.readAsArrayBuffer(blob);
18475 }
18476}
18477
18478// simplified API. universal browser support is assumed
18479function readAsArrayBuffer(blob, callback) {
18480 var reader = new FileReader();
18481 reader.onloadend = function (e) {
18482 var result = e.target.result || new ArrayBuffer(0);
18483 callback(result);
18484 };
18485 reader.readAsArrayBuffer(blob);
18486}
18487
18488// this is not used in the browser
18489
18490var setImmediateShim = global.setImmediate || global.setTimeout;
18491var MD5_CHUNK_SIZE = 32768;
18492
18493function rawToBase64(raw) {
18494 return thisBtoa(raw);
18495}
18496
18497function sliceBlob(blob, start, end) {
18498 if (blob.webkitSlice) {
18499 return blob.webkitSlice(start, end);
18500 }
18501 return blob.slice(start, end);
18502}
18503
18504function appendBlob(buffer, blob, start, end, callback) {
18505 if (start > 0 || end < blob.size) {
18506 // only slice blob if we really need to
18507 blob = sliceBlob(blob, start, end);
18508 }
18509 readAsArrayBuffer(blob, function (arrayBuffer) {
18510 buffer.append(arrayBuffer);
18511 callback();
18512 });
18513}
18514
18515function appendString(buffer, string, start, end, callback) {
18516 if (start > 0 || end < string.length) {
18517 // only create a substring if we really need to
18518 string = string.substring(start, end);
18519 }
18520 buffer.appendBinary(string);
18521 callback();
18522}
18523
18524function binaryMd5(data, callback) {
18525 var inputIsString = typeof data === 'string';
18526 var len = inputIsString ? data.length : data.size;
18527 var chunkSize = Math.min(MD5_CHUNK_SIZE, len);
18528 var chunks = Math.ceil(len / chunkSize);
18529 var currentChunk = 0;
18530 var buffer = inputIsString ? new Md5() : new Md5.ArrayBuffer();
18531
18532 var append = inputIsString ? appendString : appendBlob;
18533
18534 function next() {
18535 setImmediateShim(loadNextChunk);
18536 }
18537
18538 function done() {
18539 var raw = buffer.end(true);
18540 var base64 = rawToBase64(raw);
18541 callback(base64);
18542 buffer.destroy();
18543 }
18544
18545 function loadNextChunk() {
18546 var start = currentChunk * chunkSize;
18547 var end = start + chunkSize;
18548 currentChunk++;
18549 if (currentChunk < chunks) {
18550 append(buffer, data, start, end, next);
18551 } else {
18552 append(buffer, data, start, end, done);
18553 }
18554 }
18555 loadNextChunk();
18556}
18557
18558function stringMd5(string) {
18559 return Md5.hash(string);
18560}
18561
18562function rev(doc, deterministic_revs) {
18563 var clonedDoc = clone(doc);
18564 if (!deterministic_revs) {
18565 return uuidV4.v4().replace(/-/g, '').toLowerCase();
18566 }
18567
18568 delete clonedDoc._rev_tree;
18569 return stringMd5(JSON.stringify(clonedDoc));
18570}
18571
18572var uuid = uuidV4.v4;
18573
18574function isFunction(f) {
18575 return 'function' === typeof f;
18576}
18577
18578function getPrefix(db) {
18579 if (isFunction(db.prefix)) {
18580 return db.prefix();
18581 }
18582 return db;
18583}
18584
18585function clone$1(_obj) {
18586 var obj = {};
18587 for (var k in _obj) {
18588 obj[k] = _obj[k];
18589 }
18590 return obj;
18591}
18592
18593function nut(db, precodec, codec) {
18594 function encodePrefix(prefix, key, opts1, opts2) {
18595 return precodec.encode([ prefix, codec.encodeKey(key, opts1, opts2 ) ]);
18596 }
18597
18598 function addEncodings(op, prefix) {
18599 if (prefix && prefix.options) {
18600 op.keyEncoding =
18601 op.keyEncoding || prefix.options.keyEncoding;
18602 op.valueEncoding =
18603 op.valueEncoding || prefix.options.valueEncoding;
18604 }
18605 return op;
18606 }
18607
18608 db.open(function () { /* no-op */});
18609
18610 return {
18611 apply: function (ops, opts, cb) {
18612 opts = opts || {};
18613
18614 var batch = [];
18615 var i = -1;
18616 var len = ops.length;
18617
18618 while (++i < len) {
18619 var op = ops[i];
18620 addEncodings(op, op.prefix);
18621 op.prefix = getPrefix(op.prefix);
18622 batch.push({
18623 key: encodePrefix(op.prefix, op.key, opts, op),
18624 value: op.type !== 'del' && codec.encodeValue(op.value, opts, op),
18625 type: op.type
18626 });
18627 }
18628 db.db.batch(batch, opts, cb);
18629 },
18630 get: function (key, prefix, opts, cb) {
18631 opts.asBuffer = codec.valueAsBuffer(opts);
18632 return db.db.get(
18633 encodePrefix(prefix, key, opts),
18634 opts,
18635 function (err, value) {
18636 if (err) {
18637 cb(err);
18638 } else {
18639 cb(null, codec.decodeValue(value, opts));
18640 }
18641 }
18642 );
18643 },
18644 createDecoder: function (opts) {
18645 return function (key, value) {
18646 return {
18647 key: codec.decodeKey(precodec.decode(key)[1], opts),
18648 value: codec.decodeValue(value, opts)
18649 };
18650 };
18651 },
18652 isClosed: function isClosed() {
18653 return db.isClosed();
18654 },
18655 close: function close(cb) {
18656 return db.close(cb);
18657 },
18658 iterator: function (_opts) {
18659 var opts = clone$1(_opts || {});
18660 var prefix = _opts.prefix || [];
18661
18662 function encodeKey(key) {
18663 return encodePrefix(prefix, key, opts, {});
18664 }
18665
18666 ltgt.toLtgt(_opts, opts, encodeKey, precodec.lowerBound, precodec.upperBound);
18667
18668 // if these legacy values are in the options, remove them
18669
18670 opts.prefix = null;
18671
18672 //************************************************
18673 //hard coded defaults, for now...
18674 //TODO: pull defaults and encoding out of levelup.
18675 opts.keyAsBuffer = opts.valueAsBuffer = false;
18676 //************************************************
18677
18678
18679 //this is vital, otherwise limit: undefined will
18680 //create an empty stream.
18681 /* istanbul ignore next */
18682 if ('number' !== typeof opts.limit) {
18683 opts.limit = -1;
18684 }
18685
18686 opts.keyAsBuffer = precodec.buffer;
18687 opts.valueAsBuffer = codec.valueAsBuffer(opts);
18688
18689 function wrapIterator(iterator) {
18690 return {
18691 next: function (cb) {
18692 return iterator.next(cb);
18693 },
18694 end: function (cb) {
18695 iterator.end(cb);
18696 }
18697 };
18698 }
18699
18700 return wrapIterator(db.db.iterator(opts));
18701 }
18702 };
18703}
18704
18705function NotFoundError() {
18706 Error.call(this);
18707}
18708
18709inherits(NotFoundError, Error);
18710
18711NotFoundError.prototype.name = 'NotFoundError';
18712
18713var EventEmitter = events__default.EventEmitter;
18714var version = "6.5.4";
18715
18716var NOT_FOUND_ERROR = new NotFoundError();
18717
18718var sublevel = function (nut, prefix, createStream, options) {
18719 var emitter = new EventEmitter();
18720 emitter.sublevels = {};
18721 emitter.options = options;
18722
18723 emitter.version = version;
18724
18725 emitter.methods = {};
18726 prefix = prefix || [];
18727
18728 function mergeOpts(opts) {
18729 var o = {};
18730 var k;
18731 if (options) {
18732 for (k in options) {
18733 if (typeof options[k] !== 'undefined') {
18734 o[k] = options[k];
18735 }
18736 }
18737 }
18738 if (opts) {
18739 for (k in opts) {
18740 if (typeof opts[k] !== 'undefined') {
18741 o[k] = opts[k];
18742 }
18743 }
18744 }
18745 return o;
18746 }
18747
18748 emitter.put = function (key, value, opts, cb) {
18749 if ('function' === typeof opts) {
18750 cb = opts;
18751 opts = {};
18752 }
18753
18754 nut.apply([{
18755 key: key, value: value,
18756 prefix: prefix.slice(), type: 'put'
18757 }], mergeOpts(opts), function (err) {
18758 /* istanbul ignore next */
18759 if (err) {
18760 return cb(err);
18761 }
18762 emitter.emit('put', key, value);
18763 cb(null);
18764 });
18765 };
18766
18767 emitter.prefix = function () {
18768 return prefix.slice();
18769 };
18770
18771 emitter.batch = function (ops, opts, cb) {
18772 if ('function' === typeof opts) {
18773 cb = opts;
18774 opts = {};
18775 }
18776
18777 ops = ops.map(function (op) {
18778 return {
18779 key: op.key,
18780 value: op.value,
18781 prefix: op.prefix || prefix,
18782 keyEncoding: op.keyEncoding, // *
18783 valueEncoding: op.valueEncoding, // * (TODO: encodings on sublevel)
18784 type: op.type
18785 };
18786 });
18787
18788 nut.apply(ops, mergeOpts(opts), function (err) {
18789 /* istanbul ignore next */
18790 if (err) {
18791 return cb(err);
18792 }
18793 emitter.emit('batch', ops);
18794 cb(null);
18795 });
18796 };
18797
18798 emitter.get = function (key, opts, cb) {
18799 /* istanbul ignore else */
18800 if ('function' === typeof opts) {
18801 cb = opts;
18802 opts = {};
18803 }
18804 nut.get(key, prefix, mergeOpts(opts), function (err, value) {
18805 if (err) {
18806 cb(NOT_FOUND_ERROR);
18807 } else {
18808 cb(null, value);
18809 }
18810 });
18811 };
18812
18813 emitter.sublevel = function (name, opts) {
18814 return emitter.sublevels[name] =
18815 emitter.sublevels[name] || sublevel(nut, prefix.concat(name), createStream, mergeOpts(opts));
18816 };
18817
18818 emitter.readStream = emitter.createReadStream = function (opts) {
18819 opts = mergeOpts(opts);
18820 opts.prefix = prefix;
18821 var stream;
18822 var it = nut.iterator(opts);
18823
18824 stream = createStream(opts, nut.createDecoder(opts));
18825 stream.setIterator(it);
18826
18827 return stream;
18828 };
18829
18830 emitter.close = function (cb) {
18831 nut.close(cb);
18832 };
18833
18834 emitter.isOpen = nut.isOpen;
18835 emitter.isClosed = nut.isClosed;
18836
18837 return emitter;
18838};
18839
18840/* Copyright (c) 2012-2014 LevelUP contributors
18841 * See list at <https://github.com/rvagg/node-levelup#contributing>
18842 * MIT License <https://github.com/rvagg/node-levelup/blob/master/LICENSE.md>
18843 */
18844
18845var Readable = ReadableStreamCore.Readable;
18846
18847function ReadStream(options, makeData) {
18848 if (!(this instanceof ReadStream)) {
18849 return new ReadStream(options, makeData);
18850 }
18851
18852 Readable.call(this, { objectMode: true, highWaterMark: options.highWaterMark });
18853
18854 // purely to keep `db` around until we're done so it's not GCed if the user doesn't keep a ref
18855
18856 this._waiting = false;
18857 this._options = options;
18858 this._makeData = makeData;
18859}
18860
18861inherits(ReadStream, Readable);
18862
18863ReadStream.prototype.setIterator = function (it) {
18864 this._iterator = it;
18865 /* istanbul ignore if */
18866 if (this._destroyed) {
18867 return it.end(function () {});
18868 }
18869 /* istanbul ignore if */
18870 if (this._waiting) {
18871 this._waiting = false;
18872 return this._read();
18873 }
18874 return this;
18875};
18876
18877ReadStream.prototype._read = function read() {
18878 var self = this;
18879 /* istanbul ignore if */
18880 if (self._destroyed) {
18881 return;
18882 }
18883 /* istanbul ignore if */
18884 if (!self._iterator) {
18885 return this._waiting = true;
18886 }
18887
18888 self._iterator.next(function (err, key, value) {
18889 if (err || (key === undefined && value === undefined)) {
18890 if (!err && !self._destroyed) {
18891 self.push(null);
18892 }
18893 return self._cleanup(err);
18894 }
18895
18896
18897 value = self._makeData(key, value);
18898 if (!self._destroyed) {
18899 self.push(value);
18900 }
18901 });
18902};
18903
18904ReadStream.prototype._cleanup = function (err) {
18905 if (this._destroyed) {
18906 return;
18907 }
18908
18909 this._destroyed = true;
18910
18911 var self = this;
18912 /* istanbul ignore if */
18913 if (err && err.message !== 'iterator has ended') {
18914 self.emit('error', err);
18915 }
18916
18917 /* istanbul ignore else */
18918 if (self._iterator) {
18919 self._iterator.end(function () {
18920 self._iterator = null;
18921 self.emit('close');
18922 });
18923 } else {
18924 self.emit('close');
18925 }
18926};
18927
18928ReadStream.prototype.destroy = function () {
18929 this._cleanup();
18930};
18931
18932var precodec = {
18933 encode: function (decodedKey) {
18934 return '\xff' + decodedKey[0] + '\xff' + decodedKey[1];
18935 },
18936 decode: function (encodedKeyAsBuffer) {
18937 var str = encodedKeyAsBuffer.toString();
18938 var idx = str.indexOf('\xff', 1);
18939 return [str.substring(1, idx), str.substring(idx + 1)];
18940 },
18941 lowerBound: '\x00',
18942 upperBound: '\xff'
18943};
18944
18945var codec = new Codec();
18946
18947function sublevelPouch(db) {
18948 return sublevel(nut(db, precodec, codec), [], ReadStream, db.options);
18949}
18950
18951function allDocsKeysQuery(api, opts) {
18952 var keys = opts.keys;
18953 var finalResults = {
18954 offset: opts.skip
18955 };
18956 return Promise.all(keys.map(function (key) {
18957 var subOpts = $inject_Object_assign({key: key, deleted: 'ok'}, opts);
18958 ['limit', 'skip', 'keys'].forEach(function (optKey) {
18959 delete subOpts[optKey];
18960 });
18961 return new Promise(function (resolve, reject) {
18962 api._allDocs(subOpts, function (err, res) {
18963 /* istanbul ignore if */
18964 if (err) {
18965 return reject(err);
18966 }
18967 /* istanbul ignore if */
18968 if (opts.update_seq && res.update_seq !== undefined) {
18969 finalResults.update_seq = res.update_seq;
18970 }
18971 finalResults.total_rows = res.total_rows;
18972 resolve(res.rows[0] || {key: key, error: 'not_found'});
18973 });
18974 });
18975 })).then(function (results) {
18976 finalResults.rows = results;
18977 return finalResults;
18978 });
18979}
18980
18981function toObject(array) {
18982 return array.reduce(function (obj, item) {
18983 obj[item] = true;
18984 return obj;
18985 }, {});
18986}
18987// List of top level reserved words for doc
18988var reservedWords = toObject([
18989 '_id',
18990 '_rev',
18991 '_attachments',
18992 '_deleted',
18993 '_revisions',
18994 '_revs_info',
18995 '_conflicts',
18996 '_deleted_conflicts',
18997 '_local_seq',
18998 '_rev_tree',
18999 //replication documents
19000 '_replication_id',
19001 '_replication_state',
19002 '_replication_state_time',
19003 '_replication_state_reason',
19004 '_replication_stats',
19005 // Specific to Couchbase Sync Gateway
19006 '_removed'
19007]);
19008
19009// List of reserved words that should end up the document
19010var dataWords = toObject([
19011 '_attachments',
19012 //replication documents
19013 '_replication_id',
19014 '_replication_state',
19015 '_replication_state_time',
19016 '_replication_state_reason',
19017 '_replication_stats'
19018]);
19019
19020function parseRevisionInfo(rev$$1) {
19021 if (!/^\d+-/.test(rev$$1)) {
19022 return createError(INVALID_REV);
19023 }
19024 var idx = rev$$1.indexOf('-');
19025 var left = rev$$1.substring(0, idx);
19026 var right = rev$$1.substring(idx + 1);
19027 return {
19028 prefix: parseInt(left, 10),
19029 id: right
19030 };
19031}
19032
19033function makeRevTreeFromRevisions(revisions, opts) {
19034 var pos = revisions.start - revisions.ids.length + 1;
19035
19036 var revisionIds = revisions.ids;
19037 var ids = [revisionIds[0], opts, []];
19038
19039 for (var i = 1, len = revisionIds.length; i < len; i++) {
19040 ids = [revisionIds[i], {status: 'missing'}, [ids]];
19041 }
19042
19043 return [{
19044 pos: pos,
19045 ids: ids
19046 }];
19047}
19048
19049// Preprocess documents, parse their revisions, assign an id and a
19050// revision for new writes that are missing them, etc
19051function parseDoc(doc, newEdits, dbOpts) {
19052 if (!dbOpts) {
19053 dbOpts = {
19054 deterministic_revs: true
19055 };
19056 }
19057
19058 var nRevNum;
19059 var newRevId;
19060 var revInfo;
19061 var opts = {status: 'available'};
19062 if (doc._deleted) {
19063 opts.deleted = true;
19064 }
19065
19066 if (newEdits) {
19067 if (!doc._id) {
19068 doc._id = uuid();
19069 }
19070 newRevId = rev(doc, dbOpts.deterministic_revs);
19071 if (doc._rev) {
19072 revInfo = parseRevisionInfo(doc._rev);
19073 if (revInfo.error) {
19074 return revInfo;
19075 }
19076 doc._rev_tree = [{
19077 pos: revInfo.prefix,
19078 ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]]
19079 }];
19080 nRevNum = revInfo.prefix + 1;
19081 } else {
19082 doc._rev_tree = [{
19083 pos: 1,
19084 ids : [newRevId, opts, []]
19085 }];
19086 nRevNum = 1;
19087 }
19088 } else {
19089 if (doc._revisions) {
19090 doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts);
19091 nRevNum = doc._revisions.start;
19092 newRevId = doc._revisions.ids[0];
19093 }
19094 if (!doc._rev_tree) {
19095 revInfo = parseRevisionInfo(doc._rev);
19096 if (revInfo.error) {
19097 return revInfo;
19098 }
19099 nRevNum = revInfo.prefix;
19100 newRevId = revInfo.id;
19101 doc._rev_tree = [{
19102 pos: nRevNum,
19103 ids: [newRevId, opts, []]
19104 }];
19105 }
19106 }
19107
19108 invalidIdError(doc._id);
19109
19110 doc._rev = nRevNum + '-' + newRevId;
19111
19112 var result = {metadata : {}, data : {}};
19113 for (var key in doc) {
19114 /* istanbul ignore else */
19115 if (Object.prototype.hasOwnProperty.call(doc, key)) {
19116 var specialKey = key[0] === '_';
19117 if (specialKey && !reservedWords[key]) {
19118 var error = createError(DOC_VALIDATION, key);
19119 error.message = DOC_VALIDATION.message + ': ' + key;
19120 throw error;
19121 } else if (specialKey && !dataWords[key]) {
19122 result.metadata[key.slice(1)] = doc[key];
19123 } else {
19124 result.data[key] = doc[key];
19125 }
19126 }
19127 }
19128 return result;
19129}
19130
19131// We fetch all leafs of the revision tree, and sort them based on tree length
19132// and whether they were deleted, undeleted documents with the longest revision
19133// tree (most edits) win
19134// The final sort algorithm is slightly documented in a sidebar here:
19135// http://guide.couchdb.org/draft/conflicts.html
19136function winningRev(metadata) {
19137 var winningId;
19138 var winningPos;
19139 var winningDeleted;
19140 var toVisit = metadata.rev_tree.slice();
19141 var node;
19142 while ((node = toVisit.pop())) {
19143 var tree = node.ids;
19144 var branches = tree[2];
19145 var pos = node.pos;
19146 if (branches.length) { // non-leaf
19147 for (var i = 0, len = branches.length; i < len; i++) {
19148 toVisit.push({pos: pos + 1, ids: branches[i]});
19149 }
19150 continue;
19151 }
19152 var deleted = !!tree[1].deleted;
19153 var id = tree[0];
19154 // sort by deleted, then pos, then id
19155 if (!winningId || (winningDeleted !== deleted ? winningDeleted :
19156 winningPos !== pos ? winningPos < pos : winningId < id)) {
19157 winningId = id;
19158 winningPos = pos;
19159 winningDeleted = deleted;
19160 }
19161 }
19162
19163 return winningPos + '-' + winningId;
19164}
19165
19166// Pretty much all below can be combined into a higher order function to
19167// traverse revisions
19168// The return value from the callback will be passed as context to all
19169// children of that node
19170function traverseRevTree(revs, callback) {
19171 var toVisit = revs.slice();
19172
19173 var node;
19174 while ((node = toVisit.pop())) {
19175 var pos = node.pos;
19176 var tree = node.ids;
19177 var branches = tree[2];
19178 var newCtx =
19179 callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]);
19180 for (var i = 0, len = branches.length; i < len; i++) {
19181 toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx});
19182 }
19183 }
19184}
19185
19186function sortByPos(a, b) {
19187 return a.pos - b.pos;
19188}
19189
19190function collectLeaves(revs) {
19191 var leaves = [];
19192 traverseRevTree(revs, function (isLeaf, pos, id, acc, opts) {
19193 if (isLeaf) {
19194 leaves.push({rev: pos + "-" + id, pos: pos, opts: opts});
19195 }
19196 });
19197 leaves.sort(sortByPos).reverse();
19198 for (var i = 0, len = leaves.length; i < len; i++) {
19199 delete leaves[i].pos;
19200 }
19201 return leaves;
19202}
19203
19204// returns revs of all conflicts that is leaves such that
19205// 1. are not deleted and
19206// 2. are different than winning revision
19207function collectConflicts(metadata) {
19208 var win = winningRev(metadata);
19209 var leaves = collectLeaves(metadata.rev_tree);
19210 var conflicts = [];
19211 for (var i = 0, len = leaves.length; i < len; i++) {
19212 var leaf = leaves[i];
19213 if (leaf.rev !== win && !leaf.opts.deleted) {
19214 conflicts.push(leaf.rev);
19215 }
19216 }
19217 return conflicts;
19218}
19219
19220// compact a tree by marking its non-leafs as missing,
19221// and return a list of revs to delete
19222function compactTree(metadata) {
19223 var revs = [];
19224 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
19225 revHash, ctx, opts) {
19226 if (opts.status === 'available' && !isLeaf) {
19227 revs.push(pos + '-' + revHash);
19228 opts.status = 'missing';
19229 }
19230 });
19231 return revs;
19232}
19233
19234// build up a list of all the paths to the leafs in this revision tree
19235function rootToLeaf(revs) {
19236 var paths = [];
19237 var toVisit = revs.slice();
19238 var node;
19239 while ((node = toVisit.pop())) {
19240 var pos = node.pos;
19241 var tree = node.ids;
19242 var id = tree[0];
19243 var opts = tree[1];
19244 var branches = tree[2];
19245 var isLeaf = branches.length === 0;
19246
19247 var history = node.history ? node.history.slice() : [];
19248 history.push({id: id, opts: opts});
19249 if (isLeaf) {
19250 paths.push({pos: (pos + 1 - history.length), ids: history});
19251 }
19252 for (var i = 0, len = branches.length; i < len; i++) {
19253 toVisit.push({pos: pos + 1, ids: branches[i], history: history});
19254 }
19255 }
19256 return paths.reverse();
19257}
19258
19259// for a better overview of what this is doing, read:
19260
19261function sortByPos$1(a, b) {
19262 return a.pos - b.pos;
19263}
19264
19265// classic binary search
19266function binarySearch(arr, item, comparator) {
19267 var low = 0;
19268 var high = arr.length;
19269 var mid;
19270 while (low < high) {
19271 mid = (low + high) >>> 1;
19272 if (comparator(arr[mid], item) < 0) {
19273 low = mid + 1;
19274 } else {
19275 high = mid;
19276 }
19277 }
19278 return low;
19279}
19280
19281// assuming the arr is sorted, insert the item in the proper place
19282function insertSorted(arr, item, comparator) {
19283 var idx = binarySearch(arr, item, comparator);
19284 arr.splice(idx, 0, item);
19285}
19286
19287// Turn a path as a flat array into a tree with a single branch.
19288// If any should be stemmed from the beginning of the array, that's passed
19289// in as the second argument
19290function pathToTree(path, numStemmed) {
19291 var root;
19292 var leaf;
19293 for (var i = numStemmed, len = path.length; i < len; i++) {
19294 var node = path[i];
19295 var currentLeaf = [node.id, node.opts, []];
19296 if (leaf) {
19297 leaf[2].push(currentLeaf);
19298 leaf = currentLeaf;
19299 } else {
19300 root = leaf = currentLeaf;
19301 }
19302 }
19303 return root;
19304}
19305
19306// compare the IDs of two trees
19307function compareTree(a, b) {
19308 return a[0] < b[0] ? -1 : 1;
19309}
19310
19311// Merge two trees together
19312// The roots of tree1 and tree2 must be the same revision
19313function mergeTree(in_tree1, in_tree2) {
19314 var queue = [{tree1: in_tree1, tree2: in_tree2}];
19315 var conflicts = false;
19316 while (queue.length > 0) {
19317 var item = queue.pop();
19318 var tree1 = item.tree1;
19319 var tree2 = item.tree2;
19320
19321 if (tree1[1].status || tree2[1].status) {
19322 tree1[1].status =
19323 (tree1[1].status === 'available' ||
19324 tree2[1].status === 'available') ? 'available' : 'missing';
19325 }
19326
19327 for (var i = 0; i < tree2[2].length; i++) {
19328 if (!tree1[2][0]) {
19329 conflicts = 'new_leaf';
19330 tree1[2][0] = tree2[2][i];
19331 continue;
19332 }
19333
19334 var merged = false;
19335 for (var j = 0; j < tree1[2].length; j++) {
19336 if (tree1[2][j][0] === tree2[2][i][0]) {
19337 queue.push({tree1: tree1[2][j], tree2: tree2[2][i]});
19338 merged = true;
19339 }
19340 }
19341 if (!merged) {
19342 conflicts = 'new_branch';
19343 insertSorted(tree1[2], tree2[2][i], compareTree);
19344 }
19345 }
19346 }
19347 return {conflicts: conflicts, tree: in_tree1};
19348}
19349
19350function doMerge(tree, path, dontExpand) {
19351 var restree = [];
19352 var conflicts = false;
19353 var merged = false;
19354 var res;
19355
19356 if (!tree.length) {
19357 return {tree: [path], conflicts: 'new_leaf'};
19358 }
19359
19360 for (var i = 0, len = tree.length; i < len; i++) {
19361 var branch = tree[i];
19362 if (branch.pos === path.pos && branch.ids[0] === path.ids[0]) {
19363 // Paths start at the same position and have the same root, so they need
19364 // merged
19365 res = mergeTree(branch.ids, path.ids);
19366 restree.push({pos: branch.pos, ids: res.tree});
19367 conflicts = conflicts || res.conflicts;
19368 merged = true;
19369 } else if (dontExpand !== true) {
19370 // The paths start at a different position, take the earliest path and
19371 // traverse up until it as at the same point from root as the path we
19372 // want to merge. If the keys match we return the longer path with the
19373 // other merged After stemming we dont want to expand the trees
19374
19375 var t1 = branch.pos < path.pos ? branch : path;
19376 var t2 = branch.pos < path.pos ? path : branch;
19377 var diff = t2.pos - t1.pos;
19378
19379 var candidateParents = [];
19380
19381 var trees = [];
19382 trees.push({ids: t1.ids, diff: diff, parent: null, parentIdx: null});
19383 while (trees.length > 0) {
19384 var item = trees.pop();
19385 if (item.diff === 0) {
19386 if (item.ids[0] === t2.ids[0]) {
19387 candidateParents.push(item);
19388 }
19389 continue;
19390 }
19391 var elements = item.ids[2];
19392 for (var j = 0, elementsLen = elements.length; j < elementsLen; j++) {
19393 trees.push({
19394 ids: elements[j],
19395 diff: item.diff - 1,
19396 parent: item.ids,
19397 parentIdx: j
19398 });
19399 }
19400 }
19401
19402 var el = candidateParents[0];
19403
19404 if (!el) {
19405 restree.push(branch);
19406 } else {
19407 res = mergeTree(el.ids, t2.ids);
19408 el.parent[2][el.parentIdx] = res.tree;
19409 restree.push({pos: t1.pos, ids: t1.ids});
19410 conflicts = conflicts || res.conflicts;
19411 merged = true;
19412 }
19413 } else {
19414 restree.push(branch);
19415 }
19416 }
19417
19418 // We didnt find
19419 if (!merged) {
19420 restree.push(path);
19421 }
19422
19423 restree.sort(sortByPos$1);
19424
19425 return {
19426 tree: restree,
19427 conflicts: conflicts || 'internal_node'
19428 };
19429}
19430
19431// To ensure we dont grow the revision tree infinitely, we stem old revisions
19432function stem(tree, depth) {
19433 // First we break out the tree into a complete list of root to leaf paths
19434 var paths = rootToLeaf(tree);
19435 var stemmedRevs;
19436
19437 var result;
19438 for (var i = 0, len = paths.length; i < len; i++) {
19439 // Then for each path, we cut off the start of the path based on the
19440 // `depth` to stem to, and generate a new set of flat trees
19441 var path = paths[i];
19442 var stemmed = path.ids;
19443 var node;
19444 if (stemmed.length > depth) {
19445 // only do the stemming work if we actually need to stem
19446 if (!stemmedRevs) {
19447 stemmedRevs = {}; // avoid allocating this object unnecessarily
19448 }
19449 var numStemmed = stemmed.length - depth;
19450 node = {
19451 pos: path.pos + numStemmed,
19452 ids: pathToTree(stemmed, numStemmed)
19453 };
19454
19455 for (var s = 0; s < numStemmed; s++) {
19456 var rev = (path.pos + s) + '-' + stemmed[s].id;
19457 stemmedRevs[rev] = true;
19458 }
19459 } else { // no need to actually stem
19460 node = {
19461 pos: path.pos,
19462 ids: pathToTree(stemmed, 0)
19463 };
19464 }
19465
19466 // Then we remerge all those flat trees together, ensuring that we dont
19467 // connect trees that would go beyond the depth limit
19468 if (result) {
19469 result = doMerge(result, node, true).tree;
19470 } else {
19471 result = [node];
19472 }
19473 }
19474
19475 // this is memory-heavy per Chrome profiler, avoid unless we actually stemmed
19476 if (stemmedRevs) {
19477 traverseRevTree(result, function (isLeaf, pos, revHash) {
19478 // some revisions may have been removed in a branch but not in another
19479 delete stemmedRevs[pos + '-' + revHash];
19480 });
19481 }
19482
19483 return {
19484 tree: result,
19485 revs: stemmedRevs ? Object.keys(stemmedRevs) : []
19486 };
19487}
19488
19489function merge(tree, path, depth) {
19490 var newTree = doMerge(tree, path);
19491 var stemmed = stem(newTree.tree, depth);
19492 return {
19493 tree: stemmed.tree,
19494 stemmedRevs: stemmed.revs,
19495 conflicts: newTree.conflicts
19496 };
19497}
19498
19499// return true if a rev exists in the rev tree, false otherwise
19500function revExists(revs, rev) {
19501 var toVisit = revs.slice();
19502 var splitRev = rev.split('-');
19503 var targetPos = parseInt(splitRev[0], 10);
19504 var targetId = splitRev[1];
19505
19506 var node;
19507 while ((node = toVisit.pop())) {
19508 if (node.pos === targetPos && node.ids[0] === targetId) {
19509 return true;
19510 }
19511 var branches = node.ids[2];
19512 for (var i = 0, len = branches.length; i < len; i++) {
19513 toVisit.push({pos: node.pos + 1, ids: branches[i]});
19514 }
19515 }
19516 return false;
19517}
19518
19519function getTrees(node) {
19520 return node.ids;
19521}
19522
19523// check if a specific revision of a doc has been deleted
19524// - metadata: the metadata object from the doc store
19525// - rev: (optional) the revision to check. defaults to winning revision
19526function isDeleted(metadata, rev) {
19527 if (!rev) {
19528 rev = winningRev(metadata);
19529 }
19530 var id = rev.substring(rev.indexOf('-') + 1);
19531 var toVisit = metadata.rev_tree.map(getTrees);
19532
19533 var tree;
19534 while ((tree = toVisit.pop())) {
19535 if (tree[0] === id) {
19536 return !!tree[1].deleted;
19537 }
19538 toVisit = toVisit.concat(tree[2]);
19539 }
19540}
19541
19542function isLocalId(id) {
19543 return (/^_local/).test(id);
19544}
19545
19546// returns the current leaf node for a given revision
19547function latest(rev, metadata) {
19548 var toVisit = metadata.rev_tree.slice();
19549 var node;
19550 while ((node = toVisit.pop())) {
19551 var pos = node.pos;
19552 var tree = node.ids;
19553 var id = tree[0];
19554 var opts = tree[1];
19555 var branches = tree[2];
19556 var isLeaf = branches.length === 0;
19557
19558 var history = node.history ? node.history.slice() : [];
19559 history.push({id: id, pos: pos, opts: opts});
19560
19561 if (isLeaf) {
19562 for (var i = 0, len = history.length; i < len; i++) {
19563 var historyNode = history[i];
19564 var historyRev = historyNode.pos + '-' + historyNode.id;
19565
19566 if (historyRev === rev) {
19567 // return the rev of this leaf
19568 return pos + '-' + id;
19569 }
19570 }
19571 }
19572
19573 for (var j = 0, l = branches.length; j < l; j++) {
19574 toVisit.push({pos: pos + 1, ids: branches[j], history: history});
19575 }
19576 }
19577
19578 /* istanbul ignore next */
19579 throw new Error('Unable to resolve latest revision for id ' + metadata.id + ', rev ' + rev);
19580}
19581
19582function updateDoc(revLimit, prev, docInfo, results,
19583 i, cb, writeDoc, newEdits) {
19584
19585 if (revExists(prev.rev_tree, docInfo.metadata.rev) && !newEdits) {
19586 results[i] = docInfo;
19587 return cb();
19588 }
19589
19590 // sometimes this is pre-calculated. historically not always
19591 var previousWinningRev = prev.winningRev || winningRev(prev);
19592 var previouslyDeleted = 'deleted' in prev ? prev.deleted :
19593 isDeleted(prev, previousWinningRev);
19594 var deleted = 'deleted' in docInfo.metadata ? docInfo.metadata.deleted :
19595 isDeleted(docInfo.metadata);
19596 var isRoot = /^1-/.test(docInfo.metadata.rev);
19597
19598 if (previouslyDeleted && !deleted && newEdits && isRoot) {
19599 var newDoc = docInfo.data;
19600 newDoc._rev = previousWinningRev;
19601 newDoc._id = docInfo.metadata.id;
19602 docInfo = parseDoc(newDoc, newEdits);
19603 }
19604
19605 var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit);
19606
19607 var inConflict = newEdits && ((
19608 (previouslyDeleted && deleted && merged.conflicts !== 'new_leaf') ||
19609 (!previouslyDeleted && merged.conflicts !== 'new_leaf') ||
19610 (previouslyDeleted && !deleted && merged.conflicts === 'new_branch')));
19611
19612 if (inConflict) {
19613 var err = createError(REV_CONFLICT);
19614 results[i] = err;
19615 return cb();
19616 }
19617
19618 var newRev = docInfo.metadata.rev;
19619 docInfo.metadata.rev_tree = merged.tree;
19620 docInfo.stemmedRevs = merged.stemmedRevs || [];
19621 /* istanbul ignore else */
19622 if (prev.rev_map) {
19623 docInfo.metadata.rev_map = prev.rev_map; // used only by leveldb
19624 }
19625
19626 // recalculate
19627 var winningRev$$1 = winningRev(docInfo.metadata);
19628 var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev$$1);
19629
19630 // calculate the total number of documents that were added/removed,
19631 // from the perspective of total_rows/doc_count
19632 var delta = (previouslyDeleted === winningRevIsDeleted) ? 0 :
19633 previouslyDeleted < winningRevIsDeleted ? -1 : 1;
19634
19635 var newRevIsDeleted;
19636 if (newRev === winningRev$$1) {
19637 // if the new rev is the same as the winning rev, we can reuse that value
19638 newRevIsDeleted = winningRevIsDeleted;
19639 } else {
19640 // if they're not the same, then we need to recalculate
19641 newRevIsDeleted = isDeleted(docInfo.metadata, newRev);
19642 }
19643
19644 writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
19645 true, delta, i, cb);
19646}
19647
19648function rootIsMissing(docInfo) {
19649 return docInfo.metadata.rev_tree[0].ids[1].status === 'missing';
19650}
19651
19652function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results,
19653 writeDoc, opts, overallCallback) {
19654
19655 // Default to 1000 locally
19656 revLimit = revLimit || 1000;
19657
19658 function insertDoc(docInfo, resultsIdx, callback) {
19659 // Cant insert new deleted documents
19660 var winningRev$$1 = winningRev(docInfo.metadata);
19661 var deleted = isDeleted(docInfo.metadata, winningRev$$1);
19662 if ('was_delete' in opts && deleted) {
19663 results[resultsIdx] = createError(MISSING_DOC, 'deleted');
19664 return callback();
19665 }
19666
19667 // 4712 - detect whether a new document was inserted with a _rev
19668 var inConflict = newEdits && rootIsMissing(docInfo);
19669
19670 if (inConflict) {
19671 var err = createError(REV_CONFLICT);
19672 results[resultsIdx] = err;
19673 return callback();
19674 }
19675
19676 var delta = deleted ? 0 : 1;
19677
19678 writeDoc(docInfo, winningRev$$1, deleted, deleted, false,
19679 delta, resultsIdx, callback);
19680 }
19681
19682 var newEdits = opts.new_edits;
19683 var idsToDocs = new ExportedMap();
19684
19685 var docsDone = 0;
19686 var docsToDo = docInfos.length;
19687
19688 function checkAllDocsDone() {
19689 if (++docsDone === docsToDo && overallCallback) {
19690 overallCallback();
19691 }
19692 }
19693
19694 docInfos.forEach(function (currentDoc, resultsIdx) {
19695
19696 if (currentDoc._id && isLocalId(currentDoc._id)) {
19697 var fun = currentDoc._deleted ? '_removeLocal' : '_putLocal';
19698 api[fun](currentDoc, {ctx: tx}, function (err, res) {
19699 results[resultsIdx] = err || res;
19700 checkAllDocsDone();
19701 });
19702 return;
19703 }
19704
19705 var id = currentDoc.metadata.id;
19706 if (idsToDocs.has(id)) {
19707 docsToDo--; // duplicate
19708 idsToDocs.get(id).push([currentDoc, resultsIdx]);
19709 } else {
19710 idsToDocs.set(id, [[currentDoc, resultsIdx]]);
19711 }
19712 });
19713
19714 // in the case of new_edits, the user can provide multiple docs
19715 // with the same id. these need to be processed sequentially
19716 idsToDocs.forEach(function (docs, id) {
19717 var numDone = 0;
19718
19719 function docWritten() {
19720 if (++numDone < docs.length) {
19721 nextDoc();
19722 } else {
19723 checkAllDocsDone();
19724 }
19725 }
19726 function nextDoc() {
19727 var value = docs[numDone];
19728 var currentDoc = value[0];
19729 var resultsIdx = value[1];
19730
19731 if (fetchedDocs.has(id)) {
19732 updateDoc(revLimit, fetchedDocs.get(id), currentDoc, results,
19733 resultsIdx, docWritten, writeDoc, newEdits);
19734 } else {
19735 // Ensure stemming applies to new writes as well
19736 var merged = merge([], currentDoc.metadata.rev_tree[0], revLimit);
19737 currentDoc.metadata.rev_tree = merged.tree;
19738 currentDoc.stemmedRevs = merged.stemmedRevs || [];
19739 insertDoc(currentDoc, resultsIdx, docWritten);
19740 }
19741 }
19742 nextDoc();
19743 });
19744}
19745
19746function safeJsonParse(str) {
19747 // This try/catch guards against stack overflow errors.
19748 // JSON.parse() is faster than vuvuzela.parse() but vuvuzela
19749 // cannot overflow.
19750 try {
19751 return JSON.parse(str);
19752 } catch (e) {
19753 /* istanbul ignore next */
19754 return vuvuzela.parse(str);
19755 }
19756}
19757
19758function safeJsonStringify(json) {
19759 try {
19760 return JSON.stringify(json);
19761 } catch (e) {
19762 /* istanbul ignore next */
19763 return vuvuzela.stringify(json);
19764 }
19765}
19766
19767function readAsBlobOrBuffer(storedObject, type) {
19768 // In the browser, we've stored a binary string. This now comes back as a
19769 // browserified Node-style Buffer (implemented as a typed array),
19770 // but we want a Blob instead.
19771 var byteArray = new Uint8Array(storedObject);
19772 return createBlob([byteArray], {type: type});
19773}
19774
19775// In the browser, we store a binary string
19776function prepareAttachmentForStorage(attData, cb) {
19777 readAsBinaryString(attData, cb);
19778}
19779
19780function createEmptyBlobOrBuffer(type) {
19781 return createBlob([''], {type: type});
19782}
19783
19784function getCacheFor(transaction, store) {
19785 var prefix = store.prefix()[0];
19786 var cache = transaction._cache;
19787 var subCache = cache.get(prefix);
19788 if (!subCache) {
19789 subCache = new ExportedMap();
19790 cache.set(prefix, subCache);
19791 }
19792 return subCache;
19793}
19794
19795function LevelTransaction() {
19796 this._batch = [];
19797 this._cache = new ExportedMap();
19798}
19799
19800LevelTransaction.prototype.get = function (store, key, callback) {
19801 var cache = getCacheFor(this, store);
19802 var exists = cache.get(key);
19803 if (exists) {
19804 return immediate(function () {
19805 callback(null, exists);
19806 });
19807 } else if (exists === null) { // deleted marker
19808 /* istanbul ignore next */
19809 return immediate(function () {
19810 callback({name: 'NotFoundError'});
19811 });
19812 }
19813 store.get(key, function (err, res) {
19814 if (err) {
19815 /* istanbul ignore else */
19816 if (err.name === 'NotFoundError') {
19817 cache.set(key, null);
19818 }
19819 return callback(err);
19820 }
19821 cache.set(key, res);
19822 callback(null, res);
19823 });
19824};
19825
19826LevelTransaction.prototype.batch = function (batch) {
19827 for (var i = 0, len = batch.length; i < len; i++) {
19828 var operation = batch[i];
19829
19830 var cache = getCacheFor(this, operation.prefix);
19831
19832 if (operation.type === 'put') {
19833 cache.set(operation.key, operation.value);
19834 } else {
19835 cache.set(operation.key, null);
19836 }
19837 }
19838 this._batch = this._batch.concat(batch);
19839};
19840
19841LevelTransaction.prototype.execute = function (db, callback) {
19842
19843 var keys = new ExportedSet();
19844 var uniqBatches = [];
19845
19846 // remove duplicates; last one wins
19847 for (var i = this._batch.length - 1; i >= 0; i--) {
19848 var operation = this._batch[i];
19849 var lookupKey = operation.prefix.prefix()[0] + '\xff' + operation.key;
19850 if (keys.has(lookupKey)) {
19851 continue;
19852 }
19853 keys.add(lookupKey);
19854 uniqBatches.push(operation);
19855 }
19856
19857 db.batch(uniqBatches, callback);
19858};
19859
19860var DOC_STORE = 'document-store';
19861var BY_SEQ_STORE = 'by-sequence';
19862var ATTACHMENT_STORE = 'attach-store';
19863var BINARY_STORE = 'attach-binary-store';
19864var LOCAL_STORE = 'local-store';
19865var META_STORE = 'meta-store';
19866
19867// leveldb barks if we try to open a db multiple times
19868// so we cache opened connections here for initstore()
19869var dbStores = new ExportedMap();
19870
19871// store the value of update_seq in the by-sequence store the key name will
19872// never conflict, since the keys in the by-sequence store are integers
19873var UPDATE_SEQ_KEY = '_local_last_update_seq';
19874var DOC_COUNT_KEY = '_local_doc_count';
19875var UUID_KEY = '_local_uuid';
19876
19877var MD5_PREFIX = 'md5-';
19878
19879var safeJsonEncoding = {
19880 encode: safeJsonStringify,
19881 decode: safeJsonParse,
19882 buffer: false,
19883 type: 'cheap-json'
19884};
19885
19886var levelChanges = new Changes();
19887
19888// winningRev and deleted are performance-killers, but
19889// in newer versions of PouchDB, they are cached on the metadata
19890function getWinningRev(metadata) {
19891 return 'winningRev' in metadata ?
19892 metadata.winningRev : winningRev(metadata);
19893}
19894
19895function getIsDeleted(metadata, winningRev$$1) {
19896 return 'deleted' in metadata ?
19897 metadata.deleted : isDeleted(metadata, winningRev$$1);
19898}
19899
19900function fetchAttachment(att, stores, opts) {
19901 var type = att.content_type;
19902 return new Promise(function (resolve, reject) {
19903 stores.binaryStore.get(att.digest, function (err, buffer) {
19904 var data;
19905 if (err) {
19906 /* istanbul ignore if */
19907 if (err.name !== 'NotFoundError') {
19908 return reject(err);
19909 } else {
19910 // empty
19911 if (!opts.binary) {
19912 data = '';
19913 } else {
19914 data = binStringToBluffer('', type);
19915 }
19916 }
19917 } else { // non-empty
19918 if (opts.binary) {
19919 data = readAsBlobOrBuffer(buffer, type);
19920 } else {
19921 data = buffer.toString('base64');
19922 }
19923 }
19924 delete att.stub;
19925 delete att.length;
19926 att.data = data;
19927 resolve();
19928 });
19929 });
19930}
19931
19932function fetchAttachments(results, stores, opts) {
19933 var atts = [];
19934 results.forEach(function (row) {
19935 if (!(row.doc && row.doc._attachments)) {
19936 return;
19937 }
19938 var attNames = Object.keys(row.doc._attachments);
19939 attNames.forEach(function (attName) {
19940 var att = row.doc._attachments[attName];
19941 if (!('data' in att)) {
19942 atts.push(att);
19943 }
19944 });
19945 });
19946
19947 return Promise.all(atts.map(function (att) {
19948 return fetchAttachment(att, stores, opts);
19949 }));
19950}
19951
19952function LevelPouch(opts, callback) {
19953 opts = clone(opts);
19954 var api = this;
19955 var instanceId;
19956 var stores = {};
19957 var revLimit = opts.revs_limit;
19958 var db;
19959 var name = opts.name;
19960 // TODO: this is undocumented and unused probably
19961 /* istanbul ignore else */
19962 if (typeof opts.createIfMissing === 'undefined') {
19963 opts.createIfMissing = true;
19964 }
19965
19966 var leveldown = opts.db;
19967
19968 var dbStore;
19969 var leveldownName = functionName(leveldown);
19970 if (dbStores.has(leveldownName)) {
19971 dbStore = dbStores.get(leveldownName);
19972 } else {
19973 dbStore = new ExportedMap();
19974 dbStores.set(leveldownName, dbStore);
19975 }
19976 if (dbStore.has(name)) {
19977 db = dbStore.get(name);
19978 afterDBCreated();
19979 } else {
19980 dbStore.set(name, sublevelPouch(levelup(leveldown(name), opts, function (err) {
19981 /* istanbul ignore if */
19982 if (err) {
19983 dbStore["delete"](name);
19984 return callback(err);
19985 }
19986 db = dbStore.get(name);
19987 db._docCount = -1;
19988 db._queue = new Deque();
19989 /* istanbul ignore else */
19990 if (typeof opts.migrate === 'object') { // migration for leveldown
19991 opts.migrate.doMigrationOne(name, db, afterDBCreated);
19992 } else {
19993 afterDBCreated();
19994 }
19995 })));
19996 }
19997
19998 function afterDBCreated() {
19999 stores.docStore = db.sublevel(DOC_STORE, {valueEncoding: safeJsonEncoding});
20000 stores.bySeqStore = db.sublevel(BY_SEQ_STORE, {valueEncoding: 'json'});
20001 stores.attachmentStore =
20002 db.sublevel(ATTACHMENT_STORE, {valueEncoding: 'json'});
20003 stores.binaryStore = db.sublevel(BINARY_STORE, {valueEncoding: 'binary'});
20004 stores.localStore = db.sublevel(LOCAL_STORE, {valueEncoding: 'json'});
20005 stores.metaStore = db.sublevel(META_STORE, {valueEncoding: 'json'});
20006 /* istanbul ignore else */
20007 if (typeof opts.migrate === 'object') { // migration for leveldown
20008 opts.migrate.doMigrationTwo(db, stores, afterLastMigration);
20009 } else {
20010 afterLastMigration();
20011 }
20012 }
20013
20014 function afterLastMigration() {
20015 stores.metaStore.get(UPDATE_SEQ_KEY, function (err, value) {
20016 if (typeof db._updateSeq === 'undefined') {
20017 db._updateSeq = value || 0;
20018 }
20019 stores.metaStore.get(DOC_COUNT_KEY, function (err, value) {
20020 db._docCount = !err ? value : 0;
20021 stores.metaStore.get(UUID_KEY, function (err, value) {
20022 instanceId = !err ? value : uuid();
20023 stores.metaStore.put(UUID_KEY, instanceId, function () {
20024 immediate(function () {
20025 callback(null, api);
20026 });
20027 });
20028 });
20029 });
20030 });
20031 }
20032
20033 function countDocs(callback) {
20034 /* istanbul ignore if */
20035 if (db.isClosed()) {
20036 return callback(new Error('database is closed'));
20037 }
20038 return callback(null, db._docCount); // use cached value
20039 }
20040
20041 api._remote = false;
20042 /* istanbul ignore next */
20043 api.type = function () {
20044 return 'leveldb';
20045 };
20046
20047 api._id = function (callback) {
20048 callback(null, instanceId);
20049 };
20050
20051 api._info = function (callback) {
20052 var res = {
20053 doc_count: db._docCount,
20054 update_seq: db._updateSeq,
20055 backend_adapter: functionName(leveldown)
20056 };
20057 return immediate(function () {
20058 callback(null, res);
20059 });
20060 };
20061
20062 function tryCode(fun, args) {
20063 try {
20064 fun.apply(null, args);
20065 } catch (err) {
20066 args[args.length - 1](err);
20067 }
20068 }
20069
20070 function executeNext() {
20071 var firstTask = db._queue.peekFront();
20072
20073 if (firstTask.type === 'read') {
20074 runReadOperation(firstTask);
20075 } else { // write, only do one at a time
20076 runWriteOperation(firstTask);
20077 }
20078 }
20079
20080 function runReadOperation(firstTask) {
20081 // do multiple reads at once simultaneously, because it's safe
20082
20083 var readTasks = [firstTask];
20084 var i = 1;
20085 var nextTask = db._queue.get(i);
20086 while (typeof nextTask !== 'undefined' && nextTask.type === 'read') {
20087 readTasks.push(nextTask);
20088 i++;
20089 nextTask = db._queue.get(i);
20090 }
20091
20092 var numDone = 0;
20093
20094 readTasks.forEach(function (readTask) {
20095 var args = readTask.args;
20096 var callback = args[args.length - 1];
20097 args[args.length - 1] = getArguments(function (cbArgs) {
20098 callback.apply(null, cbArgs);
20099 if (++numDone === readTasks.length) {
20100 immediate(function () {
20101 // all read tasks have finished
20102 readTasks.forEach(function () {
20103 db._queue.shift();
20104 });
20105 if (db._queue.length) {
20106 executeNext();
20107 }
20108 });
20109 }
20110 });
20111 tryCode(readTask.fun, args);
20112 });
20113 }
20114
20115 function runWriteOperation(firstTask) {
20116 var args = firstTask.args;
20117 var callback = args[args.length - 1];
20118 args[args.length - 1] = getArguments(function (cbArgs) {
20119 callback.apply(null, cbArgs);
20120 immediate(function () {
20121 db._queue.shift();
20122 if (db._queue.length) {
20123 executeNext();
20124 }
20125 });
20126 });
20127 tryCode(firstTask.fun, args);
20128 }
20129
20130 // all read/write operations to the database are done in a queue,
20131 // similar to how websql/idb works. this avoids problems such
20132 // as e.g. compaction needing to have a lock on the database while
20133 // it updates stuff. in the future we can revisit this.
20134 function writeLock(fun) {
20135 return getArguments(function (args) {
20136 db._queue.push({
20137 fun: fun,
20138 args: args,
20139 type: 'write'
20140 });
20141
20142 if (db._queue.length === 1) {
20143 immediate(executeNext);
20144 }
20145 });
20146 }
20147
20148 // same as the writelock, but multiple can run at once
20149 function readLock(fun) {
20150 return getArguments(function (args) {
20151 db._queue.push({
20152 fun: fun,
20153 args: args,
20154 type: 'read'
20155 });
20156
20157 if (db._queue.length === 1) {
20158 immediate(executeNext);
20159 }
20160 });
20161 }
20162
20163 function formatSeq(n) {
20164 return ('0000000000000000' + n).slice(-16);
20165 }
20166
20167 function parseSeq(s) {
20168 return parseInt(s, 10);
20169 }
20170
20171 api._get = readLock(function (id, opts, callback) {
20172 opts = clone(opts);
20173
20174 stores.docStore.get(id, function (err, metadata) {
20175
20176 if (err || !metadata) {
20177 return callback(createError(MISSING_DOC, 'missing'));
20178 }
20179
20180 var rev$$1;
20181 if (!opts.rev) {
20182 rev$$1 = getWinningRev(metadata);
20183 var deleted = getIsDeleted(metadata, rev$$1);
20184 if (deleted) {
20185 return callback(createError(MISSING_DOC, "deleted"));
20186 }
20187 } else {
20188 rev$$1 = opts.latest ? latest(opts.rev, metadata) : opts.rev;
20189 }
20190
20191 var seq = metadata.rev_map[rev$$1];
20192
20193 stores.bySeqStore.get(formatSeq(seq), function (err, doc) {
20194 if (!doc) {
20195 return callback(createError(MISSING_DOC));
20196 }
20197 /* istanbul ignore if */
20198 if ('_id' in doc && doc._id !== metadata.id) {
20199 // this failing implies something very wrong
20200 return callback(new Error('wrong doc returned'));
20201 }
20202 doc._id = metadata.id;
20203 if ('_rev' in doc) {
20204 /* istanbul ignore if */
20205 if (doc._rev !== rev$$1) {
20206 // this failing implies something very wrong
20207 return callback(new Error('wrong doc returned'));
20208 }
20209 } else {
20210 // we didn't always store this
20211 doc._rev = rev$$1;
20212 }
20213 return callback(null, {doc: doc, metadata: metadata});
20214 });
20215 });
20216 });
20217
20218 // not technically part of the spec, but if putAttachment has its own
20219 // method...
20220 api._getAttachment = function (docId, attachId, attachment, opts, callback) {
20221 var digest = attachment.digest;
20222 var type = attachment.content_type;
20223
20224 stores.binaryStore.get(digest, function (err, attach) {
20225 if (err) {
20226 /* istanbul ignore if */
20227 if (err.name !== 'NotFoundError') {
20228 return callback(err);
20229 }
20230 // Empty attachment
20231 return callback(null, opts.binary ? createEmptyBlobOrBuffer(type) : '');
20232 }
20233
20234 if (opts.binary) {
20235 callback(null, readAsBlobOrBuffer(attach, type));
20236 } else {
20237 callback(null, attach.toString('base64'));
20238 }
20239 });
20240 };
20241
20242 api._bulkDocs = writeLock(function (req, opts, callback) {
20243 var newEdits = opts.new_edits;
20244 var results = new Array(req.docs.length);
20245 var fetchedDocs = new ExportedMap();
20246 var stemmedRevs = new ExportedMap();
20247
20248 var txn = new LevelTransaction();
20249 var docCountDelta = 0;
20250 var newUpdateSeq = db._updateSeq;
20251
20252 // parse the docs and give each a sequence number
20253 var userDocs = req.docs;
20254 var docInfos = userDocs.map(function (doc) {
20255 if (doc._id && isLocalId(doc._id)) {
20256 return doc;
20257 }
20258 var newDoc = parseDoc(doc, newEdits, api.__opts);
20259
20260 if (newDoc.metadata && !newDoc.metadata.rev_map) {
20261 newDoc.metadata.rev_map = {};
20262 }
20263
20264 return newDoc;
20265 });
20266 var infoErrors = docInfos.filter(function (doc) {
20267 return doc.error;
20268 });
20269
20270 if (infoErrors.length) {
20271 return callback(infoErrors[0]);
20272 }
20273
20274 // verify any stub attachments as a precondition test
20275
20276 function verifyAttachment(digest, callback) {
20277 txn.get(stores.attachmentStore, digest, function (levelErr) {
20278 if (levelErr) {
20279 var err = createError(MISSING_STUB,
20280 'unknown stub attachment with digest ' +
20281 digest);
20282 callback(err);
20283 } else {
20284 callback();
20285 }
20286 });
20287 }
20288
20289 function verifyAttachments(finish) {
20290 var digests = [];
20291 userDocs.forEach(function (doc) {
20292 if (doc && doc._attachments) {
20293 Object.keys(doc._attachments).forEach(function (filename) {
20294 var att = doc._attachments[filename];
20295 if (att.stub) {
20296 digests.push(att.digest);
20297 }
20298 });
20299 }
20300 });
20301 if (!digests.length) {
20302 return finish();
20303 }
20304 var numDone = 0;
20305 var err;
20306
20307 digests.forEach(function (digest) {
20308 verifyAttachment(digest, function (attErr) {
20309 if (attErr && !err) {
20310 err = attErr;
20311 }
20312
20313 if (++numDone === digests.length) {
20314 finish(err);
20315 }
20316 });
20317 });
20318 }
20319
20320 function fetchExistingDocs(finish) {
20321 var numDone = 0;
20322 var overallErr;
20323 function checkDone() {
20324 if (++numDone === userDocs.length) {
20325 return finish(overallErr);
20326 }
20327 }
20328
20329 userDocs.forEach(function (doc) {
20330 if (doc._id && isLocalId(doc._id)) {
20331 // skip local docs
20332 return checkDone();
20333 }
20334 txn.get(stores.docStore, doc._id, function (err, info) {
20335 if (err) {
20336 /* istanbul ignore if */
20337 if (err.name !== 'NotFoundError') {
20338 overallErr = err;
20339 }
20340 } else {
20341 fetchedDocs.set(doc._id, info);
20342 }
20343 checkDone();
20344 });
20345 });
20346 }
20347
20348 function compact(revsMap, callback) {
20349 var promise = Promise.resolve();
20350 revsMap.forEach(function (revs, docId) {
20351 // TODO: parallelize, for now need to be sequential to
20352 // pass orphaned attachment tests
20353 promise = promise.then(function () {
20354 return new Promise(function (resolve, reject) {
20355 api._doCompactionNoLock(docId, revs, {ctx: txn}, function (err) {
20356 /* istanbul ignore if */
20357 if (err) {
20358 return reject(err);
20359 }
20360 resolve();
20361 });
20362 });
20363 });
20364 });
20365
20366 promise.then(function () {
20367 callback();
20368 }, callback);
20369 }
20370
20371 function autoCompact(callback) {
20372 var revsMap = new ExportedMap();
20373 fetchedDocs.forEach(function (metadata, docId) {
20374 revsMap.set(docId, compactTree(metadata));
20375 });
20376 compact(revsMap, callback);
20377 }
20378
20379 function finish() {
20380 compact(stemmedRevs, function (error) {
20381 /* istanbul ignore if */
20382 if (error) {
20383 complete(error);
20384 }
20385 if (api.auto_compaction) {
20386 return autoCompact(complete);
20387 }
20388 complete();
20389 });
20390 }
20391
20392 function writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
20393 isUpdate, delta, resultsIdx, callback2) {
20394 docCountDelta += delta;
20395
20396 var err = null;
20397 var recv = 0;
20398
20399 docInfo.metadata.winningRev = winningRev$$1;
20400 docInfo.metadata.deleted = winningRevIsDeleted;
20401
20402 docInfo.data._id = docInfo.metadata.id;
20403 docInfo.data._rev = docInfo.metadata.rev;
20404
20405 if (newRevIsDeleted) {
20406 docInfo.data._deleted = true;
20407 }
20408
20409 if (docInfo.stemmedRevs.length) {
20410 stemmedRevs.set(docInfo.metadata.id, docInfo.stemmedRevs);
20411 }
20412
20413 var attachments = docInfo.data._attachments ?
20414 Object.keys(docInfo.data._attachments) :
20415 [];
20416
20417 function attachmentSaved(attachmentErr) {
20418 recv++;
20419 if (!err) {
20420 /* istanbul ignore if */
20421 if (attachmentErr) {
20422 err = attachmentErr;
20423 callback2(err);
20424 } else if (recv === attachments.length) {
20425 finish();
20426 }
20427 }
20428 }
20429
20430 function onMD5Load(doc, key, data, attachmentSaved) {
20431 return function (result) {
20432 saveAttachment(doc, MD5_PREFIX + result, key, data, attachmentSaved);
20433 };
20434 }
20435
20436 function doMD5(doc, key, attachmentSaved) {
20437 return function (data) {
20438 binaryMd5(data, onMD5Load(doc, key, data, attachmentSaved));
20439 };
20440 }
20441
20442 for (var i = 0; i < attachments.length; i++) {
20443 var key = attachments[i];
20444 var att = docInfo.data._attachments[key];
20445
20446 if (att.stub) {
20447 // still need to update the refs mapping
20448 var id = docInfo.data._id;
20449 var rev$$1 = docInfo.data._rev;
20450 saveAttachmentRefs(id, rev$$1, att.digest, attachmentSaved);
20451 continue;
20452 }
20453 var data;
20454 if (typeof att.data === 'string') {
20455 // input is assumed to be a base64 string
20456 try {
20457 data = thisAtob(att.data);
20458 } catch (e) {
20459 callback(createError(BAD_ARG,
20460 'Attachment is not a valid base64 string'));
20461 return;
20462 }
20463 doMD5(docInfo, key, attachmentSaved)(data);
20464 } else {
20465 prepareAttachmentForStorage(att.data,
20466 doMD5(docInfo, key, attachmentSaved));
20467 }
20468 }
20469
20470 function finish() {
20471 var seq = docInfo.metadata.rev_map[docInfo.metadata.rev];
20472 /* istanbul ignore if */
20473 if (seq) {
20474 // check that there aren't any existing revisions with the same
20475 // revision id, else we shouldn't do anything
20476 return callback2();
20477 }
20478 seq = ++newUpdateSeq;
20479 docInfo.metadata.rev_map[docInfo.metadata.rev] =
20480 docInfo.metadata.seq = seq;
20481 var seqKey = formatSeq(seq);
20482 var batch = [{
20483 key: seqKey,
20484 value: docInfo.data,
20485 prefix: stores.bySeqStore,
20486 type: 'put'
20487 }, {
20488 key: docInfo.metadata.id,
20489 value: docInfo.metadata,
20490 prefix: stores.docStore,
20491 type: 'put'
20492 }];
20493 txn.batch(batch);
20494 results[resultsIdx] = {
20495 ok: true,
20496 id: docInfo.metadata.id,
20497 rev: docInfo.metadata.rev
20498 };
20499 fetchedDocs.set(docInfo.metadata.id, docInfo.metadata);
20500 callback2();
20501 }
20502
20503 if (!attachments.length) {
20504 finish();
20505 }
20506 }
20507
20508 // attachments are queued per-digest, otherwise the refs could be
20509 // overwritten by concurrent writes in the same bulkDocs session
20510 var attachmentQueues = {};
20511
20512 function saveAttachmentRefs(id, rev$$1, digest, callback) {
20513
20514 function fetchAtt() {
20515 return new Promise(function (resolve, reject) {
20516 txn.get(stores.attachmentStore, digest, function (err, oldAtt) {
20517 /* istanbul ignore if */
20518 if (err && err.name !== 'NotFoundError') {
20519 return reject(err);
20520 }
20521 resolve(oldAtt);
20522 });
20523 });
20524 }
20525
20526 function saveAtt(oldAtt) {
20527 var ref = [id, rev$$1].join('@');
20528 var newAtt = {};
20529
20530 if (oldAtt) {
20531 if (oldAtt.refs) {
20532 // only update references if this attachment already has them
20533 // since we cannot migrate old style attachments here without
20534 // doing a full db scan for references
20535 newAtt.refs = oldAtt.refs;
20536 newAtt.refs[ref] = true;
20537 }
20538 } else {
20539 newAtt.refs = {};
20540 newAtt.refs[ref] = true;
20541 }
20542
20543 return new Promise(function (resolve) {
20544 txn.batch([{
20545 type: 'put',
20546 prefix: stores.attachmentStore,
20547 key: digest,
20548 value: newAtt
20549 }]);
20550 resolve(!oldAtt);
20551 });
20552 }
20553
20554 // put attachments in a per-digest queue, to avoid two docs with the same
20555 // attachment overwriting each other
20556 var queue = attachmentQueues[digest] || Promise.resolve();
20557 attachmentQueues[digest] = queue.then(function () {
20558 return fetchAtt().then(saveAtt).then(function (isNewAttachment) {
20559 callback(null, isNewAttachment);
20560 }, callback);
20561 });
20562 }
20563
20564 function saveAttachment(docInfo, digest, key, data, callback) {
20565 var att = docInfo.data._attachments[key];
20566 delete att.data;
20567 att.digest = digest;
20568 att.length = data.length;
20569 var id = docInfo.metadata.id;
20570 var rev$$1 = docInfo.metadata.rev;
20571 att.revpos = parseInt(rev$$1, 10);
20572
20573 saveAttachmentRefs(id, rev$$1, digest, function (err, isNewAttachment) {
20574 /* istanbul ignore if */
20575 if (err) {
20576 return callback(err);
20577 }
20578 // do not try to store empty attachments
20579 if (data.length === 0) {
20580 return callback(err);
20581 }
20582 if (!isNewAttachment) {
20583 // small optimization - don't bother writing it again
20584 return callback(err);
20585 }
20586 txn.batch([{
20587 type: 'put',
20588 prefix: stores.binaryStore,
20589 key: digest,
20590 value: bufferFrom(data, 'binary')
20591 }]);
20592 callback();
20593 });
20594 }
20595
20596 function complete(err) {
20597 /* istanbul ignore if */
20598 if (err) {
20599 return immediate(function () {
20600 callback(err);
20601 });
20602 }
20603 txn.batch([
20604 {
20605 prefix: stores.metaStore,
20606 type: 'put',
20607 key: UPDATE_SEQ_KEY,
20608 value: newUpdateSeq
20609 },
20610 {
20611 prefix: stores.metaStore,
20612 type: 'put',
20613 key: DOC_COUNT_KEY,
20614 value: db._docCount + docCountDelta
20615 }
20616 ]);
20617 txn.execute(db, function (err) {
20618 /* istanbul ignore if */
20619 if (err) {
20620 return callback(err);
20621 }
20622 db._docCount += docCountDelta;
20623 db._updateSeq = newUpdateSeq;
20624 levelChanges.notify(name);
20625 immediate(function () {
20626 callback(null, results);
20627 });
20628 });
20629 }
20630
20631 if (!docInfos.length) {
20632 return callback(null, []);
20633 }
20634
20635 verifyAttachments(function (err) {
20636 if (err) {
20637 return callback(err);
20638 }
20639 fetchExistingDocs(function (err) {
20640 /* istanbul ignore if */
20641 if (err) {
20642 return callback(err);
20643 }
20644 processDocs(revLimit, docInfos, api, fetchedDocs, txn, results,
20645 writeDoc, opts, finish);
20646 });
20647 });
20648 });
20649 api._allDocs = function (opts, callback) {
20650 if ('keys' in opts) {
20651 return allDocsKeysQuery(this, opts);
20652 }
20653 return readLock(function (opts, callback) {
20654 opts = clone(opts);
20655 countDocs(function (err, docCount) {
20656 /* istanbul ignore if */
20657 if (err) {
20658 return callback(err);
20659 }
20660 var readstreamOpts = {};
20661 var skip = opts.skip || 0;
20662 if (opts.startkey) {
20663 readstreamOpts.gte = opts.startkey;
20664 }
20665 if (opts.endkey) {
20666 readstreamOpts.lte = opts.endkey;
20667 }
20668 if (opts.key) {
20669 readstreamOpts.gte = readstreamOpts.lte = opts.key;
20670 }
20671 if (opts.descending) {
20672 readstreamOpts.reverse = true;
20673 // switch start and ends
20674 var tmp = readstreamOpts.lte;
20675 readstreamOpts.lte = readstreamOpts.gte;
20676 readstreamOpts.gte = tmp;
20677 }
20678 var limit;
20679 if (typeof opts.limit === 'number') {
20680 limit = opts.limit;
20681 }
20682 if (limit === 0 ||
20683 ('gte' in readstreamOpts && 'lte' in readstreamOpts &&
20684 readstreamOpts.gte > readstreamOpts.lte)) {
20685 // should return 0 results when start is greater than end.
20686 // normally level would "fix" this for us by reversing the order,
20687 // so short-circuit instead
20688 var returnVal = {
20689 total_rows: docCount,
20690 offset: opts.skip,
20691 rows: []
20692 };
20693 /* istanbul ignore if */
20694 if (opts.update_seq) {
20695 returnVal.update_seq = db._updateSeq;
20696 }
20697 return callback(null, returnVal);
20698 }
20699 var results = [];
20700 var docstream = stores.docStore.readStream(readstreamOpts);
20701
20702 var throughStream = through2.obj(function (entry, _, next) {
20703 var metadata = entry.value;
20704 // winningRev and deleted are performance-killers, but
20705 // in newer versions of PouchDB, they are cached on the metadata
20706 var winningRev$$1 = getWinningRev(metadata);
20707 var deleted = getIsDeleted(metadata, winningRev$$1);
20708 if (!deleted) {
20709 if (skip-- > 0) {
20710 next();
20711 return;
20712 } else if (typeof limit === 'number' && limit-- <= 0) {
20713 docstream.unpipe();
20714 docstream.destroy();
20715 next();
20716 return;
20717 }
20718 } else if (opts.deleted !== 'ok') {
20719 next();
20720 return;
20721 }
20722 function allDocsInner(data) {
20723 var doc = {
20724 id: metadata.id,
20725 key: metadata.id,
20726 value: {
20727 rev: winningRev$$1
20728 }
20729 };
20730 if (opts.include_docs) {
20731 doc.doc = data;
20732 doc.doc._rev = doc.value.rev;
20733 if (opts.conflicts) {
20734 var conflicts = collectConflicts(metadata);
20735 if (conflicts.length) {
20736 doc.doc._conflicts = conflicts;
20737 }
20738 }
20739 for (var att in doc.doc._attachments) {
20740 if (doc.doc._attachments.hasOwnProperty(att)) {
20741 doc.doc._attachments[att].stub = true;
20742 }
20743 }
20744 }
20745 if (opts.inclusive_end === false && metadata.id === opts.endkey) {
20746 return next();
20747 } else if (deleted) {
20748 if (opts.deleted === 'ok') {
20749 doc.value.deleted = true;
20750 doc.doc = null;
20751 } else {
20752 /* istanbul ignore next */
20753 return next();
20754 }
20755 }
20756 results.push(doc);
20757 next();
20758 }
20759 if (opts.include_docs) {
20760 var seq = metadata.rev_map[winningRev$$1];
20761 stores.bySeqStore.get(formatSeq(seq), function (err, data) {
20762 allDocsInner(data);
20763 });
20764 }
20765 else {
20766 allDocsInner();
20767 }
20768 }, function (next) {
20769 Promise.resolve().then(function () {
20770 if (opts.include_docs && opts.attachments) {
20771 return fetchAttachments(results, stores, opts);
20772 }
20773 }).then(function () {
20774 var returnVal = {
20775 total_rows: docCount,
20776 offset: opts.skip,
20777 rows: results
20778 };
20779
20780 /* istanbul ignore if */
20781 if (opts.update_seq) {
20782 returnVal.update_seq = db._updateSeq;
20783 }
20784 callback(null, returnVal);
20785 }, callback);
20786 next();
20787 }).on('unpipe', function () {
20788 throughStream.end();
20789 });
20790
20791 docstream.on('error', callback);
20792
20793 docstream.pipe(throughStream);
20794 });
20795 })(opts, callback);
20796 };
20797
20798 api._changes = function (opts) {
20799 opts = clone(opts);
20800
20801 if (opts.continuous) {
20802 var id = name + ':' + uuid();
20803 levelChanges.addListener(name, id, api, opts);
20804 levelChanges.notify(name);
20805 return {
20806 cancel: function () {
20807 levelChanges.removeListener(name, id);
20808 }
20809 };
20810 }
20811
20812 var descending = opts.descending;
20813 var results = [];
20814 var lastSeq = opts.since || 0;
20815 var called = 0;
20816 var streamOpts = {
20817 reverse: descending
20818 };
20819 var limit;
20820 if ('limit' in opts && opts.limit > 0) {
20821 limit = opts.limit;
20822 }
20823 if (!streamOpts.reverse) {
20824 streamOpts.start = formatSeq(opts.since || 0);
20825 }
20826
20827 var docIds = opts.doc_ids && new ExportedSet(opts.doc_ids);
20828 var filter = filterChange(opts);
20829 var docIdsToMetadata = new ExportedMap();
20830
20831 function complete() {
20832 opts.done = true;
20833 if (opts.return_docs && opts.limit) {
20834 /* istanbul ignore if */
20835 if (opts.limit < results.length) {
20836 results.length = opts.limit;
20837 }
20838 }
20839 changeStream.unpipe(throughStream);
20840 changeStream.destroy();
20841 if (!opts.continuous && !opts.cancelled) {
20842 if (opts.include_docs && opts.attachments && opts.return_docs) {
20843 fetchAttachments(results, stores, opts).then(function () {
20844 opts.complete(null, {results: results, last_seq: lastSeq});
20845 });
20846 } else {
20847 opts.complete(null, {results: results, last_seq: lastSeq});
20848 }
20849 }
20850 }
20851 var changeStream = stores.bySeqStore.readStream(streamOpts);
20852 var throughStream = through2.obj(function (data, _, next) {
20853 if (limit && called >= limit) {
20854 complete();
20855 return next();
20856 }
20857 if (opts.cancelled || opts.done) {
20858 return next();
20859 }
20860
20861 var seq = parseSeq(data.key);
20862 var doc = data.value;
20863
20864 if (seq === opts.since && !descending) {
20865 // couchdb ignores `since` if descending=true
20866 return next();
20867 }
20868
20869 if (docIds && !docIds.has(doc._id)) {
20870 return next();
20871 }
20872
20873 var metadata;
20874
20875 function onGetMetadata(metadata) {
20876 var winningRev$$1 = getWinningRev(metadata);
20877
20878 function onGetWinningDoc(winningDoc) {
20879
20880 var change = opts.processChange(winningDoc, metadata, opts);
20881 change.seq = metadata.seq;
20882
20883 var filtered = filter(change);
20884 if (typeof filtered === 'object') {
20885 return opts.complete(filtered);
20886 }
20887
20888 if (filtered) {
20889 called++;
20890
20891 if (opts.attachments && opts.include_docs) {
20892 // fetch attachment immediately for the benefit
20893 // of live listeners
20894 fetchAttachments([change], stores, opts).then(function () {
20895 opts.onChange(change);
20896 });
20897 } else {
20898 opts.onChange(change);
20899 }
20900
20901 if (opts.return_docs) {
20902 results.push(change);
20903 }
20904 }
20905 next();
20906 }
20907
20908 if (metadata.seq !== seq) {
20909 // some other seq is later
20910 return next();
20911 }
20912
20913 lastSeq = seq;
20914
20915 if (winningRev$$1 === doc._rev) {
20916 return onGetWinningDoc(doc);
20917 }
20918
20919 // fetch the winner
20920
20921 var winningSeq = metadata.rev_map[winningRev$$1];
20922
20923 stores.bySeqStore.get(formatSeq(winningSeq), function (err, doc) {
20924 onGetWinningDoc(doc);
20925 });
20926 }
20927
20928 metadata = docIdsToMetadata.get(doc._id);
20929 if (metadata) { // cached
20930 return onGetMetadata(metadata);
20931 }
20932 // metadata not cached, have to go fetch it
20933 stores.docStore.get(doc._id, function (err, metadata) {
20934 /* istanbul ignore if */
20935 if (opts.cancelled || opts.done || db.isClosed() ||
20936 isLocalId(metadata.id)) {
20937 return next();
20938 }
20939 docIdsToMetadata.set(doc._id, metadata);
20940 onGetMetadata(metadata);
20941 });
20942 }, function (next) {
20943 if (opts.cancelled) {
20944 return next();
20945 }
20946 if (opts.return_docs && opts.limit) {
20947 /* istanbul ignore if */
20948 if (opts.limit < results.length) {
20949 results.length = opts.limit;
20950 }
20951 }
20952
20953 next();
20954 }).on('unpipe', function () {
20955 throughStream.end();
20956 complete();
20957 });
20958 changeStream.pipe(throughStream);
20959 return {
20960 cancel: function () {
20961 opts.cancelled = true;
20962 complete();
20963 }
20964 };
20965 };
20966
20967 api._close = function (callback) {
20968 /* istanbul ignore if */
20969 if (db.isClosed()) {
20970 return callback(createError(NOT_OPEN));
20971 }
20972 db.close(function (err) {
20973 /* istanbul ignore if */
20974 if (err) {
20975 callback(err);
20976 } else {
20977 dbStore["delete"](name);
20978 callback();
20979 }
20980 });
20981 };
20982
20983 api._getRevisionTree = function (docId, callback) {
20984 stores.docStore.get(docId, function (err, metadata) {
20985 if (err) {
20986 callback(createError(MISSING_DOC));
20987 } else {
20988 callback(null, metadata.rev_tree);
20989 }
20990 });
20991 };
20992
20993 api._doCompaction = writeLock(function (docId, revs, opts, callback) {
20994 api._doCompactionNoLock(docId, revs, opts, callback);
20995 });
20996
20997 // the NoLock version is for use by bulkDocs
20998 api._doCompactionNoLock = function (docId, revs, opts, callback) {
20999 if (typeof opts === 'function') {
21000 callback = opts;
21001 opts = {};
21002 }
21003
21004 if (!revs.length) {
21005 return callback();
21006 }
21007 var txn = opts.ctx || new LevelTransaction();
21008
21009 txn.get(stores.docStore, docId, function (err, metadata) {
21010 /* istanbul ignore if */
21011 if (err) {
21012 return callback(err);
21013 }
21014 var seqs = revs.map(function (rev$$1) {
21015 var seq = metadata.rev_map[rev$$1];
21016 delete metadata.rev_map[rev$$1];
21017 return seq;
21018 });
21019 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
21020 revHash, ctx, opts) {
21021 var rev$$1 = pos + '-' + revHash;
21022 if (revs.indexOf(rev$$1) !== -1) {
21023 opts.status = 'missing';
21024 }
21025 });
21026
21027 var batch = [];
21028 batch.push({
21029 key: metadata.id,
21030 value: metadata,
21031 type: 'put',
21032 prefix: stores.docStore
21033 });
21034
21035 var digestMap = {};
21036 var numDone = 0;
21037 var overallErr;
21038 function checkDone(err) {
21039 /* istanbul ignore if */
21040 if (err) {
21041 overallErr = err;
21042 }
21043 if (++numDone === revs.length) { // done
21044 /* istanbul ignore if */
21045 if (overallErr) {
21046 return callback(overallErr);
21047 }
21048 deleteOrphanedAttachments();
21049 }
21050 }
21051
21052 function finish(err) {
21053 /* istanbul ignore if */
21054 if (err) {
21055 return callback(err);
21056 }
21057 txn.batch(batch);
21058 if (opts.ctx) {
21059 // don't execute immediately
21060 return callback();
21061 }
21062 txn.execute(db, callback);
21063 }
21064
21065 function deleteOrphanedAttachments() {
21066 var possiblyOrphanedAttachments = Object.keys(digestMap);
21067 if (!possiblyOrphanedAttachments.length) {
21068 return finish();
21069 }
21070 var numDone = 0;
21071 var overallErr;
21072 function checkDone(err) {
21073 /* istanbul ignore if */
21074 if (err) {
21075 overallErr = err;
21076 }
21077 if (++numDone === possiblyOrphanedAttachments.length) {
21078 finish(overallErr);
21079 }
21080 }
21081 var refsToDelete = new ExportedMap();
21082 revs.forEach(function (rev$$1) {
21083 refsToDelete.set(docId + '@' + rev$$1, true);
21084 });
21085 possiblyOrphanedAttachments.forEach(function (digest) {
21086 txn.get(stores.attachmentStore, digest, function (err, attData) {
21087 /* istanbul ignore if */
21088 if (err) {
21089 if (err.name === 'NotFoundError') {
21090 return checkDone();
21091 } else {
21092 return checkDone(err);
21093 }
21094 }
21095 var refs = Object.keys(attData.refs || {}).filter(function (ref) {
21096 return !refsToDelete.has(ref);
21097 });
21098 var newRefs = {};
21099 refs.forEach(function (ref) {
21100 newRefs[ref] = true;
21101 });
21102 if (refs.length) { // not orphaned
21103 batch.push({
21104 key: digest,
21105 type: 'put',
21106 value: {refs: newRefs},
21107 prefix: stores.attachmentStore
21108 });
21109 } else { // orphaned, can safely delete
21110 batch = batch.concat([{
21111 key: digest,
21112 type: 'del',
21113 prefix: stores.attachmentStore
21114 }, {
21115 key: digest,
21116 type: 'del',
21117 prefix: stores.binaryStore
21118 }]);
21119 }
21120 checkDone();
21121 });
21122 });
21123 }
21124
21125 seqs.forEach(function (seq) {
21126 batch.push({
21127 key: formatSeq(seq),
21128 type: 'del',
21129 prefix: stores.bySeqStore
21130 });
21131 txn.get(stores.bySeqStore, formatSeq(seq), function (err, doc) {
21132 /* istanbul ignore if */
21133 if (err) {
21134 if (err.name === 'NotFoundError') {
21135 return checkDone();
21136 } else {
21137 return checkDone(err);
21138 }
21139 }
21140 var atts = Object.keys(doc._attachments || {});
21141 atts.forEach(function (attName) {
21142 var digest = doc._attachments[attName].digest;
21143 digestMap[digest] = true;
21144 });
21145 checkDone();
21146 });
21147 });
21148 });
21149 };
21150
21151 api._getLocal = function (id, callback) {
21152 stores.localStore.get(id, function (err, doc) {
21153 if (err) {
21154 callback(createError(MISSING_DOC));
21155 } else {
21156 callback(null, doc);
21157 }
21158 });
21159 };
21160
21161 api._putLocal = function (doc, opts, callback) {
21162 if (typeof opts === 'function') {
21163 callback = opts;
21164 opts = {};
21165 }
21166 if (opts.ctx) {
21167 api._putLocalNoLock(doc, opts, callback);
21168 } else {
21169 api._putLocalWithLock(doc, opts, callback);
21170 }
21171 };
21172
21173 api._putLocalWithLock = writeLock(function (doc, opts, callback) {
21174 api._putLocalNoLock(doc, opts, callback);
21175 });
21176
21177 // the NoLock version is for use by bulkDocs
21178 api._putLocalNoLock = function (doc, opts, callback) {
21179 delete doc._revisions; // ignore this, trust the rev
21180 var oldRev = doc._rev;
21181 var id = doc._id;
21182
21183 var txn = opts.ctx || new LevelTransaction();
21184
21185 txn.get(stores.localStore, id, function (err, resp) {
21186 if (err && oldRev) {
21187 return callback(createError(REV_CONFLICT));
21188 }
21189 if (resp && resp._rev !== oldRev) {
21190 return callback(createError(REV_CONFLICT));
21191 }
21192 doc._rev =
21193 oldRev ? '0-' + (parseInt(oldRev.split('-')[1], 10) + 1) : '0-1';
21194 var batch = [
21195 {
21196 type: 'put',
21197 prefix: stores.localStore,
21198 key: id,
21199 value: doc
21200 }
21201 ];
21202
21203 txn.batch(batch);
21204 var ret = {ok: true, id: doc._id, rev: doc._rev};
21205
21206 if (opts.ctx) {
21207 // don't execute immediately
21208 return callback(null, ret);
21209 }
21210 txn.execute(db, function (err) {
21211 /* istanbul ignore if */
21212 if (err) {
21213 return callback(err);
21214 }
21215 callback(null, ret);
21216 });
21217 });
21218 };
21219
21220 api._removeLocal = function (doc, opts, callback) {
21221 if (typeof opts === 'function') {
21222 callback = opts;
21223 opts = {};
21224 }
21225 if (opts.ctx) {
21226 api._removeLocalNoLock(doc, opts, callback);
21227 } else {
21228 api._removeLocalWithLock(doc, opts, callback);
21229 }
21230 };
21231
21232 api._removeLocalWithLock = writeLock(function (doc, opts, callback) {
21233 api._removeLocalNoLock(doc, opts, callback);
21234 });
21235
21236 // the NoLock version is for use by bulkDocs
21237 api._removeLocalNoLock = function (doc, opts, callback) {
21238 var txn = opts.ctx || new LevelTransaction();
21239 txn.get(stores.localStore, doc._id, function (err, resp) {
21240 if (err) {
21241 /* istanbul ignore if */
21242 if (err.name !== 'NotFoundError') {
21243 return callback(err);
21244 } else {
21245 return callback(createError(MISSING_DOC));
21246 }
21247 }
21248 if (resp._rev !== doc._rev) {
21249 return callback(createError(REV_CONFLICT));
21250 }
21251 txn.batch([{
21252 prefix: stores.localStore,
21253 type: 'del',
21254 key: doc._id
21255 }]);
21256 var ret = {ok: true, id: doc._id, rev: '0-0'};
21257 if (opts.ctx) {
21258 // don't execute immediately
21259 return callback(null, ret);
21260 }
21261 txn.execute(db, function (err) {
21262 /* istanbul ignore if */
21263 if (err) {
21264 return callback(err);
21265 }
21266 callback(null, ret);
21267 });
21268 });
21269 };
21270
21271 // close and delete open leveldb stores
21272 api._destroy = function (opts, callback) {
21273 var dbStore;
21274 var leveldownName = functionName(leveldown);
21275 /* istanbul ignore else */
21276 if (dbStores.has(leveldownName)) {
21277 dbStore = dbStores.get(leveldownName);
21278 } else {
21279 return callDestroy(name, callback);
21280 }
21281
21282 /* istanbul ignore else */
21283 if (dbStore.has(name)) {
21284 levelChanges.removeAllListeners(name);
21285
21286 dbStore.get(name).close(function () {
21287 dbStore["delete"](name);
21288 callDestroy(name, callback);
21289 });
21290 } else {
21291 callDestroy(name, callback);
21292 }
21293 };
21294 function callDestroy(name, cb) {
21295 // May not exist if leveldown is backed by memory adapter
21296 /* istanbul ignore else */
21297 if ('destroy' in leveldown) {
21298 leveldown.destroy(name, cb);
21299 } else {
21300 cb(null);
21301 }
21302 }
21303}
21304
21305function MemDownPouch(opts, callback) {
21306 var _opts = $inject_Object_assign({
21307 db: memdown
21308 }, opts);
21309
21310 LevelPouch.call(this, _opts, callback);
21311}
21312
21313// overrides for normal LevelDB behavior on Node
21314MemDownPouch.valid = function () {
21315 return true;
21316};
21317MemDownPouch.use_prefix = false;
21318
21319function MemoryPouchPlugin (PouchDB) {
21320 PouchDB.adapter('memory', MemDownPouch, true);
21321}
21322
21323/* global PouchDB */
21324
21325if (typeof PouchDB === 'undefined') {
21326 guardedConsole('error', 'memory adapter plugin error: ' +
21327 'Cannot find global "PouchDB" object! ' +
21328 'Did you remember to include pouchdb.js?');
21329} else {
21330 PouchDB.plugin(MemoryPouchPlugin);
21331}
21332
21333}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
21334},{"1":1,"11":11,"114":114,"120":120,"125":125,"14":14,"17":17,"18":18,"21":21,"43":43,"52":52,"54":54,"78":78,"8":8,"80":80}]},{},[126]);
21335
\No newline at end of file