UNPKG

706 kBJavaScriptView Raw
1// PouchDB in-memory plugin 8.0.0
2// Based on MemDOWN: https://github.com/rvagg/memdown
3//
4// (c) 2012-2022 Dale Harvey and the PouchDB team
5// PouchDB may be freely distributed under the Apache license, version 2.0.
6// For all details and documentation:
7// http://pouchdb.com
8(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(_dereq_,module,exports){
9(function (global){(function (){
10'use strict';
11
12var objectAssign = _dereq_(64);
13
14// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
15// original notice:
16
17/*!
18 * The buffer module from node.js, for the browser.
19 *
20 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
21 * @license MIT
22 */
23function compare(a, b) {
24 if (a === b) {
25 return 0;
26 }
27
28 var x = a.length;
29 var y = b.length;
30
31 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
32 if (a[i] !== b[i]) {
33 x = a[i];
34 y = b[i];
35 break;
36 }
37 }
38
39 if (x < y) {
40 return -1;
41 }
42 if (y < x) {
43 return 1;
44 }
45 return 0;
46}
47function isBuffer(b) {
48 if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
49 return global.Buffer.isBuffer(b);
50 }
51 return !!(b != null && b._isBuffer);
52}
53
54// based on node assert, original notice:
55// NB: The URL to the CommonJS spec is kept just for tradition.
56// node-assert has evolved a lot since then, both in API and behavior.
57
58// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
59//
60// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
61//
62// Originally from narwhal.js (http://narwhaljs.org)
63// Copyright (c) 2009 Thomas Robinson <280north.com>
64//
65// Permission is hereby granted, free of charge, to any person obtaining a copy
66// of this software and associated documentation files (the 'Software'), to
67// deal in the Software without restriction, including without limitation the
68// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
69// sell copies of the Software, and to permit persons to whom the Software is
70// furnished to do so, subject to the following conditions:
71//
72// The above copyright notice and this permission notice shall be included in
73// all copies or substantial portions of the Software.
74//
75// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
76// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
77// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
78// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
79// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
80// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
81
82var util = _dereq_(4);
83var hasOwn = Object.prototype.hasOwnProperty;
84var pSlice = Array.prototype.slice;
85var functionsHaveNames = (function () {
86 return function foo() {}.name === 'foo';
87}());
88function pToString (obj) {
89 return Object.prototype.toString.call(obj);
90}
91function isView(arrbuf) {
92 if (isBuffer(arrbuf)) {
93 return false;
94 }
95 if (typeof global.ArrayBuffer !== 'function') {
96 return false;
97 }
98 if (typeof ArrayBuffer.isView === 'function') {
99 return ArrayBuffer.isView(arrbuf);
100 }
101 if (!arrbuf) {
102 return false;
103 }
104 if (arrbuf instanceof DataView) {
105 return true;
106 }
107 if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
108 return true;
109 }
110 return false;
111}
112// 1. The assert module provides functions that throw
113// AssertionError's when particular conditions are not met. The
114// assert module must conform to the following interface.
115
116var assert = module.exports = ok;
117
118// 2. The AssertionError is defined in assert.
119// new assert.AssertionError({ message: message,
120// actual: actual,
121// expected: expected })
122
123var regex = /\s*function\s+([^\(\s]*)\s*/;
124// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
125function getName(func) {
126 if (!util.isFunction(func)) {
127 return;
128 }
129 if (functionsHaveNames) {
130 return func.name;
131 }
132 var str = func.toString();
133 var match = str.match(regex);
134 return match && match[1];
135}
136assert.AssertionError = function AssertionError(options) {
137 this.name = 'AssertionError';
138 this.actual = options.actual;
139 this.expected = options.expected;
140 this.operator = options.operator;
141 if (options.message) {
142 this.message = options.message;
143 this.generatedMessage = false;
144 } else {
145 this.message = getMessage(this);
146 this.generatedMessage = true;
147 }
148 var stackStartFunction = options.stackStartFunction || fail;
149 if (Error.captureStackTrace) {
150 Error.captureStackTrace(this, stackStartFunction);
151 } else {
152 // non v8 browsers so we can have a stacktrace
153 var err = new Error();
154 if (err.stack) {
155 var out = err.stack;
156
157 // try to strip useless frames
158 var fn_name = getName(stackStartFunction);
159 var idx = out.indexOf('\n' + fn_name);
160 if (idx >= 0) {
161 // once we have located the function frame
162 // we need to strip out everything before it (and its line)
163 var next_line = out.indexOf('\n', idx + 1);
164 out = out.substring(next_line + 1);
165 }
166
167 this.stack = out;
168 }
169 }
170};
171
172// assert.AssertionError instanceof Error
173util.inherits(assert.AssertionError, Error);
174
175function truncate(s, n) {
176 if (typeof s === 'string') {
177 return s.length < n ? s : s.slice(0, n);
178 } else {
179 return s;
180 }
181}
182function inspect(something) {
183 if (functionsHaveNames || !util.isFunction(something)) {
184 return util.inspect(something);
185 }
186 var rawname = getName(something);
187 var name = rawname ? ': ' + rawname : '';
188 return '[Function' + name + ']';
189}
190function getMessage(self) {
191 return truncate(inspect(self.actual), 128) + ' ' +
192 self.operator + ' ' +
193 truncate(inspect(self.expected), 128);
194}
195
196// At present only the three keys mentioned above are used and
197// understood by the spec. Implementations or sub modules can pass
198// other keys to the AssertionError's constructor - they will be
199// ignored.
200
201// 3. All of the following functions must throw an AssertionError
202// when a corresponding condition is not met, with a message that
203// may be undefined if not provided. All assertion methods provide
204// both the actual and expected values to the assertion error for
205// display purposes.
206
207function fail(actual, expected, message, operator, stackStartFunction) {
208 throw new assert.AssertionError({
209 message: message,
210 actual: actual,
211 expected: expected,
212 operator: operator,
213 stackStartFunction: stackStartFunction
214 });
215}
216
217// EXTENSION! allows for well behaved errors defined elsewhere.
218assert.fail = fail;
219
220// 4. Pure assertion tests whether a value is truthy, as determined
221// by !!guard.
222// assert.ok(guard, message_opt);
223// This statement is equivalent to assert.equal(true, !!guard,
224// message_opt);. To test strictly for the value true, use
225// assert.strictEqual(true, guard, message_opt);.
226
227function ok(value, message) {
228 if (!value) fail(value, true, message, '==', assert.ok);
229}
230assert.ok = ok;
231
232// 5. The equality assertion tests shallow, coercive equality with
233// ==.
234// assert.equal(actual, expected, message_opt);
235
236assert.equal = function equal(actual, expected, message) {
237 if (actual != expected) fail(actual, expected, message, '==', assert.equal);
238};
239
240// 6. The non-equality assertion tests for whether two objects are not equal
241// with != assert.notEqual(actual, expected, message_opt);
242
243assert.notEqual = function notEqual(actual, expected, message) {
244 if (actual == expected) {
245 fail(actual, expected, message, '!=', assert.notEqual);
246 }
247};
248
249// 7. The equivalence assertion tests a deep equality relation.
250// assert.deepEqual(actual, expected, message_opt);
251
252assert.deepEqual = function deepEqual(actual, expected, message) {
253 if (!_deepEqual(actual, expected, false)) {
254 fail(actual, expected, message, 'deepEqual', assert.deepEqual);
255 }
256};
257
258assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
259 if (!_deepEqual(actual, expected, true)) {
260 fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
261 }
262};
263
264function _deepEqual(actual, expected, strict, memos) {
265 // 7.1. All identical values are equivalent, as determined by ===.
266 if (actual === expected) {
267 return true;
268 } else if (isBuffer(actual) && isBuffer(expected)) {
269 return compare(actual, expected) === 0;
270
271 // 7.2. If the expected value is a Date object, the actual value is
272 // equivalent if it is also a Date object that refers to the same time.
273 } else if (util.isDate(actual) && util.isDate(expected)) {
274 return actual.getTime() === expected.getTime();
275
276 // 7.3 If the expected value is a RegExp object, the actual value is
277 // equivalent if it is also a RegExp object with the same source and
278 // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
279 } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
280 return actual.source === expected.source &&
281 actual.global === expected.global &&
282 actual.multiline === expected.multiline &&
283 actual.lastIndex === expected.lastIndex &&
284 actual.ignoreCase === expected.ignoreCase;
285
286 // 7.4. Other pairs that do not both pass typeof value == 'object',
287 // equivalence is determined by ==.
288 } else if ((actual === null || typeof actual !== 'object') &&
289 (expected === null || typeof expected !== 'object')) {
290 return strict ? actual === expected : actual == expected;
291
292 // If both values are instances of typed arrays, wrap their underlying
293 // ArrayBuffers in a Buffer each to increase performance
294 // This optimization requires the arrays to have the same type as checked by
295 // Object.prototype.toString (aka pToString). Never perform binary
296 // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
297 // bit patterns are not identical.
298 } else if (isView(actual) && isView(expected) &&
299 pToString(actual) === pToString(expected) &&
300 !(actual instanceof Float32Array ||
301 actual instanceof Float64Array)) {
302 return compare(new Uint8Array(actual.buffer),
303 new Uint8Array(expected.buffer)) === 0;
304
305 // 7.5 For all other Object pairs, including Array objects, equivalence is
306 // determined by having the same number of owned properties (as verified
307 // with Object.prototype.hasOwnProperty.call), the same set of keys
308 // (although not necessarily the same order), equivalent values for every
309 // corresponding key, and an identical 'prototype' property. Note: this
310 // accounts for both named and indexed properties on Arrays.
311 } else if (isBuffer(actual) !== isBuffer(expected)) {
312 return false;
313 } else {
314 memos = memos || {actual: [], expected: []};
315
316 var actualIndex = memos.actual.indexOf(actual);
317 if (actualIndex !== -1) {
318 if (actualIndex === memos.expected.indexOf(expected)) {
319 return true;
320 }
321 }
322
323 memos.actual.push(actual);
324 memos.expected.push(expected);
325
326 return objEquiv(actual, expected, strict, memos);
327 }
328}
329
330function isArguments(object) {
331 return Object.prototype.toString.call(object) == '[object Arguments]';
332}
333
334function objEquiv(a, b, strict, actualVisitedObjects) {
335 if (a === null || a === undefined || b === null || b === undefined)
336 return false;
337 // if one is a primitive, the other must be same
338 if (util.isPrimitive(a) || util.isPrimitive(b))
339 return a === b;
340 if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
341 return false;
342 var aIsArgs = isArguments(a);
343 var bIsArgs = isArguments(b);
344 if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
345 return false;
346 if (aIsArgs) {
347 a = pSlice.call(a);
348 b = pSlice.call(b);
349 return _deepEqual(a, b, strict);
350 }
351 var ka = objectKeys(a);
352 var kb = objectKeys(b);
353 var key, i;
354 // having the same number of owned properties (keys incorporates
355 // hasOwnProperty)
356 if (ka.length !== kb.length)
357 return false;
358 //the same set of keys (although not necessarily the same order),
359 ka.sort();
360 kb.sort();
361 //~~~cheap key test
362 for (i = ka.length - 1; i >= 0; i--) {
363 if (ka[i] !== kb[i])
364 return false;
365 }
366 //equivalent values for every corresponding key, and
367 //~~~possibly expensive deep test
368 for (i = ka.length - 1; i >= 0; i--) {
369 key = ka[i];
370 if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
371 return false;
372 }
373 return true;
374}
375
376// 8. The non-equivalence assertion tests for any deep inequality.
377// assert.notDeepEqual(actual, expected, message_opt);
378
379assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
380 if (_deepEqual(actual, expected, false)) {
381 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
382 }
383};
384
385assert.notDeepStrictEqual = notDeepStrictEqual;
386function notDeepStrictEqual(actual, expected, message) {
387 if (_deepEqual(actual, expected, true)) {
388 fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
389 }
390}
391
392
393// 9. The strict equality assertion tests strict equality, as determined by ===.
394// assert.strictEqual(actual, expected, message_opt);
395
396assert.strictEqual = function strictEqual(actual, expected, message) {
397 if (actual !== expected) {
398 fail(actual, expected, message, '===', assert.strictEqual);
399 }
400};
401
402// 10. The strict non-equality assertion tests for strict inequality, as
403// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
404
405assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
406 if (actual === expected) {
407 fail(actual, expected, message, '!==', assert.notStrictEqual);
408 }
409};
410
411function expectedException(actual, expected) {
412 if (!actual || !expected) {
413 return false;
414 }
415
416 if (Object.prototype.toString.call(expected) == '[object RegExp]') {
417 return expected.test(actual);
418 }
419
420 try {
421 if (actual instanceof expected) {
422 return true;
423 }
424 } catch (e) {
425 // Ignore. The instanceof check doesn't work for arrow functions.
426 }
427
428 if (Error.isPrototypeOf(expected)) {
429 return false;
430 }
431
432 return expected.call({}, actual) === true;
433}
434
435function _tryBlock(block) {
436 var error;
437 try {
438 block();
439 } catch (e) {
440 error = e;
441 }
442 return error;
443}
444
445function _throws(shouldThrow, block, expected, message) {
446 var actual;
447
448 if (typeof block !== 'function') {
449 throw new TypeError('"block" argument must be a function');
450 }
451
452 if (typeof expected === 'string') {
453 message = expected;
454 expected = null;
455 }
456
457 actual = _tryBlock(block);
458
459 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
460 (message ? ' ' + message : '.');
461
462 if (shouldThrow && !actual) {
463 fail(actual, expected, 'Missing expected exception' + message);
464 }
465
466 var userProvidedMessage = typeof message === 'string';
467 var isUnwantedException = !shouldThrow && util.isError(actual);
468 var isUnexpectedException = !shouldThrow && actual && !expected;
469
470 if ((isUnwantedException &&
471 userProvidedMessage &&
472 expectedException(actual, expected)) ||
473 isUnexpectedException) {
474 fail(actual, expected, 'Got unwanted exception' + message);
475 }
476
477 if ((shouldThrow && actual && expected &&
478 !expectedException(actual, expected)) || (!shouldThrow && actual)) {
479 throw actual;
480 }
481}
482
483// 11. Expected to throw an error:
484// assert.throws(block, Error_opt, message_opt);
485
486assert.throws = function(block, /*optional*/error, /*optional*/message) {
487 _throws(true, block, error, message);
488};
489
490// EXTENSION! This is annoying to write outside this module.
491assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
492 _throws(false, block, error, message);
493};
494
495assert.ifError = function(err) { if (err) throw err; };
496
497// Expose a strict only variant of assert
498function strict(value, message) {
499 if (!value) fail(value, true, message, '==', strict);
500}
501assert.strict = objectAssign(strict, assert, {
502 equal: assert.strictEqual,
503 deepEqual: assert.deepStrictEqual,
504 notEqual: assert.notStrictEqual,
505 notDeepEqual: assert.notDeepStrictEqual
506});
507assert.strict.strict = assert.strict;
508
509var objectKeys = Object.keys || function (obj) {
510 var keys = [];
511 for (var key in obj) {
512 if (hasOwn.call(obj, key)) keys.push(key);
513 }
514 return keys;
515};
516
517}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
518},{"4":4,"64":64}],2:[function(_dereq_,module,exports){
519if (typeof Object.create === 'function') {
520 // implementation from standard node.js 'util' module
521 module.exports = function inherits(ctor, superCtor) {
522 ctor.super_ = superCtor
523 ctor.prototype = Object.create(superCtor.prototype, {
524 constructor: {
525 value: ctor,
526 enumerable: false,
527 writable: true,
528 configurable: true
529 }
530 });
531 };
532} else {
533 // old school shim for old browsers
534 module.exports = function inherits(ctor, superCtor) {
535 ctor.super_ = superCtor
536 var TempCtor = function () {}
537 TempCtor.prototype = superCtor.prototype
538 ctor.prototype = new TempCtor()
539 ctor.prototype.constructor = ctor
540 }
541}
542
543},{}],3:[function(_dereq_,module,exports){
544module.exports = function isBuffer(arg) {
545 return arg && typeof arg === 'object'
546 && typeof arg.copy === 'function'
547 && typeof arg.fill === 'function'
548 && typeof arg.readUInt8 === 'function';
549}
550},{}],4:[function(_dereq_,module,exports){
551(function (process,global){(function (){
552// Copyright Joyent, Inc. and other Node contributors.
553//
554// Permission is hereby granted, free of charge, to any person obtaining a
555// copy of this software and associated documentation files (the
556// "Software"), to deal in the Software without restriction, including
557// without limitation the rights to use, copy, modify, merge, publish,
558// distribute, sublicense, and/or sell copies of the Software, and to permit
559// persons to whom the Software is furnished to do so, subject to the
560// following conditions:
561//
562// The above copyright notice and this permission notice shall be included
563// in all copies or substantial portions of the Software.
564//
565// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
566// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
567// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
568// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
569// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
570// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
571// USE OR OTHER DEALINGS IN THE SOFTWARE.
572
573var formatRegExp = /%[sdj%]/g;
574exports.format = function(f) {
575 if (!isString(f)) {
576 var objects = [];
577 for (var i = 0; i < arguments.length; i++) {
578 objects.push(inspect(arguments[i]));
579 }
580 return objects.join(' ');
581 }
582
583 var i = 1;
584 var args = arguments;
585 var len = args.length;
586 var str = String(f).replace(formatRegExp, function(x) {
587 if (x === '%%') return '%';
588 if (i >= len) return x;
589 switch (x) {
590 case '%s': return String(args[i++]);
591 case '%d': return Number(args[i++]);
592 case '%j':
593 try {
594 return JSON.stringify(args[i++]);
595 } catch (_) {
596 return '[Circular]';
597 }
598 default:
599 return x;
600 }
601 });
602 for (var x = args[i]; i < len; x = args[++i]) {
603 if (isNull(x) || !isObject(x)) {
604 str += ' ' + x;
605 } else {
606 str += ' ' + inspect(x);
607 }
608 }
609 return str;
610};
611
612
613// Mark that a method should not be used.
614// Returns a modified function which warns once by default.
615// If --no-deprecation is set, then it is a no-op.
616exports.deprecate = function(fn, msg) {
617 // Allow for deprecating things in the process of starting up.
618 if (isUndefined(global.process)) {
619 return function() {
620 return exports.deprecate(fn, msg).apply(this, arguments);
621 };
622 }
623
624 if (process.noDeprecation === true) {
625 return fn;
626 }
627
628 var warned = false;
629 function deprecated() {
630 if (!warned) {
631 if (process.throwDeprecation) {
632 throw new Error(msg);
633 } else if (process.traceDeprecation) {
634 console.trace(msg);
635 } else {
636 console.error(msg);
637 }
638 warned = true;
639 }
640 return fn.apply(this, arguments);
641 }
642
643 return deprecated;
644};
645
646
647var debugs = {};
648var debugEnviron;
649exports.debuglog = function(set) {
650 if (isUndefined(debugEnviron))
651 debugEnviron = process.env.NODE_DEBUG || '';
652 set = set.toUpperCase();
653 if (!debugs[set]) {
654 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
655 var pid = process.pid;
656 debugs[set] = function() {
657 var msg = exports.format.apply(exports, arguments);
658 console.error('%s %d: %s', set, pid, msg);
659 };
660 } else {
661 debugs[set] = function() {};
662 }
663 }
664 return debugs[set];
665};
666
667
668/**
669 * Echos the value of a value. Trys to print the value out
670 * in the best way possible given the different types.
671 *
672 * @param {Object} obj The object to print out.
673 * @param {Object} opts Optional options object that alters the output.
674 */
675/* legacy: obj, showHidden, depth, colors*/
676function inspect(obj, opts) {
677 // default options
678 var ctx = {
679 seen: [],
680 stylize: stylizeNoColor
681 };
682 // legacy...
683 if (arguments.length >= 3) ctx.depth = arguments[2];
684 if (arguments.length >= 4) ctx.colors = arguments[3];
685 if (isBoolean(opts)) {
686 // legacy...
687 ctx.showHidden = opts;
688 } else if (opts) {
689 // got an "options" object
690 exports._extend(ctx, opts);
691 }
692 // set default options
693 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
694 if (isUndefined(ctx.depth)) ctx.depth = 2;
695 if (isUndefined(ctx.colors)) ctx.colors = false;
696 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
697 if (ctx.colors) ctx.stylize = stylizeWithColor;
698 return formatValue(ctx, obj, ctx.depth);
699}
700exports.inspect = inspect;
701
702
703// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
704inspect.colors = {
705 'bold' : [1, 22],
706 'italic' : [3, 23],
707 'underline' : [4, 24],
708 'inverse' : [7, 27],
709 'white' : [37, 39],
710 'grey' : [90, 39],
711 'black' : [30, 39],
712 'blue' : [34, 39],
713 'cyan' : [36, 39],
714 'green' : [32, 39],
715 'magenta' : [35, 39],
716 'red' : [31, 39],
717 'yellow' : [33, 39]
718};
719
720// Don't use 'blue' not visible on cmd.exe
721inspect.styles = {
722 'special': 'cyan',
723 'number': 'yellow',
724 'boolean': 'yellow',
725 'undefined': 'grey',
726 'null': 'bold',
727 'string': 'green',
728 'date': 'magenta',
729 // "name": intentionally not styling
730 'regexp': 'red'
731};
732
733
734function stylizeWithColor(str, styleType) {
735 var style = inspect.styles[styleType];
736
737 if (style) {
738 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
739 '\u001b[' + inspect.colors[style][1] + 'm';
740 } else {
741 return str;
742 }
743}
744
745
746function stylizeNoColor(str, styleType) {
747 return str;
748}
749
750
751function arrayToHash(array) {
752 var hash = {};
753
754 array.forEach(function(val, idx) {
755 hash[val] = true;
756 });
757
758 return hash;
759}
760
761
762function formatValue(ctx, value, recurseTimes) {
763 // Provide a hook for user-specified inspect functions.
764 // Check that value is an object with an inspect function on it
765 if (ctx.customInspect &&
766 value &&
767 isFunction(value.inspect) &&
768 // Filter out the util module, it's inspect function is special
769 value.inspect !== exports.inspect &&
770 // Also filter out any prototype objects using the circular check.
771 !(value.constructor && value.constructor.prototype === value)) {
772 var ret = value.inspect(recurseTimes, ctx);
773 if (!isString(ret)) {
774 ret = formatValue(ctx, ret, recurseTimes);
775 }
776 return ret;
777 }
778
779 // Primitive types cannot have properties
780 var primitive = formatPrimitive(ctx, value);
781 if (primitive) {
782 return primitive;
783 }
784
785 // Look up the keys of the object.
786 var keys = Object.keys(value);
787 var visibleKeys = arrayToHash(keys);
788
789 if (ctx.showHidden) {
790 keys = Object.getOwnPropertyNames(value);
791 }
792
793 // IE doesn't make error fields non-enumerable
794 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
795 if (isError(value)
796 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
797 return formatError(value);
798 }
799
800 // Some type of object without properties can be shortcutted.
801 if (keys.length === 0) {
802 if (isFunction(value)) {
803 var name = value.name ? ': ' + value.name : '';
804 return ctx.stylize('[Function' + name + ']', 'special');
805 }
806 if (isRegExp(value)) {
807 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
808 }
809 if (isDate(value)) {
810 return ctx.stylize(Date.prototype.toString.call(value), 'date');
811 }
812 if (isError(value)) {
813 return formatError(value);
814 }
815 }
816
817 var base = '', array = false, braces = ['{', '}'];
818
819 // Make Array say that they are Array
820 if (isArray(value)) {
821 array = true;
822 braces = ['[', ']'];
823 }
824
825 // Make functions say that they are functions
826 if (isFunction(value)) {
827 var n = value.name ? ': ' + value.name : '';
828 base = ' [Function' + n + ']';
829 }
830
831 // Make RegExps say that they are RegExps
832 if (isRegExp(value)) {
833 base = ' ' + RegExp.prototype.toString.call(value);
834 }
835
836 // Make dates with properties first say the date
837 if (isDate(value)) {
838 base = ' ' + Date.prototype.toUTCString.call(value);
839 }
840
841 // Make error with message first say the error
842 if (isError(value)) {
843 base = ' ' + formatError(value);
844 }
845
846 if (keys.length === 0 && (!array || value.length == 0)) {
847 return braces[0] + base + braces[1];
848 }
849
850 if (recurseTimes < 0) {
851 if (isRegExp(value)) {
852 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
853 } else {
854 return ctx.stylize('[Object]', 'special');
855 }
856 }
857
858 ctx.seen.push(value);
859
860 var output;
861 if (array) {
862 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
863 } else {
864 output = keys.map(function(key) {
865 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
866 });
867 }
868
869 ctx.seen.pop();
870
871 return reduceToSingleString(output, base, braces);
872}
873
874
875function formatPrimitive(ctx, value) {
876 if (isUndefined(value))
877 return ctx.stylize('undefined', 'undefined');
878 if (isString(value)) {
879 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
880 .replace(/'/g, "\\'")
881 .replace(/\\"/g, '"') + '\'';
882 return ctx.stylize(simple, 'string');
883 }
884 if (isNumber(value))
885 return ctx.stylize('' + value, 'number');
886 if (isBoolean(value))
887 return ctx.stylize('' + value, 'boolean');
888 // For some reason typeof null is "object", so special case here.
889 if (isNull(value))
890 return ctx.stylize('null', 'null');
891}
892
893
894function formatError(value) {
895 return '[' + Error.prototype.toString.call(value) + ']';
896}
897
898
899function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
900 var output = [];
901 for (var i = 0, l = value.length; i < l; ++i) {
902 if (hasOwnProperty(value, String(i))) {
903 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
904 String(i), true));
905 } else {
906 output.push('');
907 }
908 }
909 keys.forEach(function(key) {
910 if (!key.match(/^\d+$/)) {
911 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
912 key, true));
913 }
914 });
915 return output;
916}
917
918
919function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
920 var name, str, desc;
921 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
922 if (desc.get) {
923 if (desc.set) {
924 str = ctx.stylize('[Getter/Setter]', 'special');
925 } else {
926 str = ctx.stylize('[Getter]', 'special');
927 }
928 } else {
929 if (desc.set) {
930 str = ctx.stylize('[Setter]', 'special');
931 }
932 }
933 if (!hasOwnProperty(visibleKeys, key)) {
934 name = '[' + key + ']';
935 }
936 if (!str) {
937 if (ctx.seen.indexOf(desc.value) < 0) {
938 if (isNull(recurseTimes)) {
939 str = formatValue(ctx, desc.value, null);
940 } else {
941 str = formatValue(ctx, desc.value, recurseTimes - 1);
942 }
943 if (str.indexOf('\n') > -1) {
944 if (array) {
945 str = str.split('\n').map(function(line) {
946 return ' ' + line;
947 }).join('\n').substr(2);
948 } else {
949 str = '\n' + str.split('\n').map(function(line) {
950 return ' ' + line;
951 }).join('\n');
952 }
953 }
954 } else {
955 str = ctx.stylize('[Circular]', 'special');
956 }
957 }
958 if (isUndefined(name)) {
959 if (array && key.match(/^\d+$/)) {
960 return str;
961 }
962 name = JSON.stringify('' + key);
963 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
964 name = name.substr(1, name.length - 2);
965 name = ctx.stylize(name, 'name');
966 } else {
967 name = name.replace(/'/g, "\\'")
968 .replace(/\\"/g, '"')
969 .replace(/(^"|"$)/g, "'");
970 name = ctx.stylize(name, 'string');
971 }
972 }
973
974 return name + ': ' + str;
975}
976
977
978function reduceToSingleString(output, base, braces) {
979 var numLinesEst = 0;
980 var length = output.reduce(function(prev, cur) {
981 numLinesEst++;
982 if (cur.indexOf('\n') >= 0) numLinesEst++;
983 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
984 }, 0);
985
986 if (length > 60) {
987 return braces[0] +
988 (base === '' ? '' : base + '\n ') +
989 ' ' +
990 output.join(',\n ') +
991 ' ' +
992 braces[1];
993 }
994
995 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
996}
997
998
999// NOTE: These type checking functions intentionally don't use `instanceof`
1000// because it is fragile and can be easily faked with `Object.create()`.
1001function isArray(ar) {
1002 return Array.isArray(ar);
1003}
1004exports.isArray = isArray;
1005
1006function isBoolean(arg) {
1007 return typeof arg === 'boolean';
1008}
1009exports.isBoolean = isBoolean;
1010
1011function isNull(arg) {
1012 return arg === null;
1013}
1014exports.isNull = isNull;
1015
1016function isNullOrUndefined(arg) {
1017 return arg == null;
1018}
1019exports.isNullOrUndefined = isNullOrUndefined;
1020
1021function isNumber(arg) {
1022 return typeof arg === 'number';
1023}
1024exports.isNumber = isNumber;
1025
1026function isString(arg) {
1027 return typeof arg === 'string';
1028}
1029exports.isString = isString;
1030
1031function isSymbol(arg) {
1032 return typeof arg === 'symbol';
1033}
1034exports.isSymbol = isSymbol;
1035
1036function isUndefined(arg) {
1037 return arg === void 0;
1038}
1039exports.isUndefined = isUndefined;
1040
1041function isRegExp(re) {
1042 return isObject(re) && objectToString(re) === '[object RegExp]';
1043}
1044exports.isRegExp = isRegExp;
1045
1046function isObject(arg) {
1047 return typeof arg === 'object' && arg !== null;
1048}
1049exports.isObject = isObject;
1050
1051function isDate(d) {
1052 return isObject(d) && objectToString(d) === '[object Date]';
1053}
1054exports.isDate = isDate;
1055
1056function isError(e) {
1057 return isObject(e) &&
1058 (objectToString(e) === '[object Error]' || e instanceof Error);
1059}
1060exports.isError = isError;
1061
1062function isFunction(arg) {
1063 return typeof arg === 'function';
1064}
1065exports.isFunction = isFunction;
1066
1067function isPrimitive(arg) {
1068 return arg === null ||
1069 typeof arg === 'boolean' ||
1070 typeof arg === 'number' ||
1071 typeof arg === 'string' ||
1072 typeof arg === 'symbol' || // ES6 symbol
1073 typeof arg === 'undefined';
1074}
1075exports.isPrimitive = isPrimitive;
1076
1077exports.isBuffer = _dereq_(3);
1078
1079function objectToString(o) {
1080 return Object.prototype.toString.call(o);
1081}
1082
1083
1084function pad(n) {
1085 return n < 10 ? '0' + n.toString(10) : n.toString(10);
1086}
1087
1088
1089var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
1090 'Oct', 'Nov', 'Dec'];
1091
1092// 26 Feb 16:19:34
1093function timestamp() {
1094 var d = new Date();
1095 var time = [pad(d.getHours()),
1096 pad(d.getMinutes()),
1097 pad(d.getSeconds())].join(':');
1098 return [d.getDate(), months[d.getMonth()], time].join(' ');
1099}
1100
1101
1102// log is just a thin wrapper to console.log that prepends a timestamp
1103exports.log = function() {
1104 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
1105};
1106
1107
1108/**
1109 * Inherit the prototype methods from one constructor into another.
1110 *
1111 * The Function.prototype.inherits from lang.js rewritten as a standalone
1112 * function (not on Function.prototype). NOTE: If this file is to be loaded
1113 * during bootstrapping this function needs to be rewritten using some native
1114 * functions as prototype setup using normal JavaScript does not work as
1115 * expected during bootstrapping (see mirror.js in r114903).
1116 *
1117 * @param {function} ctor Constructor function which needs to inherit the
1118 * prototype.
1119 * @param {function} superCtor Constructor function to inherit prototype from.
1120 */
1121exports.inherits = _dereq_(2);
1122
1123exports._extend = function(origin, add) {
1124 // Don't do anything if add isn't an object
1125 if (!add || !isObject(add)) return origin;
1126
1127 var keys = Object.keys(add);
1128 var i = keys.length;
1129 while (i--) {
1130 origin[keys[i]] = add[keys[i]];
1131 }
1132 return origin;
1133};
1134
1135function hasOwnProperty(obj, prop) {
1136 return Object.prototype.hasOwnProperty.call(obj, prop);
1137}
1138
1139}).call(this)}).call(this,_dereq_(66),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
1140},{"2":2,"3":3,"66":66}],5:[function(_dereq_,module,exports){
1141'use strict'
1142
1143exports.byteLength = byteLength
1144exports.toByteArray = toByteArray
1145exports.fromByteArray = fromByteArray
1146
1147var lookup = []
1148var revLookup = []
1149var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
1150
1151var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
1152for (var i = 0, len = code.length; i < len; ++i) {
1153 lookup[i] = code[i]
1154 revLookup[code.charCodeAt(i)] = i
1155}
1156
1157// Support decoding URL-safe base64 strings, as Node.js does.
1158// See: https://en.wikipedia.org/wiki/Base64#URL_applications
1159revLookup['-'.charCodeAt(0)] = 62
1160revLookup['_'.charCodeAt(0)] = 63
1161
1162function getLens (b64) {
1163 var len = b64.length
1164
1165 if (len % 4 > 0) {
1166 throw new Error('Invalid string. Length must be a multiple of 4')
1167 }
1168
1169 // Trim off extra bytes after placeholder bytes are found
1170 // See: https://github.com/beatgammit/base64-js/issues/42
1171 var validLen = b64.indexOf('=')
1172 if (validLen === -1) validLen = len
1173
1174 var placeHoldersLen = validLen === len
1175 ? 0
1176 : 4 - (validLen % 4)
1177
1178 return [validLen, placeHoldersLen]
1179}
1180
1181// base64 is 4/3 + up to two characters of the original data
1182function byteLength (b64) {
1183 var lens = getLens(b64)
1184 var validLen = lens[0]
1185 var placeHoldersLen = lens[1]
1186 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
1187}
1188
1189function _byteLength (b64, validLen, placeHoldersLen) {
1190 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
1191}
1192
1193function toByteArray (b64) {
1194 var tmp
1195 var lens = getLens(b64)
1196 var validLen = lens[0]
1197 var placeHoldersLen = lens[1]
1198
1199 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
1200
1201 var curByte = 0
1202
1203 // if there are placeholders, only get up to the last complete 4 chars
1204 var len = placeHoldersLen > 0
1205 ? validLen - 4
1206 : validLen
1207
1208 var i
1209 for (i = 0; i < len; i += 4) {
1210 tmp =
1211 (revLookup[b64.charCodeAt(i)] << 18) |
1212 (revLookup[b64.charCodeAt(i + 1)] << 12) |
1213 (revLookup[b64.charCodeAt(i + 2)] << 6) |
1214 revLookup[b64.charCodeAt(i + 3)]
1215 arr[curByte++] = (tmp >> 16) & 0xFF
1216 arr[curByte++] = (tmp >> 8) & 0xFF
1217 arr[curByte++] = tmp & 0xFF
1218 }
1219
1220 if (placeHoldersLen === 2) {
1221 tmp =
1222 (revLookup[b64.charCodeAt(i)] << 2) |
1223 (revLookup[b64.charCodeAt(i + 1)] >> 4)
1224 arr[curByte++] = tmp & 0xFF
1225 }
1226
1227 if (placeHoldersLen === 1) {
1228 tmp =
1229 (revLookup[b64.charCodeAt(i)] << 10) |
1230 (revLookup[b64.charCodeAt(i + 1)] << 4) |
1231 (revLookup[b64.charCodeAt(i + 2)] >> 2)
1232 arr[curByte++] = (tmp >> 8) & 0xFF
1233 arr[curByte++] = tmp & 0xFF
1234 }
1235
1236 return arr
1237}
1238
1239function tripletToBase64 (num) {
1240 return lookup[num >> 18 & 0x3F] +
1241 lookup[num >> 12 & 0x3F] +
1242 lookup[num >> 6 & 0x3F] +
1243 lookup[num & 0x3F]
1244}
1245
1246function encodeChunk (uint8, start, end) {
1247 var tmp
1248 var output = []
1249 for (var i = start; i < end; i += 3) {
1250 tmp =
1251 ((uint8[i] << 16) & 0xFF0000) +
1252 ((uint8[i + 1] << 8) & 0xFF00) +
1253 (uint8[i + 2] & 0xFF)
1254 output.push(tripletToBase64(tmp))
1255 }
1256 return output.join('')
1257}
1258
1259function fromByteArray (uint8) {
1260 var tmp
1261 var len = uint8.length
1262 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
1263 var parts = []
1264 var maxChunkLength = 16383 // must be multiple of 3
1265
1266 // go through the array every three bytes, we'll deal with trailing stuff later
1267 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
1268 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
1269 }
1270
1271 // pad the end with zeros, but make sure to not forget the extra bytes
1272 if (extraBytes === 1) {
1273 tmp = uint8[len - 1]
1274 parts.push(
1275 lookup[tmp >> 2] +
1276 lookup[(tmp << 4) & 0x3F] +
1277 '=='
1278 )
1279 } else if (extraBytes === 2) {
1280 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
1281 parts.push(
1282 lookup[tmp >> 10] +
1283 lookup[(tmp >> 4) & 0x3F] +
1284 lookup[(tmp << 2) & 0x3F] +
1285 '='
1286 )
1287 }
1288
1289 return parts.join('')
1290}
1291
1292},{}],6:[function(_dereq_,module,exports){
1293
1294},{}],7:[function(_dereq_,module,exports){
1295(function (Buffer){(function (){
1296/* eslint-disable node/no-deprecated-api */
1297
1298var toString = Object.prototype.toString
1299
1300var isModern = (
1301 typeof Buffer !== 'undefined' &&
1302 typeof Buffer.alloc === 'function' &&
1303 typeof Buffer.allocUnsafe === 'function' &&
1304 typeof Buffer.from === 'function'
1305)
1306
1307function isArrayBuffer (input) {
1308 return toString.call(input).slice(8, -1) === 'ArrayBuffer'
1309}
1310
1311function fromArrayBuffer (obj, byteOffset, length) {
1312 byteOffset >>>= 0
1313
1314 var maxLength = obj.byteLength - byteOffset
1315
1316 if (maxLength < 0) {
1317 throw new RangeError("'offset' is out of bounds")
1318 }
1319
1320 if (length === undefined) {
1321 length = maxLength
1322 } else {
1323 length >>>= 0
1324
1325 if (length > maxLength) {
1326 throw new RangeError("'length' is out of bounds")
1327 }
1328 }
1329
1330 return isModern
1331 ? Buffer.from(obj.slice(byteOffset, byteOffset + length))
1332 : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
1333}
1334
1335function fromString (string, encoding) {
1336 if (typeof encoding !== 'string' || encoding === '') {
1337 encoding = 'utf8'
1338 }
1339
1340 if (!Buffer.isEncoding(encoding)) {
1341 throw new TypeError('"encoding" must be a valid string encoding')
1342 }
1343
1344 return isModern
1345 ? Buffer.from(string, encoding)
1346 : new Buffer(string, encoding)
1347}
1348
1349function bufferFrom (value, encodingOrOffset, length) {
1350 if (typeof value === 'number') {
1351 throw new TypeError('"value" argument must not be a number')
1352 }
1353
1354 if (isArrayBuffer(value)) {
1355 return fromArrayBuffer(value, encodingOrOffset, length)
1356 }
1357
1358 if (typeof value === 'string') {
1359 return fromString(value, encodingOrOffset)
1360 }
1361
1362 return isModern
1363 ? Buffer.from(value)
1364 : new Buffer(value)
1365}
1366
1367module.exports = bufferFrom
1368
1369}).call(this)}).call(this,_dereq_(8).Buffer)
1370},{"8":8}],8:[function(_dereq_,module,exports){
1371(function (Buffer){(function (){
1372/*!
1373 * The buffer module from node.js, for the browser.
1374 *
1375 * @author Feross Aboukhadijeh <https://feross.org>
1376 * @license MIT
1377 */
1378/* eslint-disable no-proto */
1379
1380'use strict'
1381
1382var base64 = _dereq_(5)
1383var ieee754 = _dereq_(22)
1384var customInspectSymbol =
1385 (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation
1386 ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation
1387 : null
1388
1389exports.Buffer = Buffer
1390exports.SlowBuffer = SlowBuffer
1391exports.INSPECT_MAX_BYTES = 50
1392
1393var K_MAX_LENGTH = 0x7fffffff
1394exports.kMaxLength = K_MAX_LENGTH
1395
1396/**
1397 * If `Buffer.TYPED_ARRAY_SUPPORT`:
1398 * === true Use Uint8Array implementation (fastest)
1399 * === false Print warning and recommend using `buffer` v4.x which has an Object
1400 * implementation (most compatible, even IE6)
1401 *
1402 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
1403 * Opera 11.6+, iOS 4.2+.
1404 *
1405 * We report that the browser does not support typed arrays if the are not subclassable
1406 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
1407 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
1408 * for __proto__ and has a buggy typed array implementation.
1409 */
1410Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
1411
1412if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
1413 typeof console.error === 'function') {
1414 console.error(
1415 'This browser lacks typed array (Uint8Array) support which is required by ' +
1416 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
1417 )
1418}
1419
1420function typedArraySupport () {
1421 // Can typed array instances can be augmented?
1422 try {
1423 var arr = new Uint8Array(1)
1424 var proto = { foo: function () { return 42 } }
1425 Object.setPrototypeOf(proto, Uint8Array.prototype)
1426 Object.setPrototypeOf(arr, proto)
1427 return arr.foo() === 42
1428 } catch (e) {
1429 return false
1430 }
1431}
1432
1433Object.defineProperty(Buffer.prototype, 'parent', {
1434 enumerable: true,
1435 get: function () {
1436 if (!Buffer.isBuffer(this)) return undefined
1437 return this.buffer
1438 }
1439})
1440
1441Object.defineProperty(Buffer.prototype, 'offset', {
1442 enumerable: true,
1443 get: function () {
1444 if (!Buffer.isBuffer(this)) return undefined
1445 return this.byteOffset
1446 }
1447})
1448
1449function createBuffer (length) {
1450 if (length > K_MAX_LENGTH) {
1451 throw new RangeError('The value "' + length + '" is invalid for option "size"')
1452 }
1453 // Return an augmented `Uint8Array` instance
1454 var buf = new Uint8Array(length)
1455 Object.setPrototypeOf(buf, Buffer.prototype)
1456 return buf
1457}
1458
1459/**
1460 * The Buffer constructor returns instances of `Uint8Array` that have their
1461 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
1462 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
1463 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
1464 * returns a single octet.
1465 *
1466 * The `Uint8Array` prototype remains unmodified.
1467 */
1468
1469function Buffer (arg, encodingOrOffset, length) {
1470 // Common case.
1471 if (typeof arg === 'number') {
1472 if (typeof encodingOrOffset === 'string') {
1473 throw new TypeError(
1474 'The "string" argument must be of type string. Received type number'
1475 )
1476 }
1477 return allocUnsafe(arg)
1478 }
1479 return from(arg, encodingOrOffset, length)
1480}
1481
1482Buffer.poolSize = 8192 // not used by this implementation
1483
1484function from (value, encodingOrOffset, length) {
1485 if (typeof value === 'string') {
1486 return fromString(value, encodingOrOffset)
1487 }
1488
1489 if (ArrayBuffer.isView(value)) {
1490 return fromArrayView(value)
1491 }
1492
1493 if (value == null) {
1494 throw new TypeError(
1495 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
1496 'or Array-like Object. Received type ' + (typeof value)
1497 )
1498 }
1499
1500 if (isInstance(value, ArrayBuffer) ||
1501 (value && isInstance(value.buffer, ArrayBuffer))) {
1502 return fromArrayBuffer(value, encodingOrOffset, length)
1503 }
1504
1505 if (typeof SharedArrayBuffer !== 'undefined' &&
1506 (isInstance(value, SharedArrayBuffer) ||
1507 (value && isInstance(value.buffer, SharedArrayBuffer)))) {
1508 return fromArrayBuffer(value, encodingOrOffset, length)
1509 }
1510
1511 if (typeof value === 'number') {
1512 throw new TypeError(
1513 'The "value" argument must not be of type number. Received type number'
1514 )
1515 }
1516
1517 var valueOf = value.valueOf && value.valueOf()
1518 if (valueOf != null && valueOf !== value) {
1519 return Buffer.from(valueOf, encodingOrOffset, length)
1520 }
1521
1522 var b = fromObject(value)
1523 if (b) return b
1524
1525 if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
1526 typeof value[Symbol.toPrimitive] === 'function') {
1527 return Buffer.from(
1528 value[Symbol.toPrimitive]('string'), encodingOrOffset, length
1529 )
1530 }
1531
1532 throw new TypeError(
1533 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
1534 'or Array-like Object. Received type ' + (typeof value)
1535 )
1536}
1537
1538/**
1539 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
1540 * if value is a number.
1541 * Buffer.from(str[, encoding])
1542 * Buffer.from(array)
1543 * Buffer.from(buffer)
1544 * Buffer.from(arrayBuffer[, byteOffset[, length]])
1545 **/
1546Buffer.from = function (value, encodingOrOffset, length) {
1547 return from(value, encodingOrOffset, length)
1548}
1549
1550// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
1551// https://github.com/feross/buffer/pull/148
1552Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)
1553Object.setPrototypeOf(Buffer, Uint8Array)
1554
1555function assertSize (size) {
1556 if (typeof size !== 'number') {
1557 throw new TypeError('"size" argument must be of type number')
1558 } else if (size < 0) {
1559 throw new RangeError('The value "' + size + '" is invalid for option "size"')
1560 }
1561}
1562
1563function alloc (size, fill, encoding) {
1564 assertSize(size)
1565 if (size <= 0) {
1566 return createBuffer(size)
1567 }
1568 if (fill !== undefined) {
1569 // Only pay attention to encoding if it's a string. This
1570 // prevents accidentally sending in a number that would
1571 // be interpreted as a start offset.
1572 return typeof encoding === 'string'
1573 ? createBuffer(size).fill(fill, encoding)
1574 : createBuffer(size).fill(fill)
1575 }
1576 return createBuffer(size)
1577}
1578
1579/**
1580 * Creates a new filled Buffer instance.
1581 * alloc(size[, fill[, encoding]])
1582 **/
1583Buffer.alloc = function (size, fill, encoding) {
1584 return alloc(size, fill, encoding)
1585}
1586
1587function allocUnsafe (size) {
1588 assertSize(size)
1589 return createBuffer(size < 0 ? 0 : checked(size) | 0)
1590}
1591
1592/**
1593 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
1594 * */
1595Buffer.allocUnsafe = function (size) {
1596 return allocUnsafe(size)
1597}
1598/**
1599 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
1600 */
1601Buffer.allocUnsafeSlow = function (size) {
1602 return allocUnsafe(size)
1603}
1604
1605function fromString (string, encoding) {
1606 if (typeof encoding !== 'string' || encoding === '') {
1607 encoding = 'utf8'
1608 }
1609
1610 if (!Buffer.isEncoding(encoding)) {
1611 throw new TypeError('Unknown encoding: ' + encoding)
1612 }
1613
1614 var length = byteLength(string, encoding) | 0
1615 var buf = createBuffer(length)
1616
1617 var actual = buf.write(string, encoding)
1618
1619 if (actual !== length) {
1620 // Writing a hex string, for example, that contains invalid characters will
1621 // cause everything after the first invalid character to be ignored. (e.g.
1622 // 'abxxcd' will be treated as 'ab')
1623 buf = buf.slice(0, actual)
1624 }
1625
1626 return buf
1627}
1628
1629function fromArrayLike (array) {
1630 var length = array.length < 0 ? 0 : checked(array.length) | 0
1631 var buf = createBuffer(length)
1632 for (var i = 0; i < length; i += 1) {
1633 buf[i] = array[i] & 255
1634 }
1635 return buf
1636}
1637
1638function fromArrayView (arrayView) {
1639 if (isInstance(arrayView, Uint8Array)) {
1640 var copy = new Uint8Array(arrayView)
1641 return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)
1642 }
1643 return fromArrayLike(arrayView)
1644}
1645
1646function fromArrayBuffer (array, byteOffset, length) {
1647 if (byteOffset < 0 || array.byteLength < byteOffset) {
1648 throw new RangeError('"offset" is outside of buffer bounds')
1649 }
1650
1651 if (array.byteLength < byteOffset + (length || 0)) {
1652 throw new RangeError('"length" is outside of buffer bounds')
1653 }
1654
1655 var buf
1656 if (byteOffset === undefined && length === undefined) {
1657 buf = new Uint8Array(array)
1658 } else if (length === undefined) {
1659 buf = new Uint8Array(array, byteOffset)
1660 } else {
1661 buf = new Uint8Array(array, byteOffset, length)
1662 }
1663
1664 // Return an augmented `Uint8Array` instance
1665 Object.setPrototypeOf(buf, Buffer.prototype)
1666
1667 return buf
1668}
1669
1670function fromObject (obj) {
1671 if (Buffer.isBuffer(obj)) {
1672 var len = checked(obj.length) | 0
1673 var buf = createBuffer(len)
1674
1675 if (buf.length === 0) {
1676 return buf
1677 }
1678
1679 obj.copy(buf, 0, 0, len)
1680 return buf
1681 }
1682
1683 if (obj.length !== undefined) {
1684 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
1685 return createBuffer(0)
1686 }
1687 return fromArrayLike(obj)
1688 }
1689
1690 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
1691 return fromArrayLike(obj.data)
1692 }
1693}
1694
1695function checked (length) {
1696 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
1697 // length is NaN (which is otherwise coerced to zero.)
1698 if (length >= K_MAX_LENGTH) {
1699 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
1700 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
1701 }
1702 return length | 0
1703}
1704
1705function SlowBuffer (length) {
1706 if (+length != length) { // eslint-disable-line eqeqeq
1707 length = 0
1708 }
1709 return Buffer.alloc(+length)
1710}
1711
1712Buffer.isBuffer = function isBuffer (b) {
1713 return b != null && b._isBuffer === true &&
1714 b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
1715}
1716
1717Buffer.compare = function compare (a, b) {
1718 if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
1719 if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
1720 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
1721 throw new TypeError(
1722 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
1723 )
1724 }
1725
1726 if (a === b) return 0
1727
1728 var x = a.length
1729 var y = b.length
1730
1731 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
1732 if (a[i] !== b[i]) {
1733 x = a[i]
1734 y = b[i]
1735 break
1736 }
1737 }
1738
1739 if (x < y) return -1
1740 if (y < x) return 1
1741 return 0
1742}
1743
1744Buffer.isEncoding = function isEncoding (encoding) {
1745 switch (String(encoding).toLowerCase()) {
1746 case 'hex':
1747 case 'utf8':
1748 case 'utf-8':
1749 case 'ascii':
1750 case 'latin1':
1751 case 'binary':
1752 case 'base64':
1753 case 'ucs2':
1754 case 'ucs-2':
1755 case 'utf16le':
1756 case 'utf-16le':
1757 return true
1758 default:
1759 return false
1760 }
1761}
1762
1763Buffer.concat = function concat (list, length) {
1764 if (!Array.isArray(list)) {
1765 throw new TypeError('"list" argument must be an Array of Buffers')
1766 }
1767
1768 if (list.length === 0) {
1769 return Buffer.alloc(0)
1770 }
1771
1772 var i
1773 if (length === undefined) {
1774 length = 0
1775 for (i = 0; i < list.length; ++i) {
1776 length += list[i].length
1777 }
1778 }
1779
1780 var buffer = Buffer.allocUnsafe(length)
1781 var pos = 0
1782 for (i = 0; i < list.length; ++i) {
1783 var buf = list[i]
1784 if (isInstance(buf, Uint8Array)) {
1785 if (pos + buf.length > buffer.length) {
1786 Buffer.from(buf).copy(buffer, pos)
1787 } else {
1788 Uint8Array.prototype.set.call(
1789 buffer,
1790 buf,
1791 pos
1792 )
1793 }
1794 } else if (!Buffer.isBuffer(buf)) {
1795 throw new TypeError('"list" argument must be an Array of Buffers')
1796 } else {
1797 buf.copy(buffer, pos)
1798 }
1799 pos += buf.length
1800 }
1801 return buffer
1802}
1803
1804function byteLength (string, encoding) {
1805 if (Buffer.isBuffer(string)) {
1806 return string.length
1807 }
1808 if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
1809 return string.byteLength
1810 }
1811 if (typeof string !== 'string') {
1812 throw new TypeError(
1813 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
1814 'Received type ' + typeof string
1815 )
1816 }
1817
1818 var len = string.length
1819 var mustMatch = (arguments.length > 2 && arguments[2] === true)
1820 if (!mustMatch && len === 0) return 0
1821
1822 // Use a for loop to avoid recursion
1823 var loweredCase = false
1824 for (;;) {
1825 switch (encoding) {
1826 case 'ascii':
1827 case 'latin1':
1828 case 'binary':
1829 return len
1830 case 'utf8':
1831 case 'utf-8':
1832 return utf8ToBytes(string).length
1833 case 'ucs2':
1834 case 'ucs-2':
1835 case 'utf16le':
1836 case 'utf-16le':
1837 return len * 2
1838 case 'hex':
1839 return len >>> 1
1840 case 'base64':
1841 return base64ToBytes(string).length
1842 default:
1843 if (loweredCase) {
1844 return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
1845 }
1846 encoding = ('' + encoding).toLowerCase()
1847 loweredCase = true
1848 }
1849 }
1850}
1851Buffer.byteLength = byteLength
1852
1853function slowToString (encoding, start, end) {
1854 var loweredCase = false
1855
1856 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
1857 // property of a typed array.
1858
1859 // This behaves neither like String nor Uint8Array in that we set start/end
1860 // to their upper/lower bounds if the value passed is out of range.
1861 // undefined is handled specially as per ECMA-262 6th Edition,
1862 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
1863 if (start === undefined || start < 0) {
1864 start = 0
1865 }
1866 // Return early if start > this.length. Done here to prevent potential uint32
1867 // coercion fail below.
1868 if (start > this.length) {
1869 return ''
1870 }
1871
1872 if (end === undefined || end > this.length) {
1873 end = this.length
1874 }
1875
1876 if (end <= 0) {
1877 return ''
1878 }
1879
1880 // Force coercion to uint32. This will also coerce falsey/NaN values to 0.
1881 end >>>= 0
1882 start >>>= 0
1883
1884 if (end <= start) {
1885 return ''
1886 }
1887
1888 if (!encoding) encoding = 'utf8'
1889
1890 while (true) {
1891 switch (encoding) {
1892 case 'hex':
1893 return hexSlice(this, start, end)
1894
1895 case 'utf8':
1896 case 'utf-8':
1897 return utf8Slice(this, start, end)
1898
1899 case 'ascii':
1900 return asciiSlice(this, start, end)
1901
1902 case 'latin1':
1903 case 'binary':
1904 return latin1Slice(this, start, end)
1905
1906 case 'base64':
1907 return base64Slice(this, start, end)
1908
1909 case 'ucs2':
1910 case 'ucs-2':
1911 case 'utf16le':
1912 case 'utf-16le':
1913 return utf16leSlice(this, start, end)
1914
1915 default:
1916 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1917 encoding = (encoding + '').toLowerCase()
1918 loweredCase = true
1919 }
1920 }
1921}
1922
1923// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
1924// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
1925// reliably in a browserify context because there could be multiple different
1926// copies of the 'buffer' package in use. This method works even for Buffer
1927// instances that were created from another copy of the `buffer` package.
1928// See: https://github.com/feross/buffer/issues/154
1929Buffer.prototype._isBuffer = true
1930
1931function swap (b, n, m) {
1932 var i = b[n]
1933 b[n] = b[m]
1934 b[m] = i
1935}
1936
1937Buffer.prototype.swap16 = function swap16 () {
1938 var len = this.length
1939 if (len % 2 !== 0) {
1940 throw new RangeError('Buffer size must be a multiple of 16-bits')
1941 }
1942 for (var i = 0; i < len; i += 2) {
1943 swap(this, i, i + 1)
1944 }
1945 return this
1946}
1947
1948Buffer.prototype.swap32 = function swap32 () {
1949 var len = this.length
1950 if (len % 4 !== 0) {
1951 throw new RangeError('Buffer size must be a multiple of 32-bits')
1952 }
1953 for (var i = 0; i < len; i += 4) {
1954 swap(this, i, i + 3)
1955 swap(this, i + 1, i + 2)
1956 }
1957 return this
1958}
1959
1960Buffer.prototype.swap64 = function swap64 () {
1961 var len = this.length
1962 if (len % 8 !== 0) {
1963 throw new RangeError('Buffer size must be a multiple of 64-bits')
1964 }
1965 for (var i = 0; i < len; i += 8) {
1966 swap(this, i, i + 7)
1967 swap(this, i + 1, i + 6)
1968 swap(this, i + 2, i + 5)
1969 swap(this, i + 3, i + 4)
1970 }
1971 return this
1972}
1973
1974Buffer.prototype.toString = function toString () {
1975 var length = this.length
1976 if (length === 0) return ''
1977 if (arguments.length === 0) return utf8Slice(this, 0, length)
1978 return slowToString.apply(this, arguments)
1979}
1980
1981Buffer.prototype.toLocaleString = Buffer.prototype.toString
1982
1983Buffer.prototype.equals = function equals (b) {
1984 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
1985 if (this === b) return true
1986 return Buffer.compare(this, b) === 0
1987}
1988
1989Buffer.prototype.inspect = function inspect () {
1990 var str = ''
1991 var max = exports.INSPECT_MAX_BYTES
1992 str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
1993 if (this.length > max) str += ' ... '
1994 return '<Buffer ' + str + '>'
1995}
1996if (customInspectSymbol) {
1997 Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect
1998}
1999
2000Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
2001 if (isInstance(target, Uint8Array)) {
2002 target = Buffer.from(target, target.offset, target.byteLength)
2003 }
2004 if (!Buffer.isBuffer(target)) {
2005 throw new TypeError(
2006 'The "target" argument must be one of type Buffer or Uint8Array. ' +
2007 'Received type ' + (typeof target)
2008 )
2009 }
2010
2011 if (start === undefined) {
2012 start = 0
2013 }
2014 if (end === undefined) {
2015 end = target ? target.length : 0
2016 }
2017 if (thisStart === undefined) {
2018 thisStart = 0
2019 }
2020 if (thisEnd === undefined) {
2021 thisEnd = this.length
2022 }
2023
2024 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
2025 throw new RangeError('out of range index')
2026 }
2027
2028 if (thisStart >= thisEnd && start >= end) {
2029 return 0
2030 }
2031 if (thisStart >= thisEnd) {
2032 return -1
2033 }
2034 if (start >= end) {
2035 return 1
2036 }
2037
2038 start >>>= 0
2039 end >>>= 0
2040 thisStart >>>= 0
2041 thisEnd >>>= 0
2042
2043 if (this === target) return 0
2044
2045 var x = thisEnd - thisStart
2046 var y = end - start
2047 var len = Math.min(x, y)
2048
2049 var thisCopy = this.slice(thisStart, thisEnd)
2050 var targetCopy = target.slice(start, end)
2051
2052 for (var i = 0; i < len; ++i) {
2053 if (thisCopy[i] !== targetCopy[i]) {
2054 x = thisCopy[i]
2055 y = targetCopy[i]
2056 break
2057 }
2058 }
2059
2060 if (x < y) return -1
2061 if (y < x) return 1
2062 return 0
2063}
2064
2065// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
2066// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
2067//
2068// Arguments:
2069// - buffer - a Buffer to search
2070// - val - a string, Buffer, or number
2071// - byteOffset - an index into `buffer`; will be clamped to an int32
2072// - encoding - an optional encoding, relevant is val is a string
2073// - dir - true for indexOf, false for lastIndexOf
2074function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
2075 // Empty buffer means no match
2076 if (buffer.length === 0) return -1
2077
2078 // Normalize byteOffset
2079 if (typeof byteOffset === 'string') {
2080 encoding = byteOffset
2081 byteOffset = 0
2082 } else if (byteOffset > 0x7fffffff) {
2083 byteOffset = 0x7fffffff
2084 } else if (byteOffset < -0x80000000) {
2085 byteOffset = -0x80000000
2086 }
2087 byteOffset = +byteOffset // Coerce to Number.
2088 if (numberIsNaN(byteOffset)) {
2089 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
2090 byteOffset = dir ? 0 : (buffer.length - 1)
2091 }
2092
2093 // Normalize byteOffset: negative offsets start from the end of the buffer
2094 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
2095 if (byteOffset >= buffer.length) {
2096 if (dir) return -1
2097 else byteOffset = buffer.length - 1
2098 } else if (byteOffset < 0) {
2099 if (dir) byteOffset = 0
2100 else return -1
2101 }
2102
2103 // Normalize val
2104 if (typeof val === 'string') {
2105 val = Buffer.from(val, encoding)
2106 }
2107
2108 // Finally, search either indexOf (if dir is true) or lastIndexOf
2109 if (Buffer.isBuffer(val)) {
2110 // Special case: looking for empty string/buffer always fails
2111 if (val.length === 0) {
2112 return -1
2113 }
2114 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
2115 } else if (typeof val === 'number') {
2116 val = val & 0xFF // Search for a byte value [0-255]
2117 if (typeof Uint8Array.prototype.indexOf === 'function') {
2118 if (dir) {
2119 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
2120 } else {
2121 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
2122 }
2123 }
2124 return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
2125 }
2126
2127 throw new TypeError('val must be string, number or Buffer')
2128}
2129
2130function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
2131 var indexSize = 1
2132 var arrLength = arr.length
2133 var valLength = val.length
2134
2135 if (encoding !== undefined) {
2136 encoding = String(encoding).toLowerCase()
2137 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
2138 encoding === 'utf16le' || encoding === 'utf-16le') {
2139 if (arr.length < 2 || val.length < 2) {
2140 return -1
2141 }
2142 indexSize = 2
2143 arrLength /= 2
2144 valLength /= 2
2145 byteOffset /= 2
2146 }
2147 }
2148
2149 function read (buf, i) {
2150 if (indexSize === 1) {
2151 return buf[i]
2152 } else {
2153 return buf.readUInt16BE(i * indexSize)
2154 }
2155 }
2156
2157 var i
2158 if (dir) {
2159 var foundIndex = -1
2160 for (i = byteOffset; i < arrLength; i++) {
2161 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
2162 if (foundIndex === -1) foundIndex = i
2163 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
2164 } else {
2165 if (foundIndex !== -1) i -= i - foundIndex
2166 foundIndex = -1
2167 }
2168 }
2169 } else {
2170 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
2171 for (i = byteOffset; i >= 0; i--) {
2172 var found = true
2173 for (var j = 0; j < valLength; j++) {
2174 if (read(arr, i + j) !== read(val, j)) {
2175 found = false
2176 break
2177 }
2178 }
2179 if (found) return i
2180 }
2181 }
2182
2183 return -1
2184}
2185
2186Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
2187 return this.indexOf(val, byteOffset, encoding) !== -1
2188}
2189
2190Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
2191 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
2192}
2193
2194Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
2195 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
2196}
2197
2198function hexWrite (buf, string, offset, length) {
2199 offset = Number(offset) || 0
2200 var remaining = buf.length - offset
2201 if (!length) {
2202 length = remaining
2203 } else {
2204 length = Number(length)
2205 if (length > remaining) {
2206 length = remaining
2207 }
2208 }
2209
2210 var strLen = string.length
2211
2212 if (length > strLen / 2) {
2213 length = strLen / 2
2214 }
2215 for (var i = 0; i < length; ++i) {
2216 var parsed = parseInt(string.substr(i * 2, 2), 16)
2217 if (numberIsNaN(parsed)) return i
2218 buf[offset + i] = parsed
2219 }
2220 return i
2221}
2222
2223function utf8Write (buf, string, offset, length) {
2224 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
2225}
2226
2227function asciiWrite (buf, string, offset, length) {
2228 return blitBuffer(asciiToBytes(string), buf, offset, length)
2229}
2230
2231function base64Write (buf, string, offset, length) {
2232 return blitBuffer(base64ToBytes(string), buf, offset, length)
2233}
2234
2235function ucs2Write (buf, string, offset, length) {
2236 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
2237}
2238
2239Buffer.prototype.write = function write (string, offset, length, encoding) {
2240 // Buffer#write(string)
2241 if (offset === undefined) {
2242 encoding = 'utf8'
2243 length = this.length
2244 offset = 0
2245 // Buffer#write(string, encoding)
2246 } else if (length === undefined && typeof offset === 'string') {
2247 encoding = offset
2248 length = this.length
2249 offset = 0
2250 // Buffer#write(string, offset[, length][, encoding])
2251 } else if (isFinite(offset)) {
2252 offset = offset >>> 0
2253 if (isFinite(length)) {
2254 length = length >>> 0
2255 if (encoding === undefined) encoding = 'utf8'
2256 } else {
2257 encoding = length
2258 length = undefined
2259 }
2260 } else {
2261 throw new Error(
2262 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
2263 )
2264 }
2265
2266 var remaining = this.length - offset
2267 if (length === undefined || length > remaining) length = remaining
2268
2269 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
2270 throw new RangeError('Attempt to write outside buffer bounds')
2271 }
2272
2273 if (!encoding) encoding = 'utf8'
2274
2275 var loweredCase = false
2276 for (;;) {
2277 switch (encoding) {
2278 case 'hex':
2279 return hexWrite(this, string, offset, length)
2280
2281 case 'utf8':
2282 case 'utf-8':
2283 return utf8Write(this, string, offset, length)
2284
2285 case 'ascii':
2286 case 'latin1':
2287 case 'binary':
2288 return asciiWrite(this, string, offset, length)
2289
2290 case 'base64':
2291 // Warning: maxLength not taken into account in base64Write
2292 return base64Write(this, string, offset, length)
2293
2294 case 'ucs2':
2295 case 'ucs-2':
2296 case 'utf16le':
2297 case 'utf-16le':
2298 return ucs2Write(this, string, offset, length)
2299
2300 default:
2301 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
2302 encoding = ('' + encoding).toLowerCase()
2303 loweredCase = true
2304 }
2305 }
2306}
2307
2308Buffer.prototype.toJSON = function toJSON () {
2309 return {
2310 type: 'Buffer',
2311 data: Array.prototype.slice.call(this._arr || this, 0)
2312 }
2313}
2314
2315function base64Slice (buf, start, end) {
2316 if (start === 0 && end === buf.length) {
2317 return base64.fromByteArray(buf)
2318 } else {
2319 return base64.fromByteArray(buf.slice(start, end))
2320 }
2321}
2322
2323function utf8Slice (buf, start, end) {
2324 end = Math.min(buf.length, end)
2325 var res = []
2326
2327 var i = start
2328 while (i < end) {
2329 var firstByte = buf[i]
2330 var codePoint = null
2331 var bytesPerSequence = (firstByte > 0xEF)
2332 ? 4
2333 : (firstByte > 0xDF)
2334 ? 3
2335 : (firstByte > 0xBF)
2336 ? 2
2337 : 1
2338
2339 if (i + bytesPerSequence <= end) {
2340 var secondByte, thirdByte, fourthByte, tempCodePoint
2341
2342 switch (bytesPerSequence) {
2343 case 1:
2344 if (firstByte < 0x80) {
2345 codePoint = firstByte
2346 }
2347 break
2348 case 2:
2349 secondByte = buf[i + 1]
2350 if ((secondByte & 0xC0) === 0x80) {
2351 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
2352 if (tempCodePoint > 0x7F) {
2353 codePoint = tempCodePoint
2354 }
2355 }
2356 break
2357 case 3:
2358 secondByte = buf[i + 1]
2359 thirdByte = buf[i + 2]
2360 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
2361 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
2362 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
2363 codePoint = tempCodePoint
2364 }
2365 }
2366 break
2367 case 4:
2368 secondByte = buf[i + 1]
2369 thirdByte = buf[i + 2]
2370 fourthByte = buf[i + 3]
2371 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
2372 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
2373 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
2374 codePoint = tempCodePoint
2375 }
2376 }
2377 }
2378 }
2379
2380 if (codePoint === null) {
2381 // we did not generate a valid codePoint so insert a
2382 // replacement char (U+FFFD) and advance only 1 byte
2383 codePoint = 0xFFFD
2384 bytesPerSequence = 1
2385 } else if (codePoint > 0xFFFF) {
2386 // encode to utf16 (surrogate pair dance)
2387 codePoint -= 0x10000
2388 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
2389 codePoint = 0xDC00 | codePoint & 0x3FF
2390 }
2391
2392 res.push(codePoint)
2393 i += bytesPerSequence
2394 }
2395
2396 return decodeCodePointsArray(res)
2397}
2398
2399// Based on http://stackoverflow.com/a/22747272/680742, the browser with
2400// the lowest limit is Chrome, with 0x10000 args.
2401// We go 1 magnitude less, for safety
2402var MAX_ARGUMENTS_LENGTH = 0x1000
2403
2404function decodeCodePointsArray (codePoints) {
2405 var len = codePoints.length
2406 if (len <= MAX_ARGUMENTS_LENGTH) {
2407 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
2408 }
2409
2410 // Decode in chunks to avoid "call stack size exceeded".
2411 var res = ''
2412 var i = 0
2413 while (i < len) {
2414 res += String.fromCharCode.apply(
2415 String,
2416 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
2417 )
2418 }
2419 return res
2420}
2421
2422function asciiSlice (buf, start, end) {
2423 var ret = ''
2424 end = Math.min(buf.length, end)
2425
2426 for (var i = start; i < end; ++i) {
2427 ret += String.fromCharCode(buf[i] & 0x7F)
2428 }
2429 return ret
2430}
2431
2432function latin1Slice (buf, start, end) {
2433 var ret = ''
2434 end = Math.min(buf.length, end)
2435
2436 for (var i = start; i < end; ++i) {
2437 ret += String.fromCharCode(buf[i])
2438 }
2439 return ret
2440}
2441
2442function hexSlice (buf, start, end) {
2443 var len = buf.length
2444
2445 if (!start || start < 0) start = 0
2446 if (!end || end < 0 || end > len) end = len
2447
2448 var out = ''
2449 for (var i = start; i < end; ++i) {
2450 out += hexSliceLookupTable[buf[i]]
2451 }
2452 return out
2453}
2454
2455function utf16leSlice (buf, start, end) {
2456 var bytes = buf.slice(start, end)
2457 var res = ''
2458 // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)
2459 for (var i = 0; i < bytes.length - 1; i += 2) {
2460 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
2461 }
2462 return res
2463}
2464
2465Buffer.prototype.slice = function slice (start, end) {
2466 var len = this.length
2467 start = ~~start
2468 end = end === undefined ? len : ~~end
2469
2470 if (start < 0) {
2471 start += len
2472 if (start < 0) start = 0
2473 } else if (start > len) {
2474 start = len
2475 }
2476
2477 if (end < 0) {
2478 end += len
2479 if (end < 0) end = 0
2480 } else if (end > len) {
2481 end = len
2482 }
2483
2484 if (end < start) end = start
2485
2486 var newBuf = this.subarray(start, end)
2487 // Return an augmented `Uint8Array` instance
2488 Object.setPrototypeOf(newBuf, Buffer.prototype)
2489
2490 return newBuf
2491}
2492
2493/*
2494 * Need to make sure that buffer isn't trying to write out of bounds.
2495 */
2496function checkOffset (offset, ext, length) {
2497 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
2498 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
2499}
2500
2501Buffer.prototype.readUintLE =
2502Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
2503 offset = offset >>> 0
2504 byteLength = byteLength >>> 0
2505 if (!noAssert) checkOffset(offset, byteLength, this.length)
2506
2507 var val = this[offset]
2508 var mul = 1
2509 var i = 0
2510 while (++i < byteLength && (mul *= 0x100)) {
2511 val += this[offset + i] * mul
2512 }
2513
2514 return val
2515}
2516
2517Buffer.prototype.readUintBE =
2518Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
2519 offset = offset >>> 0
2520 byteLength = byteLength >>> 0
2521 if (!noAssert) {
2522 checkOffset(offset, byteLength, this.length)
2523 }
2524
2525 var val = this[offset + --byteLength]
2526 var mul = 1
2527 while (byteLength > 0 && (mul *= 0x100)) {
2528 val += this[offset + --byteLength] * mul
2529 }
2530
2531 return val
2532}
2533
2534Buffer.prototype.readUint8 =
2535Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
2536 offset = offset >>> 0
2537 if (!noAssert) checkOffset(offset, 1, this.length)
2538 return this[offset]
2539}
2540
2541Buffer.prototype.readUint16LE =
2542Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
2543 offset = offset >>> 0
2544 if (!noAssert) checkOffset(offset, 2, this.length)
2545 return this[offset] | (this[offset + 1] << 8)
2546}
2547
2548Buffer.prototype.readUint16BE =
2549Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
2550 offset = offset >>> 0
2551 if (!noAssert) checkOffset(offset, 2, this.length)
2552 return (this[offset] << 8) | this[offset + 1]
2553}
2554
2555Buffer.prototype.readUint32LE =
2556Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
2557 offset = offset >>> 0
2558 if (!noAssert) checkOffset(offset, 4, this.length)
2559
2560 return ((this[offset]) |
2561 (this[offset + 1] << 8) |
2562 (this[offset + 2] << 16)) +
2563 (this[offset + 3] * 0x1000000)
2564}
2565
2566Buffer.prototype.readUint32BE =
2567Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
2568 offset = offset >>> 0
2569 if (!noAssert) checkOffset(offset, 4, this.length)
2570
2571 return (this[offset] * 0x1000000) +
2572 ((this[offset + 1] << 16) |
2573 (this[offset + 2] << 8) |
2574 this[offset + 3])
2575}
2576
2577Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
2578 offset = offset >>> 0
2579 byteLength = byteLength >>> 0
2580 if (!noAssert) checkOffset(offset, byteLength, this.length)
2581
2582 var val = this[offset]
2583 var mul = 1
2584 var i = 0
2585 while (++i < byteLength && (mul *= 0x100)) {
2586 val += this[offset + i] * mul
2587 }
2588 mul *= 0x80
2589
2590 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
2591
2592 return val
2593}
2594
2595Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
2596 offset = offset >>> 0
2597 byteLength = byteLength >>> 0
2598 if (!noAssert) checkOffset(offset, byteLength, this.length)
2599
2600 var i = byteLength
2601 var mul = 1
2602 var val = this[offset + --i]
2603 while (i > 0 && (mul *= 0x100)) {
2604 val += this[offset + --i] * mul
2605 }
2606 mul *= 0x80
2607
2608 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
2609
2610 return val
2611}
2612
2613Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
2614 offset = offset >>> 0
2615 if (!noAssert) checkOffset(offset, 1, this.length)
2616 if (!(this[offset] & 0x80)) return (this[offset])
2617 return ((0xff - this[offset] + 1) * -1)
2618}
2619
2620Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
2621 offset = offset >>> 0
2622 if (!noAssert) checkOffset(offset, 2, this.length)
2623 var val = this[offset] | (this[offset + 1] << 8)
2624 return (val & 0x8000) ? val | 0xFFFF0000 : val
2625}
2626
2627Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
2628 offset = offset >>> 0
2629 if (!noAssert) checkOffset(offset, 2, this.length)
2630 var val = this[offset + 1] | (this[offset] << 8)
2631 return (val & 0x8000) ? val | 0xFFFF0000 : val
2632}
2633
2634Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
2635 offset = offset >>> 0
2636 if (!noAssert) checkOffset(offset, 4, this.length)
2637
2638 return (this[offset]) |
2639 (this[offset + 1] << 8) |
2640 (this[offset + 2] << 16) |
2641 (this[offset + 3] << 24)
2642}
2643
2644Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
2645 offset = offset >>> 0
2646 if (!noAssert) checkOffset(offset, 4, this.length)
2647
2648 return (this[offset] << 24) |
2649 (this[offset + 1] << 16) |
2650 (this[offset + 2] << 8) |
2651 (this[offset + 3])
2652}
2653
2654Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
2655 offset = offset >>> 0
2656 if (!noAssert) checkOffset(offset, 4, this.length)
2657 return ieee754.read(this, offset, true, 23, 4)
2658}
2659
2660Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
2661 offset = offset >>> 0
2662 if (!noAssert) checkOffset(offset, 4, this.length)
2663 return ieee754.read(this, offset, false, 23, 4)
2664}
2665
2666Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
2667 offset = offset >>> 0
2668 if (!noAssert) checkOffset(offset, 8, this.length)
2669 return ieee754.read(this, offset, true, 52, 8)
2670}
2671
2672Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
2673 offset = offset >>> 0
2674 if (!noAssert) checkOffset(offset, 8, this.length)
2675 return ieee754.read(this, offset, false, 52, 8)
2676}
2677
2678function checkInt (buf, value, offset, ext, max, min) {
2679 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
2680 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
2681 if (offset + ext > buf.length) throw new RangeError('Index out of range')
2682}
2683
2684Buffer.prototype.writeUintLE =
2685Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
2686 value = +value
2687 offset = offset >>> 0
2688 byteLength = byteLength >>> 0
2689 if (!noAssert) {
2690 var maxBytes = Math.pow(2, 8 * byteLength) - 1
2691 checkInt(this, value, offset, byteLength, maxBytes, 0)
2692 }
2693
2694 var mul = 1
2695 var i = 0
2696 this[offset] = value & 0xFF
2697 while (++i < byteLength && (mul *= 0x100)) {
2698 this[offset + i] = (value / mul) & 0xFF
2699 }
2700
2701 return offset + byteLength
2702}
2703
2704Buffer.prototype.writeUintBE =
2705Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
2706 value = +value
2707 offset = offset >>> 0
2708 byteLength = byteLength >>> 0
2709 if (!noAssert) {
2710 var maxBytes = Math.pow(2, 8 * byteLength) - 1
2711 checkInt(this, value, offset, byteLength, maxBytes, 0)
2712 }
2713
2714 var i = byteLength - 1
2715 var mul = 1
2716 this[offset + i] = value & 0xFF
2717 while (--i >= 0 && (mul *= 0x100)) {
2718 this[offset + i] = (value / mul) & 0xFF
2719 }
2720
2721 return offset + byteLength
2722}
2723
2724Buffer.prototype.writeUint8 =
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 =
2734Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
2735 value = +value
2736 offset = offset >>> 0
2737 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
2738 this[offset] = (value & 0xff)
2739 this[offset + 1] = (value >>> 8)
2740 return offset + 2
2741}
2742
2743Buffer.prototype.writeUint16BE =
2744Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
2745 value = +value
2746 offset = offset >>> 0
2747 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
2748 this[offset] = (value >>> 8)
2749 this[offset + 1] = (value & 0xff)
2750 return offset + 2
2751}
2752
2753Buffer.prototype.writeUint32LE =
2754Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
2755 value = +value
2756 offset = offset >>> 0
2757 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
2758 this[offset + 3] = (value >>> 24)
2759 this[offset + 2] = (value >>> 16)
2760 this[offset + 1] = (value >>> 8)
2761 this[offset] = (value & 0xff)
2762 return offset + 4
2763}
2764
2765Buffer.prototype.writeUint32BE =
2766Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
2767 value = +value
2768 offset = offset >>> 0
2769 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
2770 this[offset] = (value >>> 24)
2771 this[offset + 1] = (value >>> 16)
2772 this[offset + 2] = (value >>> 8)
2773 this[offset + 3] = (value & 0xff)
2774 return offset + 4
2775}
2776
2777Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
2778 value = +value
2779 offset = offset >>> 0
2780 if (!noAssert) {
2781 var limit = Math.pow(2, (8 * byteLength) - 1)
2782
2783 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2784 }
2785
2786 var i = 0
2787 var mul = 1
2788 var sub = 0
2789 this[offset] = value & 0xFF
2790 while (++i < byteLength && (mul *= 0x100)) {
2791 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
2792 sub = 1
2793 }
2794 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2795 }
2796
2797 return offset + byteLength
2798}
2799
2800Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
2801 value = +value
2802 offset = offset >>> 0
2803 if (!noAssert) {
2804 var limit = Math.pow(2, (8 * byteLength) - 1)
2805
2806 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2807 }
2808
2809 var i = byteLength - 1
2810 var mul = 1
2811 var sub = 0
2812 this[offset + i] = value & 0xFF
2813 while (--i >= 0 && (mul *= 0x100)) {
2814 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
2815 sub = 1
2816 }
2817 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2818 }
2819
2820 return offset + byteLength
2821}
2822
2823Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
2824 value = +value
2825 offset = offset >>> 0
2826 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
2827 if (value < 0) value = 0xff + value + 1
2828 this[offset] = (value & 0xff)
2829 return offset + 1
2830}
2831
2832Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
2833 value = +value
2834 offset = offset >>> 0
2835 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2836 this[offset] = (value & 0xff)
2837 this[offset + 1] = (value >>> 8)
2838 return offset + 2
2839}
2840
2841Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
2842 value = +value
2843 offset = offset >>> 0
2844 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2845 this[offset] = (value >>> 8)
2846 this[offset + 1] = (value & 0xff)
2847 return offset + 2
2848}
2849
2850Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
2851 value = +value
2852 offset = offset >>> 0
2853 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2854 this[offset] = (value & 0xff)
2855 this[offset + 1] = (value >>> 8)
2856 this[offset + 2] = (value >>> 16)
2857 this[offset + 3] = (value >>> 24)
2858 return offset + 4
2859}
2860
2861Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
2862 value = +value
2863 offset = offset >>> 0
2864 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2865 if (value < 0) value = 0xffffffff + value + 1
2866 this[offset] = (value >>> 24)
2867 this[offset + 1] = (value >>> 16)
2868 this[offset + 2] = (value >>> 8)
2869 this[offset + 3] = (value & 0xff)
2870 return offset + 4
2871}
2872
2873function checkIEEE754 (buf, value, offset, ext, max, min) {
2874 if (offset + ext > buf.length) throw new RangeError('Index out of range')
2875 if (offset < 0) throw new RangeError('Index out of range')
2876}
2877
2878function writeFloat (buf, value, offset, littleEndian, noAssert) {
2879 value = +value
2880 offset = offset >>> 0
2881 if (!noAssert) {
2882 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
2883 }
2884 ieee754.write(buf, value, offset, littleEndian, 23, 4)
2885 return offset + 4
2886}
2887
2888Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
2889 return writeFloat(this, value, offset, true, noAssert)
2890}
2891
2892Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
2893 return writeFloat(this, value, offset, false, noAssert)
2894}
2895
2896function writeDouble (buf, value, offset, littleEndian, noAssert) {
2897 value = +value
2898 offset = offset >>> 0
2899 if (!noAssert) {
2900 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
2901 }
2902 ieee754.write(buf, value, offset, littleEndian, 52, 8)
2903 return offset + 8
2904}
2905
2906Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
2907 return writeDouble(this, value, offset, true, noAssert)
2908}
2909
2910Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
2911 return writeDouble(this, value, offset, false, noAssert)
2912}
2913
2914// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
2915Buffer.prototype.copy = function copy (target, targetStart, start, end) {
2916 if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
2917 if (!start) start = 0
2918 if (!end && end !== 0) end = this.length
2919 if (targetStart >= target.length) targetStart = target.length
2920 if (!targetStart) targetStart = 0
2921 if (end > 0 && end < start) end = start
2922
2923 // Copy 0 bytes; we're done
2924 if (end === start) return 0
2925 if (target.length === 0 || this.length === 0) return 0
2926
2927 // Fatal error conditions
2928 if (targetStart < 0) {
2929 throw new RangeError('targetStart out of bounds')
2930 }
2931 if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
2932 if (end < 0) throw new RangeError('sourceEnd out of bounds')
2933
2934 // Are we oob?
2935 if (end > this.length) end = this.length
2936 if (target.length - targetStart < end - start) {
2937 end = target.length - targetStart + start
2938 }
2939
2940 var len = end - start
2941
2942 if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
2943 // Use built-in when available, missing from IE11
2944 this.copyWithin(targetStart, start, end)
2945 } else {
2946 Uint8Array.prototype.set.call(
2947 target,
2948 this.subarray(start, end),
2949 targetStart
2950 )
2951 }
2952
2953 return len
2954}
2955
2956// Usage:
2957// buffer.fill(number[, offset[, end]])
2958// buffer.fill(buffer[, offset[, end]])
2959// buffer.fill(string[, offset[, end]][, encoding])
2960Buffer.prototype.fill = function fill (val, start, end, encoding) {
2961 // Handle string cases:
2962 if (typeof val === 'string') {
2963 if (typeof start === 'string') {
2964 encoding = start
2965 start = 0
2966 end = this.length
2967 } else if (typeof end === 'string') {
2968 encoding = end
2969 end = this.length
2970 }
2971 if (encoding !== undefined && typeof encoding !== 'string') {
2972 throw new TypeError('encoding must be a string')
2973 }
2974 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
2975 throw new TypeError('Unknown encoding: ' + encoding)
2976 }
2977 if (val.length === 1) {
2978 var code = val.charCodeAt(0)
2979 if ((encoding === 'utf8' && code < 128) ||
2980 encoding === 'latin1') {
2981 // Fast path: If `val` fits into a single byte, use that numeric value.
2982 val = code
2983 }
2984 }
2985 } else if (typeof val === 'number') {
2986 val = val & 255
2987 } else if (typeof val === 'boolean') {
2988 val = Number(val)
2989 }
2990
2991 // Invalid ranges are not set to a default, so can range check early.
2992 if (start < 0 || this.length < start || this.length < end) {
2993 throw new RangeError('Out of range index')
2994 }
2995
2996 if (end <= start) {
2997 return this
2998 }
2999
3000 start = start >>> 0
3001 end = end === undefined ? this.length : end >>> 0
3002
3003 if (!val) val = 0
3004
3005 var i
3006 if (typeof val === 'number') {
3007 for (i = start; i < end; ++i) {
3008 this[i] = val
3009 }
3010 } else {
3011 var bytes = Buffer.isBuffer(val)
3012 ? val
3013 : Buffer.from(val, encoding)
3014 var len = bytes.length
3015 if (len === 0) {
3016 throw new TypeError('The value "' + val +
3017 '" is invalid for argument "value"')
3018 }
3019 for (i = 0; i < end - start; ++i) {
3020 this[i + start] = bytes[i % len]
3021 }
3022 }
3023
3024 return this
3025}
3026
3027// HELPER FUNCTIONS
3028// ================
3029
3030var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
3031
3032function base64clean (str) {
3033 // Node takes equal signs as end of the Base64 encoding
3034 str = str.split('=')[0]
3035 // Node strips out invalid characters like \n and \t from the string, base64-js does not
3036 str = str.trim().replace(INVALID_BASE64_RE, '')
3037 // Node converts strings with length < 2 to ''
3038 if (str.length < 2) return ''
3039 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
3040 while (str.length % 4 !== 0) {
3041 str = str + '='
3042 }
3043 return str
3044}
3045
3046function utf8ToBytes (string, units) {
3047 units = units || Infinity
3048 var codePoint
3049 var length = string.length
3050 var leadSurrogate = null
3051 var bytes = []
3052
3053 for (var i = 0; i < length; ++i) {
3054 codePoint = string.charCodeAt(i)
3055
3056 // is surrogate component
3057 if (codePoint > 0xD7FF && codePoint < 0xE000) {
3058 // last char was a lead
3059 if (!leadSurrogate) {
3060 // no lead yet
3061 if (codePoint > 0xDBFF) {
3062 // unexpected trail
3063 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3064 continue
3065 } else if (i + 1 === length) {
3066 // unpaired lead
3067 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3068 continue
3069 }
3070
3071 // valid lead
3072 leadSurrogate = codePoint
3073
3074 continue
3075 }
3076
3077 // 2 leads in a row
3078 if (codePoint < 0xDC00) {
3079 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3080 leadSurrogate = codePoint
3081 continue
3082 }
3083
3084 // valid surrogate pair
3085 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
3086 } else if (leadSurrogate) {
3087 // valid bmp char, but last char was a lead
3088 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3089 }
3090
3091 leadSurrogate = null
3092
3093 // encode utf8
3094 if (codePoint < 0x80) {
3095 if ((units -= 1) < 0) break
3096 bytes.push(codePoint)
3097 } else if (codePoint < 0x800) {
3098 if ((units -= 2) < 0) break
3099 bytes.push(
3100 codePoint >> 0x6 | 0xC0,
3101 codePoint & 0x3F | 0x80
3102 )
3103 } else if (codePoint < 0x10000) {
3104 if ((units -= 3) < 0) break
3105 bytes.push(
3106 codePoint >> 0xC | 0xE0,
3107 codePoint >> 0x6 & 0x3F | 0x80,
3108 codePoint & 0x3F | 0x80
3109 )
3110 } else if (codePoint < 0x110000) {
3111 if ((units -= 4) < 0) break
3112 bytes.push(
3113 codePoint >> 0x12 | 0xF0,
3114 codePoint >> 0xC & 0x3F | 0x80,
3115 codePoint >> 0x6 & 0x3F | 0x80,
3116 codePoint & 0x3F | 0x80
3117 )
3118 } else {
3119 throw new Error('Invalid code point')
3120 }
3121 }
3122
3123 return bytes
3124}
3125
3126function asciiToBytes (str) {
3127 var byteArray = []
3128 for (var i = 0; i < str.length; ++i) {
3129 // Node's code seems to be doing this and not & 0x7F..
3130 byteArray.push(str.charCodeAt(i) & 0xFF)
3131 }
3132 return byteArray
3133}
3134
3135function utf16leToBytes (str, units) {
3136 var c, hi, lo
3137 var byteArray = []
3138 for (var i = 0; i < str.length; ++i) {
3139 if ((units -= 2) < 0) break
3140
3141 c = str.charCodeAt(i)
3142 hi = c >> 8
3143 lo = c % 256
3144 byteArray.push(lo)
3145 byteArray.push(hi)
3146 }
3147
3148 return byteArray
3149}
3150
3151function base64ToBytes (str) {
3152 return base64.toByteArray(base64clean(str))
3153}
3154
3155function blitBuffer (src, dst, offset, length) {
3156 for (var i = 0; i < length; ++i) {
3157 if ((i + offset >= dst.length) || (i >= src.length)) break
3158 dst[i + offset] = src[i]
3159 }
3160 return i
3161}
3162
3163// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
3164// the `instanceof` check but they should be treated as of that type.
3165// See: https://github.com/feross/buffer/issues/166
3166function isInstance (obj, type) {
3167 return obj instanceof type ||
3168 (obj != null && obj.constructor != null && obj.constructor.name != null &&
3169 obj.constructor.name === type.name)
3170}
3171function numberIsNaN (obj) {
3172 // For IE11 support
3173 return obj !== obj // eslint-disable-line no-self-compare
3174}
3175
3176// Create lookup table for `toString('hex')`
3177// See: https://github.com/feross/buffer/issues/219
3178var hexSliceLookupTable = (function () {
3179 var alphabet = '0123456789abcdef'
3180 var table = new Array(256)
3181 for (var i = 0; i < 16; ++i) {
3182 var i16 = i * 16
3183 for (var j = 0; j < 16; ++j) {
3184 table[i16 + j] = alphabet[i] + alphabet[j]
3185 }
3186 }
3187 return table
3188})()
3189
3190}).call(this)}).call(this,_dereq_(8).Buffer)
3191},{"22":22,"5":5,"8":8}],9:[function(_dereq_,module,exports){
3192// Copyright Joyent, Inc. and other Node contributors.
3193//
3194// Permission is hereby granted, free of charge, to any person obtaining a
3195// copy of this software and associated documentation files (the
3196// "Software"), to deal in the Software without restriction, including
3197// without limitation the rights to use, copy, modify, merge, publish,
3198// distribute, sublicense, and/or sell copies of the Software, and to permit
3199// persons to whom the Software is furnished to do so, subject to the
3200// following conditions:
3201//
3202// The above copyright notice and this permission notice shall be included
3203// in all copies or substantial portions of the Software.
3204//
3205// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3206// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3207// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3208// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3209// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3210// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3211// USE OR OTHER DEALINGS IN THE SOFTWARE.
3212
3213// NOTE: These type checking functions intentionally don't use `instanceof`
3214// because it is fragile and can be easily faked with `Object.create()`.
3215
3216function isArray(arg) {
3217 if (Array.isArray) {
3218 return Array.isArray(arg);
3219 }
3220 return objectToString(arg) === '[object Array]';
3221}
3222exports.isArray = isArray;
3223
3224function isBoolean(arg) {
3225 return typeof arg === 'boolean';
3226}
3227exports.isBoolean = isBoolean;
3228
3229function isNull(arg) {
3230 return arg === null;
3231}
3232exports.isNull = isNull;
3233
3234function isNullOrUndefined(arg) {
3235 return arg == null;
3236}
3237exports.isNullOrUndefined = isNullOrUndefined;
3238
3239function isNumber(arg) {
3240 return typeof arg === 'number';
3241}
3242exports.isNumber = isNumber;
3243
3244function isString(arg) {
3245 return typeof arg === 'string';
3246}
3247exports.isString = isString;
3248
3249function isSymbol(arg) {
3250 return typeof arg === 'symbol';
3251}
3252exports.isSymbol = isSymbol;
3253
3254function isUndefined(arg) {
3255 return arg === void 0;
3256}
3257exports.isUndefined = isUndefined;
3258
3259function isRegExp(re) {
3260 return objectToString(re) === '[object RegExp]';
3261}
3262exports.isRegExp = isRegExp;
3263
3264function isObject(arg) {
3265 return typeof arg === 'object' && arg !== null;
3266}
3267exports.isObject = isObject;
3268
3269function isDate(d) {
3270 return objectToString(d) === '[object Date]';
3271}
3272exports.isDate = isDate;
3273
3274function isError(e) {
3275 return (objectToString(e) === '[object Error]' || e instanceof Error);
3276}
3277exports.isError = isError;
3278
3279function isFunction(arg) {
3280 return typeof arg === 'function';
3281}
3282exports.isFunction = isFunction;
3283
3284function isPrimitive(arg) {
3285 return arg === null ||
3286 typeof arg === 'boolean' ||
3287 typeof arg === 'number' ||
3288 typeof arg === 'string' ||
3289 typeof arg === 'symbol' || // ES6 symbol
3290 typeof arg === 'undefined';
3291}
3292exports.isPrimitive = isPrimitive;
3293
3294exports.isBuffer = _dereq_(8).Buffer.isBuffer;
3295
3296function objectToString(o) {
3297 return Object.prototype.toString.call(o);
3298}
3299
3300},{"8":8}],10:[function(_dereq_,module,exports){
3301var AbstractIterator = _dereq_(15).AbstractIterator
3302var inherits = _dereq_(29)
3303
3304function DeferredIterator (db, options) {
3305 AbstractIterator.call(this, db)
3306
3307 this._options = options
3308 this._iterator = null
3309 this._operations = []
3310}
3311
3312inherits(DeferredIterator, AbstractIterator)
3313
3314DeferredIterator.prototype.setDb = function (db) {
3315 var it = this._iterator = db.iterator(this._options)
3316 this._operations.forEach(function (op) {
3317 it[op.method].apply(it, op.args)
3318 })
3319}
3320
3321DeferredIterator.prototype._operation = function (method, args) {
3322 if (this._iterator) return this._iterator[method].apply(this._iterator, args)
3323 this._operations.push({ method: method, args: args })
3324}
3325
3326'next end'.split(' ').forEach(function (m) {
3327 DeferredIterator.prototype['_' + m] = function () {
3328 this._operation(m, arguments)
3329 }
3330})
3331
3332// Must defer seek() rather than _seek() because it requires db._serializeKey to be available
3333DeferredIterator.prototype.seek = function () {
3334 this._operation('seek', arguments)
3335}
3336
3337module.exports = DeferredIterator
3338
3339},{"15":15,"29":29}],11:[function(_dereq_,module,exports){
3340var AbstractLevelDOWN = _dereq_(15).AbstractLevelDOWN
3341var inherits = _dereq_(29)
3342var DeferredIterator = _dereq_(10)
3343var deferrables = 'put get del batch clear'.split(' ')
3344var optionalDeferrables = 'approximateSize compactRange'.split(' ')
3345
3346function DeferredLevelDOWN (db) {
3347 AbstractLevelDOWN.call(this, db.supports || {})
3348
3349 // TODO (future major): remove this fallback; db must have manifest that
3350 // declares approximateSize and compactRange in additionalMethods.
3351 optionalDeferrables.forEach(function (m) {
3352 if (typeof db[m] === 'function' && !this.supports.additionalMethods[m]) {
3353 this.supports.additionalMethods[m] = true
3354 }
3355 }, this)
3356
3357 this._db = db
3358 this._operations = []
3359 closed(this)
3360}
3361
3362inherits(DeferredLevelDOWN, AbstractLevelDOWN)
3363
3364DeferredLevelDOWN.prototype.type = 'deferred-leveldown'
3365
3366DeferredLevelDOWN.prototype._open = function (options, callback) {
3367 var self = this
3368
3369 this._db.open(options, function (err) {
3370 if (err) return callback(err)
3371
3372 self._operations.forEach(function (op) {
3373 if (op.iterator) {
3374 op.iterator.setDb(self._db)
3375 } else {
3376 self._db[op.method].apply(self._db, op.args)
3377 }
3378 })
3379 self._operations = []
3380
3381 open(self)
3382 callback()
3383 })
3384}
3385
3386DeferredLevelDOWN.prototype._close = function (callback) {
3387 var self = this
3388
3389 this._db.close(function (err) {
3390 if (err) return callback(err)
3391 closed(self)
3392 callback()
3393 })
3394}
3395
3396function open (self) {
3397 deferrables.concat('iterator').forEach(function (m) {
3398 self['_' + m] = function () {
3399 return this._db[m].apply(this._db, arguments)
3400 }
3401 })
3402 Object.keys(self.supports.additionalMethods).forEach(function (m) {
3403 self[m] = function () {
3404 return this._db[m].apply(this._db, arguments)
3405 }
3406 })
3407}
3408
3409function closed (self) {
3410 deferrables.forEach(function (m) {
3411 self['_' + m] = function () {
3412 this._operations.push({ method: m, args: arguments })
3413 }
3414 })
3415 Object.keys(self.supports.additionalMethods).forEach(function (m) {
3416 self[m] = function () {
3417 this._operations.push({ method: m, args: arguments })
3418 }
3419 })
3420 self._iterator = function (options) {
3421 var it = new DeferredIterator(self, options)
3422 this._operations.push({ iterator: it })
3423 return it
3424 }
3425}
3426
3427DeferredLevelDOWN.prototype._serializeKey = function (key) {
3428 return key
3429}
3430
3431DeferredLevelDOWN.prototype._serializeValue = function (value) {
3432 return value
3433}
3434
3435module.exports = DeferredLevelDOWN
3436module.exports.DeferredIterator = DeferredIterator
3437
3438},{"10":10,"15":15,"29":29}],12:[function(_dereq_,module,exports){
3439var nextTick = _dereq_(16)
3440
3441function AbstractChainedBatch (db) {
3442 if (typeof db !== 'object' || db === null) {
3443 throw new TypeError('First argument must be an abstract-leveldown compliant store')
3444 }
3445
3446 this.db = db
3447 this._operations = []
3448 this._written = false
3449}
3450
3451AbstractChainedBatch.prototype._checkWritten = function () {
3452 if (this._written) {
3453 throw new Error('write() already called on this batch')
3454 }
3455}
3456
3457AbstractChainedBatch.prototype.put = function (key, value) {
3458 this._checkWritten()
3459
3460 var err = this.db._checkKey(key) || this.db._checkValue(value)
3461 if (err) throw err
3462
3463 key = this.db._serializeKey(key)
3464 value = this.db._serializeValue(value)
3465
3466 this._put(key, value)
3467
3468 return this
3469}
3470
3471AbstractChainedBatch.prototype._put = function (key, value) {
3472 this._operations.push({ type: 'put', key: key, value: value })
3473}
3474
3475AbstractChainedBatch.prototype.del = function (key) {
3476 this._checkWritten()
3477
3478 var err = this.db._checkKey(key)
3479 if (err) throw err
3480
3481 key = this.db._serializeKey(key)
3482 this._del(key)
3483
3484 return this
3485}
3486
3487AbstractChainedBatch.prototype._del = function (key) {
3488 this._operations.push({ type: 'del', key: key })
3489}
3490
3491AbstractChainedBatch.prototype.clear = function () {
3492 this._checkWritten()
3493 this._clear()
3494
3495 return this
3496}
3497
3498AbstractChainedBatch.prototype._clear = function () {
3499 this._operations = []
3500}
3501
3502AbstractChainedBatch.prototype.write = function (options, callback) {
3503 this._checkWritten()
3504
3505 if (typeof options === 'function') { callback = options }
3506 if (typeof callback !== 'function') {
3507 throw new Error('write() requires a callback argument')
3508 }
3509 if (typeof options !== 'object' || options === null) {
3510 options = {}
3511 }
3512
3513 this._written = true
3514 this._write(options, callback)
3515}
3516
3517AbstractChainedBatch.prototype._write = function (options, callback) {
3518 this.db._batch(this._operations, options, callback)
3519}
3520
3521// Expose browser-compatible nextTick for dependents
3522AbstractChainedBatch.prototype._nextTick = nextTick
3523
3524module.exports = AbstractChainedBatch
3525
3526},{"16":16}],13:[function(_dereq_,module,exports){
3527var nextTick = _dereq_(16)
3528
3529function AbstractIterator (db) {
3530 if (typeof db !== 'object' || db === null) {
3531 throw new TypeError('First argument must be an abstract-leveldown compliant store')
3532 }
3533
3534 this.db = db
3535 this._ended = false
3536 this._nexting = false
3537}
3538
3539AbstractIterator.prototype.next = function (callback) {
3540 var self = this
3541
3542 if (typeof callback !== 'function') {
3543 throw new Error('next() requires a callback argument')
3544 }
3545
3546 if (self._ended) {
3547 nextTick(callback, new Error('cannot call next() after end()'))
3548 return self
3549 }
3550
3551 if (self._nexting) {
3552 nextTick(callback, new Error('cannot call next() before previous next() has completed'))
3553 return self
3554 }
3555
3556 self._nexting = true
3557 self._next(function () {
3558 self._nexting = false
3559 callback.apply(null, arguments)
3560 })
3561
3562 return self
3563}
3564
3565AbstractIterator.prototype._next = function (callback) {
3566 nextTick(callback)
3567}
3568
3569AbstractIterator.prototype.seek = function (target) {
3570 if (this._ended) {
3571 throw new Error('cannot call seek() after end()')
3572 }
3573 if (this._nexting) {
3574 throw new Error('cannot call seek() before next() has completed')
3575 }
3576
3577 target = this.db._serializeKey(target)
3578 this._seek(target)
3579}
3580
3581AbstractIterator.prototype._seek = function (target) {}
3582
3583AbstractIterator.prototype.end = function (callback) {
3584 if (typeof callback !== 'function') {
3585 throw new Error('end() requires a callback argument')
3586 }
3587
3588 if (this._ended) {
3589 return nextTick(callback, new Error('end() already called on iterator'))
3590 }
3591
3592 this._ended = true
3593 this._end(callback)
3594}
3595
3596AbstractIterator.prototype._end = function (callback) {
3597 nextTick(callback)
3598}
3599
3600// Expose browser-compatible nextTick for dependents
3601AbstractIterator.prototype._nextTick = nextTick
3602
3603module.exports = AbstractIterator
3604
3605},{"16":16}],14:[function(_dereq_,module,exports){
3606var xtend = _dereq_(133)
3607var supports = _dereq_(50)
3608var Buffer = _dereq_(8).Buffer
3609var AbstractIterator = _dereq_(13)
3610var AbstractChainedBatch = _dereq_(12)
3611var nextTick = _dereq_(16)
3612var hasOwnProperty = Object.prototype.hasOwnProperty
3613var rangeOptions = 'start end gt gte lt lte'.split(' ')
3614
3615function AbstractLevelDOWN (manifest) {
3616 this.status = 'new'
3617
3618 // TODO (next major): make this mandatory
3619 this.supports = supports(manifest, {
3620 status: true
3621 })
3622}
3623
3624AbstractLevelDOWN.prototype.open = function (options, callback) {
3625 var self = this
3626 var oldStatus = this.status
3627
3628 if (typeof options === 'function') callback = options
3629
3630 if (typeof callback !== 'function') {
3631 throw new Error('open() requires a callback argument')
3632 }
3633
3634 if (typeof options !== 'object' || options === null) options = {}
3635
3636 options.createIfMissing = options.createIfMissing !== false
3637 options.errorIfExists = !!options.errorIfExists
3638
3639 this.status = 'opening'
3640 this._open(options, function (err) {
3641 if (err) {
3642 self.status = oldStatus
3643 return callback(err)
3644 }
3645 self.status = 'open'
3646 callback()
3647 })
3648}
3649
3650AbstractLevelDOWN.prototype._open = function (options, callback) {
3651 nextTick(callback)
3652}
3653
3654AbstractLevelDOWN.prototype.close = function (callback) {
3655 var self = this
3656 var oldStatus = this.status
3657
3658 if (typeof callback !== 'function') {
3659 throw new Error('close() requires a callback argument')
3660 }
3661
3662 this.status = 'closing'
3663 this._close(function (err) {
3664 if (err) {
3665 self.status = oldStatus
3666 return callback(err)
3667 }
3668 self.status = 'closed'
3669 callback()
3670 })
3671}
3672
3673AbstractLevelDOWN.prototype._close = function (callback) {
3674 nextTick(callback)
3675}
3676
3677AbstractLevelDOWN.prototype.get = function (key, options, callback) {
3678 if (typeof options === 'function') callback = options
3679
3680 if (typeof callback !== 'function') {
3681 throw new Error('get() requires a callback argument')
3682 }
3683
3684 var err = this._checkKey(key)
3685 if (err) return nextTick(callback, err)
3686
3687 key = this._serializeKey(key)
3688
3689 if (typeof options !== 'object' || options === null) options = {}
3690
3691 options.asBuffer = options.asBuffer !== false
3692
3693 this._get(key, options, callback)
3694}
3695
3696AbstractLevelDOWN.prototype._get = function (key, options, callback) {
3697 nextTick(function () { callback(new Error('NotFound')) })
3698}
3699
3700AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
3701 if (typeof options === 'function') callback = options
3702
3703 if (typeof callback !== 'function') {
3704 throw new Error('put() requires a callback argument')
3705 }
3706
3707 var err = this._checkKey(key) || this._checkValue(value)
3708 if (err) return nextTick(callback, err)
3709
3710 key = this._serializeKey(key)
3711 value = this._serializeValue(value)
3712
3713 if (typeof options !== 'object' || options === null) options = {}
3714
3715 this._put(key, value, options, callback)
3716}
3717
3718AbstractLevelDOWN.prototype._put = function (key, value, options, callback) {
3719 nextTick(callback)
3720}
3721
3722AbstractLevelDOWN.prototype.del = function (key, options, callback) {
3723 if (typeof options === 'function') callback = options
3724
3725 if (typeof callback !== 'function') {
3726 throw new Error('del() requires a callback argument')
3727 }
3728
3729 var err = this._checkKey(key)
3730 if (err) return nextTick(callback, err)
3731
3732 key = this._serializeKey(key)
3733
3734 if (typeof options !== 'object' || options === null) options = {}
3735
3736 this._del(key, options, callback)
3737}
3738
3739AbstractLevelDOWN.prototype._del = function (key, options, callback) {
3740 nextTick(callback)
3741}
3742
3743AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
3744 if (!arguments.length) return this._chainedBatch()
3745
3746 if (typeof options === 'function') callback = options
3747
3748 if (typeof array === 'function') callback = array
3749
3750 if (typeof callback !== 'function') {
3751 throw new Error('batch(array) requires a callback argument')
3752 }
3753
3754 if (!Array.isArray(array)) {
3755 return nextTick(callback, new Error('batch(array) requires an array argument'))
3756 }
3757
3758 if (array.length === 0) {
3759 return nextTick(callback)
3760 }
3761
3762 if (typeof options !== 'object' || options === null) options = {}
3763
3764 var serialized = new Array(array.length)
3765
3766 for (var i = 0; i < array.length; i++) {
3767 if (typeof array[i] !== 'object' || array[i] === null) {
3768 return nextTick(callback, new Error('batch(array) element must be an object and not `null`'))
3769 }
3770
3771 var e = xtend(array[i])
3772
3773 if (e.type !== 'put' && e.type !== 'del') {
3774 return nextTick(callback, new Error("`type` must be 'put' or 'del'"))
3775 }
3776
3777 var err = this._checkKey(e.key)
3778 if (err) return nextTick(callback, err)
3779
3780 e.key = this._serializeKey(e.key)
3781
3782 if (e.type === 'put') {
3783 var valueErr = this._checkValue(e.value)
3784 if (valueErr) return nextTick(callback, valueErr)
3785
3786 e.value = this._serializeValue(e.value)
3787 }
3788
3789 serialized[i] = e
3790 }
3791
3792 this._batch(serialized, options, callback)
3793}
3794
3795AbstractLevelDOWN.prototype._batch = function (array, options, callback) {
3796 nextTick(callback)
3797}
3798
3799AbstractLevelDOWN.prototype.clear = function (options, callback) {
3800 if (typeof options === 'function') {
3801 callback = options
3802 } else if (typeof callback !== 'function') {
3803 throw new Error('clear() requires a callback argument')
3804 }
3805
3806 options = cleanRangeOptions(this, options)
3807 options.reverse = !!options.reverse
3808 options.limit = 'limit' in options ? options.limit : -1
3809
3810 this._clear(options, callback)
3811}
3812
3813AbstractLevelDOWN.prototype._clear = function (options, callback) {
3814 // Avoid setupIteratorOptions, would serialize range options a second time.
3815 options.keys = true
3816 options.values = false
3817 options.keyAsBuffer = true
3818 options.valueAsBuffer = true
3819
3820 var iterator = this._iterator(options)
3821 var emptyOptions = {}
3822 var self = this
3823
3824 var next = function (err) {
3825 if (err) {
3826 return iterator.end(function () {
3827 callback(err)
3828 })
3829 }
3830
3831 iterator.next(function (err, key) {
3832 if (err) return next(err)
3833 if (key === undefined) return iterator.end(callback)
3834
3835 // This could be optimized by using a batch, but the default _clear
3836 // is not meant to be fast. Implementations have more room to optimize
3837 // if they override _clear. Note: using _del bypasses key serialization.
3838 self._del(key, emptyOptions, next)
3839 })
3840 }
3841
3842 next()
3843}
3844
3845AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
3846 options = cleanRangeOptions(this, options)
3847
3848 options.reverse = !!options.reverse
3849 options.keys = options.keys !== false
3850 options.values = options.values !== false
3851 options.limit = 'limit' in options ? options.limit : -1
3852 options.keyAsBuffer = options.keyAsBuffer !== false
3853 options.valueAsBuffer = options.valueAsBuffer !== false
3854
3855 return options
3856}
3857
3858function cleanRangeOptions (db, options) {
3859 var result = {}
3860
3861 for (var k in options) {
3862 if (!hasOwnProperty.call(options, k)) continue
3863
3864 var opt = options[k]
3865
3866 if (isRangeOption(k)) {
3867 // Note that we don't reject nullish and empty options here. While
3868 // those types are invalid as keys, they are valid as range options.
3869 opt = db._serializeKey(opt)
3870 }
3871
3872 result[k] = opt
3873 }
3874
3875 return result
3876}
3877
3878function isRangeOption (k) {
3879 return rangeOptions.indexOf(k) !== -1
3880}
3881
3882AbstractLevelDOWN.prototype.iterator = function (options) {
3883 if (typeof options !== 'object' || options === null) options = {}
3884 options = this._setupIteratorOptions(options)
3885 return this._iterator(options)
3886}
3887
3888AbstractLevelDOWN.prototype._iterator = function (options) {
3889 return new AbstractIterator(this)
3890}
3891
3892AbstractLevelDOWN.prototype._chainedBatch = function () {
3893 return new AbstractChainedBatch(this)
3894}
3895
3896AbstractLevelDOWN.prototype._serializeKey = function (key) {
3897 return key
3898}
3899
3900AbstractLevelDOWN.prototype._serializeValue = function (value) {
3901 return value
3902}
3903
3904AbstractLevelDOWN.prototype._checkKey = function (key) {
3905 if (key === null || key === undefined) {
3906 return new Error('key cannot be `null` or `undefined`')
3907 } else if (Buffer.isBuffer(key) && key.length === 0) {
3908 return new Error('key cannot be an empty Buffer')
3909 } else if (key === '') {
3910 return new Error('key cannot be an empty String')
3911 } else if (Array.isArray(key) && key.length === 0) {
3912 return new Error('key cannot be an empty Array')
3913 }
3914}
3915
3916AbstractLevelDOWN.prototype._checkValue = function (value) {
3917 if (value === null || value === undefined) {
3918 return new Error('value cannot be `null` or `undefined`')
3919 }
3920}
3921
3922// Expose browser-compatible nextTick for dependents
3923AbstractLevelDOWN.prototype._nextTick = nextTick
3924
3925module.exports = AbstractLevelDOWN
3926
3927},{"12":12,"13":13,"133":133,"16":16,"50":50,"8":8}],15:[function(_dereq_,module,exports){
3928exports.AbstractLevelDOWN = _dereq_(14)
3929exports.AbstractIterator = _dereq_(13)
3930exports.AbstractChainedBatch = _dereq_(12)
3931
3932},{"12":12,"13":13,"14":14}],16:[function(_dereq_,module,exports){
3933module.exports = _dereq_(23)
3934
3935},{"23":23}],17:[function(_dereq_,module,exports){
3936/**
3937 * Copyright (c) 2013 Petka Antonov
3938 *
3939 * Permission is hereby granted, free of charge, to any person obtaining a copy
3940 * of this software and associated documentation files (the "Software"), to deal
3941 * in the Software without restriction, including without limitation the rights
3942 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
3943 * copies of the Software, and to permit persons to whom the Software is
3944 * furnished to do so, subject to the following conditions:</p>
3945 *
3946 * The above copyright notice and this permission notice shall be included in
3947 * all copies or substantial portions of the Software.
3948 *
3949 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
3950 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
3951 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
3952 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
3953 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
3954 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
3955 * THE SOFTWARE.
3956 */
3957"use strict";
3958function Deque(capacity) {
3959 this._capacity = getCapacity(capacity);
3960 this._length = 0;
3961 this._front = 0;
3962 if (isArray(capacity)) {
3963 var len = capacity.length;
3964 for (var i = 0; i < len; ++i) {
3965 this[i] = capacity[i];
3966 }
3967 this._length = len;
3968 }
3969}
3970
3971Deque.prototype.toArray = function Deque$toArray() {
3972 var len = this._length;
3973 var ret = new Array(len);
3974 var front = this._front;
3975 var capacity = this._capacity;
3976 for (var j = 0; j < len; ++j) {
3977 ret[j] = this[(front + j) & (capacity - 1)];
3978 }
3979 return ret;
3980};
3981
3982Deque.prototype.push = function Deque$push(item) {
3983 var argsLength = arguments.length;
3984 var length = this._length;
3985 if (argsLength > 1) {
3986 var capacity = this._capacity;
3987 if (length + argsLength > capacity) {
3988 for (var i = 0; i < argsLength; ++i) {
3989 this._checkCapacity(length + 1);
3990 var j = (this._front + length) & (this._capacity - 1);
3991 this[j] = arguments[i];
3992 length++;
3993 this._length = length;
3994 }
3995 return length;
3996 }
3997 else {
3998 var j = this._front;
3999 for (var i = 0; i < argsLength; ++i) {
4000 this[(j + length) & (capacity - 1)] = arguments[i];
4001 j++;
4002 }
4003 this._length = length + argsLength;
4004 return length + argsLength;
4005 }
4006
4007 }
4008
4009 if (argsLength === 0) return length;
4010
4011 this._checkCapacity(length + 1);
4012 var i = (this._front + length) & (this._capacity - 1);
4013 this[i] = item;
4014 this._length = length + 1;
4015 return length + 1;
4016};
4017
4018Deque.prototype.pop = function Deque$pop() {
4019 var length = this._length;
4020 if (length === 0) {
4021 return void 0;
4022 }
4023 var i = (this._front + length - 1) & (this._capacity - 1);
4024 var ret = this[i];
4025 this[i] = void 0;
4026 this._length = length - 1;
4027 return ret;
4028};
4029
4030Deque.prototype.shift = function Deque$shift() {
4031 var length = this._length;
4032 if (length === 0) {
4033 return void 0;
4034 }
4035 var front = this._front;
4036 var ret = this[front];
4037 this[front] = void 0;
4038 this._front = (front + 1) & (this._capacity - 1);
4039 this._length = length - 1;
4040 return ret;
4041};
4042
4043Deque.prototype.unshift = function Deque$unshift(item) {
4044 var length = this._length;
4045 var argsLength = arguments.length;
4046
4047
4048 if (argsLength > 1) {
4049 var capacity = this._capacity;
4050 if (length + argsLength > capacity) {
4051 for (var i = argsLength - 1; i >= 0; i--) {
4052 this._checkCapacity(length + 1);
4053 var capacity = this._capacity;
4054 var j = (((( this._front - 1 ) &
4055 ( capacity - 1) ) ^ capacity ) - capacity );
4056 this[j] = arguments[i];
4057 length++;
4058 this._length = length;
4059 this._front = j;
4060 }
4061 return length;
4062 }
4063 else {
4064 var front = this._front;
4065 for (var i = argsLength - 1; i >= 0; i--) {
4066 var j = (((( front - 1 ) &
4067 ( capacity - 1) ) ^ capacity ) - capacity );
4068 this[j] = arguments[i];
4069 front = j;
4070 }
4071 this._front = front;
4072 this._length = length + argsLength;
4073 return length + argsLength;
4074 }
4075 }
4076
4077 if (argsLength === 0) return length;
4078
4079 this._checkCapacity(length + 1);
4080 var capacity = this._capacity;
4081 var i = (((( this._front - 1 ) &
4082 ( capacity - 1) ) ^ capacity ) - capacity );
4083 this[i] = item;
4084 this._length = length + 1;
4085 this._front = i;
4086 return length + 1;
4087};
4088
4089Deque.prototype.peekBack = function Deque$peekBack() {
4090 var length = this._length;
4091 if (length === 0) {
4092 return void 0;
4093 }
4094 var index = (this._front + length - 1) & (this._capacity - 1);
4095 return this[index];
4096};
4097
4098Deque.prototype.peekFront = function Deque$peekFront() {
4099 if (this._length === 0) {
4100 return void 0;
4101 }
4102 return this[this._front];
4103};
4104
4105Deque.prototype.get = function Deque$get(index) {
4106 var i = index;
4107 if ((i !== (i | 0))) {
4108 return void 0;
4109 }
4110 var len = this._length;
4111 if (i < 0) {
4112 i = i + len;
4113 }
4114 if (i < 0 || i >= len) {
4115 return void 0;
4116 }
4117 return this[(this._front + i) & (this._capacity - 1)];
4118};
4119
4120Deque.prototype.isEmpty = function Deque$isEmpty() {
4121 return this._length === 0;
4122};
4123
4124Deque.prototype.clear = function Deque$clear() {
4125 var len = this._length;
4126 var front = this._front;
4127 var capacity = this._capacity;
4128 for (var j = 0; j < len; ++j) {
4129 this[(front + j) & (capacity - 1)] = void 0;
4130 }
4131 this._length = 0;
4132 this._front = 0;
4133};
4134
4135Deque.prototype.toString = function Deque$toString() {
4136 return this.toArray().toString();
4137};
4138
4139Deque.prototype.valueOf = Deque.prototype.toString;
4140Deque.prototype.removeFront = Deque.prototype.shift;
4141Deque.prototype.removeBack = Deque.prototype.pop;
4142Deque.prototype.insertFront = Deque.prototype.unshift;
4143Deque.prototype.insertBack = Deque.prototype.push;
4144Deque.prototype.enqueue = Deque.prototype.push;
4145Deque.prototype.dequeue = Deque.prototype.shift;
4146Deque.prototype.toJSON = Deque.prototype.toArray;
4147
4148Object.defineProperty(Deque.prototype, "length", {
4149 get: function() {
4150 return this._length;
4151 },
4152 set: function() {
4153 throw new RangeError("");
4154 }
4155});
4156
4157Deque.prototype._checkCapacity = function Deque$_checkCapacity(size) {
4158 if (this._capacity < size) {
4159 this._resizeTo(getCapacity(this._capacity * 1.5 + 16));
4160 }
4161};
4162
4163Deque.prototype._resizeTo = function Deque$_resizeTo(capacity) {
4164 var oldCapacity = this._capacity;
4165 this._capacity = capacity;
4166 var front = this._front;
4167 var length = this._length;
4168 if (front + length > oldCapacity) {
4169 var moveItemsCount = (front + length) & (oldCapacity - 1);
4170 arrayMove(this, 0, this, oldCapacity, moveItemsCount);
4171 }
4172};
4173
4174
4175var isArray = Array.isArray;
4176
4177function arrayMove(src, srcIndex, dst, dstIndex, len) {
4178 for (var j = 0; j < len; ++j) {
4179 dst[j + dstIndex] = src[j + srcIndex];
4180 src[j + srcIndex] = void 0;
4181 }
4182}
4183
4184function pow2AtLeast(n) {
4185 n = n >>> 0;
4186 n = n - 1;
4187 n = n | (n >> 1);
4188 n = n | (n >> 2);
4189 n = n | (n >> 4);
4190 n = n | (n >> 8);
4191 n = n | (n >> 16);
4192 return n + 1;
4193}
4194
4195function getCapacity(capacity) {
4196 if (typeof capacity !== "number") {
4197 if (isArray(capacity)) {
4198 capacity = capacity.length;
4199 }
4200 else {
4201 return 16;
4202 }
4203 }
4204 return pow2AtLeast(
4205 Math.min(
4206 Math.max(16, capacity), 1073741824)
4207 );
4208}
4209
4210module.exports = Deque;
4211
4212},{}],18:[function(_dereq_,module,exports){
4213var prr = _dereq_(67)
4214
4215function init (type, message, cause) {
4216 if (!!message && typeof message != 'string') {
4217 message = message.message || message.name
4218 }
4219 prr(this, {
4220 type : type
4221 , name : type
4222 // can be passed just a 'cause'
4223 , cause : typeof message != 'string' ? message : cause
4224 , message : message
4225 }, 'ewr')
4226}
4227
4228// generic prototype, not intended to be actually used - helpful for `instanceof`
4229function CustomError (message, cause) {
4230 Error.call(this)
4231 if (Error.captureStackTrace)
4232 Error.captureStackTrace(this, this.constructor)
4233 init.call(this, 'CustomError', message, cause)
4234}
4235
4236CustomError.prototype = new Error()
4237
4238function createError (errno, type, proto) {
4239 var err = function (message, cause) {
4240 init.call(this, type, message, cause)
4241 //TODO: the specificity here is stupid, errno should be available everywhere
4242 if (type == 'FilesystemError') {
4243 this.code = this.cause.code
4244 this.path = this.cause.path
4245 this.errno = this.cause.errno
4246 this.message =
4247 (errno.errno[this.cause.errno]
4248 ? errno.errno[this.cause.errno].description
4249 : this.cause.message)
4250 + (this.cause.path ? ' [' + this.cause.path + ']' : '')
4251 }
4252 Error.call(this)
4253 if (Error.captureStackTrace)
4254 Error.captureStackTrace(this, err)
4255 }
4256 err.prototype = !!proto ? new proto() : new CustomError()
4257 return err
4258}
4259
4260module.exports = function (errno) {
4261 var ce = function (type, proto) {
4262 return createError(errno, type, proto)
4263 }
4264 return {
4265 CustomError : CustomError
4266 , FilesystemError : ce('FilesystemError')
4267 , createError : ce
4268 }
4269}
4270
4271},{"67":67}],19:[function(_dereq_,module,exports){
4272var all = module.exports.all = [
4273 {
4274 errno: -2,
4275 code: 'ENOENT',
4276 description: 'no such file or directory'
4277 },
4278 {
4279 errno: -1,
4280 code: 'UNKNOWN',
4281 description: 'unknown error'
4282 },
4283 {
4284 errno: 0,
4285 code: 'OK',
4286 description: 'success'
4287 },
4288 {
4289 errno: 1,
4290 code: 'EOF',
4291 description: 'end of file'
4292 },
4293 {
4294 errno: 2,
4295 code: 'EADDRINFO',
4296 description: 'getaddrinfo error'
4297 },
4298 {
4299 errno: 3,
4300 code: 'EACCES',
4301 description: 'permission denied'
4302 },
4303 {
4304 errno: 4,
4305 code: 'EAGAIN',
4306 description: 'resource temporarily unavailable'
4307 },
4308 {
4309 errno: 5,
4310 code: 'EADDRINUSE',
4311 description: 'address already in use'
4312 },
4313 {
4314 errno: 6,
4315 code: 'EADDRNOTAVAIL',
4316 description: 'address not available'
4317 },
4318 {
4319 errno: 7,
4320 code: 'EAFNOSUPPORT',
4321 description: 'address family not supported'
4322 },
4323 {
4324 errno: 8,
4325 code: 'EALREADY',
4326 description: 'connection already in progress'
4327 },
4328 {
4329 errno: 9,
4330 code: 'EBADF',
4331 description: 'bad file descriptor'
4332 },
4333 {
4334 errno: 10,
4335 code: 'EBUSY',
4336 description: 'resource busy or locked'
4337 },
4338 {
4339 errno: 11,
4340 code: 'ECONNABORTED',
4341 description: 'software caused connection abort'
4342 },
4343 {
4344 errno: 12,
4345 code: 'ECONNREFUSED',
4346 description: 'connection refused'
4347 },
4348 {
4349 errno: 13,
4350 code: 'ECONNRESET',
4351 description: 'connection reset by peer'
4352 },
4353 {
4354 errno: 14,
4355 code: 'EDESTADDRREQ',
4356 description: 'destination address required'
4357 },
4358 {
4359 errno: 15,
4360 code: 'EFAULT',
4361 description: 'bad address in system call argument'
4362 },
4363 {
4364 errno: 16,
4365 code: 'EHOSTUNREACH',
4366 description: 'host is unreachable'
4367 },
4368 {
4369 errno: 17,
4370 code: 'EINTR',
4371 description: 'interrupted system call'
4372 },
4373 {
4374 errno: 18,
4375 code: 'EINVAL',
4376 description: 'invalid argument'
4377 },
4378 {
4379 errno: 19,
4380 code: 'EISCONN',
4381 description: 'socket is already connected'
4382 },
4383 {
4384 errno: 20,
4385 code: 'EMFILE',
4386 description: 'too many open files'
4387 },
4388 {
4389 errno: 21,
4390 code: 'EMSGSIZE',
4391 description: 'message too long'
4392 },
4393 {
4394 errno: 22,
4395 code: 'ENETDOWN',
4396 description: 'network is down'
4397 },
4398 {
4399 errno: 23,
4400 code: 'ENETUNREACH',
4401 description: 'network is unreachable'
4402 },
4403 {
4404 errno: 24,
4405 code: 'ENFILE',
4406 description: 'file table overflow'
4407 },
4408 {
4409 errno: 25,
4410 code: 'ENOBUFS',
4411 description: 'no buffer space available'
4412 },
4413 {
4414 errno: 26,
4415 code: 'ENOMEM',
4416 description: 'not enough memory'
4417 },
4418 {
4419 errno: 27,
4420 code: 'ENOTDIR',
4421 description: 'not a directory'
4422 },
4423 {
4424 errno: 28,
4425 code: 'EISDIR',
4426 description: 'illegal operation on a directory'
4427 },
4428 {
4429 errno: 29,
4430 code: 'ENONET',
4431 description: 'machine is not on the network'
4432 },
4433 {
4434 errno: 31,
4435 code: 'ENOTCONN',
4436 description: 'socket is not connected'
4437 },
4438 {
4439 errno: 32,
4440 code: 'ENOTSOCK',
4441 description: 'socket operation on non-socket'
4442 },
4443 {
4444 errno: 33,
4445 code: 'ENOTSUP',
4446 description: 'operation not supported on socket'
4447 },
4448 {
4449 errno: 34,
4450 code: 'ENOENT',
4451 description: 'no such file or directory'
4452 },
4453 {
4454 errno: 35,
4455 code: 'ENOSYS',
4456 description: 'function not implemented'
4457 },
4458 {
4459 errno: 36,
4460 code: 'EPIPE',
4461 description: 'broken pipe'
4462 },
4463 {
4464 errno: 37,
4465 code: 'EPROTO',
4466 description: 'protocol error'
4467 },
4468 {
4469 errno: 38,
4470 code: 'EPROTONOSUPPORT',
4471 description: 'protocol not supported'
4472 },
4473 {
4474 errno: 39,
4475 code: 'EPROTOTYPE',
4476 description: 'protocol wrong type for socket'
4477 },
4478 {
4479 errno: 40,
4480 code: 'ETIMEDOUT',
4481 description: 'connection timed out'
4482 },
4483 {
4484 errno: 41,
4485 code: 'ECHARSET',
4486 description: 'invalid Unicode character'
4487 },
4488 {
4489 errno: 42,
4490 code: 'EAIFAMNOSUPPORT',
4491 description: 'address family for hostname not supported'
4492 },
4493 {
4494 errno: 44,
4495 code: 'EAISERVICE',
4496 description: 'servname not supported for ai_socktype'
4497 },
4498 {
4499 errno: 45,
4500 code: 'EAISOCKTYPE',
4501 description: 'ai_socktype not supported'
4502 },
4503 {
4504 errno: 46,
4505 code: 'ESHUTDOWN',
4506 description: 'cannot send after transport endpoint shutdown'
4507 },
4508 {
4509 errno: 47,
4510 code: 'EEXIST',
4511 description: 'file already exists'
4512 },
4513 {
4514 errno: 48,
4515 code: 'ESRCH',
4516 description: 'no such process'
4517 },
4518 {
4519 errno: 49,
4520 code: 'ENAMETOOLONG',
4521 description: 'name too long'
4522 },
4523 {
4524 errno: 50,
4525 code: 'EPERM',
4526 description: 'operation not permitted'
4527 },
4528 {
4529 errno: 51,
4530 code: 'ELOOP',
4531 description: 'too many symbolic links encountered'
4532 },
4533 {
4534 errno: 52,
4535 code: 'EXDEV',
4536 description: 'cross-device link not permitted'
4537 },
4538 {
4539 errno: 53,
4540 code: 'ENOTEMPTY',
4541 description: 'directory not empty'
4542 },
4543 {
4544 errno: 54,
4545 code: 'ENOSPC',
4546 description: 'no space left on device'
4547 },
4548 {
4549 errno: 55,
4550 code: 'EIO',
4551 description: 'i/o error'
4552 },
4553 {
4554 errno: 56,
4555 code: 'EROFS',
4556 description: 'read-only file system'
4557 },
4558 {
4559 errno: 57,
4560 code: 'ENODEV',
4561 description: 'no such device'
4562 },
4563 {
4564 errno: 58,
4565 code: 'ESPIPE',
4566 description: 'invalid seek'
4567 },
4568 {
4569 errno: 59,
4570 code: 'ECANCELED',
4571 description: 'operation canceled'
4572 }
4573]
4574
4575module.exports.errno = {}
4576module.exports.code = {}
4577
4578all.forEach(function (error) {
4579 module.exports.errno[error.errno] = error
4580 module.exports.code[error.code] = error
4581})
4582
4583module.exports.custom = _dereq_(18)(module.exports)
4584module.exports.create = module.exports.custom.createError
4585
4586},{"18":18}],20:[function(_dereq_,module,exports){
4587// Copyright Joyent, Inc. and other Node contributors.
4588//
4589// Permission is hereby granted, free of charge, to any person obtaining a
4590// copy of this software and associated documentation files (the
4591// "Software"), to deal in the Software without restriction, including
4592// without limitation the rights to use, copy, modify, merge, publish,
4593// distribute, sublicense, and/or sell copies of the Software, and to permit
4594// persons to whom the Software is furnished to do so, subject to the
4595// following conditions:
4596//
4597// The above copyright notice and this permission notice shall be included
4598// in all copies or substantial portions of the Software.
4599//
4600// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4601// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4602// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4603// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4604// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4605// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4606// USE OR OTHER DEALINGS IN THE SOFTWARE.
4607
4608var objectCreate = Object.create || objectCreatePolyfill
4609var objectKeys = Object.keys || objectKeysPolyfill
4610var bind = Function.prototype.bind || functionBindPolyfill
4611
4612function EventEmitter() {
4613 if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
4614 this._events = objectCreate(null);
4615 this._eventsCount = 0;
4616 }
4617
4618 this._maxListeners = this._maxListeners || undefined;
4619}
4620module.exports = EventEmitter;
4621
4622// Backwards-compat with node 0.10.x
4623EventEmitter.EventEmitter = EventEmitter;
4624
4625EventEmitter.prototype._events = undefined;
4626EventEmitter.prototype._maxListeners = undefined;
4627
4628// By default EventEmitters will print a warning if more than 10 listeners are
4629// added to it. This is a useful default which helps finding memory leaks.
4630var defaultMaxListeners = 10;
4631
4632var hasDefineProperty;
4633try {
4634 var o = {};
4635 if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
4636 hasDefineProperty = o.x === 0;
4637} catch (err) { hasDefineProperty = false }
4638if (hasDefineProperty) {
4639 Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
4640 enumerable: true,
4641 get: function() {
4642 return defaultMaxListeners;
4643 },
4644 set: function(arg) {
4645 // check whether the input is a positive number (whose value is zero or
4646 // greater and not a NaN).
4647 if (typeof arg !== 'number' || arg < 0 || arg !== arg)
4648 throw new TypeError('"defaultMaxListeners" must be a positive number');
4649 defaultMaxListeners = arg;
4650 }
4651 });
4652} else {
4653 EventEmitter.defaultMaxListeners = defaultMaxListeners;
4654}
4655
4656// Obviously not all Emitters should be limited to 10. This function allows
4657// that to be increased. Set to zero for unlimited.
4658EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
4659 if (typeof n !== 'number' || n < 0 || isNaN(n))
4660 throw new TypeError('"n" argument must be a positive number');
4661 this._maxListeners = n;
4662 return this;
4663};
4664
4665function $getMaxListeners(that) {
4666 if (that._maxListeners === undefined)
4667 return EventEmitter.defaultMaxListeners;
4668 return that._maxListeners;
4669}
4670
4671EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
4672 return $getMaxListeners(this);
4673};
4674
4675// These standalone emit* functions are used to optimize calling of event
4676// handlers for fast cases because emit() itself often has a variable number of
4677// arguments and can be deoptimized because of that. These functions always have
4678// the same number of arguments and thus do not get deoptimized, so the code
4679// inside them can execute faster.
4680function emitNone(handler, isFn, self) {
4681 if (isFn)
4682 handler.call(self);
4683 else {
4684 var len = handler.length;
4685 var listeners = arrayClone(handler, len);
4686 for (var i = 0; i < len; ++i)
4687 listeners[i].call(self);
4688 }
4689}
4690function emitOne(handler, isFn, self, arg1) {
4691 if (isFn)
4692 handler.call(self, arg1);
4693 else {
4694 var len = handler.length;
4695 var listeners = arrayClone(handler, len);
4696 for (var i = 0; i < len; ++i)
4697 listeners[i].call(self, arg1);
4698 }
4699}
4700function emitTwo(handler, isFn, self, arg1, arg2) {
4701 if (isFn)
4702 handler.call(self, arg1, arg2);
4703 else {
4704 var len = handler.length;
4705 var listeners = arrayClone(handler, len);
4706 for (var i = 0; i < len; ++i)
4707 listeners[i].call(self, arg1, arg2);
4708 }
4709}
4710function emitThree(handler, isFn, self, arg1, arg2, arg3) {
4711 if (isFn)
4712 handler.call(self, arg1, arg2, arg3);
4713 else {
4714 var len = handler.length;
4715 var listeners = arrayClone(handler, len);
4716 for (var i = 0; i < len; ++i)
4717 listeners[i].call(self, arg1, arg2, arg3);
4718 }
4719}
4720
4721function emitMany(handler, isFn, self, args) {
4722 if (isFn)
4723 handler.apply(self, args);
4724 else {
4725 var len = handler.length;
4726 var listeners = arrayClone(handler, len);
4727 for (var i = 0; i < len; ++i)
4728 listeners[i].apply(self, args);
4729 }
4730}
4731
4732EventEmitter.prototype.emit = function emit(type) {
4733 var er, handler, len, args, i, events;
4734 var doError = (type === 'error');
4735
4736 events = this._events;
4737 if (events)
4738 doError = (doError && events.error == null);
4739 else if (!doError)
4740 return false;
4741
4742 // If there is no 'error' event listener then throw.
4743 if (doError) {
4744 if (arguments.length > 1)
4745 er = arguments[1];
4746 if (er instanceof Error) {
4747 throw er; // Unhandled 'error' event
4748 } else {
4749 // At least give some kind of context to the user
4750 var err = new Error('Unhandled "error" event. (' + er + ')');
4751 err.context = er;
4752 throw err;
4753 }
4754 return false;
4755 }
4756
4757 handler = events[type];
4758
4759 if (!handler)
4760 return false;
4761
4762 var isFn = typeof handler === 'function';
4763 len = arguments.length;
4764 switch (len) {
4765 // fast cases
4766 case 1:
4767 emitNone(handler, isFn, this);
4768 break;
4769 case 2:
4770 emitOne(handler, isFn, this, arguments[1]);
4771 break;
4772 case 3:
4773 emitTwo(handler, isFn, this, arguments[1], arguments[2]);
4774 break;
4775 case 4:
4776 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
4777 break;
4778 // slower
4779 default:
4780 args = new Array(len - 1);
4781 for (i = 1; i < len; i++)
4782 args[i - 1] = arguments[i];
4783 emitMany(handler, isFn, this, args);
4784 }
4785
4786 return true;
4787};
4788
4789function _addListener(target, type, listener, prepend) {
4790 var m;
4791 var events;
4792 var existing;
4793
4794 if (typeof listener !== 'function')
4795 throw new TypeError('"listener" argument must be a function');
4796
4797 events = target._events;
4798 if (!events) {
4799 events = target._events = objectCreate(null);
4800 target._eventsCount = 0;
4801 } else {
4802 // To avoid recursion in the case that type === "newListener"! Before
4803 // adding it to the listeners, first emit "newListener".
4804 if (events.newListener) {
4805 target.emit('newListener', type,
4806 listener.listener ? listener.listener : listener);
4807
4808 // Re-assign `events` because a newListener handler could have caused the
4809 // this._events to be assigned to a new object
4810 events = target._events;
4811 }
4812 existing = events[type];
4813 }
4814
4815 if (!existing) {
4816 // Optimize the case of one listener. Don't need the extra array object.
4817 existing = events[type] = listener;
4818 ++target._eventsCount;
4819 } else {
4820 if (typeof existing === 'function') {
4821 // Adding the second element, need to change to array.
4822 existing = events[type] =
4823 prepend ? [listener, existing] : [existing, listener];
4824 } else {
4825 // If we've already got an array, just append.
4826 if (prepend) {
4827 existing.unshift(listener);
4828 } else {
4829 existing.push(listener);
4830 }
4831 }
4832
4833 // Check for listener leak
4834 if (!existing.warned) {
4835 m = $getMaxListeners(target);
4836 if (m && m > 0 && existing.length > m) {
4837 existing.warned = true;
4838 var w = new Error('Possible EventEmitter memory leak detected. ' +
4839 existing.length + ' "' + String(type) + '" listeners ' +
4840 'added. Use emitter.setMaxListeners() to ' +
4841 'increase limit.');
4842 w.name = 'MaxListenersExceededWarning';
4843 w.emitter = target;
4844 w.type = type;
4845 w.count = existing.length;
4846 if (typeof console === 'object' && console.warn) {
4847 console.warn('%s: %s', w.name, w.message);
4848 }
4849 }
4850 }
4851 }
4852
4853 return target;
4854}
4855
4856EventEmitter.prototype.addListener = function addListener(type, listener) {
4857 return _addListener(this, type, listener, false);
4858};
4859
4860EventEmitter.prototype.on = EventEmitter.prototype.addListener;
4861
4862EventEmitter.prototype.prependListener =
4863 function prependListener(type, listener) {
4864 return _addListener(this, type, listener, true);
4865 };
4866
4867function onceWrapper() {
4868 if (!this.fired) {
4869 this.target.removeListener(this.type, this.wrapFn);
4870 this.fired = true;
4871 switch (arguments.length) {
4872 case 0:
4873 return this.listener.call(this.target);
4874 case 1:
4875 return this.listener.call(this.target, arguments[0]);
4876 case 2:
4877 return this.listener.call(this.target, arguments[0], arguments[1]);
4878 case 3:
4879 return this.listener.call(this.target, arguments[0], arguments[1],
4880 arguments[2]);
4881 default:
4882 var args = new Array(arguments.length);
4883 for (var i = 0; i < args.length; ++i)
4884 args[i] = arguments[i];
4885 this.listener.apply(this.target, args);
4886 }
4887 }
4888}
4889
4890function _onceWrap(target, type, listener) {
4891 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
4892 var wrapped = bind.call(onceWrapper, state);
4893 wrapped.listener = listener;
4894 state.wrapFn = wrapped;
4895 return wrapped;
4896}
4897
4898EventEmitter.prototype.once = function once(type, listener) {
4899 if (typeof listener !== 'function')
4900 throw new TypeError('"listener" argument must be a function');
4901 this.on(type, _onceWrap(this, type, listener));
4902 return this;
4903};
4904
4905EventEmitter.prototype.prependOnceListener =
4906 function prependOnceListener(type, listener) {
4907 if (typeof listener !== 'function')
4908 throw new TypeError('"listener" argument must be a function');
4909 this.prependListener(type, _onceWrap(this, type, listener));
4910 return this;
4911 };
4912
4913// Emits a 'removeListener' event if and only if the listener was removed.
4914EventEmitter.prototype.removeListener =
4915 function removeListener(type, listener) {
4916 var list, events, position, i, originalListener;
4917
4918 if (typeof listener !== 'function')
4919 throw new TypeError('"listener" argument must be a function');
4920
4921 events = this._events;
4922 if (!events)
4923 return this;
4924
4925 list = events[type];
4926 if (!list)
4927 return this;
4928
4929 if (list === listener || list.listener === listener) {
4930 if (--this._eventsCount === 0)
4931 this._events = objectCreate(null);
4932 else {
4933 delete events[type];
4934 if (events.removeListener)
4935 this.emit('removeListener', type, list.listener || listener);
4936 }
4937 } else if (typeof list !== 'function') {
4938 position = -1;
4939
4940 for (i = list.length - 1; i >= 0; i--) {
4941 if (list[i] === listener || list[i].listener === listener) {
4942 originalListener = list[i].listener;
4943 position = i;
4944 break;
4945 }
4946 }
4947
4948 if (position < 0)
4949 return this;
4950
4951 if (position === 0)
4952 list.shift();
4953 else
4954 spliceOne(list, position);
4955
4956 if (list.length === 1)
4957 events[type] = list[0];
4958
4959 if (events.removeListener)
4960 this.emit('removeListener', type, originalListener || listener);
4961 }
4962
4963 return this;
4964 };
4965
4966EventEmitter.prototype.removeAllListeners =
4967 function removeAllListeners(type) {
4968 var listeners, events, i;
4969
4970 events = this._events;
4971 if (!events)
4972 return this;
4973
4974 // not listening for removeListener, no need to emit
4975 if (!events.removeListener) {
4976 if (arguments.length === 0) {
4977 this._events = objectCreate(null);
4978 this._eventsCount = 0;
4979 } else if (events[type]) {
4980 if (--this._eventsCount === 0)
4981 this._events = objectCreate(null);
4982 else
4983 delete events[type];
4984 }
4985 return this;
4986 }
4987
4988 // emit removeListener for all listeners on all events
4989 if (arguments.length === 0) {
4990 var keys = objectKeys(events);
4991 var key;
4992 for (i = 0; i < keys.length; ++i) {
4993 key = keys[i];
4994 if (key === 'removeListener') continue;
4995 this.removeAllListeners(key);
4996 }
4997 this.removeAllListeners('removeListener');
4998 this._events = objectCreate(null);
4999 this._eventsCount = 0;
5000 return this;
5001 }
5002
5003 listeners = events[type];
5004
5005 if (typeof listeners === 'function') {
5006 this.removeListener(type, listeners);
5007 } else if (listeners) {
5008 // LIFO order
5009 for (i = listeners.length - 1; i >= 0; i--) {
5010 this.removeListener(type, listeners[i]);
5011 }
5012 }
5013
5014 return this;
5015 };
5016
5017function _listeners(target, type, unwrap) {
5018 var events = target._events;
5019
5020 if (!events)
5021 return [];
5022
5023 var evlistener = events[type];
5024 if (!evlistener)
5025 return [];
5026
5027 if (typeof evlistener === 'function')
5028 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
5029
5030 return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
5031}
5032
5033EventEmitter.prototype.listeners = function listeners(type) {
5034 return _listeners(this, type, true);
5035};
5036
5037EventEmitter.prototype.rawListeners = function rawListeners(type) {
5038 return _listeners(this, type, false);
5039};
5040
5041EventEmitter.listenerCount = function(emitter, type) {
5042 if (typeof emitter.listenerCount === 'function') {
5043 return emitter.listenerCount(type);
5044 } else {
5045 return listenerCount.call(emitter, type);
5046 }
5047};
5048
5049EventEmitter.prototype.listenerCount = listenerCount;
5050function listenerCount(type) {
5051 var events = this._events;
5052
5053 if (events) {
5054 var evlistener = events[type];
5055
5056 if (typeof evlistener === 'function') {
5057 return 1;
5058 } else if (evlistener) {
5059 return evlistener.length;
5060 }
5061 }
5062
5063 return 0;
5064}
5065
5066EventEmitter.prototype.eventNames = function eventNames() {
5067 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
5068};
5069
5070// About 1.5x faster than the two-arg version of Array#splice().
5071function spliceOne(list, index) {
5072 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
5073 list[i] = list[k];
5074 list.pop();
5075}
5076
5077function arrayClone(arr, n) {
5078 var copy = new Array(n);
5079 for (var i = 0; i < n; ++i)
5080 copy[i] = arr[i];
5081 return copy;
5082}
5083
5084function unwrapListeners(arr) {
5085 var ret = new Array(arr.length);
5086 for (var i = 0; i < ret.length; ++i) {
5087 ret[i] = arr[i].listener || arr[i];
5088 }
5089 return ret;
5090}
5091
5092function objectCreatePolyfill(proto) {
5093 var F = function() {};
5094 F.prototype = proto;
5095 return new F;
5096}
5097function objectKeysPolyfill(obj) {
5098 var keys = [];
5099 for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
5100 keys.push(k);
5101 }
5102 return k;
5103}
5104function functionBindPolyfill(context) {
5105 var fn = this;
5106 return function () {
5107 return fn.apply(context, arguments);
5108 };
5109}
5110
5111},{}],21:[function(_dereq_,module,exports){
5112"use strict"
5113
5114module.exports = createRBTree
5115
5116var RED = 0
5117var BLACK = 1
5118
5119function RBNode(color, key, value, left, right, count) {
5120 this._color = color
5121 this.key = key
5122 this.value = value
5123 this.left = left
5124 this.right = right
5125 this._count = count
5126}
5127
5128function cloneNode(node) {
5129 return new RBNode(node._color, node.key, node.value, node.left, node.right, node._count)
5130}
5131
5132function repaint(color, node) {
5133 return new RBNode(color, node.key, node.value, node.left, node.right, node._count)
5134}
5135
5136function recount(node) {
5137 node._count = 1 + (node.left ? node.left._count : 0) + (node.right ? node.right._count : 0)
5138}
5139
5140function RedBlackTree(compare, root) {
5141 this._compare = compare
5142 this.root = root
5143}
5144
5145var proto = RedBlackTree.prototype
5146
5147Object.defineProperty(proto, "keys", {
5148 get: function() {
5149 var result = []
5150 this.forEach(function(k,v) {
5151 result.push(k)
5152 })
5153 return result
5154 }
5155})
5156
5157Object.defineProperty(proto, "values", {
5158 get: function() {
5159 var result = []
5160 this.forEach(function(k,v) {
5161 result.push(v)
5162 })
5163 return result
5164 }
5165})
5166
5167//Returns the number of nodes in the tree
5168Object.defineProperty(proto, "length", {
5169 get: function() {
5170 if(this.root) {
5171 return this.root._count
5172 }
5173 return 0
5174 }
5175})
5176
5177//Insert a new item into the tree
5178proto.insert = function(key, value) {
5179 var cmp = this._compare
5180 //Find point to insert new node at
5181 var n = this.root
5182 var n_stack = []
5183 var d_stack = []
5184 while(n) {
5185 var d = cmp(key, n.key)
5186 n_stack.push(n)
5187 d_stack.push(d)
5188 if(d <= 0) {
5189 n = n.left
5190 } else {
5191 n = n.right
5192 }
5193 }
5194 //Rebuild path to leaf node
5195 n_stack.push(new RBNode(RED, key, value, null, null, 1))
5196 for(var s=n_stack.length-2; s>=0; --s) {
5197 var n = n_stack[s]
5198 if(d_stack[s] <= 0) {
5199 n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s+1], n.right, n._count+1)
5200 } else {
5201 n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s+1], n._count+1)
5202 }
5203 }
5204 //Rebalance tree using rotations
5205 //console.log("start insert", key, d_stack)
5206 for(var s=n_stack.length-1; s>1; --s) {
5207 var p = n_stack[s-1]
5208 var n = n_stack[s]
5209 if(p._color === BLACK || n._color === BLACK) {
5210 break
5211 }
5212 var pp = n_stack[s-2]
5213 if(pp.left === p) {
5214 if(p.left === n) {
5215 var y = pp.right
5216 if(y && y._color === RED) {
5217 //console.log("LLr")
5218 p._color = BLACK
5219 pp.right = repaint(BLACK, y)
5220 pp._color = RED
5221 s -= 1
5222 } else {
5223 //console.log("LLb")
5224 pp._color = RED
5225 pp.left = p.right
5226 p._color = BLACK
5227 p.right = pp
5228 n_stack[s-2] = p
5229 n_stack[s-1] = n
5230 recount(pp)
5231 recount(p)
5232 if(s >= 3) {
5233 var ppp = n_stack[s-3]
5234 if(ppp.left === pp) {
5235 ppp.left = p
5236 } else {
5237 ppp.right = p
5238 }
5239 }
5240 break
5241 }
5242 } else {
5243 var y = pp.right
5244 if(y && y._color === RED) {
5245 //console.log("LRr")
5246 p._color = BLACK
5247 pp.right = repaint(BLACK, y)
5248 pp._color = RED
5249 s -= 1
5250 } else {
5251 //console.log("LRb")
5252 p.right = n.left
5253 pp._color = RED
5254 pp.left = n.right
5255 n._color = BLACK
5256 n.left = p
5257 n.right = pp
5258 n_stack[s-2] = n
5259 n_stack[s-1] = p
5260 recount(pp)
5261 recount(p)
5262 recount(n)
5263 if(s >= 3) {
5264 var ppp = n_stack[s-3]
5265 if(ppp.left === pp) {
5266 ppp.left = n
5267 } else {
5268 ppp.right = n
5269 }
5270 }
5271 break
5272 }
5273 }
5274 } else {
5275 if(p.right === n) {
5276 var y = pp.left
5277 if(y && y._color === RED) {
5278 //console.log("RRr", y.key)
5279 p._color = BLACK
5280 pp.left = repaint(BLACK, y)
5281 pp._color = RED
5282 s -= 1
5283 } else {
5284 //console.log("RRb")
5285 pp._color = RED
5286 pp.right = p.left
5287 p._color = BLACK
5288 p.left = pp
5289 n_stack[s-2] = p
5290 n_stack[s-1] = n
5291 recount(pp)
5292 recount(p)
5293 if(s >= 3) {
5294 var ppp = n_stack[s-3]
5295 if(ppp.right === pp) {
5296 ppp.right = p
5297 } else {
5298 ppp.left = p
5299 }
5300 }
5301 break
5302 }
5303 } else {
5304 var y = pp.left
5305 if(y && y._color === RED) {
5306 //console.log("RLr")
5307 p._color = BLACK
5308 pp.left = repaint(BLACK, y)
5309 pp._color = RED
5310 s -= 1
5311 } else {
5312 //console.log("RLb")
5313 p.left = n.right
5314 pp._color = RED
5315 pp.right = n.left
5316 n._color = BLACK
5317 n.right = p
5318 n.left = pp
5319 n_stack[s-2] = n
5320 n_stack[s-1] = p
5321 recount(pp)
5322 recount(p)
5323 recount(n)
5324 if(s >= 3) {
5325 var ppp = n_stack[s-3]
5326 if(ppp.right === pp) {
5327 ppp.right = n
5328 } else {
5329 ppp.left = n
5330 }
5331 }
5332 break
5333 }
5334 }
5335 }
5336 }
5337 //Return new tree
5338 n_stack[0]._color = BLACK
5339 return new RedBlackTree(cmp, n_stack[0])
5340}
5341
5342
5343//Visit all nodes inorder
5344function doVisitFull(visit, node) {
5345 if(node.left) {
5346 var v = doVisitFull(visit, node.left)
5347 if(v) { return v }
5348 }
5349 var v = visit(node.key, node.value)
5350 if(v) { return v }
5351 if(node.right) {
5352 return doVisitFull(visit, node.right)
5353 }
5354}
5355
5356//Visit half nodes in order
5357function doVisitHalf(lo, compare, visit, node) {
5358 var l = compare(lo, node.key)
5359 if(l <= 0) {
5360 if(node.left) {
5361 var v = doVisitHalf(lo, compare, visit, node.left)
5362 if(v) { return v }
5363 }
5364 var v = visit(node.key, node.value)
5365 if(v) { return v }
5366 }
5367 if(node.right) {
5368 return doVisitHalf(lo, compare, visit, node.right)
5369 }
5370}
5371
5372//Visit all nodes within a range
5373function doVisit(lo, hi, compare, visit, node) {
5374 var l = compare(lo, node.key)
5375 var h = compare(hi, node.key)
5376 var v
5377 if(l <= 0) {
5378 if(node.left) {
5379 v = doVisit(lo, hi, compare, visit, node.left)
5380 if(v) { return v }
5381 }
5382 if(h > 0) {
5383 v = visit(node.key, node.value)
5384 if(v) { return v }
5385 }
5386 }
5387 if(h > 0 && node.right) {
5388 return doVisit(lo, hi, compare, visit, node.right)
5389 }
5390}
5391
5392
5393proto.forEach = function rbTreeForEach(visit, lo, hi) {
5394 if(!this.root) {
5395 return
5396 }
5397 switch(arguments.length) {
5398 case 1:
5399 return doVisitFull(visit, this.root)
5400 break
5401
5402 case 2:
5403 return doVisitHalf(lo, this._compare, visit, this.root)
5404 break
5405
5406 case 3:
5407 if(this._compare(lo, hi) >= 0) {
5408 return
5409 }
5410 return doVisit(lo, hi, this._compare, visit, this.root)
5411 break
5412 }
5413}
5414
5415//First item in list
5416Object.defineProperty(proto, "begin", {
5417 get: function() {
5418 var stack = []
5419 var n = this.root
5420 while(n) {
5421 stack.push(n)
5422 n = n.left
5423 }
5424 return new RedBlackTreeIterator(this, stack)
5425 }
5426})
5427
5428//Last item in list
5429Object.defineProperty(proto, "end", {
5430 get: function() {
5431 var stack = []
5432 var n = this.root
5433 while(n) {
5434 stack.push(n)
5435 n = n.right
5436 }
5437 return new RedBlackTreeIterator(this, stack)
5438 }
5439})
5440
5441//Find the ith item in the tree
5442proto.at = function(idx) {
5443 if(idx < 0) {
5444 return new RedBlackTreeIterator(this, [])
5445 }
5446 var n = this.root
5447 var stack = []
5448 while(true) {
5449 stack.push(n)
5450 if(n.left) {
5451 if(idx < n.left._count) {
5452 n = n.left
5453 continue
5454 }
5455 idx -= n.left._count
5456 }
5457 if(!idx) {
5458 return new RedBlackTreeIterator(this, stack)
5459 }
5460 idx -= 1
5461 if(n.right) {
5462 if(idx >= n.right._count) {
5463 break
5464 }
5465 n = n.right
5466 } else {
5467 break
5468 }
5469 }
5470 return new RedBlackTreeIterator(this, [])
5471}
5472
5473proto.ge = function(key) {
5474 var cmp = this._compare
5475 var n = this.root
5476 var stack = []
5477 var last_ptr = 0
5478 while(n) {
5479 var d = cmp(key, n.key)
5480 stack.push(n)
5481 if(d <= 0) {
5482 last_ptr = stack.length
5483 }
5484 if(d <= 0) {
5485 n = n.left
5486 } else {
5487 n = n.right
5488 }
5489 }
5490 stack.length = last_ptr
5491 return new RedBlackTreeIterator(this, stack)
5492}
5493
5494proto.gt = function(key) {
5495 var cmp = this._compare
5496 var n = this.root
5497 var stack = []
5498 var last_ptr = 0
5499 while(n) {
5500 var d = cmp(key, n.key)
5501 stack.push(n)
5502 if(d < 0) {
5503 last_ptr = stack.length
5504 }
5505 if(d < 0) {
5506 n = n.left
5507 } else {
5508 n = n.right
5509 }
5510 }
5511 stack.length = last_ptr
5512 return new RedBlackTreeIterator(this, stack)
5513}
5514
5515proto.lt = function(key) {
5516 var cmp = this._compare
5517 var n = this.root
5518 var stack = []
5519 var last_ptr = 0
5520 while(n) {
5521 var d = cmp(key, n.key)
5522 stack.push(n)
5523 if(d > 0) {
5524 last_ptr = stack.length
5525 }
5526 if(d <= 0) {
5527 n = n.left
5528 } else {
5529 n = n.right
5530 }
5531 }
5532 stack.length = last_ptr
5533 return new RedBlackTreeIterator(this, stack)
5534}
5535
5536proto.le = function(key) {
5537 var cmp = this._compare
5538 var n = this.root
5539 var stack = []
5540 var last_ptr = 0
5541 while(n) {
5542 var d = cmp(key, n.key)
5543 stack.push(n)
5544 if(d >= 0) {
5545 last_ptr = stack.length
5546 }
5547 if(d < 0) {
5548 n = n.left
5549 } else {
5550 n = n.right
5551 }
5552 }
5553 stack.length = last_ptr
5554 return new RedBlackTreeIterator(this, stack)
5555}
5556
5557//Finds the item with key if it exists
5558proto.find = function(key) {
5559 var cmp = this._compare
5560 var n = this.root
5561 var stack = []
5562 while(n) {
5563 var d = cmp(key, n.key)
5564 stack.push(n)
5565 if(d === 0) {
5566 return new RedBlackTreeIterator(this, stack)
5567 }
5568 if(d <= 0) {
5569 n = n.left
5570 } else {
5571 n = n.right
5572 }
5573 }
5574 return new RedBlackTreeIterator(this, [])
5575}
5576
5577//Removes item with key from tree
5578proto.remove = function(key) {
5579 var iter = this.find(key)
5580 if(iter) {
5581 return iter.remove()
5582 }
5583 return this
5584}
5585
5586//Returns the item at `key`
5587proto.get = function(key) {
5588 var cmp = this._compare
5589 var n = this.root
5590 while(n) {
5591 var d = cmp(key, n.key)
5592 if(d === 0) {
5593 return n.value
5594 }
5595 if(d <= 0) {
5596 n = n.left
5597 } else {
5598 n = n.right
5599 }
5600 }
5601 return
5602}
5603
5604//Iterator for red black tree
5605function RedBlackTreeIterator(tree, stack) {
5606 this.tree = tree
5607 this._stack = stack
5608}
5609
5610var iproto = RedBlackTreeIterator.prototype
5611
5612//Test if iterator is valid
5613Object.defineProperty(iproto, "valid", {
5614 get: function() {
5615 return this._stack.length > 0
5616 }
5617})
5618
5619//Node of the iterator
5620Object.defineProperty(iproto, "node", {
5621 get: function() {
5622 if(this._stack.length > 0) {
5623 return this._stack[this._stack.length-1]
5624 }
5625 return null
5626 },
5627 enumerable: true
5628})
5629
5630//Makes a copy of an iterator
5631iproto.clone = function() {
5632 return new RedBlackTreeIterator(this.tree, this._stack.slice())
5633}
5634
5635//Swaps two nodes
5636function swapNode(n, v) {
5637 n.key = v.key
5638 n.value = v.value
5639 n.left = v.left
5640 n.right = v.right
5641 n._color = v._color
5642 n._count = v._count
5643}
5644
5645//Fix up a double black node in a tree
5646function fixDoubleBlack(stack) {
5647 var n, p, s, z
5648 for(var i=stack.length-1; i>=0; --i) {
5649 n = stack[i]
5650 if(i === 0) {
5651 n._color = BLACK
5652 return
5653 }
5654 //console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key)
5655 p = stack[i-1]
5656 if(p.left === n) {
5657 //console.log("left child")
5658 s = p.right
5659 if(s.right && s.right._color === RED) {
5660 //console.log("case 1: right sibling child red")
5661 s = p.right = cloneNode(s)
5662 z = s.right = cloneNode(s.right)
5663 p.right = s.left
5664 s.left = p
5665 s.right = z
5666 s._color = p._color
5667 n._color = BLACK
5668 p._color = BLACK
5669 z._color = BLACK
5670 recount(p)
5671 recount(s)
5672 if(i > 1) {
5673 var pp = stack[i-2]
5674 if(pp.left === p) {
5675 pp.left = s
5676 } else {
5677 pp.right = s
5678 }
5679 }
5680 stack[i-1] = s
5681 return
5682 } else if(s.left && s.left._color === RED) {
5683 //console.log("case 1: left sibling child red")
5684 s = p.right = cloneNode(s)
5685 z = s.left = cloneNode(s.left)
5686 p.right = z.left
5687 s.left = z.right
5688 z.left = p
5689 z.right = s
5690 z._color = p._color
5691 p._color = BLACK
5692 s._color = BLACK
5693 n._color = BLACK
5694 recount(p)
5695 recount(s)
5696 recount(z)
5697 if(i > 1) {
5698 var pp = stack[i-2]
5699 if(pp.left === p) {
5700 pp.left = z
5701 } else {
5702 pp.right = z
5703 }
5704 }
5705 stack[i-1] = z
5706 return
5707 }
5708 if(s._color === BLACK) {
5709 if(p._color === RED) {
5710 //console.log("case 2: black sibling, red parent", p.right.value)
5711 p._color = BLACK
5712 p.right = repaint(RED, s)
5713 return
5714 } else {
5715 //console.log("case 2: black sibling, black parent", p.right.value)
5716 p.right = repaint(RED, s)
5717 continue
5718 }
5719 } else {
5720 //console.log("case 3: red sibling")
5721 s = cloneNode(s)
5722 p.right = s.left
5723 s.left = p
5724 s._color = p._color
5725 p._color = RED
5726 recount(p)
5727 recount(s)
5728 if(i > 1) {
5729 var pp = stack[i-2]
5730 if(pp.left === p) {
5731 pp.left = s
5732 } else {
5733 pp.right = s
5734 }
5735 }
5736 stack[i-1] = s
5737 stack[i] = p
5738 if(i+1 < stack.length) {
5739 stack[i+1] = n
5740 } else {
5741 stack.push(n)
5742 }
5743 i = i+2
5744 }
5745 } else {
5746 //console.log("right child")
5747 s = p.left
5748 if(s.left && s.left._color === RED) {
5749 //console.log("case 1: left sibling child red", p.value, p._color)
5750 s = p.left = cloneNode(s)
5751 z = s.left = cloneNode(s.left)
5752 p.left = s.right
5753 s.right = p
5754 s.left = z
5755 s._color = p._color
5756 n._color = BLACK
5757 p._color = BLACK
5758 z._color = BLACK
5759 recount(p)
5760 recount(s)
5761 if(i > 1) {
5762 var pp = stack[i-2]
5763 if(pp.right === p) {
5764 pp.right = s
5765 } else {
5766 pp.left = s
5767 }
5768 }
5769 stack[i-1] = s
5770 return
5771 } else if(s.right && s.right._color === RED) {
5772 //console.log("case 1: right sibling child red")
5773 s = p.left = cloneNode(s)
5774 z = s.right = cloneNode(s.right)
5775 p.left = z.right
5776 s.right = z.left
5777 z.right = p
5778 z.left = s
5779 z._color = p._color
5780 p._color = BLACK
5781 s._color = BLACK
5782 n._color = BLACK
5783 recount(p)
5784 recount(s)
5785 recount(z)
5786 if(i > 1) {
5787 var pp = stack[i-2]
5788 if(pp.right === p) {
5789 pp.right = z
5790 } else {
5791 pp.left = z
5792 }
5793 }
5794 stack[i-1] = z
5795 return
5796 }
5797 if(s._color === BLACK) {
5798 if(p._color === RED) {
5799 //console.log("case 2: black sibling, red parent")
5800 p._color = BLACK
5801 p.left = repaint(RED, s)
5802 return
5803 } else {
5804 //console.log("case 2: black sibling, black parent")
5805 p.left = repaint(RED, s)
5806 continue
5807 }
5808 } else {
5809 //console.log("case 3: red sibling")
5810 s = cloneNode(s)
5811 p.left = s.right
5812 s.right = p
5813 s._color = p._color
5814 p._color = RED
5815 recount(p)
5816 recount(s)
5817 if(i > 1) {
5818 var pp = stack[i-2]
5819 if(pp.right === p) {
5820 pp.right = s
5821 } else {
5822 pp.left = s
5823 }
5824 }
5825 stack[i-1] = s
5826 stack[i] = p
5827 if(i+1 < stack.length) {
5828 stack[i+1] = n
5829 } else {
5830 stack.push(n)
5831 }
5832 i = i+2
5833 }
5834 }
5835 }
5836}
5837
5838//Removes item at iterator from tree
5839iproto.remove = function() {
5840 var stack = this._stack
5841 if(stack.length === 0) {
5842 return this.tree
5843 }
5844 //First copy path to node
5845 var cstack = new Array(stack.length)
5846 var n = stack[stack.length-1]
5847 cstack[cstack.length-1] = new RBNode(n._color, n.key, n.value, n.left, n.right, n._count)
5848 for(var i=stack.length-2; i>=0; --i) {
5849 var n = stack[i]
5850 if(n.left === stack[i+1]) {
5851 cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count)
5852 } else {
5853 cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
5854 }
5855 }
5856
5857 //Get node
5858 n = cstack[cstack.length-1]
5859 //console.log("start remove: ", n.value)
5860
5861 //If not leaf, then swap with previous node
5862 if(n.left && n.right) {
5863 //console.log("moving to leaf")
5864
5865 //First walk to previous leaf
5866 var split = cstack.length
5867 n = n.left
5868 while(n.right) {
5869 cstack.push(n)
5870 n = n.right
5871 }
5872 //Copy path to leaf
5873 var v = cstack[split-1]
5874 cstack.push(new RBNode(n._color, v.key, v.value, n.left, n.right, n._count))
5875 cstack[split-1].key = n.key
5876 cstack[split-1].value = n.value
5877
5878 //Fix up stack
5879 for(var i=cstack.length-2; i>=split; --i) {
5880 n = cstack[i]
5881 cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
5882 }
5883 cstack[split-1].left = cstack[split]
5884 }
5885 //console.log("stack=", cstack.map(function(v) { return v.value }))
5886
5887 //Remove leaf node
5888 n = cstack[cstack.length-1]
5889 if(n._color === RED) {
5890 //Easy case: removing red leaf
5891 //console.log("RED leaf")
5892 var p = cstack[cstack.length-2]
5893 if(p.left === n) {
5894 p.left = null
5895 } else if(p.right === n) {
5896 p.right = null
5897 }
5898 cstack.pop()
5899 for(var i=0; i<cstack.length; ++i) {
5900 cstack[i]._count--
5901 }
5902 return new RedBlackTree(this.tree._compare, cstack[0])
5903 } else {
5904 if(n.left || n.right) {
5905 //Second easy case: Single child black parent
5906 //console.log("BLACK single child")
5907 if(n.left) {
5908 swapNode(n, n.left)
5909 } else if(n.right) {
5910 swapNode(n, n.right)
5911 }
5912 //Child must be red, so repaint it black to balance color
5913 n._color = BLACK
5914 for(var i=0; i<cstack.length-1; ++i) {
5915 cstack[i]._count--
5916 }
5917 return new RedBlackTree(this.tree._compare, cstack[0])
5918 } else if(cstack.length === 1) {
5919 //Third easy case: root
5920 //console.log("ROOT")
5921 return new RedBlackTree(this.tree._compare, null)
5922 } else {
5923 //Hard case: Repaint n, and then do some nasty stuff
5924 //console.log("BLACK leaf no children")
5925 for(var i=0; i<cstack.length; ++i) {
5926 cstack[i]._count--
5927 }
5928 var parent = cstack[cstack.length-2]
5929 fixDoubleBlack(cstack)
5930 //Fix up links
5931 if(parent.left === n) {
5932 parent.left = null
5933 } else {
5934 parent.right = null
5935 }
5936 }
5937 }
5938 return new RedBlackTree(this.tree._compare, cstack[0])
5939}
5940
5941//Returns key
5942Object.defineProperty(iproto, "key", {
5943 get: function() {
5944 if(this._stack.length > 0) {
5945 return this._stack[this._stack.length-1].key
5946 }
5947 return
5948 },
5949 enumerable: true
5950})
5951
5952//Returns value
5953Object.defineProperty(iproto, "value", {
5954 get: function() {
5955 if(this._stack.length > 0) {
5956 return this._stack[this._stack.length-1].value
5957 }
5958 return
5959 },
5960 enumerable: true
5961})
5962
5963
5964//Returns the position of this iterator in the sorted list
5965Object.defineProperty(iproto, "index", {
5966 get: function() {
5967 var idx = 0
5968 var stack = this._stack
5969 if(stack.length === 0) {
5970 var r = this.tree.root
5971 if(r) {
5972 return r._count
5973 }
5974 return 0
5975 } else if(stack[stack.length-1].left) {
5976 idx = stack[stack.length-1].left._count
5977 }
5978 for(var s=stack.length-2; s>=0; --s) {
5979 if(stack[s+1] === stack[s].right) {
5980 ++idx
5981 if(stack[s].left) {
5982 idx += stack[s].left._count
5983 }
5984 }
5985 }
5986 return idx
5987 },
5988 enumerable: true
5989})
5990
5991//Advances iterator to next element in list
5992iproto.next = function() {
5993 var stack = this._stack
5994 if(stack.length === 0) {
5995 return
5996 }
5997 var n = stack[stack.length-1]
5998 if(n.right) {
5999 n = n.right
6000 while(n) {
6001 stack.push(n)
6002 n = n.left
6003 }
6004 } else {
6005 stack.pop()
6006 while(stack.length > 0 && stack[stack.length-1].right === n) {
6007 n = stack[stack.length-1]
6008 stack.pop()
6009 }
6010 }
6011}
6012
6013//Checks if iterator is at end of tree
6014Object.defineProperty(iproto, "hasNext", {
6015 get: function() {
6016 var stack = this._stack
6017 if(stack.length === 0) {
6018 return false
6019 }
6020 if(stack[stack.length-1].right) {
6021 return true
6022 }
6023 for(var s=stack.length-1; s>0; --s) {
6024 if(stack[s-1].left === stack[s]) {
6025 return true
6026 }
6027 }
6028 return false
6029 }
6030})
6031
6032//Update value
6033iproto.update = function(value) {
6034 var stack = this._stack
6035 if(stack.length === 0) {
6036 throw new Error("Can't update empty node!")
6037 }
6038 var cstack = new Array(stack.length)
6039 var n = stack[stack.length-1]
6040 cstack[cstack.length-1] = new RBNode(n._color, n.key, value, n.left, n.right, n._count)
6041 for(var i=stack.length-2; i>=0; --i) {
6042 n = stack[i]
6043 if(n.left === stack[i+1]) {
6044 cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count)
6045 } else {
6046 cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
6047 }
6048 }
6049 return new RedBlackTree(this.tree._compare, cstack[0])
6050}
6051
6052//Moves iterator backward one element
6053iproto.prev = function() {
6054 var stack = this._stack
6055 if(stack.length === 0) {
6056 return
6057 }
6058 var n = stack[stack.length-1]
6059 if(n.left) {
6060 n = n.left
6061 while(n) {
6062 stack.push(n)
6063 n = n.right
6064 }
6065 } else {
6066 stack.pop()
6067 while(stack.length > 0 && stack[stack.length-1].left === n) {
6068 n = stack[stack.length-1]
6069 stack.pop()
6070 }
6071 }
6072}
6073
6074//Checks if iterator is at start of tree
6075Object.defineProperty(iproto, "hasPrev", {
6076 get: function() {
6077 var stack = this._stack
6078 if(stack.length === 0) {
6079 return false
6080 }
6081 if(stack[stack.length-1].left) {
6082 return true
6083 }
6084 for(var s=stack.length-1; s>0; --s) {
6085 if(stack[s-1].right === stack[s]) {
6086 return true
6087 }
6088 }
6089 return false
6090 }
6091})
6092
6093//Default comparison function
6094function defaultCompare(a, b) {
6095 if(a < b) {
6096 return -1
6097 }
6098 if(a > b) {
6099 return 1
6100 }
6101 return 0
6102}
6103
6104//Build a tree
6105function createRBTree(compare) {
6106 return new RedBlackTree(compare || defaultCompare, null)
6107}
6108},{}],22:[function(_dereq_,module,exports){
6109/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
6110exports.read = function (buffer, offset, isLE, mLen, nBytes) {
6111 var e, m
6112 var eLen = (nBytes * 8) - mLen - 1
6113 var eMax = (1 << eLen) - 1
6114 var eBias = eMax >> 1
6115 var nBits = -7
6116 var i = isLE ? (nBytes - 1) : 0
6117 var d = isLE ? -1 : 1
6118 var s = buffer[offset + i]
6119
6120 i += d
6121
6122 e = s & ((1 << (-nBits)) - 1)
6123 s >>= (-nBits)
6124 nBits += eLen
6125 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
6126
6127 m = e & ((1 << (-nBits)) - 1)
6128 e >>= (-nBits)
6129 nBits += mLen
6130 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
6131
6132 if (e === 0) {
6133 e = 1 - eBias
6134 } else if (e === eMax) {
6135 return m ? NaN : ((s ? -1 : 1) * Infinity)
6136 } else {
6137 m = m + Math.pow(2, mLen)
6138 e = e - eBias
6139 }
6140 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
6141}
6142
6143exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
6144 var e, m, c
6145 var eLen = (nBytes * 8) - mLen - 1
6146 var eMax = (1 << eLen) - 1
6147 var eBias = eMax >> 1
6148 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
6149 var i = isLE ? 0 : (nBytes - 1)
6150 var d = isLE ? 1 : -1
6151 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
6152
6153 value = Math.abs(value)
6154
6155 if (isNaN(value) || value === Infinity) {
6156 m = isNaN(value) ? 1 : 0
6157 e = eMax
6158 } else {
6159 e = Math.floor(Math.log(value) / Math.LN2)
6160 if (value * (c = Math.pow(2, -e)) < 1) {
6161 e--
6162 c *= 2
6163 }
6164 if (e + eBias >= 1) {
6165 value += rt / c
6166 } else {
6167 value += rt * Math.pow(2, 1 - eBias)
6168 }
6169 if (value * c >= 2) {
6170 e++
6171 c /= 2
6172 }
6173
6174 if (e + eBias >= eMax) {
6175 m = 0
6176 e = eMax
6177 } else if (e + eBias >= 1) {
6178 m = ((value * c) - 1) * Math.pow(2, mLen)
6179 e = e + eBias
6180 } else {
6181 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
6182 e = 0
6183 }
6184 }
6185
6186 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
6187
6188 e = (e << mLen) | m
6189 eLen += mLen
6190 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
6191
6192 buffer[offset + i - d] |= s * 128
6193}
6194
6195},{}],23:[function(_dereq_,module,exports){
6196'use strict';
6197var types = [
6198 _dereq_(6),
6199 _dereq_(26),
6200 _dereq_(25),
6201 _dereq_(24),
6202 _dereq_(27),
6203 _dereq_(28)
6204];
6205var draining;
6206var currentQueue;
6207var queueIndex = -1;
6208var queue = [];
6209var scheduled = false;
6210function cleanUpNextTick() {
6211 if (!draining || !currentQueue) {
6212 return;
6213 }
6214 draining = false;
6215 if (currentQueue.length) {
6216 queue = currentQueue.concat(queue);
6217 } else {
6218 queueIndex = -1;
6219 }
6220 if (queue.length) {
6221 nextTick();
6222 }
6223}
6224
6225//named nextTick for less confusing stack traces
6226function nextTick() {
6227 if (draining) {
6228 return;
6229 }
6230 scheduled = false;
6231 draining = true;
6232 var len = queue.length;
6233 var timeout = setTimeout(cleanUpNextTick);
6234 while (len) {
6235 currentQueue = queue;
6236 queue = [];
6237 while (currentQueue && ++queueIndex < len) {
6238 currentQueue[queueIndex].run();
6239 }
6240 queueIndex = -1;
6241 len = queue.length;
6242 }
6243 currentQueue = null;
6244 queueIndex = -1;
6245 draining = false;
6246 clearTimeout(timeout);
6247}
6248var scheduleDrain;
6249var i = -1;
6250var len = types.length;
6251while (++i < len) {
6252 if (types[i] && types[i].test && types[i].test()) {
6253 scheduleDrain = types[i].install(nextTick);
6254 break;
6255 }
6256}
6257// v8 likes predictible objects
6258function Item(fun, array) {
6259 this.fun = fun;
6260 this.array = array;
6261}
6262Item.prototype.run = function () {
6263 var fun = this.fun;
6264 var array = this.array;
6265 switch (array.length) {
6266 case 0:
6267 return fun();
6268 case 1:
6269 return fun(array[0]);
6270 case 2:
6271 return fun(array[0], array[1]);
6272 case 3:
6273 return fun(array[0], array[1], array[2]);
6274 default:
6275 return fun.apply(null, array);
6276 }
6277
6278};
6279module.exports = immediate;
6280function immediate(task) {
6281 var args = new Array(arguments.length - 1);
6282 if (arguments.length > 1) {
6283 for (var i = 1; i < arguments.length; i++) {
6284 args[i - 1] = arguments[i];
6285 }
6286 }
6287 queue.push(new Item(task, args));
6288 if (!scheduled && !draining) {
6289 scheduled = true;
6290 scheduleDrain();
6291 }
6292}
6293
6294},{"24":24,"25":25,"26":26,"27":27,"28":28,"6":6}],24:[function(_dereq_,module,exports){
6295(function (global){(function (){
6296'use strict';
6297
6298exports.test = function () {
6299 if (global.setImmediate) {
6300 // we can only get here in IE10
6301 // which doesn't handel postMessage well
6302 return false;
6303 }
6304 return typeof global.MessageChannel !== 'undefined';
6305};
6306
6307exports.install = function (func) {
6308 var channel = new global.MessageChannel();
6309 channel.port1.onmessage = func;
6310 return function () {
6311 channel.port2.postMessage(0);
6312 };
6313};
6314}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
6315},{}],25:[function(_dereq_,module,exports){
6316(function (global){(function (){
6317'use strict';
6318//based off rsvp https://github.com/tildeio/rsvp.js
6319//license https://github.com/tildeio/rsvp.js/blob/master/LICENSE
6320//https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/asap.js
6321
6322var Mutation = global.MutationObserver || global.WebKitMutationObserver;
6323
6324exports.test = function () {
6325 return Mutation;
6326};
6327
6328exports.install = function (handle) {
6329 var called = 0;
6330 var observer = new Mutation(handle);
6331 var element = global.document.createTextNode('');
6332 observer.observe(element, {
6333 characterData: true
6334 });
6335 return function () {
6336 element.data = (called = ++called % 2);
6337 };
6338};
6339}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
6340},{}],26:[function(_dereq_,module,exports){
6341(function (global){(function (){
6342'use strict';
6343exports.test = function () {
6344 return typeof global.queueMicrotask === 'function';
6345};
6346
6347exports.install = function (func) {
6348 return function () {
6349 global.queueMicrotask(func);
6350 };
6351};
6352
6353}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
6354},{}],27:[function(_dereq_,module,exports){
6355(function (global){(function (){
6356'use strict';
6357
6358exports.test = function () {
6359 return 'document' in global && 'onreadystatechange' in global.document.createElement('script');
6360};
6361
6362exports.install = function (handle) {
6363 return function () {
6364
6365 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
6366 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
6367 var scriptEl = global.document.createElement('script');
6368 scriptEl.onreadystatechange = function () {
6369 handle();
6370
6371 scriptEl.onreadystatechange = null;
6372 scriptEl.parentNode.removeChild(scriptEl);
6373 scriptEl = null;
6374 };
6375 global.document.documentElement.appendChild(scriptEl);
6376
6377 return handle;
6378 };
6379};
6380}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
6381},{}],28:[function(_dereq_,module,exports){
6382'use strict';
6383exports.test = function () {
6384 return true;
6385};
6386
6387exports.install = function (t) {
6388 return function () {
6389 setTimeout(t, 0);
6390 };
6391};
6392},{}],29:[function(_dereq_,module,exports){
6393if (typeof Object.create === 'function') {
6394 // implementation from standard node.js 'util' module
6395 module.exports = function inherits(ctor, superCtor) {
6396 if (superCtor) {
6397 ctor.super_ = superCtor
6398 ctor.prototype = Object.create(superCtor.prototype, {
6399 constructor: {
6400 value: ctor,
6401 enumerable: false,
6402 writable: true,
6403 configurable: true
6404 }
6405 })
6406 }
6407 };
6408} else {
6409 // old school shim for old browsers
6410 module.exports = function inherits(ctor, superCtor) {
6411 if (superCtor) {
6412 ctor.super_ = superCtor
6413 var TempCtor = function () {}
6414 TempCtor.prototype = superCtor.prototype
6415 ctor.prototype = new TempCtor()
6416 ctor.prototype.constructor = ctor
6417 }
6418 }
6419}
6420
6421},{}],30:[function(_dereq_,module,exports){
6422/*!
6423 * Determine if an object is a Buffer
6424 *
6425 * @author Feross Aboukhadijeh <https://feross.org>
6426 * @license MIT
6427 */
6428
6429// The _isBuffer check is for Safari 5-7 support, because it's missing
6430// Object.prototype.constructor. Remove this eventually
6431module.exports = function (obj) {
6432 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
6433}
6434
6435function isBuffer (obj) {
6436 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
6437}
6438
6439// For Node v0.10 support. Remove this eventually.
6440function isSlowBuffer (obj) {
6441 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
6442}
6443
6444},{}],31:[function(_dereq_,module,exports){
6445var encodings = _dereq_(32)
6446
6447module.exports = Codec
6448
6449function Codec (opts) {
6450 if (!(this instanceof Codec)) {
6451 return new Codec(opts)
6452 }
6453 this.opts = opts || {}
6454 this.encodings = encodings
6455}
6456
6457Codec.prototype._encoding = function (encoding) {
6458 if (typeof encoding === 'string') encoding = encodings[encoding]
6459 if (!encoding) encoding = encodings.id
6460 return encoding
6461}
6462
6463Codec.prototype._keyEncoding = function (opts, batchOpts) {
6464 return this._encoding((batchOpts && batchOpts.keyEncoding) ||
6465 (opts && opts.keyEncoding) ||
6466 this.opts.keyEncoding)
6467}
6468
6469Codec.prototype._valueEncoding = function (opts, batchOpts) {
6470 return this._encoding((batchOpts && (batchOpts.valueEncoding || batchOpts.encoding)) ||
6471 (opts && (opts.valueEncoding || opts.encoding)) ||
6472 (this.opts.valueEncoding || this.opts.encoding))
6473}
6474
6475Codec.prototype.encodeKey = function (key, opts, batchOpts) {
6476 return this._keyEncoding(opts, batchOpts).encode(key)
6477}
6478
6479Codec.prototype.encodeValue = function (value, opts, batchOpts) {
6480 return this._valueEncoding(opts, batchOpts).encode(value)
6481}
6482
6483Codec.prototype.decodeKey = function (key, opts) {
6484 return this._keyEncoding(opts).decode(key)
6485}
6486
6487Codec.prototype.decodeValue = function (value, opts) {
6488 return this._valueEncoding(opts).decode(value)
6489}
6490
6491Codec.prototype.encodeBatch = function (ops, opts) {
6492 var self = this
6493
6494 return ops.map(function (_op) {
6495 var op = {
6496 type: _op.type,
6497 key: self.encodeKey(_op.key, opts, _op)
6498 }
6499 if (self.keyAsBuffer(opts, _op)) op.keyEncoding = 'binary'
6500 if (_op.prefix) op.prefix = _op.prefix
6501 if ('value' in _op) {
6502 op.value = self.encodeValue(_op.value, opts, _op)
6503 if (self.valueAsBuffer(opts, _op)) op.valueEncoding = 'binary'
6504 }
6505 return op
6506 })
6507}
6508
6509var ltgtKeys = ['lt', 'gt', 'lte', 'gte', 'start', 'end']
6510
6511Codec.prototype.encodeLtgt = function (ltgt) {
6512 var self = this
6513 var ret = {}
6514 Object.keys(ltgt).forEach(function (key) {
6515 ret[key] = ltgtKeys.indexOf(key) > -1
6516 ? self.encodeKey(ltgt[key], ltgt)
6517 : ltgt[key]
6518 })
6519 return ret
6520}
6521
6522Codec.prototype.createStreamDecoder = function (opts) {
6523 var self = this
6524
6525 if (opts.keys && opts.values) {
6526 return function (key, value) {
6527 return {
6528 key: self.decodeKey(key, opts),
6529 value: self.decodeValue(value, opts)
6530 }
6531 }
6532 } else if (opts.keys) {
6533 return function (key) {
6534 return self.decodeKey(key, opts)
6535 }
6536 } else if (opts.values) {
6537 return function (_, value) {
6538 return self.decodeValue(value, opts)
6539 }
6540 } else {
6541 return function () {}
6542 }
6543}
6544
6545Codec.prototype.keyAsBuffer = function (opts) {
6546 return this._keyEncoding(opts).buffer
6547}
6548
6549Codec.prototype.valueAsBuffer = function (opts) {
6550 return this._valueEncoding(opts).buffer
6551}
6552
6553},{"32":32}],32:[function(_dereq_,module,exports){
6554var Buffer = _dereq_(8).Buffer
6555
6556exports.utf8 = exports['utf-8'] = {
6557 encode: function (data) {
6558 return isBinary(data) ? data : String(data)
6559 },
6560 decode: identity,
6561 buffer: false,
6562 type: 'utf8'
6563}
6564
6565exports.json = {
6566 encode: JSON.stringify,
6567 decode: JSON.parse,
6568 buffer: false,
6569 type: 'json'
6570}
6571
6572exports.binary = {
6573 encode: function (data) {
6574 return isBinary(data) ? data : Buffer.from(data)
6575 },
6576 decode: identity,
6577 buffer: true,
6578 type: 'binary'
6579}
6580
6581exports.none = {
6582 encode: identity,
6583 decode: identity,
6584 buffer: false,
6585 type: 'id'
6586}
6587
6588exports.id = exports.none
6589
6590var bufferEncodings = [
6591 'hex',
6592 'ascii',
6593 'base64',
6594 'ucs2',
6595 'ucs-2',
6596 'utf16le',
6597 'utf-16le'
6598]
6599
6600bufferEncodings.forEach(function (type) {
6601 exports[type] = {
6602 encode: function (data) {
6603 return isBinary(data) ? data : Buffer.from(data, type)
6604 },
6605 decode: function (buffer) {
6606 return buffer.toString(type)
6607 },
6608 buffer: true,
6609 type: type
6610 }
6611})
6612
6613function identity (value) {
6614 return value
6615}
6616
6617function isBinary (data) {
6618 return data === undefined || data === null || Buffer.isBuffer(data)
6619}
6620
6621},{"8":8}],33:[function(_dereq_,module,exports){
6622var createError = _dereq_(19).create
6623var LevelUPError = createError('LevelUPError')
6624var NotFoundError = createError('NotFoundError', LevelUPError)
6625
6626NotFoundError.prototype.notFound = true
6627NotFoundError.prototype.status = 404
6628
6629module.exports = {
6630 LevelUPError: LevelUPError,
6631 InitializationError: createError('InitializationError', LevelUPError),
6632 OpenError: createError('OpenError', LevelUPError),
6633 ReadError: createError('ReadError', LevelUPError),
6634 WriteError: createError('WriteError', LevelUPError),
6635 NotFoundError: NotFoundError,
6636 EncodingError: createError('EncodingError', LevelUPError)
6637}
6638
6639},{"19":19}],34:[function(_dereq_,module,exports){
6640var inherits = _dereq_(29)
6641var Readable = _dereq_(49).Readable
6642var extend = _dereq_(133)
6643
6644module.exports = ReadStream
6645inherits(ReadStream, Readable)
6646
6647function ReadStream (iterator, options) {
6648 if (!(this instanceof ReadStream)) return new ReadStream(iterator, options)
6649 options = options || {}
6650 Readable.call(this, extend(options, {
6651 objectMode: true
6652 }))
6653 this._iterator = iterator
6654 this._options = options
6655 this.on('end', this.destroy.bind(this, null, null))
6656}
6657
6658ReadStream.prototype._read = function () {
6659 var self = this
6660 var options = this._options
6661 if (this.destroyed) return
6662
6663 this._iterator.next(function (err, key, value) {
6664 if (self.destroyed) return
6665 if (err) return self.destroy(err)
6666
6667 if (key === undefined && value === undefined) {
6668 self.push(null)
6669 } else if (options.keys !== false && options.values === false) {
6670 self.push(key)
6671 } else if (options.keys === false && options.values !== false) {
6672 self.push(value)
6673 } else {
6674 self.push({ key: key, value: value })
6675 }
6676 })
6677}
6678
6679ReadStream.prototype._destroy = function (err, callback) {
6680 this._iterator.end(function (err2) {
6681 callback(err || err2)
6682 })
6683}
6684
6685},{"133":133,"29":29,"49":49}],35:[function(_dereq_,module,exports){
6686'use strict';
6687
6688function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
6689
6690var codes = {};
6691
6692function createErrorType(code, message, Base) {
6693 if (!Base) {
6694 Base = Error;
6695 }
6696
6697 function getMessage(arg1, arg2, arg3) {
6698 if (typeof message === 'string') {
6699 return message;
6700 } else {
6701 return message(arg1, arg2, arg3);
6702 }
6703 }
6704
6705 var NodeError =
6706 /*#__PURE__*/
6707 function (_Base) {
6708 _inheritsLoose(NodeError, _Base);
6709
6710 function NodeError(arg1, arg2, arg3) {
6711 return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
6712 }
6713
6714 return NodeError;
6715 }(Base);
6716
6717 NodeError.prototype.name = Base.name;
6718 NodeError.prototype.code = code;
6719 codes[code] = NodeError;
6720} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
6721
6722
6723function oneOf(expected, thing) {
6724 if (Array.isArray(expected)) {
6725 var len = expected.length;
6726 expected = expected.map(function (i) {
6727 return String(i);
6728 });
6729
6730 if (len > 2) {
6731 return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
6732 } else if (len === 2) {
6733 return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
6734 } else {
6735 return "of ".concat(thing, " ").concat(expected[0]);
6736 }
6737 } else {
6738 return "of ".concat(thing, " ").concat(String(expected));
6739 }
6740} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
6741
6742
6743function startsWith(str, search, pos) {
6744 return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
6745} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
6746
6747
6748function endsWith(str, search, this_len) {
6749 if (this_len === undefined || this_len > str.length) {
6750 this_len = str.length;
6751 }
6752
6753 return str.substring(this_len - search.length, this_len) === search;
6754} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
6755
6756
6757function includes(str, search, start) {
6758 if (typeof start !== 'number') {
6759 start = 0;
6760 }
6761
6762 if (start + search.length > str.length) {
6763 return false;
6764 } else {
6765 return str.indexOf(search, start) !== -1;
6766 }
6767}
6768
6769createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
6770 return 'The value "' + value + '" is invalid for option "' + name + '"';
6771}, TypeError);
6772createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
6773 // determiner: 'must be' or 'must not be'
6774 var determiner;
6775
6776 if (typeof expected === 'string' && startsWith(expected, 'not ')) {
6777 determiner = 'must not be';
6778 expected = expected.replace(/^not /, '');
6779 } else {
6780 determiner = 'must be';
6781 }
6782
6783 var msg;
6784
6785 if (endsWith(name, ' argument')) {
6786 // For cases like 'first argument'
6787 msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
6788 } else {
6789 var type = includes(name, '.') ? 'property' : 'argument';
6790 msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
6791 }
6792
6793 msg += ". Received type ".concat(typeof actual);
6794 return msg;
6795}, TypeError);
6796createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
6797createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
6798 return 'The ' + name + ' method is not implemented';
6799});
6800createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
6801createErrorType('ERR_STREAM_DESTROYED', function (name) {
6802 return 'Cannot call ' + name + ' after a stream was destroyed';
6803});
6804createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
6805createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
6806createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
6807createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
6808createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
6809 return 'Unknown encoding: ' + arg;
6810}, TypeError);
6811createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
6812module.exports.codes = codes;
6813
6814},{}],36:[function(_dereq_,module,exports){
6815(function (process){(function (){
6816// Copyright Joyent, Inc. and other Node contributors.
6817//
6818// Permission is hereby granted, free of charge, to any person obtaining a
6819// copy of this software and associated documentation files (the
6820// "Software"), to deal in the Software without restriction, including
6821// without limitation the rights to use, copy, modify, merge, publish,
6822// distribute, sublicense, and/or sell copies of the Software, and to permit
6823// persons to whom the Software is furnished to do so, subject to the
6824// following conditions:
6825//
6826// The above copyright notice and this permission notice shall be included
6827// in all copies or substantial portions of the Software.
6828//
6829// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6830// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6831// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6832// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6833// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6834// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6835// USE OR OTHER DEALINGS IN THE SOFTWARE.
6836// a duplex stream is just a stream that is both readable and writable.
6837// Since JS doesn't have multiple prototypal inheritance, this class
6838// prototypally inherits from Readable, and then parasitically from
6839// Writable.
6840'use strict';
6841/*<replacement>*/
6842
6843var objectKeys = Object.keys || function (obj) {
6844 var keys = [];
6845
6846 for (var key in obj) {
6847 keys.push(key);
6848 }
6849
6850 return keys;
6851};
6852/*</replacement>*/
6853
6854
6855module.exports = Duplex;
6856
6857var Readable = _dereq_(38);
6858
6859var Writable = _dereq_(40);
6860
6861_dereq_(29)(Duplex, Readable);
6862
6863{
6864 // Allow the keys array to be GC'ed.
6865 var keys = objectKeys(Writable.prototype);
6866
6867 for (var v = 0; v < keys.length; v++) {
6868 var method = keys[v];
6869 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
6870 }
6871}
6872
6873function Duplex(options) {
6874 if (!(this instanceof Duplex)) return new Duplex(options);
6875 Readable.call(this, options);
6876 Writable.call(this, options);
6877 this.allowHalfOpen = true;
6878
6879 if (options) {
6880 if (options.readable === false) this.readable = false;
6881 if (options.writable === false) this.writable = false;
6882
6883 if (options.allowHalfOpen === false) {
6884 this.allowHalfOpen = false;
6885 this.once('end', onend);
6886 }
6887 }
6888}
6889
6890Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
6891 // making it explicit this property is not enumerable
6892 // because otherwise some prototype manipulation in
6893 // userland will fail
6894 enumerable: false,
6895 get: function get() {
6896 return this._writableState.highWaterMark;
6897 }
6898});
6899Object.defineProperty(Duplex.prototype, 'writableBuffer', {
6900 // making it explicit this property is not enumerable
6901 // because otherwise some prototype manipulation in
6902 // userland will fail
6903 enumerable: false,
6904 get: function get() {
6905 return this._writableState && this._writableState.getBuffer();
6906 }
6907});
6908Object.defineProperty(Duplex.prototype, 'writableLength', {
6909 // making it explicit this property is not enumerable
6910 // because otherwise some prototype manipulation in
6911 // userland will fail
6912 enumerable: false,
6913 get: function get() {
6914 return this._writableState.length;
6915 }
6916}); // the no-half-open enforcer
6917
6918function onend() {
6919 // If the writable side ended, then we're ok.
6920 if (this._writableState.ended) return; // no more data can be written.
6921 // But allow more writes to happen in this tick.
6922
6923 process.nextTick(onEndNT, this);
6924}
6925
6926function onEndNT(self) {
6927 self.end();
6928}
6929
6930Object.defineProperty(Duplex.prototype, 'destroyed', {
6931 // making it explicit this property is not enumerable
6932 // because otherwise some prototype manipulation in
6933 // userland will fail
6934 enumerable: false,
6935 get: function get() {
6936 if (this._readableState === undefined || this._writableState === undefined) {
6937 return false;
6938 }
6939
6940 return this._readableState.destroyed && this._writableState.destroyed;
6941 },
6942 set: function set(value) {
6943 // we ignore the value if the stream
6944 // has not been initialized yet
6945 if (this._readableState === undefined || this._writableState === undefined) {
6946 return;
6947 } // backward compatibility, the user is explicitly
6948 // managing destroyed
6949
6950
6951 this._readableState.destroyed = value;
6952 this._writableState.destroyed = value;
6953 }
6954});
6955}).call(this)}).call(this,_dereq_(66))
6956},{"29":29,"38":38,"40":40,"66":66}],37:[function(_dereq_,module,exports){
6957// Copyright Joyent, Inc. and other Node contributors.
6958//
6959// Permission is hereby granted, free of charge, to any person obtaining a
6960// copy of this software and associated documentation files (the
6961// "Software"), to deal in the Software without restriction, including
6962// without limitation the rights to use, copy, modify, merge, publish,
6963// distribute, sublicense, and/or sell copies of the Software, and to permit
6964// persons to whom the Software is furnished to do so, subject to the
6965// following conditions:
6966//
6967// The above copyright notice and this permission notice shall be included
6968// in all copies or substantial portions of the Software.
6969//
6970// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6971// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6972// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6973// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6974// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6975// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6976// USE OR OTHER DEALINGS IN THE SOFTWARE.
6977// a passthrough stream.
6978// basically just the most minimal sort of Transform stream.
6979// Every written chunk gets output as-is.
6980'use strict';
6981
6982module.exports = PassThrough;
6983
6984var Transform = _dereq_(39);
6985
6986_dereq_(29)(PassThrough, Transform);
6987
6988function PassThrough(options) {
6989 if (!(this instanceof PassThrough)) return new PassThrough(options);
6990 Transform.call(this, options);
6991}
6992
6993PassThrough.prototype._transform = function (chunk, encoding, cb) {
6994 cb(null, chunk);
6995};
6996},{"29":29,"39":39}],38:[function(_dereq_,module,exports){
6997(function (process,global){(function (){
6998// Copyright Joyent, Inc. and other Node contributors.
6999//
7000// Permission is hereby granted, free of charge, to any person obtaining a
7001// copy of this software and associated documentation files (the
7002// "Software"), to deal in the Software without restriction, including
7003// without limitation the rights to use, copy, modify, merge, publish,
7004// distribute, sublicense, and/or sell copies of the Software, and to permit
7005// persons to whom the Software is furnished to do so, subject to the
7006// following conditions:
7007//
7008// The above copyright notice and this permission notice shall be included
7009// in all copies or substantial portions of the Software.
7010//
7011// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7012// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7013// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7014// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7015// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7016// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7017// USE OR OTHER DEALINGS IN THE SOFTWARE.
7018'use strict';
7019
7020module.exports = Readable;
7021/*<replacement>*/
7022
7023var Duplex;
7024/*</replacement>*/
7025
7026Readable.ReadableState = ReadableState;
7027/*<replacement>*/
7028
7029var EE = _dereq_(20).EventEmitter;
7030
7031var EElistenerCount = function EElistenerCount(emitter, type) {
7032 return emitter.listeners(type).length;
7033};
7034/*</replacement>*/
7035
7036/*<replacement>*/
7037
7038
7039var Stream = _dereq_(48);
7040/*</replacement>*/
7041
7042
7043var Buffer = _dereq_(8).Buffer;
7044
7045var OurUint8Array = global.Uint8Array || function () {};
7046
7047function _uint8ArrayToBuffer(chunk) {
7048 return Buffer.from(chunk);
7049}
7050
7051function _isUint8Array(obj) {
7052 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
7053}
7054/*<replacement>*/
7055
7056
7057var debugUtil = _dereq_(6);
7058
7059var debug;
7060
7061if (debugUtil && debugUtil.debuglog) {
7062 debug = debugUtil.debuglog('stream');
7063} else {
7064 debug = function debug() {};
7065}
7066/*</replacement>*/
7067
7068
7069var BufferList = _dereq_(42);
7070
7071var destroyImpl = _dereq_(43);
7072
7073var _require = _dereq_(47),
7074 getHighWaterMark = _require.getHighWaterMark;
7075
7076var _require$codes = _dereq_(35).codes,
7077 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
7078 ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
7079 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
7080 ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.
7081
7082
7083var StringDecoder;
7084var createReadableStreamAsyncIterator;
7085var from;
7086
7087_dereq_(29)(Readable, Stream);
7088
7089var errorOrDestroy = destroyImpl.errorOrDestroy;
7090var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
7091
7092function prependListener(emitter, event, fn) {
7093 // Sadly this is not cacheable as some libraries bundle their own
7094 // event emitter implementation with them.
7095 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
7096 // userland ones. NEVER DO THIS. This is here only because this code needs
7097 // to continue to work with older versions of Node.js that do not include
7098 // the prependListener() method. The goal is to eventually remove this hack.
7099
7100 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]];
7101}
7102
7103function ReadableState(options, stream, isDuplex) {
7104 Duplex = Duplex || _dereq_(36);
7105 options = options || {}; // Duplex streams are both readable and writable, but share
7106 // the same options object.
7107 // However, some cases require setting options to different
7108 // values for the readable and the writable sides of the duplex stream.
7109 // These options can be provided separately as readableXXX and writableXXX.
7110
7111 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to
7112 // make all the buffer merging and length checks go away
7113
7114 this.objectMode = !!options.objectMode;
7115 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
7116 // Note: 0 is a valid value, means "don't call _read preemptively ever"
7117
7118 this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the
7119 // linked list can remove elements from the beginning faster than
7120 // array.shift()
7121
7122 this.buffer = new BufferList();
7123 this.length = 0;
7124 this.pipes = null;
7125 this.pipesCount = 0;
7126 this.flowing = null;
7127 this.ended = false;
7128 this.endEmitted = false;
7129 this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted
7130 // immediately, or on a later tick. We set this to true at first, because
7131 // any actions that shouldn't happen until "later" should generally also
7132 // not happen before the first read call.
7133
7134 this.sync = true; // whenever we return null, then we set a flag to say
7135 // that we're awaiting a 'readable' event emission.
7136
7137 this.needReadable = false;
7138 this.emittedReadable = false;
7139 this.readableListening = false;
7140 this.resumeScheduled = false;
7141 this.paused = true; // Should close be emitted on destroy. Defaults to true.
7142
7143 this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')
7144
7145 this.autoDestroy = !!options.autoDestroy; // has it been destroyed
7146
7147 this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string
7148 // encoding is 'binary' so we have to make this configurable.
7149 // Everything else in the universe uses 'utf8', though.
7150
7151 this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s
7152
7153 this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled
7154
7155 this.readingMore = false;
7156 this.decoder = null;
7157 this.encoding = null;
7158
7159 if (options.encoding) {
7160 if (!StringDecoder) StringDecoder = _dereq_(95).StringDecoder;
7161 this.decoder = new StringDecoder(options.encoding);
7162 this.encoding = options.encoding;
7163 }
7164}
7165
7166function Readable(options) {
7167 Duplex = Duplex || _dereq_(36);
7168 if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside
7169 // the ReadableState constructor, at least with V8 6.5
7170
7171 var isDuplex = this instanceof Duplex;
7172 this._readableState = new ReadableState(options, this, isDuplex); // legacy
7173
7174 this.readable = true;
7175
7176 if (options) {
7177 if (typeof options.read === 'function') this._read = options.read;
7178 if (typeof options.destroy === 'function') this._destroy = options.destroy;
7179 }
7180
7181 Stream.call(this);
7182}
7183
7184Object.defineProperty(Readable.prototype, 'destroyed', {
7185 // making it explicit this property is not enumerable
7186 // because otherwise some prototype manipulation in
7187 // userland will fail
7188 enumerable: false,
7189 get: function get() {
7190 if (this._readableState === undefined) {
7191 return false;
7192 }
7193
7194 return this._readableState.destroyed;
7195 },
7196 set: function set(value) {
7197 // we ignore the value if the stream
7198 // has not been initialized yet
7199 if (!this._readableState) {
7200 return;
7201 } // backward compatibility, the user is explicitly
7202 // managing destroyed
7203
7204
7205 this._readableState.destroyed = value;
7206 }
7207});
7208Readable.prototype.destroy = destroyImpl.destroy;
7209Readable.prototype._undestroy = destroyImpl.undestroy;
7210
7211Readable.prototype._destroy = function (err, cb) {
7212 cb(err);
7213}; // Manually shove something into the read() buffer.
7214// This returns true if the highWaterMark has not been hit yet,
7215// similar to how Writable.write() returns true if you should
7216// write() some more.
7217
7218
7219Readable.prototype.push = function (chunk, encoding) {
7220 var state = this._readableState;
7221 var skipChunkCheck;
7222
7223 if (!state.objectMode) {
7224 if (typeof chunk === 'string') {
7225 encoding = encoding || state.defaultEncoding;
7226
7227 if (encoding !== state.encoding) {
7228 chunk = Buffer.from(chunk, encoding);
7229 encoding = '';
7230 }
7231
7232 skipChunkCheck = true;
7233 }
7234 } else {
7235 skipChunkCheck = true;
7236 }
7237
7238 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
7239}; // Unshift should *always* be something directly out of read()
7240
7241
7242Readable.prototype.unshift = function (chunk) {
7243 return readableAddChunk(this, chunk, null, true, false);
7244};
7245
7246function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
7247 debug('readableAddChunk', chunk);
7248 var state = stream._readableState;
7249
7250 if (chunk === null) {
7251 state.reading = false;
7252 onEofChunk(stream, state);
7253 } else {
7254 var er;
7255 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
7256
7257 if (er) {
7258 errorOrDestroy(stream, er);
7259 } else if (state.objectMode || chunk && chunk.length > 0) {
7260 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
7261 chunk = _uint8ArrayToBuffer(chunk);
7262 }
7263
7264 if (addToFront) {
7265 if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
7266 } else if (state.ended) {
7267 errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
7268 } else if (state.destroyed) {
7269 return false;
7270 } else {
7271 state.reading = false;
7272
7273 if (state.decoder && !encoding) {
7274 chunk = state.decoder.write(chunk);
7275 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
7276 } else {
7277 addChunk(stream, state, chunk, false);
7278 }
7279 }
7280 } else if (!addToFront) {
7281 state.reading = false;
7282 maybeReadMore(stream, state);
7283 }
7284 } // We can push more data if we are below the highWaterMark.
7285 // Also, if we have no data yet, we can stand some more bytes.
7286 // This is to work around cases where hwm=0, such as the repl.
7287
7288
7289 return !state.ended && (state.length < state.highWaterMark || state.length === 0);
7290}
7291
7292function addChunk(stream, state, chunk, addToFront) {
7293 if (state.flowing && state.length === 0 && !state.sync) {
7294 state.awaitDrain = 0;
7295 stream.emit('data', chunk);
7296 } else {
7297 // update the buffer info.
7298 state.length += state.objectMode ? 1 : chunk.length;
7299 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
7300 if (state.needReadable) emitReadable(stream);
7301 }
7302
7303 maybeReadMore(stream, state);
7304}
7305
7306function chunkInvalid(state, chunk) {
7307 var er;
7308
7309 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
7310 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
7311 }
7312
7313 return er;
7314}
7315
7316Readable.prototype.isPaused = function () {
7317 return this._readableState.flowing === false;
7318}; // backwards compatibility.
7319
7320
7321Readable.prototype.setEncoding = function (enc) {
7322 if (!StringDecoder) StringDecoder = _dereq_(95).StringDecoder;
7323 var decoder = new StringDecoder(enc);
7324 this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8
7325
7326 this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:
7327
7328 var p = this._readableState.buffer.head;
7329 var content = '';
7330
7331 while (p !== null) {
7332 content += decoder.write(p.data);
7333 p = p.next;
7334 }
7335
7336 this._readableState.buffer.clear();
7337
7338 if (content !== '') this._readableState.buffer.push(content);
7339 this._readableState.length = content.length;
7340 return this;
7341}; // Don't raise the hwm > 1GB
7342
7343
7344var MAX_HWM = 0x40000000;
7345
7346function computeNewHighWaterMark(n) {
7347 if (n >= MAX_HWM) {
7348 // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
7349 n = MAX_HWM;
7350 } else {
7351 // Get the next highest power of 2 to prevent increasing hwm excessively in
7352 // tiny amounts
7353 n--;
7354 n |= n >>> 1;
7355 n |= n >>> 2;
7356 n |= n >>> 4;
7357 n |= n >>> 8;
7358 n |= n >>> 16;
7359 n++;
7360 }
7361
7362 return n;
7363} // This function is designed to be inlinable, so please take care when making
7364// changes to the function body.
7365
7366
7367function howMuchToRead(n, state) {
7368 if (n <= 0 || state.length === 0 && state.ended) return 0;
7369 if (state.objectMode) return 1;
7370
7371 if (n !== n) {
7372 // Only flow one buffer at a time
7373 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
7374 } // If we're asking for more than the current hwm, then raise the hwm.
7375
7376
7377 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
7378 if (n <= state.length) return n; // Don't have enough
7379
7380 if (!state.ended) {
7381 state.needReadable = true;
7382 return 0;
7383 }
7384
7385 return state.length;
7386} // you can override either this method, or the async _read(n) below.
7387
7388
7389Readable.prototype.read = function (n) {
7390 debug('read', n);
7391 n = parseInt(n, 10);
7392 var state = this._readableState;
7393 var nOrig = n;
7394 if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we
7395 // already have a bunch of data in the buffer, then just trigger
7396 // the 'readable' event and move on.
7397
7398 if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
7399 debug('read: emitReadable', state.length, state.ended);
7400 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
7401 return null;
7402 }
7403
7404 n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.
7405
7406 if (n === 0 && state.ended) {
7407 if (state.length === 0) endReadable(this);
7408 return null;
7409 } // All the actual chunk generation logic needs to be
7410 // *below* the call to _read. The reason is that in certain
7411 // synthetic stream cases, such as passthrough streams, _read
7412 // may be a completely synchronous operation which may change
7413 // the state of the read buffer, providing enough data when
7414 // before there was *not* enough.
7415 //
7416 // So, the steps are:
7417 // 1. Figure out what the state of things will be after we do
7418 // a read from the buffer.
7419 //
7420 // 2. If that resulting state will trigger a _read, then call _read.
7421 // Note that this may be asynchronous, or synchronous. Yes, it is
7422 // deeply ugly to write APIs this way, but that still doesn't mean
7423 // that the Readable class should behave improperly, as streams are
7424 // designed to be sync/async agnostic.
7425 // Take note if the _read call is sync or async (ie, if the read call
7426 // has returned yet), so that we know whether or not it's safe to emit
7427 // 'readable' etc.
7428 //
7429 // 3. Actually pull the requested chunks out of the buffer and return.
7430 // if we need a readable event, then we need to do some reading.
7431
7432
7433 var doRead = state.needReadable;
7434 debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some
7435
7436 if (state.length === 0 || state.length - n < state.highWaterMark) {
7437 doRead = true;
7438 debug('length less than watermark', doRead);
7439 } // however, if we've ended, then there's no point, and if we're already
7440 // reading, then it's unnecessary.
7441
7442
7443 if (state.ended || state.reading) {
7444 doRead = false;
7445 debug('reading or ended', doRead);
7446 } else if (doRead) {
7447 debug('do read');
7448 state.reading = true;
7449 state.sync = true; // if the length is currently zero, then we *need* a readable event.
7450
7451 if (state.length === 0) state.needReadable = true; // call internal read method
7452
7453 this._read(state.highWaterMark);
7454
7455 state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
7456 // and we need to re-evaluate how much data we can return to the user.
7457
7458 if (!state.reading) n = howMuchToRead(nOrig, state);
7459 }
7460
7461 var ret;
7462 if (n > 0) ret = fromList(n, state);else ret = null;
7463
7464 if (ret === null) {
7465 state.needReadable = state.length <= state.highWaterMark;
7466 n = 0;
7467 } else {
7468 state.length -= n;
7469 state.awaitDrain = 0;
7470 }
7471
7472 if (state.length === 0) {
7473 // If we have nothing in the buffer, then we want to know
7474 // as soon as we *do* get something into the buffer.
7475 if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
7476
7477 if (nOrig !== n && state.ended) endReadable(this);
7478 }
7479
7480 if (ret !== null) this.emit('data', ret);
7481 return ret;
7482};
7483
7484function onEofChunk(stream, state) {
7485 debug('onEofChunk');
7486 if (state.ended) return;
7487
7488 if (state.decoder) {
7489 var chunk = state.decoder.end();
7490
7491 if (chunk && chunk.length) {
7492 state.buffer.push(chunk);
7493 state.length += state.objectMode ? 1 : chunk.length;
7494 }
7495 }
7496
7497 state.ended = true;
7498
7499 if (state.sync) {
7500 // if we are sync, wait until next tick to emit the data.
7501 // Otherwise we risk emitting data in the flow()
7502 // the readable code triggers during a read() call
7503 emitReadable(stream);
7504 } else {
7505 // emit 'readable' now to make sure it gets picked up.
7506 state.needReadable = false;
7507
7508 if (!state.emittedReadable) {
7509 state.emittedReadable = true;
7510 emitReadable_(stream);
7511 }
7512 }
7513} // Don't emit readable right away in sync mode, because this can trigger
7514// another read() call => stack overflow. This way, it might trigger
7515// a nextTick recursion warning, but that's not so bad.
7516
7517
7518function emitReadable(stream) {
7519 var state = stream._readableState;
7520 debug('emitReadable', state.needReadable, state.emittedReadable);
7521 state.needReadable = false;
7522
7523 if (!state.emittedReadable) {
7524 debug('emitReadable', state.flowing);
7525 state.emittedReadable = true;
7526 process.nextTick(emitReadable_, stream);
7527 }
7528}
7529
7530function emitReadable_(stream) {
7531 var state = stream._readableState;
7532 debug('emitReadable_', state.destroyed, state.length, state.ended);
7533
7534 if (!state.destroyed && (state.length || state.ended)) {
7535 stream.emit('readable');
7536 state.emittedReadable = false;
7537 } // The stream needs another readable event if
7538 // 1. It is not flowing, as the flow mechanism will take
7539 // care of it.
7540 // 2. It is not ended.
7541 // 3. It is below the highWaterMark, so we can schedule
7542 // another readable later.
7543
7544
7545 state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
7546 flow(stream);
7547} // at this point, the user has presumably seen the 'readable' event,
7548// and called read() to consume some data. that may have triggered
7549// in turn another _read(n) call, in which case reading = true if
7550// it's in progress.
7551// However, if we're not ended, or reading, and the length < hwm,
7552// then go ahead and try to read some more preemptively.
7553
7554
7555function maybeReadMore(stream, state) {
7556 if (!state.readingMore) {
7557 state.readingMore = true;
7558 process.nextTick(maybeReadMore_, stream, state);
7559 }
7560}
7561
7562function maybeReadMore_(stream, state) {
7563 // Attempt to read more data if we should.
7564 //
7565 // The conditions for reading more data are (one of):
7566 // - Not enough data buffered (state.length < state.highWaterMark). The loop
7567 // is responsible for filling the buffer with enough data if such data
7568 // is available. If highWaterMark is 0 and we are not in the flowing mode
7569 // we should _not_ attempt to buffer any extra data. We'll get more data
7570 // when the stream consumer calls read() instead.
7571 // - No data in the buffer, and the stream is in flowing mode. In this mode
7572 // the loop below is responsible for ensuring read() is called. Failing to
7573 // call read here would abort the flow and there's no other mechanism for
7574 // continuing the flow if the stream consumer has just subscribed to the
7575 // 'data' event.
7576 //
7577 // In addition to the above conditions to keep reading data, the following
7578 // conditions prevent the data from being read:
7579 // - The stream has ended (state.ended).
7580 // - There is already a pending 'read' operation (state.reading). This is a
7581 // case where the the stream has called the implementation defined _read()
7582 // method, but they are processing the call asynchronously and have _not_
7583 // called push() with new data. In this case we skip performing more
7584 // read()s. The execution ends in this method again after the _read() ends
7585 // up calling push() with more data.
7586 while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
7587 var len = state.length;
7588 debug('maybeReadMore read 0');
7589 stream.read(0);
7590 if (len === state.length) // didn't get any data, stop spinning.
7591 break;
7592 }
7593
7594 state.readingMore = false;
7595} // abstract method. to be overridden in specific implementation classes.
7596// call cb(er, data) where data is <= n in length.
7597// for virtual (non-string, non-buffer) streams, "length" is somewhat
7598// arbitrary, and perhaps not very meaningful.
7599
7600
7601Readable.prototype._read = function (n) {
7602 errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
7603};
7604
7605Readable.prototype.pipe = function (dest, pipeOpts) {
7606 var src = this;
7607 var state = this._readableState;
7608
7609 switch (state.pipesCount) {
7610 case 0:
7611 state.pipes = dest;
7612 break;
7613
7614 case 1:
7615 state.pipes = [state.pipes, dest];
7616 break;
7617
7618 default:
7619 state.pipes.push(dest);
7620 break;
7621 }
7622
7623 state.pipesCount += 1;
7624 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
7625 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
7626 var endFn = doEnd ? onend : unpipe;
7627 if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
7628 dest.on('unpipe', onunpipe);
7629
7630 function onunpipe(readable, unpipeInfo) {
7631 debug('onunpipe');
7632
7633 if (readable === src) {
7634 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
7635 unpipeInfo.hasUnpiped = true;
7636 cleanup();
7637 }
7638 }
7639 }
7640
7641 function onend() {
7642 debug('onend');
7643 dest.end();
7644 } // when the dest drains, it reduces the awaitDrain counter
7645 // on the source. This would be more elegant with a .once()
7646 // handler in flow(), but adding and removing repeatedly is
7647 // too slow.
7648
7649
7650 var ondrain = pipeOnDrain(src);
7651 dest.on('drain', ondrain);
7652 var cleanedUp = false;
7653
7654 function cleanup() {
7655 debug('cleanup'); // cleanup event handlers once the pipe is broken
7656
7657 dest.removeListener('close', onclose);
7658 dest.removeListener('finish', onfinish);
7659 dest.removeListener('drain', ondrain);
7660 dest.removeListener('error', onerror);
7661 dest.removeListener('unpipe', onunpipe);
7662 src.removeListener('end', onend);
7663 src.removeListener('end', unpipe);
7664 src.removeListener('data', ondata);
7665 cleanedUp = true; // if the reader is waiting for a drain event from this
7666 // specific writer, then it would cause it to never start
7667 // flowing again.
7668 // So, if this is awaiting a drain, then we just call it now.
7669 // If we don't know, then assume that we are waiting for one.
7670
7671 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
7672 }
7673
7674 src.on('data', ondata);
7675
7676 function ondata(chunk) {
7677 debug('ondata');
7678 var ret = dest.write(chunk);
7679 debug('dest.write', ret);
7680
7681 if (ret === false) {
7682 // If the user unpiped during `dest.write()`, it is possible
7683 // to get stuck in a permanently paused state if that write
7684 // also returned false.
7685 // => Check whether `dest` is still a piping destination.
7686 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
7687 debug('false write response, pause', state.awaitDrain);
7688 state.awaitDrain++;
7689 }
7690
7691 src.pause();
7692 }
7693 } // if the dest has an error, then stop piping into it.
7694 // however, don't suppress the throwing behavior for this.
7695
7696
7697 function onerror(er) {
7698 debug('onerror', er);
7699 unpipe();
7700 dest.removeListener('error', onerror);
7701 if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
7702 } // Make sure our error handler is attached before userland ones.
7703
7704
7705 prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
7706
7707 function onclose() {
7708 dest.removeListener('finish', onfinish);
7709 unpipe();
7710 }
7711
7712 dest.once('close', onclose);
7713
7714 function onfinish() {
7715 debug('onfinish');
7716 dest.removeListener('close', onclose);
7717 unpipe();
7718 }
7719
7720 dest.once('finish', onfinish);
7721
7722 function unpipe() {
7723 debug('unpipe');
7724 src.unpipe(dest);
7725 } // tell the dest that it's being piped to
7726
7727
7728 dest.emit('pipe', src); // start the flow if it hasn't been started already.
7729
7730 if (!state.flowing) {
7731 debug('pipe resume');
7732 src.resume();
7733 }
7734
7735 return dest;
7736};
7737
7738function pipeOnDrain(src) {
7739 return function pipeOnDrainFunctionResult() {
7740 var state = src._readableState;
7741 debug('pipeOnDrain', state.awaitDrain);
7742 if (state.awaitDrain) state.awaitDrain--;
7743
7744 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
7745 state.flowing = true;
7746 flow(src);
7747 }
7748 };
7749}
7750
7751Readable.prototype.unpipe = function (dest) {
7752 var state = this._readableState;
7753 var unpipeInfo = {
7754 hasUnpiped: false
7755 }; // if we're not piping anywhere, then do nothing.
7756
7757 if (state.pipesCount === 0) return this; // just one destination. most common case.
7758
7759 if (state.pipesCount === 1) {
7760 // passed in one, but it's not the right one.
7761 if (dest && dest !== state.pipes) return this;
7762 if (!dest) dest = state.pipes; // got a match.
7763
7764 state.pipes = null;
7765 state.pipesCount = 0;
7766 state.flowing = false;
7767 if (dest) dest.emit('unpipe', this, unpipeInfo);
7768 return this;
7769 } // slow case. multiple pipe destinations.
7770
7771
7772 if (!dest) {
7773 // remove all.
7774 var dests = state.pipes;
7775 var len = state.pipesCount;
7776 state.pipes = null;
7777 state.pipesCount = 0;
7778 state.flowing = false;
7779
7780 for (var i = 0; i < len; i++) {
7781 dests[i].emit('unpipe', this, {
7782 hasUnpiped: false
7783 });
7784 }
7785
7786 return this;
7787 } // try to find the right one.
7788
7789
7790 var index = indexOf(state.pipes, dest);
7791 if (index === -1) return this;
7792 state.pipes.splice(index, 1);
7793 state.pipesCount -= 1;
7794 if (state.pipesCount === 1) state.pipes = state.pipes[0];
7795 dest.emit('unpipe', this, unpipeInfo);
7796 return this;
7797}; // set up data events if they are asked for
7798// Ensure readable listeners eventually get something
7799
7800
7801Readable.prototype.on = function (ev, fn) {
7802 var res = Stream.prototype.on.call(this, ev, fn);
7803 var state = this._readableState;
7804
7805 if (ev === 'data') {
7806 // update readableListening so that resume() may be a no-op
7807 // a few lines down. This is needed to support once('readable').
7808 state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused
7809
7810 if (state.flowing !== false) this.resume();
7811 } else if (ev === 'readable') {
7812 if (!state.endEmitted && !state.readableListening) {
7813 state.readableListening = state.needReadable = true;
7814 state.flowing = false;
7815 state.emittedReadable = false;
7816 debug('on readable', state.length, state.reading);
7817
7818 if (state.length) {
7819 emitReadable(this);
7820 } else if (!state.reading) {
7821 process.nextTick(nReadingNextTick, this);
7822 }
7823 }
7824 }
7825
7826 return res;
7827};
7828
7829Readable.prototype.addListener = Readable.prototype.on;
7830
7831Readable.prototype.removeListener = function (ev, fn) {
7832 var res = Stream.prototype.removeListener.call(this, ev, fn);
7833
7834 if (ev === 'readable') {
7835 // We need to check if there is someone still listening to
7836 // readable and reset the state. However this needs to happen
7837 // after readable has been emitted but before I/O (nextTick) to
7838 // support once('readable', fn) cycles. This means that calling
7839 // resume within the same tick will have no
7840 // effect.
7841 process.nextTick(updateReadableListening, this);
7842 }
7843
7844 return res;
7845};
7846
7847Readable.prototype.removeAllListeners = function (ev) {
7848 var res = Stream.prototype.removeAllListeners.apply(this, arguments);
7849
7850 if (ev === 'readable' || ev === undefined) {
7851 // We need to check if there is someone still listening to
7852 // readable and reset the state. However this needs to happen
7853 // after readable has been emitted but before I/O (nextTick) to
7854 // support once('readable', fn) cycles. This means that calling
7855 // resume within the same tick will have no
7856 // effect.
7857 process.nextTick(updateReadableListening, this);
7858 }
7859
7860 return res;
7861};
7862
7863function updateReadableListening(self) {
7864 var state = self._readableState;
7865 state.readableListening = self.listenerCount('readable') > 0;
7866
7867 if (state.resumeScheduled && !state.paused) {
7868 // flowing needs to be set to true now, otherwise
7869 // the upcoming resume will not flow.
7870 state.flowing = true; // crude way to check if we should resume
7871 } else if (self.listenerCount('data') > 0) {
7872 self.resume();
7873 }
7874}
7875
7876function nReadingNextTick(self) {
7877 debug('readable nexttick read 0');
7878 self.read(0);
7879} // pause() and resume() are remnants of the legacy readable stream API
7880// If the user uses them, then switch into old mode.
7881
7882
7883Readable.prototype.resume = function () {
7884 var state = this._readableState;
7885
7886 if (!state.flowing) {
7887 debug('resume'); // we flow only if there is no one listening
7888 // for readable, but we still have to call
7889 // resume()
7890
7891 state.flowing = !state.readableListening;
7892 resume(this, state);
7893 }
7894
7895 state.paused = false;
7896 return this;
7897};
7898
7899function resume(stream, state) {
7900 if (!state.resumeScheduled) {
7901 state.resumeScheduled = true;
7902 process.nextTick(resume_, stream, state);
7903 }
7904}
7905
7906function resume_(stream, state) {
7907 debug('resume', state.reading);
7908
7909 if (!state.reading) {
7910 stream.read(0);
7911 }
7912
7913 state.resumeScheduled = false;
7914 stream.emit('resume');
7915 flow(stream);
7916 if (state.flowing && !state.reading) stream.read(0);
7917}
7918
7919Readable.prototype.pause = function () {
7920 debug('call pause flowing=%j', this._readableState.flowing);
7921
7922 if (this._readableState.flowing !== false) {
7923 debug('pause');
7924 this._readableState.flowing = false;
7925 this.emit('pause');
7926 }
7927
7928 this._readableState.paused = true;
7929 return this;
7930};
7931
7932function flow(stream) {
7933 var state = stream._readableState;
7934 debug('flow', state.flowing);
7935
7936 while (state.flowing && stream.read() !== null) {
7937 ;
7938 }
7939} // wrap an old-style stream as the async data source.
7940// This is *not* part of the readable stream interface.
7941// It is an ugly unfortunate mess of history.
7942
7943
7944Readable.prototype.wrap = function (stream) {
7945 var _this = this;
7946
7947 var state = this._readableState;
7948 var paused = false;
7949 stream.on('end', function () {
7950 debug('wrapped end');
7951
7952 if (state.decoder && !state.ended) {
7953 var chunk = state.decoder.end();
7954 if (chunk && chunk.length) _this.push(chunk);
7955 }
7956
7957 _this.push(null);
7958 });
7959 stream.on('data', function (chunk) {
7960 debug('wrapped data');
7961 if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
7962
7963 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
7964
7965 var ret = _this.push(chunk);
7966
7967 if (!ret) {
7968 paused = true;
7969 stream.pause();
7970 }
7971 }); // proxy all the other methods.
7972 // important when wrapping filters and duplexes.
7973
7974 for (var i in stream) {
7975 if (this[i] === undefined && typeof stream[i] === 'function') {
7976 this[i] = function methodWrap(method) {
7977 return function methodWrapReturnFunction() {
7978 return stream[method].apply(stream, arguments);
7979 };
7980 }(i);
7981 }
7982 } // proxy certain important events.
7983
7984
7985 for (var n = 0; n < kProxyEvents.length; n++) {
7986 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
7987 } // when we try to consume some more bytes, simply unpause the
7988 // underlying stream.
7989
7990
7991 this._read = function (n) {
7992 debug('wrapped _read', n);
7993
7994 if (paused) {
7995 paused = false;
7996 stream.resume();
7997 }
7998 };
7999
8000 return this;
8001};
8002
8003if (typeof Symbol === 'function') {
8004 Readable.prototype[Symbol.asyncIterator] = function () {
8005 if (createReadableStreamAsyncIterator === undefined) {
8006 createReadableStreamAsyncIterator = _dereq_(41);
8007 }
8008
8009 return createReadableStreamAsyncIterator(this);
8010 };
8011}
8012
8013Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
8014 // making it explicit this property is not enumerable
8015 // because otherwise some prototype manipulation in
8016 // userland will fail
8017 enumerable: false,
8018 get: function get() {
8019 return this._readableState.highWaterMark;
8020 }
8021});
8022Object.defineProperty(Readable.prototype, 'readableBuffer', {
8023 // making it explicit this property is not enumerable
8024 // because otherwise some prototype manipulation in
8025 // userland will fail
8026 enumerable: false,
8027 get: function get() {
8028 return this._readableState && this._readableState.buffer;
8029 }
8030});
8031Object.defineProperty(Readable.prototype, 'readableFlowing', {
8032 // making it explicit this property is not enumerable
8033 // because otherwise some prototype manipulation in
8034 // userland will fail
8035 enumerable: false,
8036 get: function get() {
8037 return this._readableState.flowing;
8038 },
8039 set: function set(state) {
8040 if (this._readableState) {
8041 this._readableState.flowing = state;
8042 }
8043 }
8044}); // exposed for testing purposes only.
8045
8046Readable._fromList = fromList;
8047Object.defineProperty(Readable.prototype, 'readableLength', {
8048 // making it explicit this property is not enumerable
8049 // because otherwise some prototype manipulation in
8050 // userland will fail
8051 enumerable: false,
8052 get: function get() {
8053 return this._readableState.length;
8054 }
8055}); // Pluck off n bytes from an array of buffers.
8056// Length is the combined lengths of all the buffers in the list.
8057// This function is designed to be inlinable, so please take care when making
8058// changes to the function body.
8059
8060function fromList(n, state) {
8061 // nothing buffered
8062 if (state.length === 0) return null;
8063 var ret;
8064 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
8065 // read it all, truncate the list
8066 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
8067 state.buffer.clear();
8068 } else {
8069 // read part of list
8070 ret = state.buffer.consume(n, state.decoder);
8071 }
8072 return ret;
8073}
8074
8075function endReadable(stream) {
8076 var state = stream._readableState;
8077 debug('endReadable', state.endEmitted);
8078
8079 if (!state.endEmitted) {
8080 state.ended = true;
8081 process.nextTick(endReadableNT, state, stream);
8082 }
8083}
8084
8085function endReadableNT(state, stream) {
8086 debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.
8087
8088 if (!state.endEmitted && state.length === 0) {
8089 state.endEmitted = true;
8090 stream.readable = false;
8091 stream.emit('end');
8092
8093 if (state.autoDestroy) {
8094 // In case of duplex streams we need a way to detect
8095 // if the writable side is ready for autoDestroy as well
8096 var wState = stream._writableState;
8097
8098 if (!wState || wState.autoDestroy && wState.finished) {
8099 stream.destroy();
8100 }
8101 }
8102 }
8103}
8104
8105if (typeof Symbol === 'function') {
8106 Readable.from = function (iterable, opts) {
8107 if (from === undefined) {
8108 from = _dereq_(45);
8109 }
8110
8111 return from(Readable, iterable, opts);
8112 };
8113}
8114
8115function indexOf(xs, x) {
8116 for (var i = 0, l = xs.length; i < l; i++) {
8117 if (xs[i] === x) return i;
8118 }
8119
8120 return -1;
8121}
8122}).call(this)}).call(this,_dereq_(66),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
8123},{"20":20,"29":29,"35":35,"36":36,"41":41,"42":42,"43":43,"45":45,"47":47,"48":48,"6":6,"66":66,"8":8,"95":95}],39:[function(_dereq_,module,exports){
8124// Copyright Joyent, Inc. and other Node contributors.
8125//
8126// Permission is hereby granted, free of charge, to any person obtaining a
8127// copy of this software and associated documentation files (the
8128// "Software"), to deal in the Software without restriction, including
8129// without limitation the rights to use, copy, modify, merge, publish,
8130// distribute, sublicense, and/or sell copies of the Software, and to permit
8131// persons to whom the Software is furnished to do so, subject to the
8132// following conditions:
8133//
8134// The above copyright notice and this permission notice shall be included
8135// in all copies or substantial portions of the Software.
8136//
8137// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
8138// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
8139// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
8140// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
8141// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
8142// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
8143// USE OR OTHER DEALINGS IN THE SOFTWARE.
8144// a transform stream is a readable/writable stream where you do
8145// something with the data. Sometimes it's called a "filter",
8146// but that's not a great name for it, since that implies a thing where
8147// some bits pass through, and others are simply ignored. (That would
8148// be a valid example of a transform, of course.)
8149//
8150// While the output is causally related to the input, it's not a
8151// necessarily symmetric or synchronous transformation. For example,
8152// a zlib stream might take multiple plain-text writes(), and then
8153// emit a single compressed chunk some time in the future.
8154//
8155// Here's how this works:
8156//
8157// The Transform stream has all the aspects of the readable and writable
8158// stream classes. When you write(chunk), that calls _write(chunk,cb)
8159// internally, and returns false if there's a lot of pending writes
8160// buffered up. When you call read(), that calls _read(n) until
8161// there's enough pending readable data buffered up.
8162//
8163// In a transform stream, the written data is placed in a buffer. When
8164// _read(n) is called, it transforms the queued up data, calling the
8165// buffered _write cb's as it consumes chunks. If consuming a single
8166// written chunk would result in multiple output chunks, then the first
8167// outputted bit calls the readcb, and subsequent chunks just go into
8168// the read buffer, and will cause it to emit 'readable' if necessary.
8169//
8170// This way, back-pressure is actually determined by the reading side,
8171// since _read has to be called to start processing a new chunk. However,
8172// a pathological inflate type of transform can cause excessive buffering
8173// here. For example, imagine a stream where every byte of input is
8174// interpreted as an integer from 0-255, and then results in that many
8175// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
8176// 1kb of data being output. In this case, you could write a very small
8177// amount of input, and end up with a very large amount of output. In
8178// such a pathological inflating mechanism, there'd be no way to tell
8179// the system to stop doing the transform. A single 4MB write could
8180// cause the system to run out of memory.
8181//
8182// However, even in such a pathological case, only a single written chunk
8183// would be consumed, and then the rest would wait (un-transformed) until
8184// the results of the previous transformed chunk were consumed.
8185'use strict';
8186
8187module.exports = Transform;
8188
8189var _require$codes = _dereq_(35).codes,
8190 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
8191 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
8192 ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
8193 ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
8194
8195var Duplex = _dereq_(36);
8196
8197_dereq_(29)(Transform, Duplex);
8198
8199function afterTransform(er, data) {
8200 var ts = this._transformState;
8201 ts.transforming = false;
8202 var cb = ts.writecb;
8203
8204 if (cb === null) {
8205 return this.emit('error', new ERR_MULTIPLE_CALLBACK());
8206 }
8207
8208 ts.writechunk = null;
8209 ts.writecb = null;
8210 if (data != null) // single equals check for both `null` and `undefined`
8211 this.push(data);
8212 cb(er);
8213 var rs = this._readableState;
8214 rs.reading = false;
8215
8216 if (rs.needReadable || rs.length < rs.highWaterMark) {
8217 this._read(rs.highWaterMark);
8218 }
8219}
8220
8221function Transform(options) {
8222 if (!(this instanceof Transform)) return new Transform(options);
8223 Duplex.call(this, options);
8224 this._transformState = {
8225 afterTransform: afterTransform.bind(this),
8226 needTransform: false,
8227 transforming: false,
8228 writecb: null,
8229 writechunk: null,
8230 writeencoding: null
8231 }; // start out asking for a readable event once data is transformed.
8232
8233 this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
8234 // that Readable wants before the first _read call, so unset the
8235 // sync guard flag.
8236
8237 this._readableState.sync = false;
8238
8239 if (options) {
8240 if (typeof options.transform === 'function') this._transform = options.transform;
8241 if (typeof options.flush === 'function') this._flush = options.flush;
8242 } // When the writable side finishes, then flush out anything remaining.
8243
8244
8245 this.on('prefinish', prefinish);
8246}
8247
8248function prefinish() {
8249 var _this = this;
8250
8251 if (typeof this._flush === 'function' && !this._readableState.destroyed) {
8252 this._flush(function (er, data) {
8253 done(_this, er, data);
8254 });
8255 } else {
8256 done(this, null, null);
8257 }
8258}
8259
8260Transform.prototype.push = function (chunk, encoding) {
8261 this._transformState.needTransform = false;
8262 return Duplex.prototype.push.call(this, chunk, encoding);
8263}; // This is the part where you do stuff!
8264// override this function in implementation classes.
8265// 'chunk' is an input chunk.
8266//
8267// Call `push(newChunk)` to pass along transformed output
8268// to the readable side. You may call 'push' zero or more times.
8269//
8270// Call `cb(err)` when you are done with this chunk. If you pass
8271// an error, then that'll put the hurt on the whole operation. If you
8272// never call cb(), then you'll never get another chunk.
8273
8274
8275Transform.prototype._transform = function (chunk, encoding, cb) {
8276 cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
8277};
8278
8279Transform.prototype._write = function (chunk, encoding, cb) {
8280 var ts = this._transformState;
8281 ts.writecb = cb;
8282 ts.writechunk = chunk;
8283 ts.writeencoding = encoding;
8284
8285 if (!ts.transforming) {
8286 var rs = this._readableState;
8287 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
8288 }
8289}; // Doesn't matter what the args are here.
8290// _transform does all the work.
8291// That we got here means that the readable side wants more data.
8292
8293
8294Transform.prototype._read = function (n) {
8295 var ts = this._transformState;
8296
8297 if (ts.writechunk !== null && !ts.transforming) {
8298 ts.transforming = true;
8299
8300 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
8301 } else {
8302 // mark that we need a transform, so that any data that comes in
8303 // will get processed, now that we've asked for it.
8304 ts.needTransform = true;
8305 }
8306};
8307
8308Transform.prototype._destroy = function (err, cb) {
8309 Duplex.prototype._destroy.call(this, err, function (err2) {
8310 cb(err2);
8311 });
8312};
8313
8314function done(stream, er, data) {
8315 if (er) return stream.emit('error', er);
8316 if (data != null) // single equals check for both `null` and `undefined`
8317 stream.push(data); // TODO(BridgeAR): Write a test for these two error cases
8318 // if there's nothing in the write buffer, then that means
8319 // that nothing more will ever be provided
8320
8321 if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
8322 if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
8323 return stream.push(null);
8324}
8325},{"29":29,"35":35,"36":36}],40:[function(_dereq_,module,exports){
8326(function (process,global){(function (){
8327// Copyright Joyent, Inc. and other Node contributors.
8328//
8329// Permission is hereby granted, free of charge, to any person obtaining a
8330// copy of this software and associated documentation files (the
8331// "Software"), to deal in the Software without restriction, including
8332// without limitation the rights to use, copy, modify, merge, publish,
8333// distribute, sublicense, and/or sell copies of the Software, and to permit
8334// persons to whom the Software is furnished to do so, subject to the
8335// following conditions:
8336//
8337// The above copyright notice and this permission notice shall be included
8338// in all copies or substantial portions of the Software.
8339//
8340// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
8341// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
8342// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
8343// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
8344// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
8345// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
8346// USE OR OTHER DEALINGS IN THE SOFTWARE.
8347// A bit simpler than readable streams.
8348// Implement an async ._write(chunk, encoding, cb), and it'll handle all
8349// the drain event emission and buffering.
8350'use strict';
8351
8352module.exports = Writable;
8353/* <replacement> */
8354
8355function WriteReq(chunk, encoding, cb) {
8356 this.chunk = chunk;
8357 this.encoding = encoding;
8358 this.callback = cb;
8359 this.next = null;
8360} // It seems a linked list but it is not
8361// there will be only 2 of these for each stream
8362
8363
8364function CorkedRequest(state) {
8365 var _this = this;
8366
8367 this.next = null;
8368 this.entry = null;
8369
8370 this.finish = function () {
8371 onCorkedFinish(_this, state);
8372 };
8373}
8374/* </replacement> */
8375
8376/*<replacement>*/
8377
8378
8379var Duplex;
8380/*</replacement>*/
8381
8382Writable.WritableState = WritableState;
8383/*<replacement>*/
8384
8385var internalUtil = {
8386 deprecate: _dereq_(113)
8387};
8388/*</replacement>*/
8389
8390/*<replacement>*/
8391
8392var Stream = _dereq_(48);
8393/*</replacement>*/
8394
8395
8396var Buffer = _dereq_(8).Buffer;
8397
8398var OurUint8Array = global.Uint8Array || function () {};
8399
8400function _uint8ArrayToBuffer(chunk) {
8401 return Buffer.from(chunk);
8402}
8403
8404function _isUint8Array(obj) {
8405 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
8406}
8407
8408var destroyImpl = _dereq_(43);
8409
8410var _require = _dereq_(47),
8411 getHighWaterMark = _require.getHighWaterMark;
8412
8413var _require$codes = _dereq_(35).codes,
8414 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
8415 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
8416 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
8417 ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
8418 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
8419 ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
8420 ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
8421 ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
8422
8423var errorOrDestroy = destroyImpl.errorOrDestroy;
8424
8425_dereq_(29)(Writable, Stream);
8426
8427function nop() {}
8428
8429function WritableState(options, stream, isDuplex) {
8430 Duplex = Duplex || _dereq_(36);
8431 options = options || {}; // Duplex streams are both readable and writable, but share
8432 // the same options object.
8433 // However, some cases require setting options to different
8434 // values for the readable and the writable sides of the duplex stream,
8435 // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
8436
8437 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream
8438 // contains buffers or objects.
8439
8440 this.objectMode = !!options.objectMode;
8441 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
8442 // Note: 0 is a valid value, means that we always return false if
8443 // the entire buffer is not flushed immediately on write()
8444
8445 this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called
8446
8447 this.finalCalled = false; // drain event flag.
8448
8449 this.needDrain = false; // at the start of calling end()
8450
8451 this.ending = false; // when end() has been called, and returned
8452
8453 this.ended = false; // when 'finish' is emitted
8454
8455 this.finished = false; // has it been destroyed
8456
8457 this.destroyed = false; // should we decode strings into buffers before passing to _write?
8458 // this is here so that some node-core streams can optimize string
8459 // handling at a lower level.
8460
8461 var noDecode = options.decodeStrings === false;
8462 this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string
8463 // encoding is 'binary' so we have to make this configurable.
8464 // Everything else in the universe uses 'utf8', though.
8465
8466 this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement
8467 // of how much we're waiting to get pushed to some underlying
8468 // socket or file.
8469
8470 this.length = 0; // a flag to see when we're in the middle of a write.
8471
8472 this.writing = false; // when true all writes will be buffered until .uncork() call
8473
8474 this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,
8475 // or on a later tick. We set this to true at first, because any
8476 // actions that shouldn't happen until "later" should generally also
8477 // not happen before the first write call.
8478
8479 this.sync = true; // a flag to know if we're processing previously buffered items, which
8480 // may call the _write() callback in the same tick, so that we don't
8481 // end up in an overlapped onwrite situation.
8482
8483 this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)
8484
8485 this.onwrite = function (er) {
8486 onwrite(stream, er);
8487 }; // the callback that the user supplies to write(chunk,encoding,cb)
8488
8489
8490 this.writecb = null; // the amount that is being written when _write is called.
8491
8492 this.writelen = 0;
8493 this.bufferedRequest = null;
8494 this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
8495 // this must be 0 before 'finish' can be emitted
8496
8497 this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
8498 // This is relevant for synchronous Transform streams
8499
8500 this.prefinished = false; // True if the error was already emitted and should not be thrown again
8501
8502 this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.
8503
8504 this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')
8505
8506 this.autoDestroy = !!options.autoDestroy; // count buffered requests
8507
8508 this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always
8509 // one allocated and free to use, and we maintain at most two
8510
8511 this.corkedRequestsFree = new CorkedRequest(this);
8512}
8513
8514WritableState.prototype.getBuffer = function getBuffer() {
8515 var current = this.bufferedRequest;
8516 var out = [];
8517
8518 while (current) {
8519 out.push(current);
8520 current = current.next;
8521 }
8522
8523 return out;
8524};
8525
8526(function () {
8527 try {
8528 Object.defineProperty(WritableState.prototype, 'buffer', {
8529 get: internalUtil.deprecate(function writableStateBufferGetter() {
8530 return this.getBuffer();
8531 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
8532 });
8533 } catch (_) {}
8534})(); // Test _writableState for inheritance to account for Duplex streams,
8535// whose prototype chain only points to Readable.
8536
8537
8538var realHasInstance;
8539
8540if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
8541 realHasInstance = Function.prototype[Symbol.hasInstance];
8542 Object.defineProperty(Writable, Symbol.hasInstance, {
8543 value: function value(object) {
8544 if (realHasInstance.call(this, object)) return true;
8545 if (this !== Writable) return false;
8546 return object && object._writableState instanceof WritableState;
8547 }
8548 });
8549} else {
8550 realHasInstance = function realHasInstance(object) {
8551 return object instanceof this;
8552 };
8553}
8554
8555function Writable(options) {
8556 Duplex = Duplex || _dereq_(36); // Writable ctor is applied to Duplexes, too.
8557 // `realHasInstance` is necessary because using plain `instanceof`
8558 // would return false, as no `_writableState` property is attached.
8559 // Trying to use the custom `instanceof` for Writable here will also break the
8560 // Node.js LazyTransform implementation, which has a non-trivial getter for
8561 // `_writableState` that would lead to infinite recursion.
8562 // Checking for a Stream.Duplex instance is faster here instead of inside
8563 // the WritableState constructor, at least with V8 6.5
8564
8565 var isDuplex = this instanceof Duplex;
8566 if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
8567 this._writableState = new WritableState(options, this, isDuplex); // legacy.
8568
8569 this.writable = true;
8570
8571 if (options) {
8572 if (typeof options.write === 'function') this._write = options.write;
8573 if (typeof options.writev === 'function') this._writev = options.writev;
8574 if (typeof options.destroy === 'function') this._destroy = options.destroy;
8575 if (typeof options.final === 'function') this._final = options.final;
8576 }
8577
8578 Stream.call(this);
8579} // Otherwise people can pipe Writable streams, which is just wrong.
8580
8581
8582Writable.prototype.pipe = function () {
8583 errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
8584};
8585
8586function writeAfterEnd(stream, cb) {
8587 var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
8588
8589 errorOrDestroy(stream, er);
8590 process.nextTick(cb, er);
8591} // Checks that a user-supplied chunk is valid, especially for the particular
8592// mode the stream is in. Currently this means that `null` is never accepted
8593// and undefined/non-string values are only allowed in object mode.
8594
8595
8596function validChunk(stream, state, chunk, cb) {
8597 var er;
8598
8599 if (chunk === null) {
8600 er = new ERR_STREAM_NULL_VALUES();
8601 } else if (typeof chunk !== 'string' && !state.objectMode) {
8602 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
8603 }
8604
8605 if (er) {
8606 errorOrDestroy(stream, er);
8607 process.nextTick(cb, er);
8608 return false;
8609 }
8610
8611 return true;
8612}
8613
8614Writable.prototype.write = function (chunk, encoding, cb) {
8615 var state = this._writableState;
8616 var ret = false;
8617
8618 var isBuf = !state.objectMode && _isUint8Array(chunk);
8619
8620 if (isBuf && !Buffer.isBuffer(chunk)) {
8621 chunk = _uint8ArrayToBuffer(chunk);
8622 }
8623
8624 if (typeof encoding === 'function') {
8625 cb = encoding;
8626 encoding = null;
8627 }
8628
8629 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
8630 if (typeof cb !== 'function') cb = nop;
8631 if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
8632 state.pendingcb++;
8633 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
8634 }
8635 return ret;
8636};
8637
8638Writable.prototype.cork = function () {
8639 this._writableState.corked++;
8640};
8641
8642Writable.prototype.uncork = function () {
8643 var state = this._writableState;
8644
8645 if (state.corked) {
8646 state.corked--;
8647 if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
8648 }
8649};
8650
8651Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
8652 // node::ParseEncoding() requires lower case.
8653 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
8654 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);
8655 this._writableState.defaultEncoding = encoding;
8656 return this;
8657};
8658
8659Object.defineProperty(Writable.prototype, 'writableBuffer', {
8660 // making it explicit this property is not enumerable
8661 // because otherwise some prototype manipulation in
8662 // userland will fail
8663 enumerable: false,
8664 get: function get() {
8665 return this._writableState && this._writableState.getBuffer();
8666 }
8667});
8668
8669function decodeChunk(state, chunk, encoding) {
8670 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
8671 chunk = Buffer.from(chunk, encoding);
8672 }
8673
8674 return chunk;
8675}
8676
8677Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
8678 // making it explicit this property is not enumerable
8679 // because otherwise some prototype manipulation in
8680 // userland will fail
8681 enumerable: false,
8682 get: function get() {
8683 return this._writableState.highWaterMark;
8684 }
8685}); // if we're already writing something, then just put this
8686// in the queue, and wait our turn. Otherwise, call _write
8687// If we return false, then we need a drain event, so set that flag.
8688
8689function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
8690 if (!isBuf) {
8691 var newChunk = decodeChunk(state, chunk, encoding);
8692
8693 if (chunk !== newChunk) {
8694 isBuf = true;
8695 encoding = 'buffer';
8696 chunk = newChunk;
8697 }
8698 }
8699
8700 var len = state.objectMode ? 1 : chunk.length;
8701 state.length += len;
8702 var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
8703
8704 if (!ret) state.needDrain = true;
8705
8706 if (state.writing || state.corked) {
8707 var last = state.lastBufferedRequest;
8708 state.lastBufferedRequest = {
8709 chunk: chunk,
8710 encoding: encoding,
8711 isBuf: isBuf,
8712 callback: cb,
8713 next: null
8714 };
8715
8716 if (last) {
8717 last.next = state.lastBufferedRequest;
8718 } else {
8719 state.bufferedRequest = state.lastBufferedRequest;
8720 }
8721
8722 state.bufferedRequestCount += 1;
8723 } else {
8724 doWrite(stream, state, false, len, chunk, encoding, cb);
8725 }
8726
8727 return ret;
8728}
8729
8730function doWrite(stream, state, writev, len, chunk, encoding, cb) {
8731 state.writelen = len;
8732 state.writecb = cb;
8733 state.writing = true;
8734 state.sync = true;
8735 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);
8736 state.sync = false;
8737}
8738
8739function onwriteError(stream, state, sync, er, cb) {
8740 --state.pendingcb;
8741
8742 if (sync) {
8743 // defer the callback if we are being called synchronously
8744 // to avoid piling up things on the stack
8745 process.nextTick(cb, er); // this can emit finish, and it will always happen
8746 // after error
8747
8748 process.nextTick(finishMaybe, stream, state);
8749 stream._writableState.errorEmitted = true;
8750 errorOrDestroy(stream, er);
8751 } else {
8752 // the caller expect this to happen before if
8753 // it is async
8754 cb(er);
8755 stream._writableState.errorEmitted = true;
8756 errorOrDestroy(stream, er); // this can emit finish, but finish must
8757 // always follow error
8758
8759 finishMaybe(stream, state);
8760 }
8761}
8762
8763function onwriteStateUpdate(state) {
8764 state.writing = false;
8765 state.writecb = null;
8766 state.length -= state.writelen;
8767 state.writelen = 0;
8768}
8769
8770function onwrite(stream, er) {
8771 var state = stream._writableState;
8772 var sync = state.sync;
8773 var cb = state.writecb;
8774 if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
8775 onwriteStateUpdate(state);
8776 if (er) onwriteError(stream, state, sync, er, cb);else {
8777 // Check if we're actually ready to finish, but don't emit yet
8778 var finished = needFinish(state) || stream.destroyed;
8779
8780 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
8781 clearBuffer(stream, state);
8782 }
8783
8784 if (sync) {
8785 process.nextTick(afterWrite, stream, state, finished, cb);
8786 } else {
8787 afterWrite(stream, state, finished, cb);
8788 }
8789 }
8790}
8791
8792function afterWrite(stream, state, finished, cb) {
8793 if (!finished) onwriteDrain(stream, state);
8794 state.pendingcb--;
8795 cb();
8796 finishMaybe(stream, state);
8797} // Must force callback to be called on nextTick, so that we don't
8798// emit 'drain' before the write() consumer gets the 'false' return
8799// value, and has a chance to attach a 'drain' listener.
8800
8801
8802function onwriteDrain(stream, state) {
8803 if (state.length === 0 && state.needDrain) {
8804 state.needDrain = false;
8805 stream.emit('drain');
8806 }
8807} // if there's something in the buffer waiting, then process it
8808
8809
8810function clearBuffer(stream, state) {
8811 state.bufferProcessing = true;
8812 var entry = state.bufferedRequest;
8813
8814 if (stream._writev && entry && entry.next) {
8815 // Fast case, write everything using _writev()
8816 var l = state.bufferedRequestCount;
8817 var buffer = new Array(l);
8818 var holder = state.corkedRequestsFree;
8819 holder.entry = entry;
8820 var count = 0;
8821 var allBuffers = true;
8822
8823 while (entry) {
8824 buffer[count] = entry;
8825 if (!entry.isBuf) allBuffers = false;
8826 entry = entry.next;
8827 count += 1;
8828 }
8829
8830 buffer.allBuffers = allBuffers;
8831 doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
8832 // as the hot path ends with doWrite
8833
8834 state.pendingcb++;
8835 state.lastBufferedRequest = null;
8836
8837 if (holder.next) {
8838 state.corkedRequestsFree = holder.next;
8839 holder.next = null;
8840 } else {
8841 state.corkedRequestsFree = new CorkedRequest(state);
8842 }
8843
8844 state.bufferedRequestCount = 0;
8845 } else {
8846 // Slow case, write chunks one-by-one
8847 while (entry) {
8848 var chunk = entry.chunk;
8849 var encoding = entry.encoding;
8850 var cb = entry.callback;
8851 var len = state.objectMode ? 1 : chunk.length;
8852 doWrite(stream, state, false, len, chunk, encoding, cb);
8853 entry = entry.next;
8854 state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then
8855 // it means that we need to wait until it does.
8856 // also, that means that the chunk and cb are currently
8857 // being processed, so move the buffer counter past them.
8858
8859 if (state.writing) {
8860 break;
8861 }
8862 }
8863
8864 if (entry === null) state.lastBufferedRequest = null;
8865 }
8866
8867 state.bufferedRequest = entry;
8868 state.bufferProcessing = false;
8869}
8870
8871Writable.prototype._write = function (chunk, encoding, cb) {
8872 cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
8873};
8874
8875Writable.prototype._writev = null;
8876
8877Writable.prototype.end = function (chunk, encoding, cb) {
8878 var state = this._writableState;
8879
8880 if (typeof chunk === 'function') {
8881 cb = chunk;
8882 chunk = null;
8883 encoding = null;
8884 } else if (typeof encoding === 'function') {
8885 cb = encoding;
8886 encoding = null;
8887 }
8888
8889 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks
8890
8891 if (state.corked) {
8892 state.corked = 1;
8893 this.uncork();
8894 } // ignore unnecessary end() calls.
8895
8896
8897 if (!state.ending) endWritable(this, state, cb);
8898 return this;
8899};
8900
8901Object.defineProperty(Writable.prototype, 'writableLength', {
8902 // making it explicit this property is not enumerable
8903 // because otherwise some prototype manipulation in
8904 // userland will fail
8905 enumerable: false,
8906 get: function get() {
8907 return this._writableState.length;
8908 }
8909});
8910
8911function needFinish(state) {
8912 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
8913}
8914
8915function callFinal(stream, state) {
8916 stream._final(function (err) {
8917 state.pendingcb--;
8918
8919 if (err) {
8920 errorOrDestroy(stream, err);
8921 }
8922
8923 state.prefinished = true;
8924 stream.emit('prefinish');
8925 finishMaybe(stream, state);
8926 });
8927}
8928
8929function prefinish(stream, state) {
8930 if (!state.prefinished && !state.finalCalled) {
8931 if (typeof stream._final === 'function' && !state.destroyed) {
8932 state.pendingcb++;
8933 state.finalCalled = true;
8934 process.nextTick(callFinal, stream, state);
8935 } else {
8936 state.prefinished = true;
8937 stream.emit('prefinish');
8938 }
8939 }
8940}
8941
8942function finishMaybe(stream, state) {
8943 var need = needFinish(state);
8944
8945 if (need) {
8946 prefinish(stream, state);
8947
8948 if (state.pendingcb === 0) {
8949 state.finished = true;
8950 stream.emit('finish');
8951
8952 if (state.autoDestroy) {
8953 // In case of duplex streams we need a way to detect
8954 // if the readable side is ready for autoDestroy as well
8955 var rState = stream._readableState;
8956
8957 if (!rState || rState.autoDestroy && rState.endEmitted) {
8958 stream.destroy();
8959 }
8960 }
8961 }
8962 }
8963
8964 return need;
8965}
8966
8967function endWritable(stream, state, cb) {
8968 state.ending = true;
8969 finishMaybe(stream, state);
8970
8971 if (cb) {
8972 if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
8973 }
8974
8975 state.ended = true;
8976 stream.writable = false;
8977}
8978
8979function onCorkedFinish(corkReq, state, err) {
8980 var entry = corkReq.entry;
8981 corkReq.entry = null;
8982
8983 while (entry) {
8984 var cb = entry.callback;
8985 state.pendingcb--;
8986 cb(err);
8987 entry = entry.next;
8988 } // reuse the free corkReq.
8989
8990
8991 state.corkedRequestsFree.next = corkReq;
8992}
8993
8994Object.defineProperty(Writable.prototype, 'destroyed', {
8995 // making it explicit this property is not enumerable
8996 // because otherwise some prototype manipulation in
8997 // userland will fail
8998 enumerable: false,
8999 get: function get() {
9000 if (this._writableState === undefined) {
9001 return false;
9002 }
9003
9004 return this._writableState.destroyed;
9005 },
9006 set: function set(value) {
9007 // we ignore the value if the stream
9008 // has not been initialized yet
9009 if (!this._writableState) {
9010 return;
9011 } // backward compatibility, the user is explicitly
9012 // managing destroyed
9013
9014
9015 this._writableState.destroyed = value;
9016 }
9017});
9018Writable.prototype.destroy = destroyImpl.destroy;
9019Writable.prototype._undestroy = destroyImpl.undestroy;
9020
9021Writable.prototype._destroy = function (err, cb) {
9022 cb(err);
9023};
9024}).call(this)}).call(this,_dereq_(66),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
9025},{"113":113,"29":29,"35":35,"36":36,"43":43,"47":47,"48":48,"66":66,"8":8}],41:[function(_dereq_,module,exports){
9026(function (process){(function (){
9027'use strict';
9028
9029var _Object$setPrototypeO;
9030
9031function _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; }
9032
9033var finished = _dereq_(44);
9034
9035var kLastResolve = Symbol('lastResolve');
9036var kLastReject = Symbol('lastReject');
9037var kError = Symbol('error');
9038var kEnded = Symbol('ended');
9039var kLastPromise = Symbol('lastPromise');
9040var kHandlePromise = Symbol('handlePromise');
9041var kStream = Symbol('stream');
9042
9043function createIterResult(value, done) {
9044 return {
9045 value: value,
9046 done: done
9047 };
9048}
9049
9050function readAndResolve(iter) {
9051 var resolve = iter[kLastResolve];
9052
9053 if (resolve !== null) {
9054 var data = iter[kStream].read(); // we defer if data is null
9055 // we can be expecting either 'end' or
9056 // 'error'
9057
9058 if (data !== null) {
9059 iter[kLastPromise] = null;
9060 iter[kLastResolve] = null;
9061 iter[kLastReject] = null;
9062 resolve(createIterResult(data, false));
9063 }
9064 }
9065}
9066
9067function onReadable(iter) {
9068 // we wait for the next tick, because it might
9069 // emit an error with process.nextTick
9070 process.nextTick(readAndResolve, iter);
9071}
9072
9073function wrapForNext(lastPromise, iter) {
9074 return function (resolve, reject) {
9075 lastPromise.then(function () {
9076 if (iter[kEnded]) {
9077 resolve(createIterResult(undefined, true));
9078 return;
9079 }
9080
9081 iter[kHandlePromise](resolve, reject);
9082 }, reject);
9083 };
9084}
9085
9086var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
9087var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
9088 get stream() {
9089 return this[kStream];
9090 },
9091
9092 next: function next() {
9093 var _this = this;
9094
9095 // if we have detected an error in the meanwhile
9096 // reject straight away
9097 var error = this[kError];
9098
9099 if (error !== null) {
9100 return Promise.reject(error);
9101 }
9102
9103 if (this[kEnded]) {
9104 return Promise.resolve(createIterResult(undefined, true));
9105 }
9106
9107 if (this[kStream].destroyed) {
9108 // We need to defer via nextTick because if .destroy(err) is
9109 // called, the error will be emitted via nextTick, and
9110 // we cannot guarantee that there is no error lingering around
9111 // waiting to be emitted.
9112 return new Promise(function (resolve, reject) {
9113 process.nextTick(function () {
9114 if (_this[kError]) {
9115 reject(_this[kError]);
9116 } else {
9117 resolve(createIterResult(undefined, true));
9118 }
9119 });
9120 });
9121 } // if we have multiple next() calls
9122 // we will wait for the previous Promise to finish
9123 // this logic is optimized to support for await loops,
9124 // where next() is only called once at a time
9125
9126
9127 var lastPromise = this[kLastPromise];
9128 var promise;
9129
9130 if (lastPromise) {
9131 promise = new Promise(wrapForNext(lastPromise, this));
9132 } else {
9133 // fast path needed to support multiple this.push()
9134 // without triggering the next() queue
9135 var data = this[kStream].read();
9136
9137 if (data !== null) {
9138 return Promise.resolve(createIterResult(data, false));
9139 }
9140
9141 promise = new Promise(this[kHandlePromise]);
9142 }
9143
9144 this[kLastPromise] = promise;
9145 return promise;
9146 }
9147}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
9148 return this;
9149}), _defineProperty(_Object$setPrototypeO, "return", function _return() {
9150 var _this2 = this;
9151
9152 // destroy(err, cb) is a private API
9153 // we can guarantee we have that here, because we control the
9154 // Readable class this is attached to
9155 return new Promise(function (resolve, reject) {
9156 _this2[kStream].destroy(null, function (err) {
9157 if (err) {
9158 reject(err);
9159 return;
9160 }
9161
9162 resolve(createIterResult(undefined, true));
9163 });
9164 });
9165}), _Object$setPrototypeO), AsyncIteratorPrototype);
9166
9167var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
9168 var _Object$create;
9169
9170 var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
9171 value: stream,
9172 writable: true
9173 }), _defineProperty(_Object$create, kLastResolve, {
9174 value: null,
9175 writable: true
9176 }), _defineProperty(_Object$create, kLastReject, {
9177 value: null,
9178 writable: true
9179 }), _defineProperty(_Object$create, kError, {
9180 value: null,
9181 writable: true
9182 }), _defineProperty(_Object$create, kEnded, {
9183 value: stream._readableState.endEmitted,
9184 writable: true
9185 }), _defineProperty(_Object$create, kHandlePromise, {
9186 value: function value(resolve, reject) {
9187 var data = iterator[kStream].read();
9188
9189 if (data) {
9190 iterator[kLastPromise] = null;
9191 iterator[kLastResolve] = null;
9192 iterator[kLastReject] = null;
9193 resolve(createIterResult(data, false));
9194 } else {
9195 iterator[kLastResolve] = resolve;
9196 iterator[kLastReject] = reject;
9197 }
9198 },
9199 writable: true
9200 }), _Object$create));
9201 iterator[kLastPromise] = null;
9202 finished(stream, function (err) {
9203 if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
9204 var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise
9205 // returned by next() and store the error
9206
9207 if (reject !== null) {
9208 iterator[kLastPromise] = null;
9209 iterator[kLastResolve] = null;
9210 iterator[kLastReject] = null;
9211 reject(err);
9212 }
9213
9214 iterator[kError] = err;
9215 return;
9216 }
9217
9218 var resolve = iterator[kLastResolve];
9219
9220 if (resolve !== null) {
9221 iterator[kLastPromise] = null;
9222 iterator[kLastResolve] = null;
9223 iterator[kLastReject] = null;
9224 resolve(createIterResult(undefined, true));
9225 }
9226
9227 iterator[kEnded] = true;
9228 });
9229 stream.on('readable', onReadable.bind(null, iterator));
9230 return iterator;
9231};
9232
9233module.exports = createReadableStreamAsyncIterator;
9234}).call(this)}).call(this,_dereq_(66))
9235},{"44":44,"66":66}],42:[function(_dereq_,module,exports){
9236'use strict';
9237
9238function 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; }
9239
9240function _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; }
9241
9242function _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; }
9243
9244function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
9245
9246function _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); } }
9247
9248function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
9249
9250var _require = _dereq_(8),
9251 Buffer = _require.Buffer;
9252
9253var _require2 = _dereq_(6),
9254 inspect = _require2.inspect;
9255
9256var custom = inspect && inspect.custom || 'inspect';
9257
9258function copyBuffer(src, target, offset) {
9259 Buffer.prototype.copy.call(src, target, offset);
9260}
9261
9262module.exports =
9263/*#__PURE__*/
9264function () {
9265 function BufferList() {
9266 _classCallCheck(this, BufferList);
9267
9268 this.head = null;
9269 this.tail = null;
9270 this.length = 0;
9271 }
9272
9273 _createClass(BufferList, [{
9274 key: "push",
9275 value: function push(v) {
9276 var entry = {
9277 data: v,
9278 next: null
9279 };
9280 if (this.length > 0) this.tail.next = entry;else this.head = entry;
9281 this.tail = entry;
9282 ++this.length;
9283 }
9284 }, {
9285 key: "unshift",
9286 value: function unshift(v) {
9287 var entry = {
9288 data: v,
9289 next: this.head
9290 };
9291 if (this.length === 0) this.tail = entry;
9292 this.head = entry;
9293 ++this.length;
9294 }
9295 }, {
9296 key: "shift",
9297 value: function shift() {
9298 if (this.length === 0) return;
9299 var ret = this.head.data;
9300 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
9301 --this.length;
9302 return ret;
9303 }
9304 }, {
9305 key: "clear",
9306 value: function clear() {
9307 this.head = this.tail = null;
9308 this.length = 0;
9309 }
9310 }, {
9311 key: "join",
9312 value: function join(s) {
9313 if (this.length === 0) return '';
9314 var p = this.head;
9315 var ret = '' + p.data;
9316
9317 while (p = p.next) {
9318 ret += s + p.data;
9319 }
9320
9321 return ret;
9322 }
9323 }, {
9324 key: "concat",
9325 value: function concat(n) {
9326 if (this.length === 0) return Buffer.alloc(0);
9327 var ret = Buffer.allocUnsafe(n >>> 0);
9328 var p = this.head;
9329 var i = 0;
9330
9331 while (p) {
9332 copyBuffer(p.data, ret, i);
9333 i += p.data.length;
9334 p = p.next;
9335 }
9336
9337 return ret;
9338 } // Consumes a specified amount of bytes or characters from the buffered data.
9339
9340 }, {
9341 key: "consume",
9342 value: function consume(n, hasStrings) {
9343 var ret;
9344
9345 if (n < this.head.data.length) {
9346 // `slice` is the same for buffers and strings.
9347 ret = this.head.data.slice(0, n);
9348 this.head.data = this.head.data.slice(n);
9349 } else if (n === this.head.data.length) {
9350 // First chunk is a perfect match.
9351 ret = this.shift();
9352 } else {
9353 // Result spans more than one buffer.
9354 ret = hasStrings ? this._getString(n) : this._getBuffer(n);
9355 }
9356
9357 return ret;
9358 }
9359 }, {
9360 key: "first",
9361 value: function first() {
9362 return this.head.data;
9363 } // Consumes a specified amount of characters from the buffered data.
9364
9365 }, {
9366 key: "_getString",
9367 value: function _getString(n) {
9368 var p = this.head;
9369 var c = 1;
9370 var ret = p.data;
9371 n -= ret.length;
9372
9373 while (p = p.next) {
9374 var str = p.data;
9375 var nb = n > str.length ? str.length : n;
9376 if (nb === str.length) ret += str;else ret += str.slice(0, n);
9377 n -= nb;
9378
9379 if (n === 0) {
9380 if (nb === str.length) {
9381 ++c;
9382 if (p.next) this.head = p.next;else this.head = this.tail = null;
9383 } else {
9384 this.head = p;
9385 p.data = str.slice(nb);
9386 }
9387
9388 break;
9389 }
9390
9391 ++c;
9392 }
9393
9394 this.length -= c;
9395 return ret;
9396 } // Consumes a specified amount of bytes from the buffered data.
9397
9398 }, {
9399 key: "_getBuffer",
9400 value: function _getBuffer(n) {
9401 var ret = Buffer.allocUnsafe(n);
9402 var p = this.head;
9403 var c = 1;
9404 p.data.copy(ret);
9405 n -= p.data.length;
9406
9407 while (p = p.next) {
9408 var buf = p.data;
9409 var nb = n > buf.length ? buf.length : n;
9410 buf.copy(ret, ret.length - n, 0, nb);
9411 n -= nb;
9412
9413 if (n === 0) {
9414 if (nb === buf.length) {
9415 ++c;
9416 if (p.next) this.head = p.next;else this.head = this.tail = null;
9417 } else {
9418 this.head = p;
9419 p.data = buf.slice(nb);
9420 }
9421
9422 break;
9423 }
9424
9425 ++c;
9426 }
9427
9428 this.length -= c;
9429 return ret;
9430 } // Make sure the linked list only shows the minimal necessary information.
9431
9432 }, {
9433 key: custom,
9434 value: function value(_, options) {
9435 return inspect(this, _objectSpread({}, options, {
9436 // Only inspect one level.
9437 depth: 0,
9438 // It should not recurse.
9439 customInspect: false
9440 }));
9441 }
9442 }]);
9443
9444 return BufferList;
9445}();
9446},{"6":6,"8":8}],43:[function(_dereq_,module,exports){
9447(function (process){(function (){
9448'use strict'; // undocumented cb() API, needed for core, not for public API
9449
9450function destroy(err, cb) {
9451 var _this = this;
9452
9453 var readableDestroyed = this._readableState && this._readableState.destroyed;
9454 var writableDestroyed = this._writableState && this._writableState.destroyed;
9455
9456 if (readableDestroyed || writableDestroyed) {
9457 if (cb) {
9458 cb(err);
9459 } else if (err) {
9460 if (!this._writableState) {
9461 process.nextTick(emitErrorNT, this, err);
9462 } else if (!this._writableState.errorEmitted) {
9463 this._writableState.errorEmitted = true;
9464 process.nextTick(emitErrorNT, this, err);
9465 }
9466 }
9467
9468 return this;
9469 } // we set destroyed to true before firing error callbacks in order
9470 // to make it re-entrance safe in case destroy() is called within callbacks
9471
9472
9473 if (this._readableState) {
9474 this._readableState.destroyed = true;
9475 } // if this is a duplex stream mark the writable part as destroyed as well
9476
9477
9478 if (this._writableState) {
9479 this._writableState.destroyed = true;
9480 }
9481
9482 this._destroy(err || null, function (err) {
9483 if (!cb && err) {
9484 if (!_this._writableState) {
9485 process.nextTick(emitErrorAndCloseNT, _this, err);
9486 } else if (!_this._writableState.errorEmitted) {
9487 _this._writableState.errorEmitted = true;
9488 process.nextTick(emitErrorAndCloseNT, _this, err);
9489 } else {
9490 process.nextTick(emitCloseNT, _this);
9491 }
9492 } else if (cb) {
9493 process.nextTick(emitCloseNT, _this);
9494 cb(err);
9495 } else {
9496 process.nextTick(emitCloseNT, _this);
9497 }
9498 });
9499
9500 return this;
9501}
9502
9503function emitErrorAndCloseNT(self, err) {
9504 emitErrorNT(self, err);
9505 emitCloseNT(self);
9506}
9507
9508function emitCloseNT(self) {
9509 if (self._writableState && !self._writableState.emitClose) return;
9510 if (self._readableState && !self._readableState.emitClose) return;
9511 self.emit('close');
9512}
9513
9514function undestroy() {
9515 if (this._readableState) {
9516 this._readableState.destroyed = false;
9517 this._readableState.reading = false;
9518 this._readableState.ended = false;
9519 this._readableState.endEmitted = false;
9520 }
9521
9522 if (this._writableState) {
9523 this._writableState.destroyed = false;
9524 this._writableState.ended = false;
9525 this._writableState.ending = false;
9526 this._writableState.finalCalled = false;
9527 this._writableState.prefinished = false;
9528 this._writableState.finished = false;
9529 this._writableState.errorEmitted = false;
9530 }
9531}
9532
9533function emitErrorNT(self, err) {
9534 self.emit('error', err);
9535}
9536
9537function errorOrDestroy(stream, err) {
9538 // We have tests that rely on errors being emitted
9539 // in the same tick, so changing this is semver major.
9540 // For now when you opt-in to autoDestroy we allow
9541 // the error to be emitted nextTick. In a future
9542 // semver major update we should change the default to this.
9543 var rState = stream._readableState;
9544 var wState = stream._writableState;
9545 if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
9546}
9547
9548module.exports = {
9549 destroy: destroy,
9550 undestroy: undestroy,
9551 errorOrDestroy: errorOrDestroy
9552};
9553}).call(this)}).call(this,_dereq_(66))
9554},{"66":66}],44:[function(_dereq_,module,exports){
9555// Ported from https://github.com/mafintosh/end-of-stream with
9556// permission from the author, Mathias Buus (@mafintosh).
9557'use strict';
9558
9559var ERR_STREAM_PREMATURE_CLOSE = _dereq_(35).codes.ERR_STREAM_PREMATURE_CLOSE;
9560
9561function once(callback) {
9562 var called = false;
9563 return function () {
9564 if (called) return;
9565 called = true;
9566
9567 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
9568 args[_key] = arguments[_key];
9569 }
9570
9571 callback.apply(this, args);
9572 };
9573}
9574
9575function noop() {}
9576
9577function isRequest(stream) {
9578 return stream.setHeader && typeof stream.abort === 'function';
9579}
9580
9581function eos(stream, opts, callback) {
9582 if (typeof opts === 'function') return eos(stream, null, opts);
9583 if (!opts) opts = {};
9584 callback = once(callback || noop);
9585 var readable = opts.readable || opts.readable !== false && stream.readable;
9586 var writable = opts.writable || opts.writable !== false && stream.writable;
9587
9588 var onlegacyfinish = function onlegacyfinish() {
9589 if (!stream.writable) onfinish();
9590 };
9591
9592 var writableEnded = stream._writableState && stream._writableState.finished;
9593
9594 var onfinish = function onfinish() {
9595 writable = false;
9596 writableEnded = true;
9597 if (!readable) callback.call(stream);
9598 };
9599
9600 var readableEnded = stream._readableState && stream._readableState.endEmitted;
9601
9602 var onend = function onend() {
9603 readable = false;
9604 readableEnded = true;
9605 if (!writable) callback.call(stream);
9606 };
9607
9608 var onerror = function onerror(err) {
9609 callback.call(stream, err);
9610 };
9611
9612 var onclose = function onclose() {
9613 var err;
9614
9615 if (readable && !readableEnded) {
9616 if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
9617 return callback.call(stream, err);
9618 }
9619
9620 if (writable && !writableEnded) {
9621 if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
9622 return callback.call(stream, err);
9623 }
9624 };
9625
9626 var onrequest = function onrequest() {
9627 stream.req.on('finish', onfinish);
9628 };
9629
9630 if (isRequest(stream)) {
9631 stream.on('complete', onfinish);
9632 stream.on('abort', onclose);
9633 if (stream.req) onrequest();else stream.on('request', onrequest);
9634 } else if (writable && !stream._writableState) {
9635 // legacy streams
9636 stream.on('end', onlegacyfinish);
9637 stream.on('close', onlegacyfinish);
9638 }
9639
9640 stream.on('end', onend);
9641 stream.on('finish', onfinish);
9642 if (opts.error !== false) stream.on('error', onerror);
9643 stream.on('close', onclose);
9644 return function () {
9645 stream.removeListener('complete', onfinish);
9646 stream.removeListener('abort', onclose);
9647 stream.removeListener('request', onrequest);
9648 if (stream.req) stream.req.removeListener('finish', onfinish);
9649 stream.removeListener('end', onlegacyfinish);
9650 stream.removeListener('close', onlegacyfinish);
9651 stream.removeListener('finish', onfinish);
9652 stream.removeListener('end', onend);
9653 stream.removeListener('error', onerror);
9654 stream.removeListener('close', onclose);
9655 };
9656}
9657
9658module.exports = eos;
9659},{"35":35}],45:[function(_dereq_,module,exports){
9660module.exports = function () {
9661 throw new Error('Readable.from is not available in the browser')
9662};
9663
9664},{}],46:[function(_dereq_,module,exports){
9665// Ported from https://github.com/mafintosh/pump with
9666// permission from the author, Mathias Buus (@mafintosh).
9667'use strict';
9668
9669var eos;
9670
9671function once(callback) {
9672 var called = false;
9673 return function () {
9674 if (called) return;
9675 called = true;
9676 callback.apply(void 0, arguments);
9677 };
9678}
9679
9680var _require$codes = _dereq_(35).codes,
9681 ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
9682 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
9683
9684function noop(err) {
9685 // Rethrow the error if it exists to avoid swallowing it
9686 if (err) throw err;
9687}
9688
9689function isRequest(stream) {
9690 return stream.setHeader && typeof stream.abort === 'function';
9691}
9692
9693function destroyer(stream, reading, writing, callback) {
9694 callback = once(callback);
9695 var closed = false;
9696 stream.on('close', function () {
9697 closed = true;
9698 });
9699 if (eos === undefined) eos = _dereq_(44);
9700 eos(stream, {
9701 readable: reading,
9702 writable: writing
9703 }, function (err) {
9704 if (err) return callback(err);
9705 closed = true;
9706 callback();
9707 });
9708 var destroyed = false;
9709 return function (err) {
9710 if (closed) return;
9711 if (destroyed) return;
9712 destroyed = true; // request.destroy just do .end - .abort is what we want
9713
9714 if (isRequest(stream)) return stream.abort();
9715 if (typeof stream.destroy === 'function') return stream.destroy();
9716 callback(err || new ERR_STREAM_DESTROYED('pipe'));
9717 };
9718}
9719
9720function call(fn) {
9721 fn();
9722}
9723
9724function pipe(from, to) {
9725 return from.pipe(to);
9726}
9727
9728function popCallback(streams) {
9729 if (!streams.length) return noop;
9730 if (typeof streams[streams.length - 1] !== 'function') return noop;
9731 return streams.pop();
9732}
9733
9734function pipeline() {
9735 for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
9736 streams[_key] = arguments[_key];
9737 }
9738
9739 var callback = popCallback(streams);
9740 if (Array.isArray(streams[0])) streams = streams[0];
9741
9742 if (streams.length < 2) {
9743 throw new ERR_MISSING_ARGS('streams');
9744 }
9745
9746 var error;
9747 var destroys = streams.map(function (stream, i) {
9748 var reading = i < streams.length - 1;
9749 var writing = i > 0;
9750 return destroyer(stream, reading, writing, function (err) {
9751 if (!error) error = err;
9752 if (err) destroys.forEach(call);
9753 if (reading) return;
9754 destroys.forEach(call);
9755 callback(error);
9756 });
9757 });
9758 return streams.reduce(pipe);
9759}
9760
9761module.exports = pipeline;
9762},{"35":35,"44":44}],47:[function(_dereq_,module,exports){
9763'use strict';
9764
9765var ERR_INVALID_OPT_VALUE = _dereq_(35).codes.ERR_INVALID_OPT_VALUE;
9766
9767function highWaterMarkFrom(options, isDuplex, duplexKey) {
9768 return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
9769}
9770
9771function getHighWaterMark(state, options, duplexKey, isDuplex) {
9772 var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
9773
9774 if (hwm != null) {
9775 if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
9776 var name = isDuplex ? duplexKey : 'highWaterMark';
9777 throw new ERR_INVALID_OPT_VALUE(name, hwm);
9778 }
9779
9780 return Math.floor(hwm);
9781 } // Default value
9782
9783
9784 return state.objectMode ? 16 : 16 * 1024;
9785}
9786
9787module.exports = {
9788 getHighWaterMark: getHighWaterMark
9789};
9790},{"35":35}],48:[function(_dereq_,module,exports){
9791module.exports = _dereq_(20).EventEmitter;
9792
9793},{"20":20}],49:[function(_dereq_,module,exports){
9794exports = module.exports = _dereq_(38);
9795exports.Stream = exports;
9796exports.Readable = exports;
9797exports.Writable = _dereq_(40);
9798exports.Duplex = _dereq_(36);
9799exports.Transform = _dereq_(39);
9800exports.PassThrough = _dereq_(37);
9801exports.finished = _dereq_(44);
9802exports.pipeline = _dereq_(46);
9803
9804},{"36":36,"37":37,"38":38,"39":39,"40":40,"44":44,"46":46}],50:[function(_dereq_,module,exports){
9805'use strict'
9806
9807// For (old) browser support
9808var xtend = _dereq_(133)
9809var assign = _dereq_(134)
9810
9811module.exports = function supports () {
9812 var manifest = xtend.apply(null, arguments)
9813
9814 return assign(manifest, {
9815 // Features of abstract-leveldown
9816 bufferKeys: manifest.bufferKeys || false,
9817 snapshots: manifest.snapshots || false,
9818 permanence: manifest.permanence || false,
9819 seek: manifest.seek || false,
9820 clear: manifest.clear || false,
9821
9822 // Features of abstract-leveldown that levelup doesn't have
9823 status: manifest.status || false,
9824
9825 // Features of disk-based implementations
9826 createIfMissing: manifest.createIfMissing || false,
9827 errorIfExists: manifest.errorIfExists || false,
9828
9829 // Features of level(up) that abstract-leveldown doesn't have yet
9830 deferredOpen: manifest.deferredOpen || false,
9831 openCallback: manifest.openCallback || false,
9832 promises: manifest.promises || false,
9833 streams: manifest.streams || false,
9834 encodings: manifest.encodings || false,
9835
9836 // Methods that are not part of abstract-leveldown or levelup
9837 additionalMethods: xtend(manifest.additionalMethods)
9838 })
9839}
9840
9841},{"133":133,"134":134}],51:[function(_dereq_,module,exports){
9842var WriteError = _dereq_(33).WriteError
9843var promisify = _dereq_(54)
9844var getCallback = _dereq_(52).getCallback
9845var getOptions = _dereq_(52).getOptions
9846
9847function Batch (levelup) {
9848 // TODO (next major): remove this._levelup alias
9849 this.db = this._levelup = levelup
9850 this.batch = levelup.db.batch()
9851 this.ops = []
9852 this.length = 0
9853}
9854
9855Batch.prototype.put = function (key, value) {
9856 try {
9857 this.batch.put(key, value)
9858 } catch (e) {
9859 throw new WriteError(e)
9860 }
9861
9862 this.ops.push({ type: 'put', key: key, value: value })
9863 this.length++
9864
9865 return this
9866}
9867
9868Batch.prototype.del = function (key) {
9869 try {
9870 this.batch.del(key)
9871 } catch (err) {
9872 throw new WriteError(err)
9873 }
9874
9875 this.ops.push({ type: 'del', key: key })
9876 this.length++
9877
9878 return this
9879}
9880
9881Batch.prototype.clear = function () {
9882 try {
9883 this.batch.clear()
9884 } catch (err) {
9885 throw new WriteError(err)
9886 }
9887
9888 this.ops = []
9889 this.length = 0
9890
9891 return this
9892}
9893
9894Batch.prototype.write = function (options, callback) {
9895 var levelup = this._levelup
9896 var ops = this.ops
9897 var promise
9898
9899 callback = getCallback(options, callback)
9900
9901 if (!callback) {
9902 callback = promisify()
9903 promise = callback.promise
9904 }
9905
9906 options = getOptions(options)
9907
9908 try {
9909 this.batch.write(options, function (err) {
9910 if (err) { return callback(new WriteError(err)) }
9911 levelup.emit('batch', ops)
9912 callback()
9913 })
9914 } catch (err) {
9915 throw new WriteError(err)
9916 }
9917
9918 return promise
9919}
9920
9921module.exports = Batch
9922
9923},{"33":33,"52":52,"54":54}],52:[function(_dereq_,module,exports){
9924exports.getCallback = function (options, callback) {
9925 return typeof options === 'function' ? options : callback
9926}
9927
9928exports.getOptions = function (options) {
9929 return typeof options === 'object' && options !== null ? options : {}
9930}
9931
9932},{}],53:[function(_dereq_,module,exports){
9933(function (process){(function (){
9934var EventEmitter = _dereq_(20).EventEmitter
9935var inherits = _dereq_(116).inherits
9936var extend = _dereq_(133)
9937var DeferredLevelDOWN = _dereq_(11)
9938var IteratorStream = _dereq_(34)
9939var Batch = _dereq_(51)
9940var errors = _dereq_(33)
9941var supports = _dereq_(50)
9942var assert = _dereq_(1)
9943var promisify = _dereq_(54)
9944var getCallback = _dereq_(52).getCallback
9945var getOptions = _dereq_(52).getOptions
9946
9947var WriteError = errors.WriteError
9948var ReadError = errors.ReadError
9949var NotFoundError = errors.NotFoundError
9950var OpenError = errors.OpenError
9951var InitializationError = errors.InitializationError
9952
9953// Possible AbstractLevelDOWN#status values:
9954// - 'new' - newly created, not opened or closed
9955// - 'opening' - waiting for the database to be opened, post open()
9956// - 'open' - successfully opened the database, available for use
9957// - 'closing' - waiting for the database to be closed, post close()
9958// - 'closed' - database has been successfully closed, should not be
9959// used except for another open() operation
9960
9961function LevelUP (db, options, callback) {
9962 if (!(this instanceof LevelUP)) {
9963 return new LevelUP(db, options, callback)
9964 }
9965
9966 var error
9967 var self = this
9968
9969 EventEmitter.call(this)
9970 this.setMaxListeners(Infinity)
9971
9972 if (typeof options === 'function') {
9973 callback = options
9974 options = {}
9975 }
9976
9977 options = options || {}
9978
9979 if (!db || typeof db !== 'object') {
9980 error = new InitializationError('First argument must be an abstract-leveldown compliant store')
9981 if (typeof callback === 'function') {
9982 return process.nextTick(callback, error)
9983 }
9984 throw error
9985 }
9986
9987 assert.strictEqual(typeof db.status, 'string', '.status required, old abstract-leveldown')
9988
9989 this.options = getOptions(options)
9990 this._db = db
9991 this.db = new DeferredLevelDOWN(db)
9992 this.open(callback || function (err) {
9993 if (err) self.emit('error', err)
9994 })
9995
9996 // Create manifest based on deferred-leveldown's
9997 this.supports = supports(this.db.supports, {
9998 status: false,
9999 deferredOpen: true,
10000 openCallback: true,
10001 promises: true,
10002 streams: true
10003 })
10004
10005 // Experimental: enrich levelup interface
10006 Object.keys(this.supports.additionalMethods).forEach(function (method) {
10007 if (this[method] != null) return
10008
10009 // Don't do this.db[method].bind() because this.db is dynamic.
10010 this[method] = function () {
10011 return this.db[method].apply(this.db, arguments)
10012 }
10013 }, this)
10014}
10015
10016LevelUP.prototype.emit = EventEmitter.prototype.emit
10017LevelUP.prototype.once = EventEmitter.prototype.once
10018inherits(LevelUP, EventEmitter)
10019
10020LevelUP.prototype.open = function (opts, callback) {
10021 var self = this
10022 var promise
10023
10024 if (typeof opts === 'function') {
10025 callback = opts
10026 opts = null
10027 }
10028
10029 if (!callback) {
10030 callback = promisify()
10031 promise = callback.promise
10032 }
10033
10034 if (!opts) {
10035 opts = this.options
10036 }
10037
10038 if (this.isOpen()) {
10039 process.nextTick(callback, null, self)
10040 return promise
10041 }
10042
10043 if (this._isOpening()) {
10044 this.once('open', function () { callback(null, self) })
10045 return promise
10046 }
10047
10048 this.emit('opening')
10049
10050 this.db.open(opts, function (err) {
10051 if (err) {
10052 return callback(new OpenError(err))
10053 }
10054 self.db = self._db
10055 callback(null, self)
10056 self.emit('open')
10057 self.emit('ready')
10058 })
10059
10060 return promise
10061}
10062
10063LevelUP.prototype.close = function (callback) {
10064 var self = this
10065 var promise
10066
10067 if (!callback) {
10068 callback = promisify()
10069 promise = callback.promise
10070 }
10071
10072 if (this.isOpen()) {
10073 this.db.close(function () {
10074 self.emit('closed')
10075 callback.apply(null, arguments)
10076 })
10077 this.emit('closing')
10078 this.db = new DeferredLevelDOWN(this._db)
10079 } else if (this.isClosed()) {
10080 process.nextTick(callback)
10081 } else if (this.db.status === 'closing') {
10082 this.once('closed', callback)
10083 } else if (this._isOpening()) {
10084 this.once('open', function () {
10085 self.close(callback)
10086 })
10087 }
10088
10089 return promise
10090}
10091
10092LevelUP.prototype.isOpen = function () {
10093 return this.db.status === 'open'
10094}
10095
10096LevelUP.prototype._isOpening = function () {
10097 return this.db.status === 'opening'
10098}
10099
10100LevelUP.prototype.isClosed = function () {
10101 return (/^clos|new/).test(this.db.status)
10102}
10103
10104LevelUP.prototype.get = function (key, options, callback) {
10105 var promise
10106
10107 callback = getCallback(options, callback)
10108
10109 if (!callback) {
10110 callback = promisify()
10111 promise = callback.promise
10112 }
10113
10114 if (maybeError(this, callback)) { return promise }
10115
10116 options = getOptions(options)
10117
10118 this.db.get(key, options, function (err, value) {
10119 if (err) {
10120 if ((/notfound/i).test(err) || err.notFound) {
10121 err = new NotFoundError('Key not found in database [' + key + ']', err)
10122 } else {
10123 err = new ReadError(err)
10124 }
10125 return callback(err)
10126 }
10127 callback(null, value)
10128 })
10129
10130 return promise
10131}
10132
10133LevelUP.prototype.put = function (key, value, options, callback) {
10134 var self = this
10135 var promise
10136
10137 callback = getCallback(options, callback)
10138
10139 if (!callback) {
10140 callback = promisify()
10141 promise = callback.promise
10142 }
10143
10144 if (maybeError(this, callback)) { return promise }
10145
10146 options = getOptions(options)
10147
10148 this.db.put(key, value, options, function (err) {
10149 if (err) {
10150 return callback(new WriteError(err))
10151 }
10152 self.emit('put', key, value)
10153 callback()
10154 })
10155
10156 return promise
10157}
10158
10159LevelUP.prototype.del = function (key, options, callback) {
10160 var self = this
10161 var promise
10162
10163 callback = getCallback(options, callback)
10164
10165 if (!callback) {
10166 callback = promisify()
10167 promise = callback.promise
10168 }
10169
10170 if (maybeError(this, callback)) { return promise }
10171
10172 options = getOptions(options)
10173
10174 this.db.del(key, options, function (err) {
10175 if (err) {
10176 return callback(new WriteError(err))
10177 }
10178 self.emit('del', key)
10179 callback()
10180 })
10181
10182 return promise
10183}
10184
10185LevelUP.prototype.batch = function (arr, options, callback) {
10186 if (!arguments.length) {
10187 return new Batch(this)
10188 }
10189
10190 var self = this
10191 var promise
10192
10193 if (typeof arr === 'function') callback = arr
10194 else callback = getCallback(options, callback)
10195
10196 if (!callback) {
10197 callback = promisify()
10198 promise = callback.promise
10199 }
10200
10201 if (maybeError(this, callback)) { return promise }
10202
10203 options = getOptions(options)
10204
10205 this.db.batch(arr, options, function (err) {
10206 if (err) {
10207 return callback(new WriteError(err))
10208 }
10209 self.emit('batch', arr)
10210 callback()
10211 })
10212
10213 return promise
10214}
10215
10216LevelUP.prototype.iterator = function (options) {
10217 return this.db.iterator(options)
10218}
10219
10220LevelUP.prototype.clear = function (options, callback) {
10221 var self = this
10222 var promise
10223
10224 callback = getCallback(options, callback)
10225 options = getOptions(options)
10226
10227 if (!callback) {
10228 callback = promisify()
10229 promise = callback.promise
10230 }
10231
10232 if (maybeError(this, callback)) {
10233 return promise
10234 }
10235
10236 this.db.clear(options, function (err) {
10237 if (err) {
10238 return callback(new WriteError(err))
10239 }
10240 self.emit('clear', options)
10241 callback()
10242 })
10243
10244 return promise
10245}
10246
10247LevelUP.prototype.readStream =
10248LevelUP.prototype.createReadStream = function (options) {
10249 options = extend({ keys: true, values: true }, options)
10250 if (typeof options.limit !== 'number') { options.limit = -1 }
10251 return new IteratorStream(this.db.iterator(options), options)
10252}
10253
10254LevelUP.prototype.keyStream =
10255LevelUP.prototype.createKeyStream = function (options) {
10256 return this.createReadStream(extend(options, { keys: true, values: false }))
10257}
10258
10259LevelUP.prototype.valueStream =
10260LevelUP.prototype.createValueStream = function (options) {
10261 return this.createReadStream(extend(options, { keys: false, values: true }))
10262}
10263
10264LevelUP.prototype.toString = function () {
10265 return 'LevelUP'
10266}
10267
10268LevelUP.prototype.type = 'levelup'
10269
10270function maybeError (db, callback) {
10271 if (!db._isOpening() && !db.isOpen()) {
10272 process.nextTick(callback, new ReadError('Database is not open'))
10273 return true
10274 }
10275}
10276
10277LevelUP.errors = errors
10278module.exports = LevelUP.default = LevelUP
10279
10280}).call(this)}).call(this,_dereq_(66))
10281},{"1":1,"11":11,"116":116,"133":133,"20":20,"33":33,"34":34,"50":50,"51":51,"52":52,"54":54,"66":66}],54:[function(_dereq_,module,exports){
10282function promisify () {
10283 var callback
10284 var promise = new Promise(function (resolve, reject) {
10285 callback = function callback (err, value) {
10286 if (err) reject(err)
10287 else resolve(value)
10288 }
10289 })
10290 callback.promise = promise
10291 return callback
10292}
10293
10294module.exports = promisify
10295
10296},{}],55:[function(_dereq_,module,exports){
10297(function (Buffer){(function (){
10298
10299exports.compare = function (a, b) {
10300
10301 if(Buffer.isBuffer(a)) {
10302 var l = Math.min(a.length, b.length)
10303 for(var i = 0; i < l; i++) {
10304 var cmp = a[i] - b[i]
10305 if(cmp) return cmp
10306 }
10307 return a.length - b.length
10308 }
10309
10310 return a < b ? -1 : a > b ? 1 : 0
10311}
10312
10313// to be compatible with the current abstract-leveldown tests
10314// nullish or empty strings.
10315// I could use !!val but I want to permit numbers and booleans,
10316// if possible.
10317
10318function isDef (val) {
10319 return val !== undefined && val !== ''
10320}
10321
10322function has (range, name) {
10323 return Object.hasOwnProperty.call(range, name)
10324}
10325
10326function hasKey(range, name) {
10327 return Object.hasOwnProperty.call(range, name) && name
10328}
10329
10330var lowerBoundKey = exports.lowerBoundKey = function (range) {
10331 return (
10332 hasKey(range, 'gt')
10333 || hasKey(range, 'gte')
10334 || hasKey(range, 'min')
10335 || (range.reverse ? hasKey(range, 'end') : hasKey(range, 'start'))
10336 || undefined
10337 )
10338}
10339
10340var lowerBound = exports.lowerBound = function (range, def) {
10341 var k = lowerBoundKey(range)
10342 return k ? range[k] : def
10343}
10344
10345var lowerBoundInclusive = exports.lowerBoundInclusive = function (range) {
10346 return has(range, 'gt') ? false : true
10347}
10348
10349var upperBoundInclusive = exports.upperBoundInclusive =
10350 function (range) {
10351 return (has(range, 'lt') /*&& !range.maxEx*/) ? false : true
10352 }
10353
10354var lowerBoundExclusive = exports.lowerBoundExclusive =
10355 function (range) {
10356 return !lowerBoundInclusive(range)
10357 }
10358
10359var upperBoundExclusive = exports.upperBoundExclusive =
10360 function (range) {
10361 return !upperBoundInclusive(range)
10362 }
10363
10364var upperBoundKey = exports.upperBoundKey = function (range) {
10365 return (
10366 hasKey(range, 'lt')
10367 || hasKey(range, 'lte')
10368 || hasKey(range, 'max')
10369 || (range.reverse ? hasKey(range, 'start') : hasKey(range, 'end'))
10370 || undefined
10371 )
10372}
10373
10374var upperBound = exports.upperBound = function (range, def) {
10375 var k = upperBoundKey(range)
10376 return k ? range[k] : def
10377}
10378
10379exports.start = function (range, def) {
10380 return range.reverse ? upperBound(range, def) : lowerBound(range, def)
10381}
10382exports.end = function (range, def) {
10383 return range.reverse ? lowerBound(range, def) : upperBound(range, def)
10384}
10385exports.startInclusive = function (range) {
10386 return (
10387 range.reverse
10388 ? upperBoundInclusive(range)
10389 : lowerBoundInclusive(range)
10390 )
10391}
10392exports.endInclusive = function (range) {
10393 return (
10394 range.reverse
10395 ? lowerBoundInclusive(range)
10396 : upperBoundInclusive(range)
10397 )
10398}
10399
10400function id (e) { return e }
10401
10402exports.toLtgt = function (range, _range, map, lower, upper) {
10403 _range = _range || {}
10404 map = map || id
10405 var defaults = arguments.length > 3
10406 var lb = exports.lowerBoundKey(range)
10407 var ub = exports.upperBoundKey(range)
10408 if(lb) {
10409 if(lb === 'gt') _range.gt = map(range.gt, false)
10410 else _range.gte = map(range[lb], false)
10411 }
10412 else if(defaults)
10413 _range.gte = map(lower, false)
10414
10415 if(ub) {
10416 if(ub === 'lt') _range.lt = map(range.lt, true)
10417 else _range.lte = map(range[ub], true)
10418 }
10419 else if(defaults)
10420 _range.lte = map(upper, true)
10421
10422 if(range.reverse != null)
10423 _range.reverse = !!range.reverse
10424
10425 //if range was used mutably
10426 //(in level-sublevel it's part of an options object
10427 //that has more properties on it.)
10428 if(has(_range, 'max')) delete _range.max
10429 if(has(_range, 'min')) delete _range.min
10430 if(has(_range, 'start')) delete _range.start
10431 if(has(_range, 'end')) delete _range.end
10432
10433 return _range
10434}
10435
10436exports.contains = function (range, key, compare) {
10437 compare = compare || exports.compare
10438
10439 var lb = lowerBound(range)
10440 if(isDef(lb)) {
10441 var cmp = compare(key, lb)
10442 if(cmp < 0 || (cmp === 0 && lowerBoundExclusive(range)))
10443 return false
10444 }
10445
10446 var ub = upperBound(range)
10447 if(isDef(ub)) {
10448 var cmp = compare(key, ub)
10449 if(cmp > 0 || (cmp === 0) && upperBoundExclusive(range))
10450 return false
10451 }
10452
10453 return true
10454}
10455
10456exports.filter = function (range, compare) {
10457 return function (key) {
10458 return exports.contains(range, key, compare)
10459 }
10460}
10461
10462
10463
10464}).call(this)}).call(this,{"isBuffer":_dereq_(30)})
10465},{"30":30}],56:[function(_dereq_,module,exports){
10466arguments[4][16][0].apply(exports,arguments)
10467},{"16":16,"23":23}],57:[function(_dereq_,module,exports){
10468var inherits = _dereq_(29)
10469var AbstractLevelDOWN = _dereq_(61).AbstractLevelDOWN
10470var AbstractIterator = _dereq_(61).AbstractIterator
10471var ltgt = _dereq_(55)
10472var createRBT = _dereq_(21)
10473var Buffer = _dereq_(63).Buffer
10474var globalStore = {}
10475
10476// In Node, use global.setImmediate. In the browser, use a consistent
10477// microtask library to give consistent microtask experience to all browsers
10478var setImmediate = _dereq_(56)
10479
10480function gt (value) {
10481 return ltgt.compare(value, this._end) > 0
10482}
10483
10484function gte (value) {
10485 return ltgt.compare(value, this._end) >= 0
10486}
10487
10488function lt (value) {
10489 return ltgt.compare(value, this._end) < 0
10490}
10491
10492function lte (value) {
10493 return ltgt.compare(value, this._end) <= 0
10494}
10495
10496function MemIterator (db, options) {
10497 AbstractIterator.call(this, db)
10498 this._limit = options.limit
10499
10500 if (this._limit === -1) this._limit = Infinity
10501
10502 var tree = db._store[db._location]
10503
10504 this.keyAsBuffer = options.keyAsBuffer !== false
10505 this.valueAsBuffer = options.valueAsBuffer !== false
10506 this._reverse = options.reverse
10507 this._options = options
10508 this._done = 0
10509
10510 if (!this._reverse) {
10511 this._incr = 'next'
10512 this._start = ltgt.lowerBound(options)
10513 this._end = ltgt.upperBound(options)
10514
10515 if (typeof this._start === 'undefined') {
10516 this._tree = tree.begin
10517 } else if (ltgt.lowerBoundInclusive(options)) {
10518 this._tree = tree.ge(this._start)
10519 } else {
10520 this._tree = tree.gt(this._start)
10521 }
10522
10523 if (this._end) {
10524 if (ltgt.upperBoundInclusive(options)) {
10525 this._test = lte
10526 } else {
10527 this._test = lt
10528 }
10529 }
10530 } else {
10531 this._incr = 'prev'
10532 this._start = ltgt.upperBound(options)
10533 this._end = ltgt.lowerBound(options)
10534
10535 if (typeof this._start === 'undefined') {
10536 this._tree = tree.end
10537 } else if (ltgt.upperBoundInclusive(options)) {
10538 this._tree = tree.le(this._start)
10539 } else {
10540 this._tree = tree.lt(this._start)
10541 }
10542
10543 if (this._end) {
10544 if (ltgt.lowerBoundInclusive(options)) {
10545 this._test = gte
10546 } else {
10547 this._test = gt
10548 }
10549 }
10550 }
10551}
10552
10553inherits(MemIterator, AbstractIterator)
10554
10555MemIterator.prototype._next = function (callback) {
10556 var key
10557 var value
10558
10559 if (this._done++ >= this._limit) return setImmediate(callback)
10560 if (!this._tree.valid) return setImmediate(callback)
10561
10562 key = this._tree.key
10563 value = this._tree.value
10564
10565 if (!this._test(key)) return setImmediate(callback)
10566
10567 if (this.keyAsBuffer) key = Buffer.from(key)
10568 if (this.valueAsBuffer) value = Buffer.from(value)
10569
10570 this._tree[this._incr]()
10571
10572 setImmediate(function callNext () {
10573 callback(null, key, value)
10574 })
10575}
10576
10577MemIterator.prototype._test = function () {
10578 return true
10579}
10580
10581function MemDOWN (location) {
10582 if (!(this instanceof MemDOWN)) return new MemDOWN(location)
10583
10584 AbstractLevelDOWN.call(this, typeof location === 'string' ? location : '')
10585
10586 this._location = this.location ? '$' + this.location : '_tree'
10587 this._store = this.location ? globalStore : this
10588 this._store[this._location] =
10589 this._store[this._location] || createRBT(ltgt.compare)
10590}
10591
10592MemDOWN.clearGlobalStore = function (strict) {
10593 if (strict) {
10594 Object.keys(globalStore).forEach(function (key) {
10595 delete globalStore[key]
10596 })
10597 } else {
10598 globalStore = {}
10599 }
10600}
10601
10602inherits(MemDOWN, AbstractLevelDOWN)
10603
10604MemDOWN.prototype._open = function (options, callback) {
10605 var self = this
10606 setImmediate(function callNext () {
10607 callback(null, self)
10608 })
10609}
10610
10611MemDOWN.prototype._put = function (key, value, options, callback) {
10612 if (typeof value === 'undefined' || value === null) value = ''
10613
10614 var iter = this._store[this._location].find(key)
10615
10616 if (iter.valid) {
10617 this._store[this._location] = iter.update(value)
10618 } else {
10619 this._store[this._location] = this._store[this._location].insert(key, value)
10620 }
10621
10622 setImmediate(callback)
10623}
10624
10625MemDOWN.prototype._get = function (key, options, callback) {
10626 var value = this._store[this._location].get(key)
10627
10628 if (typeof value === 'undefined') {
10629 // 'NotFound' error, consistent with LevelDOWN API
10630 return setImmediate(function callNext () {
10631 callback(new Error('NotFound'))
10632 })
10633 }
10634
10635 if (options.asBuffer !== false && !this._isBuffer(value)) {
10636 value = Buffer.from(String(value))
10637 }
10638
10639 setImmediate(function callNext () {
10640 callback(null, value)
10641 })
10642}
10643
10644MemDOWN.prototype._del = function (key, options, callback) {
10645 this._store[this._location] = this._store[this._location].remove(key)
10646 setImmediate(callback)
10647}
10648
10649MemDOWN.prototype._batch = function (array, options, callback) {
10650 var i = -1
10651 var key
10652 var value
10653 var iter
10654 var len = array.length
10655 var tree = this._store[this._location]
10656
10657 while (++i < len) {
10658 if (!array[i]) continue
10659
10660 key = this._isBuffer(array[i].key) ? array[i].key : String(array[i].key)
10661 iter = tree.find(key)
10662
10663 if (array[i].type === 'put') {
10664 value = this._isBuffer(array[i].value)
10665 ? array[i].value
10666 : String(array[i].value)
10667 tree = iter.valid ? iter.update(value) : tree.insert(key, value)
10668 } else {
10669 tree = iter.remove()
10670 }
10671 }
10672
10673 this._store[this._location] = tree
10674
10675 setImmediate(callback)
10676}
10677
10678MemDOWN.prototype._iterator = function (options) {
10679 return new MemIterator(this, options)
10680}
10681
10682MemDOWN.prototype._isBuffer = function (obj) {
10683 return Buffer.isBuffer(obj)
10684}
10685
10686MemDOWN.destroy = function (name, callback) {
10687 var key = '$' + name
10688
10689 if (key in globalStore) {
10690 delete globalStore[key]
10691 }
10692
10693 setImmediate(callback)
10694}
10695
10696module.exports = MemDOWN.default = MemDOWN
10697
10698},{"21":21,"29":29,"55":55,"56":56,"61":61,"63":63}],58:[function(_dereq_,module,exports){
10699(function (process){(function (){
10700/* Copyright (c) 2017 Rod Vagg, MIT License */
10701
10702function AbstractChainedBatch (db) {
10703 this._db = db
10704 this._operations = []
10705 this._written = false
10706}
10707
10708AbstractChainedBatch.prototype._serializeKey = function (key) {
10709 return this._db._serializeKey(key)
10710}
10711
10712AbstractChainedBatch.prototype._serializeValue = function (value) {
10713 return this._db._serializeValue(value)
10714}
10715
10716AbstractChainedBatch.prototype._checkWritten = function () {
10717 if (this._written)
10718 throw new Error('write() already called on this batch')
10719}
10720
10721AbstractChainedBatch.prototype.put = function (key, value) {
10722 this._checkWritten()
10723
10724 var err = this._db._checkKey(key, 'key', this._db._isBuffer)
10725 if (err)
10726 throw err
10727
10728 key = this._serializeKey(key)
10729 value = this._serializeValue(value)
10730
10731 if (typeof this._put == 'function' )
10732 this._put(key, value)
10733 else
10734 this._operations.push({ type: 'put', key: key, value: value })
10735
10736 return this
10737}
10738
10739AbstractChainedBatch.prototype.del = function (key) {
10740 this._checkWritten()
10741
10742 var err = this._db._checkKey(key, 'key', this._db._isBuffer)
10743 if (err) throw err
10744
10745 key = this._serializeKey(key)
10746
10747 if (typeof this._del == 'function' )
10748 this._del(key)
10749 else
10750 this._operations.push({ type: 'del', key: key })
10751
10752 return this
10753}
10754
10755AbstractChainedBatch.prototype.clear = function () {
10756 this._checkWritten()
10757
10758 this._operations = []
10759
10760 if (typeof this._clear == 'function' )
10761 this._clear()
10762
10763 return this
10764}
10765
10766AbstractChainedBatch.prototype.write = function (options, callback) {
10767 this._checkWritten()
10768
10769 if (typeof options == 'function')
10770 callback = options
10771 if (typeof callback != 'function')
10772 throw new Error('write() requires a callback argument')
10773 if (typeof options != 'object')
10774 options = {}
10775
10776 this._written = true
10777
10778 if (typeof this._write == 'function' )
10779 return this._write(callback)
10780
10781 if (typeof this._db._batch == 'function')
10782 return this._db._batch(this._operations, options, callback)
10783
10784 process.nextTick(callback)
10785}
10786
10787module.exports = AbstractChainedBatch
10788
10789}).call(this)}).call(this,_dereq_(66))
10790},{"66":66}],59:[function(_dereq_,module,exports){
10791(function (process){(function (){
10792/* Copyright (c) 2017 Rod Vagg, MIT License */
10793
10794function AbstractIterator (db) {
10795 this.db = db
10796 this._ended = false
10797 this._nexting = false
10798}
10799
10800AbstractIterator.prototype.next = function (callback) {
10801 var self = this
10802
10803 if (typeof callback != 'function')
10804 throw new Error('next() requires a callback argument')
10805
10806 if (self._ended)
10807 return callback(new Error('cannot call next() after end()'))
10808 if (self._nexting)
10809 return callback(new Error('cannot call next() before previous next() has completed'))
10810
10811 self._nexting = true
10812 if (typeof self._next == 'function') {
10813 return self._next(function () {
10814 self._nexting = false
10815 callback.apply(null, arguments)
10816 })
10817 }
10818
10819 process.nextTick(function () {
10820 self._nexting = false
10821 callback()
10822 })
10823}
10824
10825AbstractIterator.prototype.end = function (callback) {
10826 if (typeof callback != 'function')
10827 throw new Error('end() requires a callback argument')
10828
10829 if (this._ended)
10830 return callback(new Error('end() already called on iterator'))
10831
10832 this._ended = true
10833
10834 if (typeof this._end == 'function')
10835 return this._end(callback)
10836
10837 process.nextTick(callback)
10838}
10839
10840module.exports = AbstractIterator
10841
10842}).call(this)}).call(this,_dereq_(66))
10843},{"66":66}],60:[function(_dereq_,module,exports){
10844(function (Buffer,process){(function (){
10845/* Copyright (c) 2017 Rod Vagg, MIT License */
10846
10847var xtend = _dereq_(133)
10848 , AbstractIterator = _dereq_(59)
10849 , AbstractChainedBatch = _dereq_(58)
10850
10851function AbstractLevelDOWN (location) {
10852 if (!arguments.length || location === undefined)
10853 throw new Error('constructor requires at least a location argument')
10854
10855 if (typeof location != 'string')
10856 throw new Error('constructor requires a location string argument')
10857
10858 this.location = location
10859 this.status = 'new'
10860}
10861
10862AbstractLevelDOWN.prototype.open = function (options, callback) {
10863 var self = this
10864 , oldStatus = this.status
10865
10866 if (typeof options == 'function')
10867 callback = options
10868
10869 if (typeof callback != 'function')
10870 throw new Error('open() requires a callback argument')
10871
10872 if (typeof options != 'object')
10873 options = {}
10874
10875 options.createIfMissing = options.createIfMissing != false
10876 options.errorIfExists = !!options.errorIfExists
10877
10878 if (typeof this._open == 'function') {
10879 this.status = 'opening'
10880 this._open(options, function (err) {
10881 if (err) {
10882 self.status = oldStatus
10883 return callback(err)
10884 }
10885 self.status = 'open'
10886 callback()
10887 })
10888 } else {
10889 this.status = 'open'
10890 process.nextTick(callback)
10891 }
10892}
10893
10894AbstractLevelDOWN.prototype.close = function (callback) {
10895 var self = this
10896 , oldStatus = this.status
10897
10898 if (typeof callback != 'function')
10899 throw new Error('close() requires a callback argument')
10900
10901 if (typeof this._close == 'function') {
10902 this.status = 'closing'
10903 this._close(function (err) {
10904 if (err) {
10905 self.status = oldStatus
10906 return callback(err)
10907 }
10908 self.status = 'closed'
10909 callback()
10910 })
10911 } else {
10912 this.status = 'closed'
10913 process.nextTick(callback)
10914 }
10915}
10916
10917AbstractLevelDOWN.prototype.get = function (key, options, callback) {
10918 var err
10919
10920 if (typeof options == 'function')
10921 callback = options
10922
10923 if (typeof callback != 'function')
10924 throw new Error('get() requires a callback argument')
10925
10926 if (err = this._checkKey(key, 'key'))
10927 return callback(err)
10928
10929 key = this._serializeKey(key)
10930
10931 if (typeof options != 'object')
10932 options = {}
10933
10934 options.asBuffer = options.asBuffer != false
10935
10936 if (typeof this._get == 'function')
10937 return this._get(key, options, callback)
10938
10939 process.nextTick(function () { callback(new Error('NotFound')) })
10940}
10941
10942AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
10943 var err
10944
10945 if (typeof options == 'function')
10946 callback = options
10947
10948 if (typeof callback != 'function')
10949 throw new Error('put() requires a callback argument')
10950
10951 if (err = this._checkKey(key, 'key'))
10952 return callback(err)
10953
10954 key = this._serializeKey(key)
10955 value = this._serializeValue(value)
10956
10957 if (typeof options != 'object')
10958 options = {}
10959
10960 if (typeof this._put == 'function')
10961 return this._put(key, value, options, callback)
10962
10963 process.nextTick(callback)
10964}
10965
10966AbstractLevelDOWN.prototype.del = function (key, options, callback) {
10967 var err
10968
10969 if (typeof options == 'function')
10970 callback = options
10971
10972 if (typeof callback != 'function')
10973 throw new Error('del() requires a callback argument')
10974
10975 if (err = this._checkKey(key, 'key'))
10976 return callback(err)
10977
10978 key = this._serializeKey(key)
10979
10980 if (typeof options != 'object')
10981 options = {}
10982
10983 if (typeof this._del == 'function')
10984 return this._del(key, options, callback)
10985
10986 process.nextTick(callback)
10987}
10988
10989AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
10990 if (!arguments.length)
10991 return this._chainedBatch()
10992
10993 if (typeof options == 'function')
10994 callback = options
10995
10996 if (typeof array == 'function')
10997 callback = array
10998
10999 if (typeof callback != 'function')
11000 throw new Error('batch(array) requires a callback argument')
11001
11002 if (!Array.isArray(array))
11003 return callback(new Error('batch(array) requires an array argument'))
11004
11005 if (!options || typeof options != 'object')
11006 options = {}
11007
11008 var i = 0
11009 , l = array.length
11010 , e
11011 , err
11012
11013 for (; i < l; i++) {
11014 e = array[i]
11015 if (typeof e != 'object')
11016 continue
11017
11018 if (err = this._checkKey(e.type, 'type'))
11019 return callback(err)
11020
11021 if (err = this._checkKey(e.key, 'key'))
11022 return callback(err)
11023 }
11024
11025 if (typeof this._batch == 'function')
11026 return this._batch(array, options, callback)
11027
11028 process.nextTick(callback)
11029}
11030
11031//TODO: remove from here, not a necessary primitive
11032AbstractLevelDOWN.prototype.approximateSize = function (start, end, callback) {
11033 if ( start == null
11034 || end == null
11035 || typeof start == 'function'
11036 || typeof end == 'function') {
11037 throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments')
11038 }
11039
11040 if (typeof callback != 'function')
11041 throw new Error('approximateSize() requires a callback argument')
11042
11043 start = this._serializeKey(start)
11044 end = this._serializeKey(end)
11045
11046 if (typeof this._approximateSize == 'function')
11047 return this._approximateSize(start, end, callback)
11048
11049 process.nextTick(function () {
11050 callback(null, 0)
11051 })
11052}
11053
11054AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
11055 var self = this
11056
11057 options = xtend(options)
11058
11059 ;[ 'start', 'end', 'gt', 'gte', 'lt', 'lte' ].forEach(function (o) {
11060 if (options[o] && self._isBuffer(options[o]) && options[o].length === 0)
11061 delete options[o]
11062 })
11063
11064 options.reverse = !!options.reverse
11065 options.keys = options.keys != false
11066 options.values = options.values != false
11067 options.limit = 'limit' in options ? options.limit : -1
11068 options.keyAsBuffer = options.keyAsBuffer != false
11069 options.valueAsBuffer = options.valueAsBuffer != false
11070
11071 return options
11072}
11073
11074AbstractLevelDOWN.prototype.iterator = function (options) {
11075 if (typeof options != 'object')
11076 options = {}
11077
11078 options = this._setupIteratorOptions(options)
11079
11080 if (typeof this._iterator == 'function')
11081 return this._iterator(options)
11082
11083 return new AbstractIterator(this)
11084}
11085
11086AbstractLevelDOWN.prototype._chainedBatch = function () {
11087 return new AbstractChainedBatch(this)
11088}
11089
11090AbstractLevelDOWN.prototype._isBuffer = function (obj) {
11091 return Buffer.isBuffer(obj)
11092}
11093
11094AbstractLevelDOWN.prototype._serializeKey = function (key) {
11095 return this._isBuffer(key)
11096 ? key
11097 : String(key)
11098}
11099
11100AbstractLevelDOWN.prototype._serializeValue = function (value) {
11101 if (value == null) return ''
11102 return this._isBuffer(value) || process.browser ? value : String(value)
11103}
11104
11105AbstractLevelDOWN.prototype._checkKey = function (obj, type) {
11106 if (obj === null || obj === undefined)
11107 return new Error(type + ' cannot be `null` or `undefined`')
11108
11109 if (this._isBuffer(obj) && obj.length === 0)
11110 return new Error(type + ' cannot be an empty Buffer')
11111 else if (String(obj) === '')
11112 return new Error(type + ' cannot be an empty String')
11113}
11114
11115module.exports = AbstractLevelDOWN
11116
11117}).call(this)}).call(this,{"isBuffer":_dereq_(30)},_dereq_(66))
11118},{"133":133,"30":30,"58":58,"59":59,"66":66}],61:[function(_dereq_,module,exports){
11119exports.AbstractLevelDOWN = _dereq_(60)
11120exports.AbstractIterator = _dereq_(59)
11121exports.AbstractChainedBatch = _dereq_(58)
11122exports.isLevelDOWN = _dereq_(62)
11123
11124},{"58":58,"59":59,"60":60,"62":62}],62:[function(_dereq_,module,exports){
11125var AbstractLevelDOWN = _dereq_(60)
11126
11127function isLevelDOWN (db) {
11128 if (!db || typeof db !== 'object')
11129 return false
11130 return Object.keys(AbstractLevelDOWN.prototype).filter(function (name) {
11131 // TODO remove approximateSize check when method is gone
11132 return name[0] != '_' && name != 'approximateSize'
11133 }).every(function (name) {
11134 return typeof db[name] == 'function'
11135 })
11136}
11137
11138module.exports = isLevelDOWN
11139
11140},{"60":60}],63:[function(_dereq_,module,exports){
11141/* eslint-disable node/no-deprecated-api */
11142var buffer = _dereq_(8)
11143var Buffer = buffer.Buffer
11144
11145// alternative to using Object.keys for old browsers
11146function copyProps (src, dst) {
11147 for (var key in src) {
11148 dst[key] = src[key]
11149 }
11150}
11151if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
11152 module.exports = buffer
11153} else {
11154 // Copy properties from require('buffer')
11155 copyProps(buffer, exports)
11156 exports.Buffer = SafeBuffer
11157}
11158
11159function SafeBuffer (arg, encodingOrOffset, length) {
11160 return Buffer(arg, encodingOrOffset, length)
11161}
11162
11163// Copy static methods from Buffer
11164copyProps(Buffer, SafeBuffer)
11165
11166SafeBuffer.from = function (arg, encodingOrOffset, length) {
11167 if (typeof arg === 'number') {
11168 throw new TypeError('Argument must not be a number')
11169 }
11170 return Buffer(arg, encodingOrOffset, length)
11171}
11172
11173SafeBuffer.alloc = function (size, fill, encoding) {
11174 if (typeof size !== 'number') {
11175 throw new TypeError('Argument must be a number')
11176 }
11177 var buf = Buffer(size)
11178 if (fill !== undefined) {
11179 if (typeof encoding === 'string') {
11180 buf.fill(fill, encoding)
11181 } else {
11182 buf.fill(fill)
11183 }
11184 } else {
11185 buf.fill(0)
11186 }
11187 return buf
11188}
11189
11190SafeBuffer.allocUnsafe = function (size) {
11191 if (typeof size !== 'number') {
11192 throw new TypeError('Argument must be a number')
11193 }
11194 return Buffer(size)
11195}
11196
11197SafeBuffer.allocUnsafeSlow = function (size) {
11198 if (typeof size !== 'number') {
11199 throw new TypeError('Argument must be a number')
11200 }
11201 return buffer.SlowBuffer(size)
11202}
11203
11204},{"8":8}],64:[function(_dereq_,module,exports){
11205/*
11206object-assign
11207(c) Sindre Sorhus
11208@license MIT
11209*/
11210
11211'use strict';
11212/* eslint-disable no-unused-vars */
11213var getOwnPropertySymbols = Object.getOwnPropertySymbols;
11214var hasOwnProperty = Object.prototype.hasOwnProperty;
11215var propIsEnumerable = Object.prototype.propertyIsEnumerable;
11216
11217function toObject(val) {
11218 if (val === null || val === undefined) {
11219 throw new TypeError('Object.assign cannot be called with null or undefined');
11220 }
11221
11222 return Object(val);
11223}
11224
11225function shouldUseNative() {
11226 try {
11227 if (!Object.assign) {
11228 return false;
11229 }
11230
11231 // Detect buggy property enumeration order in older V8 versions.
11232
11233 // https://bugs.chromium.org/p/v8/issues/detail?id=4118
11234 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
11235 test1[5] = 'de';
11236 if (Object.getOwnPropertyNames(test1)[0] === '5') {
11237 return false;
11238 }
11239
11240 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
11241 var test2 = {};
11242 for (var i = 0; i < 10; i++) {
11243 test2['_' + String.fromCharCode(i)] = i;
11244 }
11245 var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
11246 return test2[n];
11247 });
11248 if (order2.join('') !== '0123456789') {
11249 return false;
11250 }
11251
11252 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
11253 var test3 = {};
11254 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
11255 test3[letter] = letter;
11256 });
11257 if (Object.keys(Object.assign({}, test3)).join('') !==
11258 'abcdefghijklmnopqrst') {
11259 return false;
11260 }
11261
11262 return true;
11263 } catch (err) {
11264 // We don't expect any of the above to throw, but better to be safe.
11265 return false;
11266 }
11267}
11268
11269module.exports = shouldUseNative() ? Object.assign : function (target, source) {
11270 var from;
11271 var to = toObject(target);
11272 var symbols;
11273
11274 for (var s = 1; s < arguments.length; s++) {
11275 from = Object(arguments[s]);
11276
11277 for (var key in from) {
11278 if (hasOwnProperty.call(from, key)) {
11279 to[key] = from[key];
11280 }
11281 }
11282
11283 if (getOwnPropertySymbols) {
11284 symbols = getOwnPropertySymbols(from);
11285 for (var i = 0; i < symbols.length; i++) {
11286 if (propIsEnumerable.call(from, symbols[i])) {
11287 to[symbols[i]] = from[symbols[i]];
11288 }
11289 }
11290 }
11291 }
11292
11293 return to;
11294};
11295
11296},{}],65:[function(_dereq_,module,exports){
11297(function (process){(function (){
11298'use strict';
11299
11300if (typeof process === 'undefined' ||
11301 !process.version ||
11302 process.version.indexOf('v0.') === 0 ||
11303 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
11304 module.exports = { nextTick: nextTick };
11305} else {
11306 module.exports = process
11307}
11308
11309function nextTick(fn, arg1, arg2, arg3) {
11310 if (typeof fn !== 'function') {
11311 throw new TypeError('"callback" argument must be a function');
11312 }
11313 var len = arguments.length;
11314 var args, i;
11315 switch (len) {
11316 case 0:
11317 case 1:
11318 return process.nextTick(fn);
11319 case 2:
11320 return process.nextTick(function afterTickOne() {
11321 fn.call(null, arg1);
11322 });
11323 case 3:
11324 return process.nextTick(function afterTickTwo() {
11325 fn.call(null, arg1, arg2);
11326 });
11327 case 4:
11328 return process.nextTick(function afterTickThree() {
11329 fn.call(null, arg1, arg2, arg3);
11330 });
11331 default:
11332 args = new Array(len - 1);
11333 i = 0;
11334 while (i < args.length) {
11335 args[i++] = arguments[i];
11336 }
11337 return process.nextTick(function afterTick() {
11338 fn.apply(null, args);
11339 });
11340 }
11341}
11342
11343
11344}).call(this)}).call(this,_dereq_(66))
11345},{"66":66}],66:[function(_dereq_,module,exports){
11346// shim for using process in browser
11347var process = module.exports = {};
11348
11349// cached from whatever global is present so that test runners that stub it
11350// don't break things. But we need to wrap it in a try catch in case it is
11351// wrapped in strict mode code which doesn't define any globals. It's inside a
11352// function because try/catches deoptimize in certain engines.
11353
11354var cachedSetTimeout;
11355var cachedClearTimeout;
11356
11357function defaultSetTimout() {
11358 throw new Error('setTimeout has not been defined');
11359}
11360function defaultClearTimeout () {
11361 throw new Error('clearTimeout has not been defined');
11362}
11363(function () {
11364 try {
11365 if (typeof setTimeout === 'function') {
11366 cachedSetTimeout = setTimeout;
11367 } else {
11368 cachedSetTimeout = defaultSetTimout;
11369 }
11370 } catch (e) {
11371 cachedSetTimeout = defaultSetTimout;
11372 }
11373 try {
11374 if (typeof clearTimeout === 'function') {
11375 cachedClearTimeout = clearTimeout;
11376 } else {
11377 cachedClearTimeout = defaultClearTimeout;
11378 }
11379 } catch (e) {
11380 cachedClearTimeout = defaultClearTimeout;
11381 }
11382} ())
11383function runTimeout(fun) {
11384 if (cachedSetTimeout === setTimeout) {
11385 //normal enviroments in sane situations
11386 return setTimeout(fun, 0);
11387 }
11388 // if setTimeout wasn't available but was latter defined
11389 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
11390 cachedSetTimeout = setTimeout;
11391 return setTimeout(fun, 0);
11392 }
11393 try {
11394 // when when somebody has screwed with setTimeout but no I.E. maddness
11395 return cachedSetTimeout(fun, 0);
11396 } catch(e){
11397 try {
11398 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
11399 return cachedSetTimeout.call(null, fun, 0);
11400 } catch(e){
11401 // 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
11402 return cachedSetTimeout.call(this, fun, 0);
11403 }
11404 }
11405
11406
11407}
11408function runClearTimeout(marker) {
11409 if (cachedClearTimeout === clearTimeout) {
11410 //normal enviroments in sane situations
11411 return clearTimeout(marker);
11412 }
11413 // if clearTimeout wasn't available but was latter defined
11414 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
11415 cachedClearTimeout = clearTimeout;
11416 return clearTimeout(marker);
11417 }
11418 try {
11419 // when when somebody has screwed with setTimeout but no I.E. maddness
11420 return cachedClearTimeout(marker);
11421 } catch (e){
11422 try {
11423 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
11424 return cachedClearTimeout.call(null, marker);
11425 } catch (e){
11426 // 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.
11427 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
11428 return cachedClearTimeout.call(this, marker);
11429 }
11430 }
11431
11432
11433
11434}
11435var queue = [];
11436var draining = false;
11437var currentQueue;
11438var queueIndex = -1;
11439
11440function cleanUpNextTick() {
11441 if (!draining || !currentQueue) {
11442 return;
11443 }
11444 draining = false;
11445 if (currentQueue.length) {
11446 queue = currentQueue.concat(queue);
11447 } else {
11448 queueIndex = -1;
11449 }
11450 if (queue.length) {
11451 drainQueue();
11452 }
11453}
11454
11455function drainQueue() {
11456 if (draining) {
11457 return;
11458 }
11459 var timeout = runTimeout(cleanUpNextTick);
11460 draining = true;
11461
11462 var len = queue.length;
11463 while(len) {
11464 currentQueue = queue;
11465 queue = [];
11466 while (++queueIndex < len) {
11467 if (currentQueue) {
11468 currentQueue[queueIndex].run();
11469 }
11470 }
11471 queueIndex = -1;
11472 len = queue.length;
11473 }
11474 currentQueue = null;
11475 draining = false;
11476 runClearTimeout(timeout);
11477}
11478
11479process.nextTick = function (fun) {
11480 var args = new Array(arguments.length - 1);
11481 if (arguments.length > 1) {
11482 for (var i = 1; i < arguments.length; i++) {
11483 args[i - 1] = arguments[i];
11484 }
11485 }
11486 queue.push(new Item(fun, args));
11487 if (queue.length === 1 && !draining) {
11488 runTimeout(drainQueue);
11489 }
11490};
11491
11492// v8 likes predictible objects
11493function Item(fun, array) {
11494 this.fun = fun;
11495 this.array = array;
11496}
11497Item.prototype.run = function () {
11498 this.fun.apply(null, this.array);
11499};
11500process.title = 'browser';
11501process.browser = true;
11502process.env = {};
11503process.argv = [];
11504process.version = ''; // empty string to avoid regexp issues
11505process.versions = {};
11506
11507function noop() {}
11508
11509process.on = noop;
11510process.addListener = noop;
11511process.once = noop;
11512process.off = noop;
11513process.removeListener = noop;
11514process.removeAllListeners = noop;
11515process.emit = noop;
11516process.prependListener = noop;
11517process.prependOnceListener = noop;
11518
11519process.listeners = function (name) { return [] }
11520
11521process.binding = function (name) {
11522 throw new Error('process.binding is not supported');
11523};
11524
11525process.cwd = function () { return '/' };
11526process.chdir = function (dir) {
11527 throw new Error('process.chdir is not supported');
11528};
11529process.umask = function() { return 0; };
11530
11531},{}],67:[function(_dereq_,module,exports){
11532/*!
11533 * prr
11534 * (c) 2013 Rod Vagg <rod@vagg.org>
11535 * https://github.com/rvagg/prr
11536 * License: MIT
11537 */
11538
11539(function (name, context, definition) {
11540 if (typeof module != 'undefined' && module.exports)
11541 module.exports = definition()
11542 else
11543 context[name] = definition()
11544})('prr', this, function() {
11545
11546 var setProperty = typeof Object.defineProperty == 'function'
11547 ? function (obj, key, options) {
11548 Object.defineProperty(obj, key, options)
11549 return obj
11550 }
11551 : function (obj, key, options) { // < es5
11552 obj[key] = options.value
11553 return obj
11554 }
11555
11556 , makeOptions = function (value, options) {
11557 var oo = typeof options == 'object'
11558 , os = !oo && typeof options == 'string'
11559 , op = function (p) {
11560 return oo
11561 ? !!options[p]
11562 : os
11563 ? options.indexOf(p[0]) > -1
11564 : false
11565 }
11566
11567 return {
11568 enumerable : op('enumerable')
11569 , configurable : op('configurable')
11570 , writable : op('writable')
11571 , value : value
11572 }
11573 }
11574
11575 , prr = function (obj, key, value, options) {
11576 var k
11577
11578 options = makeOptions(value, options)
11579
11580 if (typeof key == 'object') {
11581 for (k in key) {
11582 if (Object.hasOwnProperty.call(key, k)) {
11583 options.value = key[k]
11584 setProperty(obj, k, options)
11585 }
11586 }
11587 return obj
11588 }
11589
11590 return setProperty(obj, key, options)
11591 }
11592
11593 return prr
11594})
11595},{}],68:[function(_dereq_,module,exports){
11596(function (process){(function (){
11597// Copyright Joyent, Inc. and other Node contributors.
11598//
11599// Permission is hereby granted, free of charge, to any person obtaining a
11600// copy of this software and associated documentation files (the
11601// "Software"), to deal in the Software without restriction, including
11602// without limitation the rights to use, copy, modify, merge, publish,
11603// distribute, sublicense, and/or sell copies of the Software, and to permit
11604// persons to whom the Software is furnished to do so, subject to the
11605// following conditions:
11606//
11607// The above copyright notice and this permission notice shall be included
11608// in all copies or substantial portions of the Software.
11609//
11610// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11611// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11612// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11613// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11614// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11615// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11616// USE OR OTHER DEALINGS IN THE SOFTWARE.
11617
11618// a duplex stream is just a stream that is both readable and writable.
11619// Since JS doesn't have multiple prototypal inheritance, this class
11620// prototypally inherits from Readable, and then parasitically from
11621// Writable.
11622
11623module.exports = Duplex;
11624
11625/*<replacement>*/
11626var objectKeys = Object.keys || function (obj) {
11627 var keys = [];
11628 for (var key in obj) keys.push(key);
11629 return keys;
11630}
11631/*</replacement>*/
11632
11633
11634/*<replacement>*/
11635var util = _dereq_(9);
11636util.inherits = _dereq_(29);
11637/*</replacement>*/
11638
11639var Readable = _dereq_(70);
11640var Writable = _dereq_(72);
11641
11642util.inherits(Duplex, Readable);
11643
11644forEach(objectKeys(Writable.prototype), function(method) {
11645 if (!Duplex.prototype[method])
11646 Duplex.prototype[method] = Writable.prototype[method];
11647});
11648
11649function Duplex(options) {
11650 if (!(this instanceof Duplex))
11651 return new Duplex(options);
11652
11653 Readable.call(this, options);
11654 Writable.call(this, options);
11655
11656 if (options && options.readable === false)
11657 this.readable = false;
11658
11659 if (options && options.writable === false)
11660 this.writable = false;
11661
11662 this.allowHalfOpen = true;
11663 if (options && options.allowHalfOpen === false)
11664 this.allowHalfOpen = false;
11665
11666 this.once('end', onend);
11667}
11668
11669// the no-half-open enforcer
11670function onend() {
11671 // if we allow half-open state, or if the writable side ended,
11672 // then we're ok.
11673 if (this.allowHalfOpen || this._writableState.ended)
11674 return;
11675
11676 // no more data can be written.
11677 // But allow more writes to happen in this tick.
11678 process.nextTick(this.end.bind(this));
11679}
11680
11681function forEach (xs, f) {
11682 for (var i = 0, l = xs.length; i < l; i++) {
11683 f(xs[i], i);
11684 }
11685}
11686
11687}).call(this)}).call(this,_dereq_(66))
11688},{"29":29,"66":66,"70":70,"72":72,"9":9}],69:[function(_dereq_,module,exports){
11689// Copyright Joyent, Inc. and other Node contributors.
11690//
11691// Permission is hereby granted, free of charge, to any person obtaining a
11692// copy of this software and associated documentation files (the
11693// "Software"), to deal in the Software without restriction, including
11694// without limitation the rights to use, copy, modify, merge, publish,
11695// distribute, sublicense, and/or sell copies of the Software, and to permit
11696// persons to whom the Software is furnished to do so, subject to the
11697// following conditions:
11698//
11699// The above copyright notice and this permission notice shall be included
11700// in all copies or substantial portions of the Software.
11701//
11702// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11703// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11704// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11705// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11706// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11707// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11708// USE OR OTHER DEALINGS IN THE SOFTWARE.
11709
11710// a passthrough stream.
11711// basically just the most minimal sort of Transform stream.
11712// Every written chunk gets output as-is.
11713
11714module.exports = PassThrough;
11715
11716var Transform = _dereq_(71);
11717
11718/*<replacement>*/
11719var util = _dereq_(9);
11720util.inherits = _dereq_(29);
11721/*</replacement>*/
11722
11723util.inherits(PassThrough, Transform);
11724
11725function PassThrough(options) {
11726 if (!(this instanceof PassThrough))
11727 return new PassThrough(options);
11728
11729 Transform.call(this, options);
11730}
11731
11732PassThrough.prototype._transform = function(chunk, encoding, cb) {
11733 cb(null, chunk);
11734};
11735
11736},{"29":29,"71":71,"9":9}],70:[function(_dereq_,module,exports){
11737(function (process){(function (){
11738// Copyright Joyent, Inc. and other Node contributors.
11739//
11740// Permission is hereby granted, free of charge, to any person obtaining a
11741// copy of this software and associated documentation files (the
11742// "Software"), to deal in the Software without restriction, including
11743// without limitation the rights to use, copy, modify, merge, publish,
11744// distribute, sublicense, and/or sell copies of the Software, and to permit
11745// persons to whom the Software is furnished to do so, subject to the
11746// following conditions:
11747//
11748// The above copyright notice and this permission notice shall be included
11749// in all copies or substantial portions of the Software.
11750//
11751// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11752// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11753// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11754// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11755// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11756// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11757// USE OR OTHER DEALINGS IN THE SOFTWARE.
11758
11759module.exports = Readable;
11760
11761/*<replacement>*/
11762var isArray = _dereq_(73);
11763/*</replacement>*/
11764
11765
11766/*<replacement>*/
11767var Buffer = _dereq_(8).Buffer;
11768/*</replacement>*/
11769
11770Readable.ReadableState = ReadableState;
11771
11772var EE = _dereq_(20).EventEmitter;
11773
11774/*<replacement>*/
11775if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
11776 return emitter.listeners(type).length;
11777};
11778/*</replacement>*/
11779
11780var Stream = _dereq_(78);
11781
11782/*<replacement>*/
11783var util = _dereq_(9);
11784util.inherits = _dereq_(29);
11785/*</replacement>*/
11786
11787var StringDecoder;
11788
11789
11790/*<replacement>*/
11791var debug = _dereq_(6);
11792if (debug && debug.debuglog) {
11793 debug = debug.debuglog('stream');
11794} else {
11795 debug = function () {};
11796}
11797/*</replacement>*/
11798
11799
11800util.inherits(Readable, Stream);
11801
11802function ReadableState(options, stream) {
11803 var Duplex = _dereq_(68);
11804
11805 options = options || {};
11806
11807 // the point at which it stops calling _read() to fill the buffer
11808 // Note: 0 is a valid value, means "don't call _read preemptively ever"
11809 var hwm = options.highWaterMark;
11810 var defaultHwm = options.objectMode ? 16 : 16 * 1024;
11811 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
11812
11813 // cast to ints.
11814 this.highWaterMark = ~~this.highWaterMark;
11815
11816 this.buffer = [];
11817 this.length = 0;
11818 this.pipes = null;
11819 this.pipesCount = 0;
11820 this.flowing = null;
11821 this.ended = false;
11822 this.endEmitted = false;
11823 this.reading = false;
11824
11825 // a flag to be able to tell if the onwrite cb is called immediately,
11826 // or on a later tick. We set this to true at first, because any
11827 // actions that shouldn't happen until "later" should generally also
11828 // not happen before the first write call.
11829 this.sync = true;
11830
11831 // whenever we return null, then we set a flag to say
11832 // that we're awaiting a 'readable' event emission.
11833 this.needReadable = false;
11834 this.emittedReadable = false;
11835 this.readableListening = false;
11836
11837
11838 // object stream flag. Used to make read(n) ignore n and to
11839 // make all the buffer merging and length checks go away
11840 this.objectMode = !!options.objectMode;
11841
11842 if (stream instanceof Duplex)
11843 this.objectMode = this.objectMode || !!options.readableObjectMode;
11844
11845 // Crypto is kind of old and crusty. Historically, its default string
11846 // encoding is 'binary' so we have to make this configurable.
11847 // Everything else in the universe uses 'utf8', though.
11848 this.defaultEncoding = options.defaultEncoding || 'utf8';
11849
11850 // when piping, we only care about 'readable' events that happen
11851 // after read()ing all the bytes and not getting any pushback.
11852 this.ranOut = false;
11853
11854 // the number of writers that are awaiting a drain event in .pipe()s
11855 this.awaitDrain = 0;
11856
11857 // if true, a maybeReadMore has been scheduled
11858 this.readingMore = false;
11859
11860 this.decoder = null;
11861 this.encoding = null;
11862 if (options.encoding) {
11863 if (!StringDecoder)
11864 StringDecoder = _dereq_(74).StringDecoder;
11865 this.decoder = new StringDecoder(options.encoding);
11866 this.encoding = options.encoding;
11867 }
11868}
11869
11870function Readable(options) {
11871 var Duplex = _dereq_(68);
11872
11873 if (!(this instanceof Readable))
11874 return new Readable(options);
11875
11876 this._readableState = new ReadableState(options, this);
11877
11878 // legacy
11879 this.readable = true;
11880
11881 Stream.call(this);
11882}
11883
11884// Manually shove something into the read() buffer.
11885// This returns true if the highWaterMark has not been hit yet,
11886// similar to how Writable.write() returns true if you should
11887// write() some more.
11888Readable.prototype.push = function(chunk, encoding) {
11889 var state = this._readableState;
11890
11891 if (util.isString(chunk) && !state.objectMode) {
11892 encoding = encoding || state.defaultEncoding;
11893 if (encoding !== state.encoding) {
11894 chunk = new Buffer(chunk, encoding);
11895 encoding = '';
11896 }
11897 }
11898
11899 return readableAddChunk(this, state, chunk, encoding, false);
11900};
11901
11902// Unshift should *always* be something directly out of read()
11903Readable.prototype.unshift = function(chunk) {
11904 var state = this._readableState;
11905 return readableAddChunk(this, state, chunk, '', true);
11906};
11907
11908function readableAddChunk(stream, state, chunk, encoding, addToFront) {
11909 var er = chunkInvalid(state, chunk);
11910 if (er) {
11911 stream.emit('error', er);
11912 } else if (util.isNullOrUndefined(chunk)) {
11913 state.reading = false;
11914 if (!state.ended)
11915 onEofChunk(stream, state);
11916 } else if (state.objectMode || chunk && chunk.length > 0) {
11917 if (state.ended && !addToFront) {
11918 var e = new Error('stream.push() after EOF');
11919 stream.emit('error', e);
11920 } else if (state.endEmitted && addToFront) {
11921 var e = new Error('stream.unshift() after end event');
11922 stream.emit('error', e);
11923 } else {
11924 if (state.decoder && !addToFront && !encoding)
11925 chunk = state.decoder.write(chunk);
11926
11927 if (!addToFront)
11928 state.reading = false;
11929
11930 // if we want the data now, just emit it.
11931 if (state.flowing && state.length === 0 && !state.sync) {
11932 stream.emit('data', chunk);
11933 stream.read(0);
11934 } else {
11935 // update the buffer info.
11936 state.length += state.objectMode ? 1 : chunk.length;
11937 if (addToFront)
11938 state.buffer.unshift(chunk);
11939 else
11940 state.buffer.push(chunk);
11941
11942 if (state.needReadable)
11943 emitReadable(stream);
11944 }
11945
11946 maybeReadMore(stream, state);
11947 }
11948 } else if (!addToFront) {
11949 state.reading = false;
11950 }
11951
11952 return needMoreData(state);
11953}
11954
11955
11956
11957// if it's past the high water mark, we can push in some more.
11958// Also, if we have no data yet, we can stand some
11959// more bytes. This is to work around cases where hwm=0,
11960// such as the repl. Also, if the push() triggered a
11961// readable event, and the user called read(largeNumber) such that
11962// needReadable was set, then we ought to push more, so that another
11963// 'readable' event will be triggered.
11964function needMoreData(state) {
11965 return !state.ended &&
11966 (state.needReadable ||
11967 state.length < state.highWaterMark ||
11968 state.length === 0);
11969}
11970
11971// backwards compatibility.
11972Readable.prototype.setEncoding = function(enc) {
11973 if (!StringDecoder)
11974 StringDecoder = _dereq_(74).StringDecoder;
11975 this._readableState.decoder = new StringDecoder(enc);
11976 this._readableState.encoding = enc;
11977 return this;
11978};
11979
11980// Don't raise the hwm > 128MB
11981var MAX_HWM = 0x800000;
11982function roundUpToNextPowerOf2(n) {
11983 if (n >= MAX_HWM) {
11984 n = MAX_HWM;
11985 } else {
11986 // Get the next highest power of 2
11987 n--;
11988 for (var p = 1; p < 32; p <<= 1) n |= n >> p;
11989 n++;
11990 }
11991 return n;
11992}
11993
11994function howMuchToRead(n, state) {
11995 if (state.length === 0 && state.ended)
11996 return 0;
11997
11998 if (state.objectMode)
11999 return n === 0 ? 0 : 1;
12000
12001 if (isNaN(n) || util.isNull(n)) {
12002 // only flow one buffer at a time
12003 if (state.flowing && state.buffer.length)
12004 return state.buffer[0].length;
12005 else
12006 return state.length;
12007 }
12008
12009 if (n <= 0)
12010 return 0;
12011
12012 // If we're asking for more than the target buffer level,
12013 // then raise the water mark. Bump up to the next highest
12014 // power of 2, to prevent increasing it excessively in tiny
12015 // amounts.
12016 if (n > state.highWaterMark)
12017 state.highWaterMark = roundUpToNextPowerOf2(n);
12018
12019 // don't have that much. return null, unless we've ended.
12020 if (n > state.length) {
12021 if (!state.ended) {
12022 state.needReadable = true;
12023 return 0;
12024 } else
12025 return state.length;
12026 }
12027
12028 return n;
12029}
12030
12031// you can override either this method, or the async _read(n) below.
12032Readable.prototype.read = function(n) {
12033 debug('read', n);
12034 var state = this._readableState;
12035 var nOrig = n;
12036
12037 if (!util.isNumber(n) || n > 0)
12038 state.emittedReadable = false;
12039
12040 // if we're doing read(0) to trigger a readable event, but we
12041 // already have a bunch of data in the buffer, then just trigger
12042 // the 'readable' event and move on.
12043 if (n === 0 &&
12044 state.needReadable &&
12045 (state.length >= state.highWaterMark || state.ended)) {
12046 debug('read: emitReadable', state.length, state.ended);
12047 if (state.length === 0 && state.ended)
12048 endReadable(this);
12049 else
12050 emitReadable(this);
12051 return null;
12052 }
12053
12054 n = howMuchToRead(n, state);
12055
12056 // if we've ended, and we're now clear, then finish it up.
12057 if (n === 0 && state.ended) {
12058 if (state.length === 0)
12059 endReadable(this);
12060 return null;
12061 }
12062
12063 // All the actual chunk generation logic needs to be
12064 // *below* the call to _read. The reason is that in certain
12065 // synthetic stream cases, such as passthrough streams, _read
12066 // may be a completely synchronous operation which may change
12067 // the state of the read buffer, providing enough data when
12068 // before there was *not* enough.
12069 //
12070 // So, the steps are:
12071 // 1. Figure out what the state of things will be after we do
12072 // a read from the buffer.
12073 //
12074 // 2. If that resulting state will trigger a _read, then call _read.
12075 // Note that this may be asynchronous, or synchronous. Yes, it is
12076 // deeply ugly to write APIs this way, but that still doesn't mean
12077 // that the Readable class should behave improperly, as streams are
12078 // designed to be sync/async agnostic.
12079 // Take note if the _read call is sync or async (ie, if the read call
12080 // has returned yet), so that we know whether or not it's safe to emit
12081 // 'readable' etc.
12082 //
12083 // 3. Actually pull the requested chunks out of the buffer and return.
12084
12085 // if we need a readable event, then we need to do some reading.
12086 var doRead = state.needReadable;
12087 debug('need readable', doRead);
12088
12089 // if we currently have less than the highWaterMark, then also read some
12090 if (state.length === 0 || state.length - n < state.highWaterMark) {
12091 doRead = true;
12092 debug('length less than watermark', doRead);
12093 }
12094
12095 // however, if we've ended, then there's no point, and if we're already
12096 // reading, then it's unnecessary.
12097 if (state.ended || state.reading) {
12098 doRead = false;
12099 debug('reading or ended', doRead);
12100 }
12101
12102 if (doRead) {
12103 debug('do read');
12104 state.reading = true;
12105 state.sync = true;
12106 // if the length is currently zero, then we *need* a readable event.
12107 if (state.length === 0)
12108 state.needReadable = true;
12109 // call internal read method
12110 this._read(state.highWaterMark);
12111 state.sync = false;
12112 }
12113
12114 // If _read pushed data synchronously, then `reading` will be false,
12115 // and we need to re-evaluate how much data we can return to the user.
12116 if (doRead && !state.reading)
12117 n = howMuchToRead(nOrig, state);
12118
12119 var ret;
12120 if (n > 0)
12121 ret = fromList(n, state);
12122 else
12123 ret = null;
12124
12125 if (util.isNull(ret)) {
12126 state.needReadable = true;
12127 n = 0;
12128 }
12129
12130 state.length -= n;
12131
12132 // If we have nothing in the buffer, then we want to know
12133 // as soon as we *do* get something into the buffer.
12134 if (state.length === 0 && !state.ended)
12135 state.needReadable = true;
12136
12137 // If we tried to read() past the EOF, then emit end on the next tick.
12138 if (nOrig !== n && state.ended && state.length === 0)
12139 endReadable(this);
12140
12141 if (!util.isNull(ret))
12142 this.emit('data', ret);
12143
12144 return ret;
12145};
12146
12147function chunkInvalid(state, chunk) {
12148 var er = null;
12149 if (!util.isBuffer(chunk) &&
12150 !util.isString(chunk) &&
12151 !util.isNullOrUndefined(chunk) &&
12152 !state.objectMode) {
12153 er = new TypeError('Invalid non-string/buffer chunk');
12154 }
12155 return er;
12156}
12157
12158
12159function onEofChunk(stream, state) {
12160 if (state.decoder && !state.ended) {
12161 var chunk = state.decoder.end();
12162 if (chunk && chunk.length) {
12163 state.buffer.push(chunk);
12164 state.length += state.objectMode ? 1 : chunk.length;
12165 }
12166 }
12167 state.ended = true;
12168
12169 // emit 'readable' now to make sure it gets picked up.
12170 emitReadable(stream);
12171}
12172
12173// Don't emit readable right away in sync mode, because this can trigger
12174// another read() call => stack overflow. This way, it might trigger
12175// a nextTick recursion warning, but that's not so bad.
12176function emitReadable(stream) {
12177 var state = stream._readableState;
12178 state.needReadable = false;
12179 if (!state.emittedReadable) {
12180 debug('emitReadable', state.flowing);
12181 state.emittedReadable = true;
12182 if (state.sync)
12183 process.nextTick(function() {
12184 emitReadable_(stream);
12185 });
12186 else
12187 emitReadable_(stream);
12188 }
12189}
12190
12191function emitReadable_(stream) {
12192 debug('emit readable');
12193 stream.emit('readable');
12194 flow(stream);
12195}
12196
12197
12198// at this point, the user has presumably seen the 'readable' event,
12199// and called read() to consume some data. that may have triggered
12200// in turn another _read(n) call, in which case reading = true if
12201// it's in progress.
12202// However, if we're not ended, or reading, and the length < hwm,
12203// then go ahead and try to read some more preemptively.
12204function maybeReadMore(stream, state) {
12205 if (!state.readingMore) {
12206 state.readingMore = true;
12207 process.nextTick(function() {
12208 maybeReadMore_(stream, state);
12209 });
12210 }
12211}
12212
12213function maybeReadMore_(stream, state) {
12214 var len = state.length;
12215 while (!state.reading && !state.flowing && !state.ended &&
12216 state.length < state.highWaterMark) {
12217 debug('maybeReadMore read 0');
12218 stream.read(0);
12219 if (len === state.length)
12220 // didn't get any data, stop spinning.
12221 break;
12222 else
12223 len = state.length;
12224 }
12225 state.readingMore = false;
12226}
12227
12228// abstract method. to be overridden in specific implementation classes.
12229// call cb(er, data) where data is <= n in length.
12230// for virtual (non-string, non-buffer) streams, "length" is somewhat
12231// arbitrary, and perhaps not very meaningful.
12232Readable.prototype._read = function(n) {
12233 this.emit('error', new Error('not implemented'));
12234};
12235
12236Readable.prototype.pipe = function(dest, pipeOpts) {
12237 var src = this;
12238 var state = this._readableState;
12239
12240 switch (state.pipesCount) {
12241 case 0:
12242 state.pipes = dest;
12243 break;
12244 case 1:
12245 state.pipes = [state.pipes, dest];
12246 break;
12247 default:
12248 state.pipes.push(dest);
12249 break;
12250 }
12251 state.pipesCount += 1;
12252 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
12253
12254 var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
12255 dest !== process.stdout &&
12256 dest !== process.stderr;
12257
12258 var endFn = doEnd ? onend : cleanup;
12259 if (state.endEmitted)
12260 process.nextTick(endFn);
12261 else
12262 src.once('end', endFn);
12263
12264 dest.on('unpipe', onunpipe);
12265 function onunpipe(readable) {
12266 debug('onunpipe');
12267 if (readable === src) {
12268 cleanup();
12269 }
12270 }
12271
12272 function onend() {
12273 debug('onend');
12274 dest.end();
12275 }
12276
12277 // when the dest drains, it reduces the awaitDrain counter
12278 // on the source. This would be more elegant with a .once()
12279 // handler in flow(), but adding and removing repeatedly is
12280 // too slow.
12281 var ondrain = pipeOnDrain(src);
12282 dest.on('drain', ondrain);
12283
12284 function cleanup() {
12285 debug('cleanup');
12286 // cleanup event handlers once the pipe is broken
12287 dest.removeListener('close', onclose);
12288 dest.removeListener('finish', onfinish);
12289 dest.removeListener('drain', ondrain);
12290 dest.removeListener('error', onerror);
12291 dest.removeListener('unpipe', onunpipe);
12292 src.removeListener('end', onend);
12293 src.removeListener('end', cleanup);
12294 src.removeListener('data', ondata);
12295
12296 // if the reader is waiting for a drain event from this
12297 // specific writer, then it would cause it to never start
12298 // flowing again.
12299 // So, if this is awaiting a drain, then we just call it now.
12300 // If we don't know, then assume that we are waiting for one.
12301 if (state.awaitDrain &&
12302 (!dest._writableState || dest._writableState.needDrain))
12303 ondrain();
12304 }
12305
12306 src.on('data', ondata);
12307 function ondata(chunk) {
12308 debug('ondata');
12309 var ret = dest.write(chunk);
12310 if (false === ret) {
12311 debug('false write response, pause',
12312 src._readableState.awaitDrain);
12313 src._readableState.awaitDrain++;
12314 src.pause();
12315 }
12316 }
12317
12318 // if the dest has an error, then stop piping into it.
12319 // however, don't suppress the throwing behavior for this.
12320 function onerror(er) {
12321 debug('onerror', er);
12322 unpipe();
12323 dest.removeListener('error', onerror);
12324 if (EE.listenerCount(dest, 'error') === 0)
12325 dest.emit('error', er);
12326 }
12327 // This is a brutally ugly hack to make sure that our error handler
12328 // is attached before any userland ones. NEVER DO THIS.
12329 if (!dest._events || !dest._events.error)
12330 dest.on('error', onerror);
12331 else if (isArray(dest._events.error))
12332 dest._events.error.unshift(onerror);
12333 else
12334 dest._events.error = [onerror, dest._events.error];
12335
12336
12337
12338 // Both close and finish should trigger unpipe, but only once.
12339 function onclose() {
12340 dest.removeListener('finish', onfinish);
12341 unpipe();
12342 }
12343 dest.once('close', onclose);
12344 function onfinish() {
12345 debug('onfinish');
12346 dest.removeListener('close', onclose);
12347 unpipe();
12348 }
12349 dest.once('finish', onfinish);
12350
12351 function unpipe() {
12352 debug('unpipe');
12353 src.unpipe(dest);
12354 }
12355
12356 // tell the dest that it's being piped to
12357 dest.emit('pipe', src);
12358
12359 // start the flow if it hasn't been started already.
12360 if (!state.flowing) {
12361 debug('pipe resume');
12362 src.resume();
12363 }
12364
12365 return dest;
12366};
12367
12368function pipeOnDrain(src) {
12369 return function() {
12370 var state = src._readableState;
12371 debug('pipeOnDrain', state.awaitDrain);
12372 if (state.awaitDrain)
12373 state.awaitDrain--;
12374 if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
12375 state.flowing = true;
12376 flow(src);
12377 }
12378 };
12379}
12380
12381
12382Readable.prototype.unpipe = function(dest) {
12383 var state = this._readableState;
12384
12385 // if we're not piping anywhere, then do nothing.
12386 if (state.pipesCount === 0)
12387 return this;
12388
12389 // just one destination. most common case.
12390 if (state.pipesCount === 1) {
12391 // passed in one, but it's not the right one.
12392 if (dest && dest !== state.pipes)
12393 return this;
12394
12395 if (!dest)
12396 dest = state.pipes;
12397
12398 // got a match.
12399 state.pipes = null;
12400 state.pipesCount = 0;
12401 state.flowing = false;
12402 if (dest)
12403 dest.emit('unpipe', this);
12404 return this;
12405 }
12406
12407 // slow case. multiple pipe destinations.
12408
12409 if (!dest) {
12410 // remove all.
12411 var dests = state.pipes;
12412 var len = state.pipesCount;
12413 state.pipes = null;
12414 state.pipesCount = 0;
12415 state.flowing = false;
12416
12417 for (var i = 0; i < len; i++)
12418 dests[i].emit('unpipe', this);
12419 return this;
12420 }
12421
12422 // try to find the right one.
12423 var i = indexOf(state.pipes, dest);
12424 if (i === -1)
12425 return this;
12426
12427 state.pipes.splice(i, 1);
12428 state.pipesCount -= 1;
12429 if (state.pipesCount === 1)
12430 state.pipes = state.pipes[0];
12431
12432 dest.emit('unpipe', this);
12433
12434 return this;
12435};
12436
12437// set up data events if they are asked for
12438// Ensure readable listeners eventually get something
12439Readable.prototype.on = function(ev, fn) {
12440 var res = Stream.prototype.on.call(this, ev, fn);
12441
12442 // If listening to data, and it has not explicitly been paused,
12443 // then call resume to start the flow of data on the next tick.
12444 if (ev === 'data' && false !== this._readableState.flowing) {
12445 this.resume();
12446 }
12447
12448 if (ev === 'readable' && this.readable) {
12449 var state = this._readableState;
12450 if (!state.readableListening) {
12451 state.readableListening = true;
12452 state.emittedReadable = false;
12453 state.needReadable = true;
12454 if (!state.reading) {
12455 var self = this;
12456 process.nextTick(function() {
12457 debug('readable nexttick read 0');
12458 self.read(0);
12459 });
12460 } else if (state.length) {
12461 emitReadable(this, state);
12462 }
12463 }
12464 }
12465
12466 return res;
12467};
12468Readable.prototype.addListener = Readable.prototype.on;
12469
12470// pause() and resume() are remnants of the legacy readable stream API
12471// If the user uses them, then switch into old mode.
12472Readable.prototype.resume = function() {
12473 var state = this._readableState;
12474 if (!state.flowing) {
12475 debug('resume');
12476 state.flowing = true;
12477 if (!state.reading) {
12478 debug('resume read 0');
12479 this.read(0);
12480 }
12481 resume(this, state);
12482 }
12483 return this;
12484};
12485
12486function resume(stream, state) {
12487 if (!state.resumeScheduled) {
12488 state.resumeScheduled = true;
12489 process.nextTick(function() {
12490 resume_(stream, state);
12491 });
12492 }
12493}
12494
12495function resume_(stream, state) {
12496 state.resumeScheduled = false;
12497 stream.emit('resume');
12498 flow(stream);
12499 if (state.flowing && !state.reading)
12500 stream.read(0);
12501}
12502
12503Readable.prototype.pause = function() {
12504 debug('call pause flowing=%j', this._readableState.flowing);
12505 if (false !== this._readableState.flowing) {
12506 debug('pause');
12507 this._readableState.flowing = false;
12508 this.emit('pause');
12509 }
12510 return this;
12511};
12512
12513function flow(stream) {
12514 var state = stream._readableState;
12515 debug('flow', state.flowing);
12516 if (state.flowing) {
12517 do {
12518 var chunk = stream.read();
12519 } while (null !== chunk && state.flowing);
12520 }
12521}
12522
12523// wrap an old-style stream as the async data source.
12524// This is *not* part of the readable stream interface.
12525// It is an ugly unfortunate mess of history.
12526Readable.prototype.wrap = function(stream) {
12527 var state = this._readableState;
12528 var paused = false;
12529
12530 var self = this;
12531 stream.on('end', function() {
12532 debug('wrapped end');
12533 if (state.decoder && !state.ended) {
12534 var chunk = state.decoder.end();
12535 if (chunk && chunk.length)
12536 self.push(chunk);
12537 }
12538
12539 self.push(null);
12540 });
12541
12542 stream.on('data', function(chunk) {
12543 debug('wrapped data');
12544 if (state.decoder)
12545 chunk = state.decoder.write(chunk);
12546 if (!chunk || !state.objectMode && !chunk.length)
12547 return;
12548
12549 var ret = self.push(chunk);
12550 if (!ret) {
12551 paused = true;
12552 stream.pause();
12553 }
12554 });
12555
12556 // proxy all the other methods.
12557 // important when wrapping filters and duplexes.
12558 for (var i in stream) {
12559 if (util.isFunction(stream[i]) && util.isUndefined(this[i])) {
12560 this[i] = function(method) { return function() {
12561 return stream[method].apply(stream, arguments);
12562 }}(i);
12563 }
12564 }
12565
12566 // proxy certain important events.
12567 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
12568 forEach(events, function(ev) {
12569 stream.on(ev, self.emit.bind(self, ev));
12570 });
12571
12572 // when we try to consume some more bytes, simply unpause the
12573 // underlying stream.
12574 self._read = function(n) {
12575 debug('wrapped _read', n);
12576 if (paused) {
12577 paused = false;
12578 stream.resume();
12579 }
12580 };
12581
12582 return self;
12583};
12584
12585
12586
12587// exposed for testing purposes only.
12588Readable._fromList = fromList;
12589
12590// Pluck off n bytes from an array of buffers.
12591// Length is the combined lengths of all the buffers in the list.
12592function fromList(n, state) {
12593 var list = state.buffer;
12594 var length = state.length;
12595 var stringMode = !!state.decoder;
12596 var objectMode = !!state.objectMode;
12597 var ret;
12598
12599 // nothing in the list, definitely empty.
12600 if (list.length === 0)
12601 return null;
12602
12603 if (length === 0)
12604 ret = null;
12605 else if (objectMode)
12606 ret = list.shift();
12607 else if (!n || n >= length) {
12608 // read it all, truncate the array.
12609 if (stringMode)
12610 ret = list.join('');
12611 else
12612 ret = Buffer.concat(list, length);
12613 list.length = 0;
12614 } else {
12615 // read just some of it.
12616 if (n < list[0].length) {
12617 // just take a part of the first list item.
12618 // slice is the same for buffers and strings.
12619 var buf = list[0];
12620 ret = buf.slice(0, n);
12621 list[0] = buf.slice(n);
12622 } else if (n === list[0].length) {
12623 // first list is a perfect match
12624 ret = list.shift();
12625 } else {
12626 // complex case.
12627 // we have enough to cover it, but it spans past the first buffer.
12628 if (stringMode)
12629 ret = '';
12630 else
12631 ret = new Buffer(n);
12632
12633 var c = 0;
12634 for (var i = 0, l = list.length; i < l && c < n; i++) {
12635 var buf = list[0];
12636 var cpy = Math.min(n - c, buf.length);
12637
12638 if (stringMode)
12639 ret += buf.slice(0, cpy);
12640 else
12641 buf.copy(ret, c, 0, cpy);
12642
12643 if (cpy < buf.length)
12644 list[0] = buf.slice(cpy);
12645 else
12646 list.shift();
12647
12648 c += cpy;
12649 }
12650 }
12651 }
12652
12653 return ret;
12654}
12655
12656function endReadable(stream) {
12657 var state = stream._readableState;
12658
12659 // If we get here before consuming all the bytes, then that is a
12660 // bug in node. Should never happen.
12661 if (state.length > 0)
12662 throw new Error('endReadable called on non-empty stream');
12663
12664 if (!state.endEmitted) {
12665 state.ended = true;
12666 process.nextTick(function() {
12667 // Check that we didn't get one last unshift.
12668 if (!state.endEmitted && state.length === 0) {
12669 state.endEmitted = true;
12670 stream.readable = false;
12671 stream.emit('end');
12672 }
12673 });
12674 }
12675}
12676
12677function forEach (xs, f) {
12678 for (var i = 0, l = xs.length; i < l; i++) {
12679 f(xs[i], i);
12680 }
12681}
12682
12683function indexOf (xs, x) {
12684 for (var i = 0, l = xs.length; i < l; i++) {
12685 if (xs[i] === x) return i;
12686 }
12687 return -1;
12688}
12689
12690}).call(this)}).call(this,_dereq_(66))
12691},{"20":20,"29":29,"6":6,"66":66,"68":68,"73":73,"74":74,"78":78,"8":8,"9":9}],71:[function(_dereq_,module,exports){
12692// Copyright Joyent, Inc. and other Node contributors.
12693//
12694// Permission is hereby granted, free of charge, to any person obtaining a
12695// copy of this software and associated documentation files (the
12696// "Software"), to deal in the Software without restriction, including
12697// without limitation the rights to use, copy, modify, merge, publish,
12698// distribute, sublicense, and/or sell copies of the Software, and to permit
12699// persons to whom the Software is furnished to do so, subject to the
12700// following conditions:
12701//
12702// The above copyright notice and this permission notice shall be included
12703// in all copies or substantial portions of the Software.
12704//
12705// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12706// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12707// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12708// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12709// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12710// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12711// USE OR OTHER DEALINGS IN THE SOFTWARE.
12712
12713
12714// a transform stream is a readable/writable stream where you do
12715// something with the data. Sometimes it's called a "filter",
12716// but that's not a great name for it, since that implies a thing where
12717// some bits pass through, and others are simply ignored. (That would
12718// be a valid example of a transform, of course.)
12719//
12720// While the output is causally related to the input, it's not a
12721// necessarily symmetric or synchronous transformation. For example,
12722// a zlib stream might take multiple plain-text writes(), and then
12723// emit a single compressed chunk some time in the future.
12724//
12725// Here's how this works:
12726//
12727// The Transform stream has all the aspects of the readable and writable
12728// stream classes. When you write(chunk), that calls _write(chunk,cb)
12729// internally, and returns false if there's a lot of pending writes
12730// buffered up. When you call read(), that calls _read(n) until
12731// there's enough pending readable data buffered up.
12732//
12733// In a transform stream, the written data is placed in a buffer. When
12734// _read(n) is called, it transforms the queued up data, calling the
12735// buffered _write cb's as it consumes chunks. If consuming a single
12736// written chunk would result in multiple output chunks, then the first
12737// outputted bit calls the readcb, and subsequent chunks just go into
12738// the read buffer, and will cause it to emit 'readable' if necessary.
12739//
12740// This way, back-pressure is actually determined by the reading side,
12741// since _read has to be called to start processing a new chunk. However,
12742// a pathological inflate type of transform can cause excessive buffering
12743// here. For example, imagine a stream where every byte of input is
12744// interpreted as an integer from 0-255, and then results in that many
12745// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
12746// 1kb of data being output. In this case, you could write a very small
12747// amount of input, and end up with a very large amount of output. In
12748// such a pathological inflating mechanism, there'd be no way to tell
12749// the system to stop doing the transform. A single 4MB write could
12750// cause the system to run out of memory.
12751//
12752// However, even in such a pathological case, only a single written chunk
12753// would be consumed, and then the rest would wait (un-transformed) until
12754// the results of the previous transformed chunk were consumed.
12755
12756module.exports = Transform;
12757
12758var Duplex = _dereq_(68);
12759
12760/*<replacement>*/
12761var util = _dereq_(9);
12762util.inherits = _dereq_(29);
12763/*</replacement>*/
12764
12765util.inherits(Transform, Duplex);
12766
12767
12768function TransformState(options, stream) {
12769 this.afterTransform = function(er, data) {
12770 return afterTransform(stream, er, data);
12771 };
12772
12773 this.needTransform = false;
12774 this.transforming = false;
12775 this.writecb = null;
12776 this.writechunk = null;
12777}
12778
12779function afterTransform(stream, er, data) {
12780 var ts = stream._transformState;
12781 ts.transforming = false;
12782
12783 var cb = ts.writecb;
12784
12785 if (!cb)
12786 return stream.emit('error', new Error('no writecb in Transform class'));
12787
12788 ts.writechunk = null;
12789 ts.writecb = null;
12790
12791 if (!util.isNullOrUndefined(data))
12792 stream.push(data);
12793
12794 if (cb)
12795 cb(er);
12796
12797 var rs = stream._readableState;
12798 rs.reading = false;
12799 if (rs.needReadable || rs.length < rs.highWaterMark) {
12800 stream._read(rs.highWaterMark);
12801 }
12802}
12803
12804
12805function Transform(options) {
12806 if (!(this instanceof Transform))
12807 return new Transform(options);
12808
12809 Duplex.call(this, options);
12810
12811 this._transformState = new TransformState(options, this);
12812
12813 // when the writable side finishes, then flush out anything remaining.
12814 var stream = this;
12815
12816 // start out asking for a readable event once data is transformed.
12817 this._readableState.needReadable = true;
12818
12819 // we have implemented the _read method, and done the other things
12820 // that Readable wants before the first _read call, so unset the
12821 // sync guard flag.
12822 this._readableState.sync = false;
12823
12824 this.once('prefinish', function() {
12825 if (util.isFunction(this._flush))
12826 this._flush(function(er) {
12827 done(stream, er);
12828 });
12829 else
12830 done(stream);
12831 });
12832}
12833
12834Transform.prototype.push = function(chunk, encoding) {
12835 this._transformState.needTransform = false;
12836 return Duplex.prototype.push.call(this, chunk, encoding);
12837};
12838
12839// This is the part where you do stuff!
12840// override this function in implementation classes.
12841// 'chunk' is an input chunk.
12842//
12843// Call `push(newChunk)` to pass along transformed output
12844// to the readable side. You may call 'push' zero or more times.
12845//
12846// Call `cb(err)` when you are done with this chunk. If you pass
12847// an error, then that'll put the hurt on the whole operation. If you
12848// never call cb(), then you'll never get another chunk.
12849Transform.prototype._transform = function(chunk, encoding, cb) {
12850 throw new Error('not implemented');
12851};
12852
12853Transform.prototype._write = function(chunk, encoding, cb) {
12854 var ts = this._transformState;
12855 ts.writecb = cb;
12856 ts.writechunk = chunk;
12857 ts.writeencoding = encoding;
12858 if (!ts.transforming) {
12859 var rs = this._readableState;
12860 if (ts.needTransform ||
12861 rs.needReadable ||
12862 rs.length < rs.highWaterMark)
12863 this._read(rs.highWaterMark);
12864 }
12865};
12866
12867// Doesn't matter what the args are here.
12868// _transform does all the work.
12869// That we got here means that the readable side wants more data.
12870Transform.prototype._read = function(n) {
12871 var ts = this._transformState;
12872
12873 if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) {
12874 ts.transforming = true;
12875 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
12876 } else {
12877 // mark that we need a transform, so that any data that comes in
12878 // will get processed, now that we've asked for it.
12879 ts.needTransform = true;
12880 }
12881};
12882
12883
12884function done(stream, er) {
12885 if (er)
12886 return stream.emit('error', er);
12887
12888 // if there's nothing in the write buffer, then that means
12889 // that nothing more will ever be provided
12890 var ws = stream._writableState;
12891 var ts = stream._transformState;
12892
12893 if (ws.length)
12894 throw new Error('calling transform done when ws.length != 0');
12895
12896 if (ts.transforming)
12897 throw new Error('calling transform done when still transforming');
12898
12899 return stream.push(null);
12900}
12901
12902},{"29":29,"68":68,"9":9}],72:[function(_dereq_,module,exports){
12903(function (process){(function (){
12904// Copyright Joyent, Inc. and other Node contributors.
12905//
12906// Permission is hereby granted, free of charge, to any person obtaining a
12907// copy of this software and associated documentation files (the
12908// "Software"), to deal in the Software without restriction, including
12909// without limitation the rights to use, copy, modify, merge, publish,
12910// distribute, sublicense, and/or sell copies of the Software, and to permit
12911// persons to whom the Software is furnished to do so, subject to the
12912// following conditions:
12913//
12914// The above copyright notice and this permission notice shall be included
12915// in all copies or substantial portions of the Software.
12916//
12917// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12918// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12919// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12920// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12921// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12922// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12923// USE OR OTHER DEALINGS IN THE SOFTWARE.
12924
12925// A bit simpler than readable streams.
12926// Implement an async ._write(chunk, cb), and it'll handle all
12927// the drain event emission and buffering.
12928
12929module.exports = Writable;
12930
12931/*<replacement>*/
12932var Buffer = _dereq_(8).Buffer;
12933/*</replacement>*/
12934
12935Writable.WritableState = WritableState;
12936
12937
12938/*<replacement>*/
12939var util = _dereq_(9);
12940util.inherits = _dereq_(29);
12941/*</replacement>*/
12942
12943var Stream = _dereq_(78);
12944
12945util.inherits(Writable, Stream);
12946
12947function WriteReq(chunk, encoding, cb) {
12948 this.chunk = chunk;
12949 this.encoding = encoding;
12950 this.callback = cb;
12951}
12952
12953function WritableState(options, stream) {
12954 var Duplex = _dereq_(68);
12955
12956 options = options || {};
12957
12958 // the point at which write() starts returning false
12959 // Note: 0 is a valid value, means that we always return false if
12960 // the entire buffer is not flushed immediately on write()
12961 var hwm = options.highWaterMark;
12962 var defaultHwm = options.objectMode ? 16 : 16 * 1024;
12963 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
12964
12965 // object stream flag to indicate whether or not this stream
12966 // contains buffers or objects.
12967 this.objectMode = !!options.objectMode;
12968
12969 if (stream instanceof Duplex)
12970 this.objectMode = this.objectMode || !!options.writableObjectMode;
12971
12972 // cast to ints.
12973 this.highWaterMark = ~~this.highWaterMark;
12974
12975 this.needDrain = false;
12976 // at the start of calling end()
12977 this.ending = false;
12978 // when end() has been called, and returned
12979 this.ended = false;
12980 // when 'finish' is emitted
12981 this.finished = false;
12982
12983 // should we decode strings into buffers before passing to _write?
12984 // this is here so that some node-core streams can optimize string
12985 // handling at a lower level.
12986 var noDecode = options.decodeStrings === false;
12987 this.decodeStrings = !noDecode;
12988
12989 // Crypto is kind of old and crusty. Historically, its default string
12990 // encoding is 'binary' so we have to make this configurable.
12991 // Everything else in the universe uses 'utf8', though.
12992 this.defaultEncoding = options.defaultEncoding || 'utf8';
12993
12994 // not an actual buffer we keep track of, but a measurement
12995 // of how much we're waiting to get pushed to some underlying
12996 // socket or file.
12997 this.length = 0;
12998
12999 // a flag to see when we're in the middle of a write.
13000 this.writing = false;
13001
13002 // when true all writes will be buffered until .uncork() call
13003 this.corked = 0;
13004
13005 // a flag to be able to tell if the onwrite cb is called immediately,
13006 // or on a later tick. We set this to true at first, because any
13007 // actions that shouldn't happen until "later" should generally also
13008 // not happen before the first write call.
13009 this.sync = true;
13010
13011 // a flag to know if we're processing previously buffered items, which
13012 // may call the _write() callback in the same tick, so that we don't
13013 // end up in an overlapped onwrite situation.
13014 this.bufferProcessing = false;
13015
13016 // the callback that's passed to _write(chunk,cb)
13017 this.onwrite = function(er) {
13018 onwrite(stream, er);
13019 };
13020
13021 // the callback that the user supplies to write(chunk,encoding,cb)
13022 this.writecb = null;
13023
13024 // the amount that is being written when _write is called.
13025 this.writelen = 0;
13026
13027 this.buffer = [];
13028
13029 // number of pending user-supplied write callbacks
13030 // this must be 0 before 'finish' can be emitted
13031 this.pendingcb = 0;
13032
13033 // emit prefinish if the only thing we're waiting for is _write cbs
13034 // This is relevant for synchronous Transform streams
13035 this.prefinished = false;
13036
13037 // True if the error was already emitted and should not be thrown again
13038 this.errorEmitted = false;
13039}
13040
13041function Writable(options) {
13042 var Duplex = _dereq_(68);
13043
13044 // Writable ctor is applied to Duplexes, though they're not
13045 // instanceof Writable, they're instanceof Readable.
13046 if (!(this instanceof Writable) && !(this instanceof Duplex))
13047 return new Writable(options);
13048
13049 this._writableState = new WritableState(options, this);
13050
13051 // legacy.
13052 this.writable = true;
13053
13054 Stream.call(this);
13055}
13056
13057// Otherwise people can pipe Writable streams, which is just wrong.
13058Writable.prototype.pipe = function() {
13059 this.emit('error', new Error('Cannot pipe. Not readable.'));
13060};
13061
13062
13063function writeAfterEnd(stream, state, cb) {
13064 var er = new Error('write after end');
13065 // TODO: defer error events consistently everywhere, not just the cb
13066 stream.emit('error', er);
13067 process.nextTick(function() {
13068 cb(er);
13069 });
13070}
13071
13072// If we get something that is not a buffer, string, null, or undefined,
13073// and we're not in objectMode, then that's an error.
13074// Otherwise stream chunks are all considered to be of length=1, and the
13075// watermarks determine how many objects to keep in the buffer, rather than
13076// how many bytes or characters.
13077function validChunk(stream, state, chunk, cb) {
13078 var valid = true;
13079 if (!util.isBuffer(chunk) &&
13080 !util.isString(chunk) &&
13081 !util.isNullOrUndefined(chunk) &&
13082 !state.objectMode) {
13083 var er = new TypeError('Invalid non-string/buffer chunk');
13084 stream.emit('error', er);
13085 process.nextTick(function() {
13086 cb(er);
13087 });
13088 valid = false;
13089 }
13090 return valid;
13091}
13092
13093Writable.prototype.write = function(chunk, encoding, cb) {
13094 var state = this._writableState;
13095 var ret = false;
13096
13097 if (util.isFunction(encoding)) {
13098 cb = encoding;
13099 encoding = null;
13100 }
13101
13102 if (util.isBuffer(chunk))
13103 encoding = 'buffer';
13104 else if (!encoding)
13105 encoding = state.defaultEncoding;
13106
13107 if (!util.isFunction(cb))
13108 cb = function() {};
13109
13110 if (state.ended)
13111 writeAfterEnd(this, state, cb);
13112 else if (validChunk(this, state, chunk, cb)) {
13113 state.pendingcb++;
13114 ret = writeOrBuffer(this, state, chunk, encoding, cb);
13115 }
13116
13117 return ret;
13118};
13119
13120Writable.prototype.cork = function() {
13121 var state = this._writableState;
13122
13123 state.corked++;
13124};
13125
13126Writable.prototype.uncork = function() {
13127 var state = this._writableState;
13128
13129 if (state.corked) {
13130 state.corked--;
13131
13132 if (!state.writing &&
13133 !state.corked &&
13134 !state.finished &&
13135 !state.bufferProcessing &&
13136 state.buffer.length)
13137 clearBuffer(this, state);
13138 }
13139};
13140
13141function decodeChunk(state, chunk, encoding) {
13142 if (!state.objectMode &&
13143 state.decodeStrings !== false &&
13144 util.isString(chunk)) {
13145 chunk = new Buffer(chunk, encoding);
13146 }
13147 return chunk;
13148}
13149
13150// if we're already writing something, then just put this
13151// in the queue, and wait our turn. Otherwise, call _write
13152// If we return false, then we need a drain event, so set that flag.
13153function writeOrBuffer(stream, state, chunk, encoding, cb) {
13154 chunk = decodeChunk(state, chunk, encoding);
13155 if (util.isBuffer(chunk))
13156 encoding = 'buffer';
13157 var len = state.objectMode ? 1 : chunk.length;
13158
13159 state.length += len;
13160
13161 var ret = state.length < state.highWaterMark;
13162 // we must ensure that previous needDrain will not be reset to false.
13163 if (!ret)
13164 state.needDrain = true;
13165
13166 if (state.writing || state.corked)
13167 state.buffer.push(new WriteReq(chunk, encoding, cb));
13168 else
13169 doWrite(stream, state, false, len, chunk, encoding, cb);
13170
13171 return ret;
13172}
13173
13174function doWrite(stream, state, writev, len, chunk, encoding, cb) {
13175 state.writelen = len;
13176 state.writecb = cb;
13177 state.writing = true;
13178 state.sync = true;
13179 if (writev)
13180 stream._writev(chunk, state.onwrite);
13181 else
13182 stream._write(chunk, encoding, state.onwrite);
13183 state.sync = false;
13184}
13185
13186function onwriteError(stream, state, sync, er, cb) {
13187 if (sync)
13188 process.nextTick(function() {
13189 state.pendingcb--;
13190 cb(er);
13191 });
13192 else {
13193 state.pendingcb--;
13194 cb(er);
13195 }
13196
13197 stream._writableState.errorEmitted = true;
13198 stream.emit('error', er);
13199}
13200
13201function onwriteStateUpdate(state) {
13202 state.writing = false;
13203 state.writecb = null;
13204 state.length -= state.writelen;
13205 state.writelen = 0;
13206}
13207
13208function onwrite(stream, er) {
13209 var state = stream._writableState;
13210 var sync = state.sync;
13211 var cb = state.writecb;
13212
13213 onwriteStateUpdate(state);
13214
13215 if (er)
13216 onwriteError(stream, state, sync, er, cb);
13217 else {
13218 // Check if we're actually ready to finish, but don't emit yet
13219 var finished = needFinish(stream, state);
13220
13221 if (!finished &&
13222 !state.corked &&
13223 !state.bufferProcessing &&
13224 state.buffer.length) {
13225 clearBuffer(stream, state);
13226 }
13227
13228 if (sync) {
13229 process.nextTick(function() {
13230 afterWrite(stream, state, finished, cb);
13231 });
13232 } else {
13233 afterWrite(stream, state, finished, cb);
13234 }
13235 }
13236}
13237
13238function afterWrite(stream, state, finished, cb) {
13239 if (!finished)
13240 onwriteDrain(stream, state);
13241 state.pendingcb--;
13242 cb();
13243 finishMaybe(stream, state);
13244}
13245
13246// Must force callback to be called on nextTick, so that we don't
13247// emit 'drain' before the write() consumer gets the 'false' return
13248// value, and has a chance to attach a 'drain' listener.
13249function onwriteDrain(stream, state) {
13250 if (state.length === 0 && state.needDrain) {
13251 state.needDrain = false;
13252 stream.emit('drain');
13253 }
13254}
13255
13256
13257// if there's something in the buffer waiting, then process it
13258function clearBuffer(stream, state) {
13259 state.bufferProcessing = true;
13260
13261 if (stream._writev && state.buffer.length > 1) {
13262 // Fast case, write everything using _writev()
13263 var cbs = [];
13264 for (var c = 0; c < state.buffer.length; c++)
13265 cbs.push(state.buffer[c].callback);
13266
13267 // count the one we are adding, as well.
13268 // TODO(isaacs) clean this up
13269 state.pendingcb++;
13270 doWrite(stream, state, true, state.length, state.buffer, '', function(err) {
13271 for (var i = 0; i < cbs.length; i++) {
13272 state.pendingcb--;
13273 cbs[i](err);
13274 }
13275 });
13276
13277 // Clear buffer
13278 state.buffer = [];
13279 } else {
13280 // Slow case, write chunks one-by-one
13281 for (var c = 0; c < state.buffer.length; c++) {
13282 var entry = state.buffer[c];
13283 var chunk = entry.chunk;
13284 var encoding = entry.encoding;
13285 var cb = entry.callback;
13286 var len = state.objectMode ? 1 : chunk.length;
13287
13288 doWrite(stream, state, false, len, chunk, encoding, cb);
13289
13290 // if we didn't call the onwrite immediately, then
13291 // it means that we need to wait until it does.
13292 // also, that means that the chunk and cb are currently
13293 // being processed, so move the buffer counter past them.
13294 if (state.writing) {
13295 c++;
13296 break;
13297 }
13298 }
13299
13300 if (c < state.buffer.length)
13301 state.buffer = state.buffer.slice(c);
13302 else
13303 state.buffer.length = 0;
13304 }
13305
13306 state.bufferProcessing = false;
13307}
13308
13309Writable.prototype._write = function(chunk, encoding, cb) {
13310 cb(new Error('not implemented'));
13311
13312};
13313
13314Writable.prototype._writev = null;
13315
13316Writable.prototype.end = function(chunk, encoding, cb) {
13317 var state = this._writableState;
13318
13319 if (util.isFunction(chunk)) {
13320 cb = chunk;
13321 chunk = null;
13322 encoding = null;
13323 } else if (util.isFunction(encoding)) {
13324 cb = encoding;
13325 encoding = null;
13326 }
13327
13328 if (!util.isNullOrUndefined(chunk))
13329 this.write(chunk, encoding);
13330
13331 // .end() fully uncorks
13332 if (state.corked) {
13333 state.corked = 1;
13334 this.uncork();
13335 }
13336
13337 // ignore unnecessary end() calls.
13338 if (!state.ending && !state.finished)
13339 endWritable(this, state, cb);
13340};
13341
13342
13343function needFinish(stream, state) {
13344 return (state.ending &&
13345 state.length === 0 &&
13346 !state.finished &&
13347 !state.writing);
13348}
13349
13350function prefinish(stream, state) {
13351 if (!state.prefinished) {
13352 state.prefinished = true;
13353 stream.emit('prefinish');
13354 }
13355}
13356
13357function finishMaybe(stream, state) {
13358 var need = needFinish(stream, state);
13359 if (need) {
13360 if (state.pendingcb === 0) {
13361 prefinish(stream, state);
13362 state.finished = true;
13363 stream.emit('finish');
13364 } else
13365 prefinish(stream, state);
13366 }
13367 return need;
13368}
13369
13370function endWritable(stream, state, cb) {
13371 state.ending = true;
13372 finishMaybe(stream, state);
13373 if (cb) {
13374 if (state.finished)
13375 process.nextTick(cb);
13376 else
13377 stream.once('finish', cb);
13378 }
13379 state.ended = true;
13380}
13381
13382}).call(this)}).call(this,_dereq_(66))
13383},{"29":29,"66":66,"68":68,"78":78,"8":8,"9":9}],73:[function(_dereq_,module,exports){
13384module.exports = Array.isArray || function (arr) {
13385 return Object.prototype.toString.call(arr) == '[object Array]';
13386};
13387
13388},{}],74:[function(_dereq_,module,exports){
13389// Copyright Joyent, Inc. and other Node contributors.
13390//
13391// Permission is hereby granted, free of charge, to any person obtaining a
13392// copy of this software and associated documentation files (the
13393// "Software"), to deal in the Software without restriction, including
13394// without limitation the rights to use, copy, modify, merge, publish,
13395// distribute, sublicense, and/or sell copies of the Software, and to permit
13396// persons to whom the Software is furnished to do so, subject to the
13397// following conditions:
13398//
13399// The above copyright notice and this permission notice shall be included
13400// in all copies or substantial portions of the Software.
13401//
13402// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13403// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13404// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13405// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13406// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13407// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13408// USE OR OTHER DEALINGS IN THE SOFTWARE.
13409
13410var Buffer = _dereq_(8).Buffer;
13411
13412var isBufferEncoding = Buffer.isEncoding
13413 || function(encoding) {
13414 switch (encoding && encoding.toLowerCase()) {
13415 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;
13416 default: return false;
13417 }
13418 }
13419
13420
13421function assertEncoding(encoding) {
13422 if (encoding && !isBufferEncoding(encoding)) {
13423 throw new Error('Unknown encoding: ' + encoding);
13424 }
13425}
13426
13427// StringDecoder provides an interface for efficiently splitting a series of
13428// buffers into a series of JS strings without breaking apart multi-byte
13429// characters. CESU-8 is handled as part of the UTF-8 encoding.
13430//
13431// @TODO Handling all encodings inside a single object makes it very difficult
13432// to reason about this code, so it should be split up in the future.
13433// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
13434// points as used by CESU-8.
13435var StringDecoder = exports.StringDecoder = function(encoding) {
13436 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
13437 assertEncoding(encoding);
13438 switch (this.encoding) {
13439 case 'utf8':
13440 // CESU-8 represents each of Surrogate Pair by 3-bytes
13441 this.surrogateSize = 3;
13442 break;
13443 case 'ucs2':
13444 case 'utf16le':
13445 // UTF-16 represents each of Surrogate Pair by 2-bytes
13446 this.surrogateSize = 2;
13447 this.detectIncompleteChar = utf16DetectIncompleteChar;
13448 break;
13449 case 'base64':
13450 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
13451 this.surrogateSize = 3;
13452 this.detectIncompleteChar = base64DetectIncompleteChar;
13453 break;
13454 default:
13455 this.write = passThroughWrite;
13456 return;
13457 }
13458
13459 // Enough space to store all bytes of a single character. UTF-8 needs 4
13460 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
13461 this.charBuffer = new Buffer(6);
13462 // Number of bytes received for the current incomplete multi-byte character.
13463 this.charReceived = 0;
13464 // Number of bytes expected for the current incomplete multi-byte character.
13465 this.charLength = 0;
13466};
13467
13468
13469// write decodes the given buffer and returns it as JS string that is
13470// guaranteed to not contain any partial multi-byte characters. Any partial
13471// character found at the end of the buffer is buffered up, and will be
13472// returned when calling write again with the remaining bytes.
13473//
13474// Note: Converting a Buffer containing an orphan surrogate to a String
13475// currently works, but converting a String to a Buffer (via `new Buffer`, or
13476// Buffer#write) will replace incomplete surrogates with the unicode
13477// replacement character. See https://codereview.chromium.org/121173009/ .
13478StringDecoder.prototype.write = function(buffer) {
13479 var charStr = '';
13480 // if our last write ended with an incomplete multibyte character
13481 while (this.charLength) {
13482 // determine how many remaining bytes this buffer has to offer for this char
13483 var available = (buffer.length >= this.charLength - this.charReceived) ?
13484 this.charLength - this.charReceived :
13485 buffer.length;
13486
13487 // add the new bytes to the char buffer
13488 buffer.copy(this.charBuffer, this.charReceived, 0, available);
13489 this.charReceived += available;
13490
13491 if (this.charReceived < this.charLength) {
13492 // still not enough chars in this buffer? wait for more ...
13493 return '';
13494 }
13495
13496 // remove bytes belonging to the current character from the buffer
13497 buffer = buffer.slice(available, buffer.length);
13498
13499 // get the character that was split
13500 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
13501
13502 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
13503 var charCode = charStr.charCodeAt(charStr.length - 1);
13504 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
13505 this.charLength += this.surrogateSize;
13506 charStr = '';
13507 continue;
13508 }
13509 this.charReceived = this.charLength = 0;
13510
13511 // if there are no more bytes in this buffer, just emit our char
13512 if (buffer.length === 0) {
13513 return charStr;
13514 }
13515 break;
13516 }
13517
13518 // determine and set charLength / charReceived
13519 this.detectIncompleteChar(buffer);
13520
13521 var end = buffer.length;
13522 if (this.charLength) {
13523 // buffer the incomplete character bytes we got
13524 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
13525 end -= this.charReceived;
13526 }
13527
13528 charStr += buffer.toString(this.encoding, 0, end);
13529
13530 var end = charStr.length - 1;
13531 var charCode = charStr.charCodeAt(end);
13532 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
13533 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
13534 var size = this.surrogateSize;
13535 this.charLength += size;
13536 this.charReceived += size;
13537 this.charBuffer.copy(this.charBuffer, size, 0, size);
13538 buffer.copy(this.charBuffer, 0, 0, size);
13539 return charStr.substring(0, end);
13540 }
13541
13542 // or just emit the charStr
13543 return charStr;
13544};
13545
13546// detectIncompleteChar determines if there is an incomplete UTF-8 character at
13547// the end of the given buffer. If so, it sets this.charLength to the byte
13548// length that character, and sets this.charReceived to the number of bytes
13549// that are available for this character.
13550StringDecoder.prototype.detectIncompleteChar = function(buffer) {
13551 // determine how many bytes we have to check at the end of this buffer
13552 var i = (buffer.length >= 3) ? 3 : buffer.length;
13553
13554 // Figure out if one of the last i bytes of our buffer announces an
13555 // incomplete char.
13556 for (; i > 0; i--) {
13557 var c = buffer[buffer.length - i];
13558
13559 // See http://en.wikipedia.org/wiki/UTF-8#Description
13560
13561 // 110XXXXX
13562 if (i == 1 && c >> 5 == 0x06) {
13563 this.charLength = 2;
13564 break;
13565 }
13566
13567 // 1110XXXX
13568 if (i <= 2 && c >> 4 == 0x0E) {
13569 this.charLength = 3;
13570 break;
13571 }
13572
13573 // 11110XXX
13574 if (i <= 3 && c >> 3 == 0x1E) {
13575 this.charLength = 4;
13576 break;
13577 }
13578 }
13579 this.charReceived = i;
13580};
13581
13582StringDecoder.prototype.end = function(buffer) {
13583 var res = '';
13584 if (buffer && buffer.length)
13585 res = this.write(buffer);
13586
13587 if (this.charReceived) {
13588 var cr = this.charReceived;
13589 var buf = this.charBuffer;
13590 var enc = this.encoding;
13591 res += buf.slice(0, cr).toString(enc);
13592 }
13593
13594 return res;
13595};
13596
13597function passThroughWrite(buffer) {
13598 return buffer.toString(this.encoding);
13599}
13600
13601function utf16DetectIncompleteChar(buffer) {
13602 this.charReceived = buffer.length % 2;
13603 this.charLength = this.charReceived ? 2 : 0;
13604}
13605
13606function base64DetectIncompleteChar(buffer) {
13607 this.charReceived = buffer.length % 3;
13608 this.charLength = this.charReceived ? 3 : 0;
13609}
13610
13611},{"8":8}],75:[function(_dereq_,module,exports){
13612(function (process){(function (){
13613exports = module.exports = _dereq_(70);
13614exports.Stream = _dereq_(78);
13615exports.Readable = exports;
13616exports.Writable = _dereq_(72);
13617exports.Duplex = _dereq_(68);
13618exports.Transform = _dereq_(71);
13619exports.PassThrough = _dereq_(69);
13620if (!process.browser && process.env.READABLE_STREAM === 'disable') {
13621 module.exports = _dereq_(78);
13622}
13623
13624}).call(this)}).call(this,_dereq_(66))
13625},{"66":66,"68":68,"69":69,"70":70,"71":71,"72":72,"78":78}],76:[function(_dereq_,module,exports){
13626/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
13627/* eslint-disable node/no-deprecated-api */
13628var buffer = _dereq_(8)
13629var Buffer = buffer.Buffer
13630
13631// alternative to using Object.keys for old browsers
13632function copyProps (src, dst) {
13633 for (var key in src) {
13634 dst[key] = src[key]
13635 }
13636}
13637if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
13638 module.exports = buffer
13639} else {
13640 // Copy properties from require('buffer')
13641 copyProps(buffer, exports)
13642 exports.Buffer = SafeBuffer
13643}
13644
13645function SafeBuffer (arg, encodingOrOffset, length) {
13646 return Buffer(arg, encodingOrOffset, length)
13647}
13648
13649SafeBuffer.prototype = Object.create(Buffer.prototype)
13650
13651// Copy static methods from Buffer
13652copyProps(Buffer, SafeBuffer)
13653
13654SafeBuffer.from = function (arg, encodingOrOffset, length) {
13655 if (typeof arg === 'number') {
13656 throw new TypeError('Argument must not be a number')
13657 }
13658 return Buffer(arg, encodingOrOffset, length)
13659}
13660
13661SafeBuffer.alloc = function (size, fill, encoding) {
13662 if (typeof size !== 'number') {
13663 throw new TypeError('Argument must be a number')
13664 }
13665 var buf = Buffer(size)
13666 if (fill !== undefined) {
13667 if (typeof encoding === 'string') {
13668 buf.fill(fill, encoding)
13669 } else {
13670 buf.fill(fill)
13671 }
13672 } else {
13673 buf.fill(0)
13674 }
13675 return buf
13676}
13677
13678SafeBuffer.allocUnsafe = function (size) {
13679 if (typeof size !== 'number') {
13680 throw new TypeError('Argument must be a number')
13681 }
13682 return Buffer(size)
13683}
13684
13685SafeBuffer.allocUnsafeSlow = function (size) {
13686 if (typeof size !== 'number') {
13687 throw new TypeError('Argument must be a number')
13688 }
13689 return buffer.SlowBuffer(size)
13690}
13691
13692},{"8":8}],77:[function(_dereq_,module,exports){
13693(function (factory) {
13694 if (typeof exports === 'object') {
13695 // Node/CommonJS
13696 module.exports = factory();
13697 } else if (typeof define === 'function' && define.amd) {
13698 // AMD
13699 define(factory);
13700 } else {
13701 // Browser globals (with support for web workers)
13702 var glob;
13703
13704 try {
13705 glob = window;
13706 } catch (e) {
13707 glob = self;
13708 }
13709
13710 glob.SparkMD5 = factory();
13711 }
13712}(function (undefined) {
13713
13714 'use strict';
13715
13716 /*
13717 * Fastest md5 implementation around (JKM md5).
13718 * Credits: Joseph Myers
13719 *
13720 * @see http://www.myersdaily.org/joseph/javascript/md5-text.html
13721 * @see http://jsperf.com/md5-shootout/7
13722 */
13723
13724 /* this function is much faster,
13725 so if possible we use it. Some IEs
13726 are the only ones I know of that
13727 need the idiotic second function,
13728 generated by an if clause. */
13729 var add32 = function (a, b) {
13730 return (a + b) & 0xFFFFFFFF;
13731 },
13732 hex_chr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
13733
13734
13735 function cmn(q, a, b, x, s, t) {
13736 a = add32(add32(a, q), add32(x, t));
13737 return add32((a << s) | (a >>> (32 - s)), b);
13738 }
13739
13740 function md5cycle(x, k) {
13741 var a = x[0],
13742 b = x[1],
13743 c = x[2],
13744 d = x[3];
13745
13746 a += (b & c | ~b & d) + k[0] - 680876936 | 0;
13747 a = (a << 7 | a >>> 25) + b | 0;
13748 d += (a & b | ~a & c) + k[1] - 389564586 | 0;
13749 d = (d << 12 | d >>> 20) + a | 0;
13750 c += (d & a | ~d & b) + k[2] + 606105819 | 0;
13751 c = (c << 17 | c >>> 15) + d | 0;
13752 b += (c & d | ~c & a) + k[3] - 1044525330 | 0;
13753 b = (b << 22 | b >>> 10) + c | 0;
13754 a += (b & c | ~b & d) + k[4] - 176418897 | 0;
13755 a = (a << 7 | a >>> 25) + b | 0;
13756 d += (a & b | ~a & c) + k[5] + 1200080426 | 0;
13757 d = (d << 12 | d >>> 20) + a | 0;
13758 c += (d & a | ~d & b) + k[6] - 1473231341 | 0;
13759 c = (c << 17 | c >>> 15) + d | 0;
13760 b += (c & d | ~c & a) + k[7] - 45705983 | 0;
13761 b = (b << 22 | b >>> 10) + c | 0;
13762 a += (b & c | ~b & d) + k[8] + 1770035416 | 0;
13763 a = (a << 7 | a >>> 25) + b | 0;
13764 d += (a & b | ~a & c) + k[9] - 1958414417 | 0;
13765 d = (d << 12 | d >>> 20) + a | 0;
13766 c += (d & a | ~d & b) + k[10] - 42063 | 0;
13767 c = (c << 17 | c >>> 15) + d | 0;
13768 b += (c & d | ~c & a) + k[11] - 1990404162 | 0;
13769 b = (b << 22 | b >>> 10) + c | 0;
13770 a += (b & c | ~b & d) + k[12] + 1804603682 | 0;
13771 a = (a << 7 | a >>> 25) + b | 0;
13772 d += (a & b | ~a & c) + k[13] - 40341101 | 0;
13773 d = (d << 12 | d >>> 20) + a | 0;
13774 c += (d & a | ~d & b) + k[14] - 1502002290 | 0;
13775 c = (c << 17 | c >>> 15) + d | 0;
13776 b += (c & d | ~c & a) + k[15] + 1236535329 | 0;
13777 b = (b << 22 | b >>> 10) + c | 0;
13778
13779 a += (b & d | c & ~d) + k[1] - 165796510 | 0;
13780 a = (a << 5 | a >>> 27) + b | 0;
13781 d += (a & c | b & ~c) + k[6] - 1069501632 | 0;
13782 d = (d << 9 | d >>> 23) + a | 0;
13783 c += (d & b | a & ~b) + k[11] + 643717713 | 0;
13784 c = (c << 14 | c >>> 18) + d | 0;
13785 b += (c & a | d & ~a) + k[0] - 373897302 | 0;
13786 b = (b << 20 | b >>> 12) + c | 0;
13787 a += (b & d | c & ~d) + k[5] - 701558691 | 0;
13788 a = (a << 5 | a >>> 27) + b | 0;
13789 d += (a & c | b & ~c) + k[10] + 38016083 | 0;
13790 d = (d << 9 | d >>> 23) + a | 0;
13791 c += (d & b | a & ~b) + k[15] - 660478335 | 0;
13792 c = (c << 14 | c >>> 18) + d | 0;
13793 b += (c & a | d & ~a) + k[4] - 405537848 | 0;
13794 b = (b << 20 | b >>> 12) + c | 0;
13795 a += (b & d | c & ~d) + k[9] + 568446438 | 0;
13796 a = (a << 5 | a >>> 27) + b | 0;
13797 d += (a & c | b & ~c) + k[14] - 1019803690 | 0;
13798 d = (d << 9 | d >>> 23) + a | 0;
13799 c += (d & b | a & ~b) + k[3] - 187363961 | 0;
13800 c = (c << 14 | c >>> 18) + d | 0;
13801 b += (c & a | d & ~a) + k[8] + 1163531501 | 0;
13802 b = (b << 20 | b >>> 12) + c | 0;
13803 a += (b & d | c & ~d) + k[13] - 1444681467 | 0;
13804 a = (a << 5 | a >>> 27) + b | 0;
13805 d += (a & c | b & ~c) + k[2] - 51403784 | 0;
13806 d = (d << 9 | d >>> 23) + a | 0;
13807 c += (d & b | a & ~b) + k[7] + 1735328473 | 0;
13808 c = (c << 14 | c >>> 18) + d | 0;
13809 b += (c & a | d & ~a) + k[12] - 1926607734 | 0;
13810 b = (b << 20 | b >>> 12) + c | 0;
13811
13812 a += (b ^ c ^ d) + k[5] - 378558 | 0;
13813 a = (a << 4 | a >>> 28) + b | 0;
13814 d += (a ^ b ^ c) + k[8] - 2022574463 | 0;
13815 d = (d << 11 | d >>> 21) + a | 0;
13816 c += (d ^ a ^ b) + k[11] + 1839030562 | 0;
13817 c = (c << 16 | c >>> 16) + d | 0;
13818 b += (c ^ d ^ a) + k[14] - 35309556 | 0;
13819 b = (b << 23 | b >>> 9) + c | 0;
13820 a += (b ^ c ^ d) + k[1] - 1530992060 | 0;
13821 a = (a << 4 | a >>> 28) + b | 0;
13822 d += (a ^ b ^ c) + k[4] + 1272893353 | 0;
13823 d = (d << 11 | d >>> 21) + a | 0;
13824 c += (d ^ a ^ b) + k[7] - 155497632 | 0;
13825 c = (c << 16 | c >>> 16) + d | 0;
13826 b += (c ^ d ^ a) + k[10] - 1094730640 | 0;
13827 b = (b << 23 | b >>> 9) + c | 0;
13828 a += (b ^ c ^ d) + k[13] + 681279174 | 0;
13829 a = (a << 4 | a >>> 28) + b | 0;
13830 d += (a ^ b ^ c) + k[0] - 358537222 | 0;
13831 d = (d << 11 | d >>> 21) + a | 0;
13832 c += (d ^ a ^ b) + k[3] - 722521979 | 0;
13833 c = (c << 16 | c >>> 16) + d | 0;
13834 b += (c ^ d ^ a) + k[6] + 76029189 | 0;
13835 b = (b << 23 | b >>> 9) + c | 0;
13836 a += (b ^ c ^ d) + k[9] - 640364487 | 0;
13837 a = (a << 4 | a >>> 28) + b | 0;
13838 d += (a ^ b ^ c) + k[12] - 421815835 | 0;
13839 d = (d << 11 | d >>> 21) + a | 0;
13840 c += (d ^ a ^ b) + k[15] + 530742520 | 0;
13841 c = (c << 16 | c >>> 16) + d | 0;
13842 b += (c ^ d ^ a) + k[2] - 995338651 | 0;
13843 b = (b << 23 | b >>> 9) + c | 0;
13844
13845 a += (c ^ (b | ~d)) + k[0] - 198630844 | 0;
13846 a = (a << 6 | a >>> 26) + b | 0;
13847 d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0;
13848 d = (d << 10 | d >>> 22) + a | 0;
13849 c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0;
13850 c = (c << 15 | c >>> 17) + d | 0;
13851 b += (d ^ (c | ~a)) + k[5] - 57434055 | 0;
13852 b = (b << 21 |b >>> 11) + c | 0;
13853 a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0;
13854 a = (a << 6 | a >>> 26) + b | 0;
13855 d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0;
13856 d = (d << 10 | d >>> 22) + a | 0;
13857 c += (a ^ (d | ~b)) + k[10] - 1051523 | 0;
13858 c = (c << 15 | c >>> 17) + d | 0;
13859 b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0;
13860 b = (b << 21 |b >>> 11) + c | 0;
13861 a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0;
13862 a = (a << 6 | a >>> 26) + b | 0;
13863 d += (b ^ (a | ~c)) + k[15] - 30611744 | 0;
13864 d = (d << 10 | d >>> 22) + a | 0;
13865 c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0;
13866 c = (c << 15 | c >>> 17) + d | 0;
13867 b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0;
13868 b = (b << 21 |b >>> 11) + c | 0;
13869 a += (c ^ (b | ~d)) + k[4] - 145523070 | 0;
13870 a = (a << 6 | a >>> 26) + b | 0;
13871 d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0;
13872 d = (d << 10 | d >>> 22) + a | 0;
13873 c += (a ^ (d | ~b)) + k[2] + 718787259 | 0;
13874 c = (c << 15 | c >>> 17) + d | 0;
13875 b += (d ^ (c | ~a)) + k[9] - 343485551 | 0;
13876 b = (b << 21 | b >>> 11) + c | 0;
13877
13878 x[0] = a + x[0] | 0;
13879 x[1] = b + x[1] | 0;
13880 x[2] = c + x[2] | 0;
13881 x[3] = d + x[3] | 0;
13882 }
13883
13884 function md5blk(s) {
13885 var md5blks = [],
13886 i; /* Andy King said do it this way. */
13887
13888 for (i = 0; i < 64; i += 4) {
13889 md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
13890 }
13891 return md5blks;
13892 }
13893
13894 function md5blk_array(a) {
13895 var md5blks = [],
13896 i; /* Andy King said do it this way. */
13897
13898 for (i = 0; i < 64; i += 4) {
13899 md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);
13900 }
13901 return md5blks;
13902 }
13903
13904 function md51(s) {
13905 var n = s.length,
13906 state = [1732584193, -271733879, -1732584194, 271733878],
13907 i,
13908 length,
13909 tail,
13910 tmp,
13911 lo,
13912 hi;
13913
13914 for (i = 64; i <= n; i += 64) {
13915 md5cycle(state, md5blk(s.substring(i - 64, i)));
13916 }
13917 s = s.substring(i - 64);
13918 length = s.length;
13919 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
13920 for (i = 0; i < length; i += 1) {
13921 tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
13922 }
13923 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13924 if (i > 55) {
13925 md5cycle(state, tail);
13926 for (i = 0; i < 16; i += 1) {
13927 tail[i] = 0;
13928 }
13929 }
13930
13931 // Beware that the final length might not fit in 32 bits so we take care of that
13932 tmp = n * 8;
13933 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
13934 lo = parseInt(tmp[2], 16);
13935 hi = parseInt(tmp[1], 16) || 0;
13936
13937 tail[14] = lo;
13938 tail[15] = hi;
13939
13940 md5cycle(state, tail);
13941 return state;
13942 }
13943
13944 function md51_array(a) {
13945 var n = a.length,
13946 state = [1732584193, -271733879, -1732584194, 271733878],
13947 i,
13948 length,
13949 tail,
13950 tmp,
13951 lo,
13952 hi;
13953
13954 for (i = 64; i <= n; i += 64) {
13955 md5cycle(state, md5blk_array(a.subarray(i - 64, i)));
13956 }
13957
13958 // Not sure if it is a bug, however IE10 will always produce a sub array of length 1
13959 // containing the last element of the parent array if the sub array specified starts
13960 // beyond the length of the parent array - weird.
13961 // https://connect.microsoft.com/IE/feedback/details/771452/typed-array-subarray-issue
13962 a = (i - 64) < n ? a.subarray(i - 64) : new Uint8Array(0);
13963
13964 length = a.length;
13965 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
13966 for (i = 0; i < length; i += 1) {
13967 tail[i >> 2] |= a[i] << ((i % 4) << 3);
13968 }
13969
13970 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13971 if (i > 55) {
13972 md5cycle(state, tail);
13973 for (i = 0; i < 16; i += 1) {
13974 tail[i] = 0;
13975 }
13976 }
13977
13978 // Beware that the final length might not fit in 32 bits so we take care of that
13979 tmp = n * 8;
13980 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
13981 lo = parseInt(tmp[2], 16);
13982 hi = parseInt(tmp[1], 16) || 0;
13983
13984 tail[14] = lo;
13985 tail[15] = hi;
13986
13987 md5cycle(state, tail);
13988
13989 return state;
13990 }
13991
13992 function rhex(n) {
13993 var s = '',
13994 j;
13995 for (j = 0; j < 4; j += 1) {
13996 s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
13997 }
13998 return s;
13999 }
14000
14001 function hex(x) {
14002 var i;
14003 for (i = 0; i < x.length; i += 1) {
14004 x[i] = rhex(x[i]);
14005 }
14006 return x.join('');
14007 }
14008
14009 // In some cases the fast add32 function cannot be used..
14010 if (hex(md51('hello')) !== '5d41402abc4b2a76b9719d911017c592') {
14011 add32 = function (x, y) {
14012 var lsw = (x & 0xFFFF) + (y & 0xFFFF),
14013 msw = (x >> 16) + (y >> 16) + (lsw >> 16);
14014 return (msw << 16) | (lsw & 0xFFFF);
14015 };
14016 }
14017
14018 // ---------------------------------------------------
14019
14020 /**
14021 * ArrayBuffer slice polyfill.
14022 *
14023 * @see https://github.com/ttaubert/node-arraybuffer-slice
14024 */
14025
14026 if (typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.prototype.slice) {
14027 (function () {
14028 function clamp(val, length) {
14029 val = (val | 0) || 0;
14030
14031 if (val < 0) {
14032 return Math.max(val + length, 0);
14033 }
14034
14035 return Math.min(val, length);
14036 }
14037
14038 ArrayBuffer.prototype.slice = function (from, to) {
14039 var length = this.byteLength,
14040 begin = clamp(from, length),
14041 end = length,
14042 num,
14043 target,
14044 targetArray,
14045 sourceArray;
14046
14047 if (to !== undefined) {
14048 end = clamp(to, length);
14049 }
14050
14051 if (begin > end) {
14052 return new ArrayBuffer(0);
14053 }
14054
14055 num = end - begin;
14056 target = new ArrayBuffer(num);
14057 targetArray = new Uint8Array(target);
14058
14059 sourceArray = new Uint8Array(this, begin, num);
14060 targetArray.set(sourceArray);
14061
14062 return target;
14063 };
14064 })();
14065 }
14066
14067 // ---------------------------------------------------
14068
14069 /**
14070 * Helpers.
14071 */
14072
14073 function toUtf8(str) {
14074 if (/[\u0080-\uFFFF]/.test(str)) {
14075 str = unescape(encodeURIComponent(str));
14076 }
14077
14078 return str;
14079 }
14080
14081 function utf8Str2ArrayBuffer(str, returnUInt8Array) {
14082 var length = str.length,
14083 buff = new ArrayBuffer(length),
14084 arr = new Uint8Array(buff),
14085 i;
14086
14087 for (i = 0; i < length; i += 1) {
14088 arr[i] = str.charCodeAt(i);
14089 }
14090
14091 return returnUInt8Array ? arr : buff;
14092 }
14093
14094 function arrayBuffer2Utf8Str(buff) {
14095 return String.fromCharCode.apply(null, new Uint8Array(buff));
14096 }
14097
14098 function concatenateArrayBuffers(first, second, returnUInt8Array) {
14099 var result = new Uint8Array(first.byteLength + second.byteLength);
14100
14101 result.set(new Uint8Array(first));
14102 result.set(new Uint8Array(second), first.byteLength);
14103
14104 return returnUInt8Array ? result : result.buffer;
14105 }
14106
14107 function hexToBinaryString(hex) {
14108 var bytes = [],
14109 length = hex.length,
14110 x;
14111
14112 for (x = 0; x < length - 1; x += 2) {
14113 bytes.push(parseInt(hex.substr(x, 2), 16));
14114 }
14115
14116 return String.fromCharCode.apply(String, bytes);
14117 }
14118
14119 // ---------------------------------------------------
14120
14121 /**
14122 * SparkMD5 OOP implementation.
14123 *
14124 * Use this class to perform an incremental md5, otherwise use the
14125 * static methods instead.
14126 */
14127
14128 function SparkMD5() {
14129 // call reset to init the instance
14130 this.reset();
14131 }
14132
14133 /**
14134 * Appends a string.
14135 * A conversion will be applied if an utf8 string is detected.
14136 *
14137 * @param {String} str The string to be appended
14138 *
14139 * @return {SparkMD5} The instance itself
14140 */
14141 SparkMD5.prototype.append = function (str) {
14142 // Converts the string to utf8 bytes if necessary
14143 // Then append as binary
14144 this.appendBinary(toUtf8(str));
14145
14146 return this;
14147 };
14148
14149 /**
14150 * Appends a binary string.
14151 *
14152 * @param {String} contents The binary string to be appended
14153 *
14154 * @return {SparkMD5} The instance itself
14155 */
14156 SparkMD5.prototype.appendBinary = function (contents) {
14157 this._buff += contents;
14158 this._length += contents.length;
14159
14160 var length = this._buff.length,
14161 i;
14162
14163 for (i = 64; i <= length; i += 64) {
14164 md5cycle(this._hash, md5blk(this._buff.substring(i - 64, i)));
14165 }
14166
14167 this._buff = this._buff.substring(i - 64);
14168
14169 return this;
14170 };
14171
14172 /**
14173 * Finishes the incremental computation, reseting the internal state and
14174 * returning the result.
14175 *
14176 * @param {Boolean} raw True to get the raw string, false to get the hex string
14177 *
14178 * @return {String} The result
14179 */
14180 SparkMD5.prototype.end = function (raw) {
14181 var buff = this._buff,
14182 length = buff.length,
14183 i,
14184 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
14185 ret;
14186
14187 for (i = 0; i < length; i += 1) {
14188 tail[i >> 2] |= buff.charCodeAt(i) << ((i % 4) << 3);
14189 }
14190
14191 this._finish(tail, length);
14192 ret = hex(this._hash);
14193
14194 if (raw) {
14195 ret = hexToBinaryString(ret);
14196 }
14197
14198 this.reset();
14199
14200 return ret;
14201 };
14202
14203 /**
14204 * Resets the internal state of the computation.
14205 *
14206 * @return {SparkMD5} The instance itself
14207 */
14208 SparkMD5.prototype.reset = function () {
14209 this._buff = '';
14210 this._length = 0;
14211 this._hash = [1732584193, -271733879, -1732584194, 271733878];
14212
14213 return this;
14214 };
14215
14216 /**
14217 * Gets the internal state of the computation.
14218 *
14219 * @return {Object} The state
14220 */
14221 SparkMD5.prototype.getState = function () {
14222 return {
14223 buff: this._buff,
14224 length: this._length,
14225 hash: this._hash.slice()
14226 };
14227 };
14228
14229 /**
14230 * Gets the internal state of the computation.
14231 *
14232 * @param {Object} state The state
14233 *
14234 * @return {SparkMD5} The instance itself
14235 */
14236 SparkMD5.prototype.setState = function (state) {
14237 this._buff = state.buff;
14238 this._length = state.length;
14239 this._hash = state.hash;
14240
14241 return this;
14242 };
14243
14244 /**
14245 * Releases memory used by the incremental buffer and other additional
14246 * resources. If you plan to use the instance again, use reset instead.
14247 */
14248 SparkMD5.prototype.destroy = function () {
14249 delete this._hash;
14250 delete this._buff;
14251 delete this._length;
14252 };
14253
14254 /**
14255 * Finish the final calculation based on the tail.
14256 *
14257 * @param {Array} tail The tail (will be modified)
14258 * @param {Number} length The length of the remaining buffer
14259 */
14260 SparkMD5.prototype._finish = function (tail, length) {
14261 var i = length,
14262 tmp,
14263 lo,
14264 hi;
14265
14266 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
14267 if (i > 55) {
14268 md5cycle(this._hash, tail);
14269 for (i = 0; i < 16; i += 1) {
14270 tail[i] = 0;
14271 }
14272 }
14273
14274 // Do the final computation based on the tail and length
14275 // Beware that the final length may not fit in 32 bits so we take care of that
14276 tmp = this._length * 8;
14277 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
14278 lo = parseInt(tmp[2], 16);
14279 hi = parseInt(tmp[1], 16) || 0;
14280
14281 tail[14] = lo;
14282 tail[15] = hi;
14283 md5cycle(this._hash, tail);
14284 };
14285
14286 /**
14287 * Performs the md5 hash on a string.
14288 * A conversion will be applied if utf8 string is detected.
14289 *
14290 * @param {String} str The string
14291 * @param {Boolean} [raw] True to get the raw string, false to get the hex string
14292 *
14293 * @return {String} The result
14294 */
14295 SparkMD5.hash = function (str, raw) {
14296 // Converts the string to utf8 bytes if necessary
14297 // Then compute it using the binary function
14298 return SparkMD5.hashBinary(toUtf8(str), raw);
14299 };
14300
14301 /**
14302 * Performs the md5 hash on a binary string.
14303 *
14304 * @param {String} content The binary string
14305 * @param {Boolean} [raw] True to get the raw string, false to get the hex string
14306 *
14307 * @return {String} The result
14308 */
14309 SparkMD5.hashBinary = function (content, raw) {
14310 var hash = md51(content),
14311 ret = hex(hash);
14312
14313 return raw ? hexToBinaryString(ret) : ret;
14314 };
14315
14316 // ---------------------------------------------------
14317
14318 /**
14319 * SparkMD5 OOP implementation for array buffers.
14320 *
14321 * Use this class to perform an incremental md5 ONLY for array buffers.
14322 */
14323 SparkMD5.ArrayBuffer = function () {
14324 // call reset to init the instance
14325 this.reset();
14326 };
14327
14328 /**
14329 * Appends an array buffer.
14330 *
14331 * @param {ArrayBuffer} arr The array to be appended
14332 *
14333 * @return {SparkMD5.ArrayBuffer} The instance itself
14334 */
14335 SparkMD5.ArrayBuffer.prototype.append = function (arr) {
14336 var buff = concatenateArrayBuffers(this._buff.buffer, arr, true),
14337 length = buff.length,
14338 i;
14339
14340 this._length += arr.byteLength;
14341
14342 for (i = 64; i <= length; i += 64) {
14343 md5cycle(this._hash, md5blk_array(buff.subarray(i - 64, i)));
14344 }
14345
14346 this._buff = (i - 64) < length ? new Uint8Array(buff.buffer.slice(i - 64)) : new Uint8Array(0);
14347
14348 return this;
14349 };
14350
14351 /**
14352 * Finishes the incremental computation, reseting the internal state and
14353 * returning the result.
14354 *
14355 * @param {Boolean} raw True to get the raw string, false to get the hex string
14356 *
14357 * @return {String} The result
14358 */
14359 SparkMD5.ArrayBuffer.prototype.end = function (raw) {
14360 var buff = this._buff,
14361 length = buff.length,
14362 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
14363 i,
14364 ret;
14365
14366 for (i = 0; i < length; i += 1) {
14367 tail[i >> 2] |= buff[i] << ((i % 4) << 3);
14368 }
14369
14370 this._finish(tail, length);
14371 ret = hex(this._hash);
14372
14373 if (raw) {
14374 ret = hexToBinaryString(ret);
14375 }
14376
14377 this.reset();
14378
14379 return ret;
14380 };
14381
14382 /**
14383 * Resets the internal state of the computation.
14384 *
14385 * @return {SparkMD5.ArrayBuffer} The instance itself
14386 */
14387 SparkMD5.ArrayBuffer.prototype.reset = function () {
14388 this._buff = new Uint8Array(0);
14389 this._length = 0;
14390 this._hash = [1732584193, -271733879, -1732584194, 271733878];
14391
14392 return this;
14393 };
14394
14395 /**
14396 * Gets the internal state of the computation.
14397 *
14398 * @return {Object} The state
14399 */
14400 SparkMD5.ArrayBuffer.prototype.getState = function () {
14401 var state = SparkMD5.prototype.getState.call(this);
14402
14403 // Convert buffer to a string
14404 state.buff = arrayBuffer2Utf8Str(state.buff);
14405
14406 return state;
14407 };
14408
14409 /**
14410 * Gets the internal state of the computation.
14411 *
14412 * @param {Object} state The state
14413 *
14414 * @return {SparkMD5.ArrayBuffer} The instance itself
14415 */
14416 SparkMD5.ArrayBuffer.prototype.setState = function (state) {
14417 // Convert string to buffer
14418 state.buff = utf8Str2ArrayBuffer(state.buff, true);
14419
14420 return SparkMD5.prototype.setState.call(this, state);
14421 };
14422
14423 SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
14424
14425 SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
14426
14427 /**
14428 * Performs the md5 hash on an array buffer.
14429 *
14430 * @param {ArrayBuffer} arr The array buffer
14431 * @param {Boolean} [raw] True to get the raw string, false to get the hex one
14432 *
14433 * @return {String} The result
14434 */
14435 SparkMD5.ArrayBuffer.hash = function (arr, raw) {
14436 var hash = md51_array(new Uint8Array(arr)),
14437 ret = hex(hash);
14438
14439 return raw ? hexToBinaryString(ret) : ret;
14440 };
14441
14442 return SparkMD5;
14443}));
14444
14445},{}],78:[function(_dereq_,module,exports){
14446// Copyright Joyent, Inc. and other Node contributors.
14447//
14448// Permission is hereby granted, free of charge, to any person obtaining a
14449// copy of this software and associated documentation files (the
14450// "Software"), to deal in the Software without restriction, including
14451// without limitation the rights to use, copy, modify, merge, publish,
14452// distribute, sublicense, and/or sell copies of the Software, and to permit
14453// persons to whom the Software is furnished to do so, subject to the
14454// following conditions:
14455//
14456// The above copyright notice and this permission notice shall be included
14457// in all copies or substantial portions of the Software.
14458//
14459// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14460// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14461// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14462// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14463// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14464// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14465// USE OR OTHER DEALINGS IN THE SOFTWARE.
14466
14467module.exports = Stream;
14468
14469var EE = _dereq_(20).EventEmitter;
14470var inherits = _dereq_(29);
14471
14472inherits(Stream, EE);
14473Stream.Readable = _dereq_(90);
14474Stream.Writable = _dereq_(92);
14475Stream.Duplex = _dereq_(80);
14476Stream.Transform = _dereq_(91);
14477Stream.PassThrough = _dereq_(89);
14478
14479// Backwards-compat with node 0.4.x
14480Stream.Stream = Stream;
14481
14482
14483
14484// old-style streams. Note that the pipe method (the only relevant
14485// part of this class) is overridden in the Readable class.
14486
14487function Stream() {
14488 EE.call(this);
14489}
14490
14491Stream.prototype.pipe = function(dest, options) {
14492 var source = this;
14493
14494 function ondata(chunk) {
14495 if (dest.writable) {
14496 if (false === dest.write(chunk) && source.pause) {
14497 source.pause();
14498 }
14499 }
14500 }
14501
14502 source.on('data', ondata);
14503
14504 function ondrain() {
14505 if (source.readable && source.resume) {
14506 source.resume();
14507 }
14508 }
14509
14510 dest.on('drain', ondrain);
14511
14512 // If the 'end' option is not supplied, dest.end() will be called when
14513 // source gets the 'end' or 'close' events. Only dest.end() once.
14514 if (!dest._isStdio && (!options || options.end !== false)) {
14515 source.on('end', onend);
14516 source.on('close', onclose);
14517 }
14518
14519 var didOnEnd = false;
14520 function onend() {
14521 if (didOnEnd) return;
14522 didOnEnd = true;
14523
14524 dest.end();
14525 }
14526
14527
14528 function onclose() {
14529 if (didOnEnd) return;
14530 didOnEnd = true;
14531
14532 if (typeof dest.destroy === 'function') dest.destroy();
14533 }
14534
14535 // don't leave dangling pipes when there are errors.
14536 function onerror(er) {
14537 cleanup();
14538 if (EE.listenerCount(this, 'error') === 0) {
14539 throw er; // Unhandled stream error in pipe.
14540 }
14541 }
14542
14543 source.on('error', onerror);
14544 dest.on('error', onerror);
14545
14546 // remove all the event listeners that were added.
14547 function cleanup() {
14548 source.removeListener('data', ondata);
14549 dest.removeListener('drain', ondrain);
14550
14551 source.removeListener('end', onend);
14552 source.removeListener('close', onclose);
14553
14554 source.removeListener('error', onerror);
14555 dest.removeListener('error', onerror);
14556
14557 source.removeListener('end', cleanup);
14558 source.removeListener('close', cleanup);
14559
14560 dest.removeListener('close', cleanup);
14561 }
14562
14563 source.on('end', cleanup);
14564 source.on('close', cleanup);
14565
14566 dest.on('close', cleanup);
14567
14568 dest.emit('pipe', source);
14569
14570 // Allow for unix-like usage: A.pipe(B).pipe(C)
14571 return dest;
14572};
14573
14574},{"20":20,"29":29,"80":80,"89":89,"90":90,"91":91,"92":92}],79:[function(_dereq_,module,exports){
14575var toString = {}.toString;
14576
14577module.exports = Array.isArray || function (arr) {
14578 return toString.call(arr) == '[object Array]';
14579};
14580
14581},{}],80:[function(_dereq_,module,exports){
14582module.exports = _dereq_(81);
14583
14584},{"81":81}],81:[function(_dereq_,module,exports){
14585// Copyright Joyent, Inc. and other Node contributors.
14586//
14587// Permission is hereby granted, free of charge, to any person obtaining a
14588// copy of this software and associated documentation files (the
14589// "Software"), to deal in the Software without restriction, including
14590// without limitation the rights to use, copy, modify, merge, publish,
14591// distribute, sublicense, and/or sell copies of the Software, and to permit
14592// persons to whom the Software is furnished to do so, subject to the
14593// following conditions:
14594//
14595// The above copyright notice and this permission notice shall be included
14596// in all copies or substantial portions of the Software.
14597//
14598// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14599// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14600// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14601// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14602// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14603// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14604// USE OR OTHER DEALINGS IN THE SOFTWARE.
14605
14606// a duplex stream is just a stream that is both readable and writable.
14607// Since JS doesn't have multiple prototypal inheritance, this class
14608// prototypally inherits from Readable, and then parasitically from
14609// Writable.
14610
14611'use strict';
14612
14613/*<replacement>*/
14614
14615var pna = _dereq_(65);
14616/*</replacement>*/
14617
14618/*<replacement>*/
14619var objectKeys = Object.keys || function (obj) {
14620 var keys = [];
14621 for (var key in obj) {
14622 keys.push(key);
14623 }return keys;
14624};
14625/*</replacement>*/
14626
14627module.exports = Duplex;
14628
14629/*<replacement>*/
14630var util = Object.create(_dereq_(9));
14631util.inherits = _dereq_(29);
14632/*</replacement>*/
14633
14634var Readable = _dereq_(83);
14635var Writable = _dereq_(85);
14636
14637util.inherits(Duplex, Readable);
14638
14639{
14640 // avoid scope creep, the keys array can then be collected
14641 var keys = objectKeys(Writable.prototype);
14642 for (var v = 0; v < keys.length; v++) {
14643 var method = keys[v];
14644 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
14645 }
14646}
14647
14648function Duplex(options) {
14649 if (!(this instanceof Duplex)) return new Duplex(options);
14650
14651 Readable.call(this, options);
14652 Writable.call(this, options);
14653
14654 if (options && options.readable === false) this.readable = false;
14655
14656 if (options && options.writable === false) this.writable = false;
14657
14658 this.allowHalfOpen = true;
14659 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
14660
14661 this.once('end', onend);
14662}
14663
14664Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
14665 // making it explicit this property is not enumerable
14666 // because otherwise some prototype manipulation in
14667 // userland will fail
14668 enumerable: false,
14669 get: function () {
14670 return this._writableState.highWaterMark;
14671 }
14672});
14673
14674// the no-half-open enforcer
14675function onend() {
14676 // if we allow half-open state, or if the writable side ended,
14677 // then we're ok.
14678 if (this.allowHalfOpen || this._writableState.ended) return;
14679
14680 // no more data can be written.
14681 // But allow more writes to happen in this tick.
14682 pna.nextTick(onEndNT, this);
14683}
14684
14685function onEndNT(self) {
14686 self.end();
14687}
14688
14689Object.defineProperty(Duplex.prototype, 'destroyed', {
14690 get: function () {
14691 if (this._readableState === undefined || this._writableState === undefined) {
14692 return false;
14693 }
14694 return this._readableState.destroyed && this._writableState.destroyed;
14695 },
14696 set: function (value) {
14697 // we ignore the value if the stream
14698 // has not been initialized yet
14699 if (this._readableState === undefined || this._writableState === undefined) {
14700 return;
14701 }
14702
14703 // backward compatibility, the user is explicitly
14704 // managing destroyed
14705 this._readableState.destroyed = value;
14706 this._writableState.destroyed = value;
14707 }
14708});
14709
14710Duplex.prototype._destroy = function (err, cb) {
14711 this.push(null);
14712 this.end();
14713
14714 pna.nextTick(cb, err);
14715};
14716},{"29":29,"65":65,"83":83,"85":85,"9":9}],82:[function(_dereq_,module,exports){
14717// Copyright Joyent, Inc. and other Node contributors.
14718//
14719// Permission is hereby granted, free of charge, to any person obtaining a
14720// copy of this software and associated documentation files (the
14721// "Software"), to deal in the Software without restriction, including
14722// without limitation the rights to use, copy, modify, merge, publish,
14723// distribute, sublicense, and/or sell copies of the Software, and to permit
14724// persons to whom the Software is furnished to do so, subject to the
14725// following conditions:
14726//
14727// The above copyright notice and this permission notice shall be included
14728// in all copies or substantial portions of the Software.
14729//
14730// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14731// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14732// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14733// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14734// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14735// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14736// USE OR OTHER DEALINGS IN THE SOFTWARE.
14737
14738// a passthrough stream.
14739// basically just the most minimal sort of Transform stream.
14740// Every written chunk gets output as-is.
14741
14742'use strict';
14743
14744module.exports = PassThrough;
14745
14746var Transform = _dereq_(84);
14747
14748/*<replacement>*/
14749var util = Object.create(_dereq_(9));
14750util.inherits = _dereq_(29);
14751/*</replacement>*/
14752
14753util.inherits(PassThrough, Transform);
14754
14755function PassThrough(options) {
14756 if (!(this instanceof PassThrough)) return new PassThrough(options);
14757
14758 Transform.call(this, options);
14759}
14760
14761PassThrough.prototype._transform = function (chunk, encoding, cb) {
14762 cb(null, chunk);
14763};
14764},{"29":29,"84":84,"9":9}],83:[function(_dereq_,module,exports){
14765(function (process,global){(function (){
14766// Copyright Joyent, Inc. and other Node contributors.
14767//
14768// Permission is hereby granted, free of charge, to any person obtaining a
14769// copy of this software and associated documentation files (the
14770// "Software"), to deal in the Software without restriction, including
14771// without limitation the rights to use, copy, modify, merge, publish,
14772// distribute, sublicense, and/or sell copies of the Software, and to permit
14773// persons to whom the Software is furnished to do so, subject to the
14774// following conditions:
14775//
14776// The above copyright notice and this permission notice shall be included
14777// in all copies or substantial portions of the Software.
14778//
14779// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14780// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14781// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14782// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14783// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14784// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14785// USE OR OTHER DEALINGS IN THE SOFTWARE.
14786
14787'use strict';
14788
14789/*<replacement>*/
14790
14791var pna = _dereq_(65);
14792/*</replacement>*/
14793
14794module.exports = Readable;
14795
14796/*<replacement>*/
14797var isArray = _dereq_(79);
14798/*</replacement>*/
14799
14800/*<replacement>*/
14801var Duplex;
14802/*</replacement>*/
14803
14804Readable.ReadableState = ReadableState;
14805
14806/*<replacement>*/
14807var EE = _dereq_(20).EventEmitter;
14808
14809var EElistenerCount = function (emitter, type) {
14810 return emitter.listeners(type).length;
14811};
14812/*</replacement>*/
14813
14814/*<replacement>*/
14815var Stream = _dereq_(88);
14816/*</replacement>*/
14817
14818/*<replacement>*/
14819
14820var Buffer = _dereq_(93).Buffer;
14821var OurUint8Array = global.Uint8Array || function () {};
14822function _uint8ArrayToBuffer(chunk) {
14823 return Buffer.from(chunk);
14824}
14825function _isUint8Array(obj) {
14826 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
14827}
14828
14829/*</replacement>*/
14830
14831/*<replacement>*/
14832var util = Object.create(_dereq_(9));
14833util.inherits = _dereq_(29);
14834/*</replacement>*/
14835
14836/*<replacement>*/
14837var debugUtil = _dereq_(6);
14838var debug = void 0;
14839if (debugUtil && debugUtil.debuglog) {
14840 debug = debugUtil.debuglog('stream');
14841} else {
14842 debug = function () {};
14843}
14844/*</replacement>*/
14845
14846var BufferList = _dereq_(86);
14847var destroyImpl = _dereq_(87);
14848var StringDecoder;
14849
14850util.inherits(Readable, Stream);
14851
14852var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
14853
14854function prependListener(emitter, event, fn) {
14855 // Sadly this is not cacheable as some libraries bundle their own
14856 // event emitter implementation with them.
14857 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
14858
14859 // This is a hack to make sure that our error handler is attached before any
14860 // userland ones. NEVER DO THIS. This is here only because this code needs
14861 // to continue to work with older versions of Node.js that do not include
14862 // the prependListener() method. The goal is to eventually remove this hack.
14863 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]];
14864}
14865
14866function ReadableState(options, stream) {
14867 Duplex = Duplex || _dereq_(81);
14868
14869 options = options || {};
14870
14871 // Duplex streams are both readable and writable, but share
14872 // the same options object.
14873 // However, some cases require setting options to different
14874 // values for the readable and the writable sides of the duplex stream.
14875 // These options can be provided separately as readableXXX and writableXXX.
14876 var isDuplex = stream instanceof Duplex;
14877
14878 // object stream flag. Used to make read(n) ignore n and to
14879 // make all the buffer merging and length checks go away
14880 this.objectMode = !!options.objectMode;
14881
14882 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
14883
14884 // the point at which it stops calling _read() to fill the buffer
14885 // Note: 0 is a valid value, means "don't call _read preemptively ever"
14886 var hwm = options.highWaterMark;
14887 var readableHwm = options.readableHighWaterMark;
14888 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
14889
14890 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
14891
14892 // cast to ints.
14893 this.highWaterMark = Math.floor(this.highWaterMark);
14894
14895 // A linked list is used to store data chunks instead of an array because the
14896 // linked list can remove elements from the beginning faster than
14897 // array.shift()
14898 this.buffer = new BufferList();
14899 this.length = 0;
14900 this.pipes = null;
14901 this.pipesCount = 0;
14902 this.flowing = null;
14903 this.ended = false;
14904 this.endEmitted = false;
14905 this.reading = false;
14906
14907 // a flag to be able to tell if the event 'readable'/'data' is emitted
14908 // immediately, or on a later tick. We set this to true at first, because
14909 // any actions that shouldn't happen until "later" should generally also
14910 // not happen before the first read call.
14911 this.sync = true;
14912
14913 // whenever we return null, then we set a flag to say
14914 // that we're awaiting a 'readable' event emission.
14915 this.needReadable = false;
14916 this.emittedReadable = false;
14917 this.readableListening = false;
14918 this.resumeScheduled = false;
14919
14920 // has it been destroyed
14921 this.destroyed = false;
14922
14923 // Crypto is kind of old and crusty. Historically, its default string
14924 // encoding is 'binary' so we have to make this configurable.
14925 // Everything else in the universe uses 'utf8', though.
14926 this.defaultEncoding = options.defaultEncoding || 'utf8';
14927
14928 // the number of writers that are awaiting a drain event in .pipe()s
14929 this.awaitDrain = 0;
14930
14931 // if true, a maybeReadMore has been scheduled
14932 this.readingMore = false;
14933
14934 this.decoder = null;
14935 this.encoding = null;
14936 if (options.encoding) {
14937 if (!StringDecoder) StringDecoder = _dereq_(94).StringDecoder;
14938 this.decoder = new StringDecoder(options.encoding);
14939 this.encoding = options.encoding;
14940 }
14941}
14942
14943function Readable(options) {
14944 Duplex = Duplex || _dereq_(81);
14945
14946 if (!(this instanceof Readable)) return new Readable(options);
14947
14948 this._readableState = new ReadableState(options, this);
14949
14950 // legacy
14951 this.readable = true;
14952
14953 if (options) {
14954 if (typeof options.read === 'function') this._read = options.read;
14955
14956 if (typeof options.destroy === 'function') this._destroy = options.destroy;
14957 }
14958
14959 Stream.call(this);
14960}
14961
14962Object.defineProperty(Readable.prototype, 'destroyed', {
14963 get: function () {
14964 if (this._readableState === undefined) {
14965 return false;
14966 }
14967 return this._readableState.destroyed;
14968 },
14969 set: function (value) {
14970 // we ignore the value if the stream
14971 // has not been initialized yet
14972 if (!this._readableState) {
14973 return;
14974 }
14975
14976 // backward compatibility, the user is explicitly
14977 // managing destroyed
14978 this._readableState.destroyed = value;
14979 }
14980});
14981
14982Readable.prototype.destroy = destroyImpl.destroy;
14983Readable.prototype._undestroy = destroyImpl.undestroy;
14984Readable.prototype._destroy = function (err, cb) {
14985 this.push(null);
14986 cb(err);
14987};
14988
14989// Manually shove something into the read() buffer.
14990// This returns true if the highWaterMark has not been hit yet,
14991// similar to how Writable.write() returns true if you should
14992// write() some more.
14993Readable.prototype.push = function (chunk, encoding) {
14994 var state = this._readableState;
14995 var skipChunkCheck;
14996
14997 if (!state.objectMode) {
14998 if (typeof chunk === 'string') {
14999 encoding = encoding || state.defaultEncoding;
15000 if (encoding !== state.encoding) {
15001 chunk = Buffer.from(chunk, encoding);
15002 encoding = '';
15003 }
15004 skipChunkCheck = true;
15005 }
15006 } else {
15007 skipChunkCheck = true;
15008 }
15009
15010 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
15011};
15012
15013// Unshift should *always* be something directly out of read()
15014Readable.prototype.unshift = function (chunk) {
15015 return readableAddChunk(this, chunk, null, true, false);
15016};
15017
15018function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
15019 var state = stream._readableState;
15020 if (chunk === null) {
15021 state.reading = false;
15022 onEofChunk(stream, state);
15023 } else {
15024 var er;
15025 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
15026 if (er) {
15027 stream.emit('error', er);
15028 } else if (state.objectMode || chunk && chunk.length > 0) {
15029 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
15030 chunk = _uint8ArrayToBuffer(chunk);
15031 }
15032
15033 if (addToFront) {
15034 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
15035 } else if (state.ended) {
15036 stream.emit('error', new Error('stream.push() after EOF'));
15037 } else {
15038 state.reading = false;
15039 if (state.decoder && !encoding) {
15040 chunk = state.decoder.write(chunk);
15041 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
15042 } else {
15043 addChunk(stream, state, chunk, false);
15044 }
15045 }
15046 } else if (!addToFront) {
15047 state.reading = false;
15048 }
15049 }
15050
15051 return needMoreData(state);
15052}
15053
15054function addChunk(stream, state, chunk, addToFront) {
15055 if (state.flowing && state.length === 0 && !state.sync) {
15056 stream.emit('data', chunk);
15057 stream.read(0);
15058 } else {
15059 // update the buffer info.
15060 state.length += state.objectMode ? 1 : chunk.length;
15061 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
15062
15063 if (state.needReadable) emitReadable(stream);
15064 }
15065 maybeReadMore(stream, state);
15066}
15067
15068function chunkInvalid(state, chunk) {
15069 var er;
15070 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
15071 er = new TypeError('Invalid non-string/buffer chunk');
15072 }
15073 return er;
15074}
15075
15076// if it's past the high water mark, we can push in some more.
15077// Also, if we have no data yet, we can stand some
15078// more bytes. This is to work around cases where hwm=0,
15079// such as the repl. Also, if the push() triggered a
15080// readable event, and the user called read(largeNumber) such that
15081// needReadable was set, then we ought to push more, so that another
15082// 'readable' event will be triggered.
15083function needMoreData(state) {
15084 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
15085}
15086
15087Readable.prototype.isPaused = function () {
15088 return this._readableState.flowing === false;
15089};
15090
15091// backwards compatibility.
15092Readable.prototype.setEncoding = function (enc) {
15093 if (!StringDecoder) StringDecoder = _dereq_(94).StringDecoder;
15094 this._readableState.decoder = new StringDecoder(enc);
15095 this._readableState.encoding = enc;
15096 return this;
15097};
15098
15099// Don't raise the hwm > 8MB
15100var MAX_HWM = 0x800000;
15101function computeNewHighWaterMark(n) {
15102 if (n >= MAX_HWM) {
15103 n = MAX_HWM;
15104 } else {
15105 // Get the next highest power of 2 to prevent increasing hwm excessively in
15106 // tiny amounts
15107 n--;
15108 n |= n >>> 1;
15109 n |= n >>> 2;
15110 n |= n >>> 4;
15111 n |= n >>> 8;
15112 n |= n >>> 16;
15113 n++;
15114 }
15115 return n;
15116}
15117
15118// This function is designed to be inlinable, so please take care when making
15119// changes to the function body.
15120function howMuchToRead(n, state) {
15121 if (n <= 0 || state.length === 0 && state.ended) return 0;
15122 if (state.objectMode) return 1;
15123 if (n !== n) {
15124 // Only flow one buffer at a time
15125 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
15126 }
15127 // If we're asking for more than the current hwm, then raise the hwm.
15128 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
15129 if (n <= state.length) return n;
15130 // Don't have enough
15131 if (!state.ended) {
15132 state.needReadable = true;
15133 return 0;
15134 }
15135 return state.length;
15136}
15137
15138// you can override either this method, or the async _read(n) below.
15139Readable.prototype.read = function (n) {
15140 debug('read', n);
15141 n = parseInt(n, 10);
15142 var state = this._readableState;
15143 var nOrig = n;
15144
15145 if (n !== 0) state.emittedReadable = false;
15146
15147 // if we're doing read(0) to trigger a readable event, but we
15148 // already have a bunch of data in the buffer, then just trigger
15149 // the 'readable' event and move on.
15150 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
15151 debug('read: emitReadable', state.length, state.ended);
15152 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
15153 return null;
15154 }
15155
15156 n = howMuchToRead(n, state);
15157
15158 // if we've ended, and we're now clear, then finish it up.
15159 if (n === 0 && state.ended) {
15160 if (state.length === 0) endReadable(this);
15161 return null;
15162 }
15163
15164 // All the actual chunk generation logic needs to be
15165 // *below* the call to _read. The reason is that in certain
15166 // synthetic stream cases, such as passthrough streams, _read
15167 // may be a completely synchronous operation which may change
15168 // the state of the read buffer, providing enough data when
15169 // before there was *not* enough.
15170 //
15171 // So, the steps are:
15172 // 1. Figure out what the state of things will be after we do
15173 // a read from the buffer.
15174 //
15175 // 2. If that resulting state will trigger a _read, then call _read.
15176 // Note that this may be asynchronous, or synchronous. Yes, it is
15177 // deeply ugly to write APIs this way, but that still doesn't mean
15178 // that the Readable class should behave improperly, as streams are
15179 // designed to be sync/async agnostic.
15180 // Take note if the _read call is sync or async (ie, if the read call
15181 // has returned yet), so that we know whether or not it's safe to emit
15182 // 'readable' etc.
15183 //
15184 // 3. Actually pull the requested chunks out of the buffer and return.
15185
15186 // if we need a readable event, then we need to do some reading.
15187 var doRead = state.needReadable;
15188 debug('need readable', doRead);
15189
15190 // if we currently have less than the highWaterMark, then also read some
15191 if (state.length === 0 || state.length - n < state.highWaterMark) {
15192 doRead = true;
15193 debug('length less than watermark', doRead);
15194 }
15195
15196 // however, if we've ended, then there's no point, and if we're already
15197 // reading, then it's unnecessary.
15198 if (state.ended || state.reading) {
15199 doRead = false;
15200 debug('reading or ended', doRead);
15201 } else if (doRead) {
15202 debug('do read');
15203 state.reading = true;
15204 state.sync = true;
15205 // if the length is currently zero, then we *need* a readable event.
15206 if (state.length === 0) state.needReadable = true;
15207 // call internal read method
15208 this._read(state.highWaterMark);
15209 state.sync = false;
15210 // If _read pushed data synchronously, then `reading` will be false,
15211 // and we need to re-evaluate how much data we can return to the user.
15212 if (!state.reading) n = howMuchToRead(nOrig, state);
15213 }
15214
15215 var ret;
15216 if (n > 0) ret = fromList(n, state);else ret = null;
15217
15218 if (ret === null) {
15219 state.needReadable = true;
15220 n = 0;
15221 } else {
15222 state.length -= n;
15223 }
15224
15225 if (state.length === 0) {
15226 // If we have nothing in the buffer, then we want to know
15227 // as soon as we *do* get something into the buffer.
15228 if (!state.ended) state.needReadable = true;
15229
15230 // If we tried to read() past the EOF, then emit end on the next tick.
15231 if (nOrig !== n && state.ended) endReadable(this);
15232 }
15233
15234 if (ret !== null) this.emit('data', ret);
15235
15236 return ret;
15237};
15238
15239function onEofChunk(stream, state) {
15240 if (state.ended) return;
15241 if (state.decoder) {
15242 var chunk = state.decoder.end();
15243 if (chunk && chunk.length) {
15244 state.buffer.push(chunk);
15245 state.length += state.objectMode ? 1 : chunk.length;
15246 }
15247 }
15248 state.ended = true;
15249
15250 // emit 'readable' now to make sure it gets picked up.
15251 emitReadable(stream);
15252}
15253
15254// Don't emit readable right away in sync mode, because this can trigger
15255// another read() call => stack overflow. This way, it might trigger
15256// a nextTick recursion warning, but that's not so bad.
15257function emitReadable(stream) {
15258 var state = stream._readableState;
15259 state.needReadable = false;
15260 if (!state.emittedReadable) {
15261 debug('emitReadable', state.flowing);
15262 state.emittedReadable = true;
15263 if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
15264 }
15265}
15266
15267function emitReadable_(stream) {
15268 debug('emit readable');
15269 stream.emit('readable');
15270 flow(stream);
15271}
15272
15273// at this point, the user has presumably seen the 'readable' event,
15274// and called read() to consume some data. that may have triggered
15275// in turn another _read(n) call, in which case reading = true if
15276// it's in progress.
15277// However, if we're not ended, or reading, and the length < hwm,
15278// then go ahead and try to read some more preemptively.
15279function maybeReadMore(stream, state) {
15280 if (!state.readingMore) {
15281 state.readingMore = true;
15282 pna.nextTick(maybeReadMore_, stream, state);
15283 }
15284}
15285
15286function maybeReadMore_(stream, state) {
15287 var len = state.length;
15288 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
15289 debug('maybeReadMore read 0');
15290 stream.read(0);
15291 if (len === state.length)
15292 // didn't get any data, stop spinning.
15293 break;else len = state.length;
15294 }
15295 state.readingMore = false;
15296}
15297
15298// abstract method. to be overridden in specific implementation classes.
15299// call cb(er, data) where data is <= n in length.
15300// for virtual (non-string, non-buffer) streams, "length" is somewhat
15301// arbitrary, and perhaps not very meaningful.
15302Readable.prototype._read = function (n) {
15303 this.emit('error', new Error('_read() is not implemented'));
15304};
15305
15306Readable.prototype.pipe = function (dest, pipeOpts) {
15307 var src = this;
15308 var state = this._readableState;
15309
15310 switch (state.pipesCount) {
15311 case 0:
15312 state.pipes = dest;
15313 break;
15314 case 1:
15315 state.pipes = [state.pipes, dest];
15316 break;
15317 default:
15318 state.pipes.push(dest);
15319 break;
15320 }
15321 state.pipesCount += 1;
15322 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
15323
15324 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
15325
15326 var endFn = doEnd ? onend : unpipe;
15327 if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
15328
15329 dest.on('unpipe', onunpipe);
15330 function onunpipe(readable, unpipeInfo) {
15331 debug('onunpipe');
15332 if (readable === src) {
15333 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
15334 unpipeInfo.hasUnpiped = true;
15335 cleanup();
15336 }
15337 }
15338 }
15339
15340 function onend() {
15341 debug('onend');
15342 dest.end();
15343 }
15344
15345 // when the dest drains, it reduces the awaitDrain counter
15346 // on the source. This would be more elegant with a .once()
15347 // handler in flow(), but adding and removing repeatedly is
15348 // too slow.
15349 var ondrain = pipeOnDrain(src);
15350 dest.on('drain', ondrain);
15351
15352 var cleanedUp = false;
15353 function cleanup() {
15354 debug('cleanup');
15355 // cleanup event handlers once the pipe is broken
15356 dest.removeListener('close', onclose);
15357 dest.removeListener('finish', onfinish);
15358 dest.removeListener('drain', ondrain);
15359 dest.removeListener('error', onerror);
15360 dest.removeListener('unpipe', onunpipe);
15361 src.removeListener('end', onend);
15362 src.removeListener('end', unpipe);
15363 src.removeListener('data', ondata);
15364
15365 cleanedUp = true;
15366
15367 // if the reader is waiting for a drain event from this
15368 // specific writer, then it would cause it to never start
15369 // flowing again.
15370 // So, if this is awaiting a drain, then we just call it now.
15371 // If we don't know, then assume that we are waiting for one.
15372 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
15373 }
15374
15375 // If the user pushes more data while we're writing to dest then we'll end up
15376 // in ondata again. However, we only want to increase awaitDrain once because
15377 // dest will only emit one 'drain' event for the multiple writes.
15378 // => Introduce a guard on increasing awaitDrain.
15379 var increasedAwaitDrain = false;
15380 src.on('data', ondata);
15381 function ondata(chunk) {
15382 debug('ondata');
15383 increasedAwaitDrain = false;
15384 var ret = dest.write(chunk);
15385 if (false === ret && !increasedAwaitDrain) {
15386 // If the user unpiped during `dest.write()`, it is possible
15387 // to get stuck in a permanently paused state if that write
15388 // also returned false.
15389 // => Check whether `dest` is still a piping destination.
15390 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
15391 debug('false write response, pause', src._readableState.awaitDrain);
15392 src._readableState.awaitDrain++;
15393 increasedAwaitDrain = true;
15394 }
15395 src.pause();
15396 }
15397 }
15398
15399 // if the dest has an error, then stop piping into it.
15400 // however, don't suppress the throwing behavior for this.
15401 function onerror(er) {
15402 debug('onerror', er);
15403 unpipe();
15404 dest.removeListener('error', onerror);
15405 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
15406 }
15407
15408 // Make sure our error handler is attached before userland ones.
15409 prependListener(dest, 'error', onerror);
15410
15411 // Both close and finish should trigger unpipe, but only once.
15412 function onclose() {
15413 dest.removeListener('finish', onfinish);
15414 unpipe();
15415 }
15416 dest.once('close', onclose);
15417 function onfinish() {
15418 debug('onfinish');
15419 dest.removeListener('close', onclose);
15420 unpipe();
15421 }
15422 dest.once('finish', onfinish);
15423
15424 function unpipe() {
15425 debug('unpipe');
15426 src.unpipe(dest);
15427 }
15428
15429 // tell the dest that it's being piped to
15430 dest.emit('pipe', src);
15431
15432 // start the flow if it hasn't been started already.
15433 if (!state.flowing) {
15434 debug('pipe resume');
15435 src.resume();
15436 }
15437
15438 return dest;
15439};
15440
15441function pipeOnDrain(src) {
15442 return function () {
15443 var state = src._readableState;
15444 debug('pipeOnDrain', state.awaitDrain);
15445 if (state.awaitDrain) state.awaitDrain--;
15446 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
15447 state.flowing = true;
15448 flow(src);
15449 }
15450 };
15451}
15452
15453Readable.prototype.unpipe = function (dest) {
15454 var state = this._readableState;
15455 var unpipeInfo = { hasUnpiped: false };
15456
15457 // if we're not piping anywhere, then do nothing.
15458 if (state.pipesCount === 0) return this;
15459
15460 // just one destination. most common case.
15461 if (state.pipesCount === 1) {
15462 // passed in one, but it's not the right one.
15463 if (dest && dest !== state.pipes) return this;
15464
15465 if (!dest) dest = state.pipes;
15466
15467 // got a match.
15468 state.pipes = null;
15469 state.pipesCount = 0;
15470 state.flowing = false;
15471 if (dest) dest.emit('unpipe', this, unpipeInfo);
15472 return this;
15473 }
15474
15475 // slow case. multiple pipe destinations.
15476
15477 if (!dest) {
15478 // remove all.
15479 var dests = state.pipes;
15480 var len = state.pipesCount;
15481 state.pipes = null;
15482 state.pipesCount = 0;
15483 state.flowing = false;
15484
15485 for (var i = 0; i < len; i++) {
15486 dests[i].emit('unpipe', this, unpipeInfo);
15487 }return this;
15488 }
15489
15490 // try to find the right one.
15491 var index = indexOf(state.pipes, dest);
15492 if (index === -1) return this;
15493
15494 state.pipes.splice(index, 1);
15495 state.pipesCount -= 1;
15496 if (state.pipesCount === 1) state.pipes = state.pipes[0];
15497
15498 dest.emit('unpipe', this, unpipeInfo);
15499
15500 return this;
15501};
15502
15503// set up data events if they are asked for
15504// Ensure readable listeners eventually get something
15505Readable.prototype.on = function (ev, fn) {
15506 var res = Stream.prototype.on.call(this, ev, fn);
15507
15508 if (ev === 'data') {
15509 // Start flowing on next tick if stream isn't explicitly paused
15510 if (this._readableState.flowing !== false) this.resume();
15511 } else if (ev === 'readable') {
15512 var state = this._readableState;
15513 if (!state.endEmitted && !state.readableListening) {
15514 state.readableListening = state.needReadable = true;
15515 state.emittedReadable = false;
15516 if (!state.reading) {
15517 pna.nextTick(nReadingNextTick, this);
15518 } else if (state.length) {
15519 emitReadable(this);
15520 }
15521 }
15522 }
15523
15524 return res;
15525};
15526Readable.prototype.addListener = Readable.prototype.on;
15527
15528function nReadingNextTick(self) {
15529 debug('readable nexttick read 0');
15530 self.read(0);
15531}
15532
15533// pause() and resume() are remnants of the legacy readable stream API
15534// If the user uses them, then switch into old mode.
15535Readable.prototype.resume = function () {
15536 var state = this._readableState;
15537 if (!state.flowing) {
15538 debug('resume');
15539 state.flowing = true;
15540 resume(this, state);
15541 }
15542 return this;
15543};
15544
15545function resume(stream, state) {
15546 if (!state.resumeScheduled) {
15547 state.resumeScheduled = true;
15548 pna.nextTick(resume_, stream, state);
15549 }
15550}
15551
15552function resume_(stream, state) {
15553 if (!state.reading) {
15554 debug('resume read 0');
15555 stream.read(0);
15556 }
15557
15558 state.resumeScheduled = false;
15559 state.awaitDrain = 0;
15560 stream.emit('resume');
15561 flow(stream);
15562 if (state.flowing && !state.reading) stream.read(0);
15563}
15564
15565Readable.prototype.pause = function () {
15566 debug('call pause flowing=%j', this._readableState.flowing);
15567 if (false !== this._readableState.flowing) {
15568 debug('pause');
15569 this._readableState.flowing = false;
15570 this.emit('pause');
15571 }
15572 return this;
15573};
15574
15575function flow(stream) {
15576 var state = stream._readableState;
15577 debug('flow', state.flowing);
15578 while (state.flowing && stream.read() !== null) {}
15579}
15580
15581// wrap an old-style stream as the async data source.
15582// This is *not* part of the readable stream interface.
15583// It is an ugly unfortunate mess of history.
15584Readable.prototype.wrap = function (stream) {
15585 var _this = this;
15586
15587 var state = this._readableState;
15588 var paused = false;
15589
15590 stream.on('end', function () {
15591 debug('wrapped end');
15592 if (state.decoder && !state.ended) {
15593 var chunk = state.decoder.end();
15594 if (chunk && chunk.length) _this.push(chunk);
15595 }
15596
15597 _this.push(null);
15598 });
15599
15600 stream.on('data', function (chunk) {
15601 debug('wrapped data');
15602 if (state.decoder) chunk = state.decoder.write(chunk);
15603
15604 // don't skip over falsy values in objectMode
15605 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
15606
15607 var ret = _this.push(chunk);
15608 if (!ret) {
15609 paused = true;
15610 stream.pause();
15611 }
15612 });
15613
15614 // proxy all the other methods.
15615 // important when wrapping filters and duplexes.
15616 for (var i in stream) {
15617 if (this[i] === undefined && typeof stream[i] === 'function') {
15618 this[i] = function (method) {
15619 return function () {
15620 return stream[method].apply(stream, arguments);
15621 };
15622 }(i);
15623 }
15624 }
15625
15626 // proxy certain important events.
15627 for (var n = 0; n < kProxyEvents.length; n++) {
15628 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
15629 }
15630
15631 // when we try to consume some more bytes, simply unpause the
15632 // underlying stream.
15633 this._read = function (n) {
15634 debug('wrapped _read', n);
15635 if (paused) {
15636 paused = false;
15637 stream.resume();
15638 }
15639 };
15640
15641 return this;
15642};
15643
15644Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
15645 // making it explicit this property is not enumerable
15646 // because otherwise some prototype manipulation in
15647 // userland will fail
15648 enumerable: false,
15649 get: function () {
15650 return this._readableState.highWaterMark;
15651 }
15652});
15653
15654// exposed for testing purposes only.
15655Readable._fromList = fromList;
15656
15657// Pluck off n bytes from an array of buffers.
15658// Length is the combined lengths of all the buffers in the list.
15659// This function is designed to be inlinable, so please take care when making
15660// changes to the function body.
15661function fromList(n, state) {
15662 // nothing buffered
15663 if (state.length === 0) return null;
15664
15665 var ret;
15666 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
15667 // read it all, truncate the list
15668 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);
15669 state.buffer.clear();
15670 } else {
15671 // read part of list
15672 ret = fromListPartial(n, state.buffer, state.decoder);
15673 }
15674
15675 return ret;
15676}
15677
15678// Extracts only enough buffered data to satisfy the amount requested.
15679// This function is designed to be inlinable, so please take care when making
15680// changes to the function body.
15681function fromListPartial(n, list, hasStrings) {
15682 var ret;
15683 if (n < list.head.data.length) {
15684 // slice is the same for buffers and strings
15685 ret = list.head.data.slice(0, n);
15686 list.head.data = list.head.data.slice(n);
15687 } else if (n === list.head.data.length) {
15688 // first chunk is a perfect match
15689 ret = list.shift();
15690 } else {
15691 // result spans more than one buffer
15692 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
15693 }
15694 return ret;
15695}
15696
15697// Copies a specified amount of characters from the list of buffered data
15698// chunks.
15699// This function is designed to be inlinable, so please take care when making
15700// changes to the function body.
15701function copyFromBufferString(n, list) {
15702 var p = list.head;
15703 var c = 1;
15704 var ret = p.data;
15705 n -= ret.length;
15706 while (p = p.next) {
15707 var str = p.data;
15708 var nb = n > str.length ? str.length : n;
15709 if (nb === str.length) ret += str;else ret += str.slice(0, n);
15710 n -= nb;
15711 if (n === 0) {
15712 if (nb === str.length) {
15713 ++c;
15714 if (p.next) list.head = p.next;else list.head = list.tail = null;
15715 } else {
15716 list.head = p;
15717 p.data = str.slice(nb);
15718 }
15719 break;
15720 }
15721 ++c;
15722 }
15723 list.length -= c;
15724 return ret;
15725}
15726
15727// Copies a specified amount of bytes from the list of buffered data chunks.
15728// This function is designed to be inlinable, so please take care when making
15729// changes to the function body.
15730function copyFromBuffer(n, list) {
15731 var ret = Buffer.allocUnsafe(n);
15732 var p = list.head;
15733 var c = 1;
15734 p.data.copy(ret);
15735 n -= p.data.length;
15736 while (p = p.next) {
15737 var buf = p.data;
15738 var nb = n > buf.length ? buf.length : n;
15739 buf.copy(ret, ret.length - n, 0, nb);
15740 n -= nb;
15741 if (n === 0) {
15742 if (nb === buf.length) {
15743 ++c;
15744 if (p.next) list.head = p.next;else list.head = list.tail = null;
15745 } else {
15746 list.head = p;
15747 p.data = buf.slice(nb);
15748 }
15749 break;
15750 }
15751 ++c;
15752 }
15753 list.length -= c;
15754 return ret;
15755}
15756
15757function endReadable(stream) {
15758 var state = stream._readableState;
15759
15760 // If we get here before consuming all the bytes, then that is a
15761 // bug in node. Should never happen.
15762 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
15763
15764 if (!state.endEmitted) {
15765 state.ended = true;
15766 pna.nextTick(endReadableNT, state, stream);
15767 }
15768}
15769
15770function endReadableNT(state, stream) {
15771 // Check that we didn't get one last unshift.
15772 if (!state.endEmitted && state.length === 0) {
15773 state.endEmitted = true;
15774 stream.readable = false;
15775 stream.emit('end');
15776 }
15777}
15778
15779function indexOf(xs, x) {
15780 for (var i = 0, l = xs.length; i < l; i++) {
15781 if (xs[i] === x) return i;
15782 }
15783 return -1;
15784}
15785}).call(this)}).call(this,_dereq_(66),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
15786},{"20":20,"29":29,"6":6,"65":65,"66":66,"79":79,"81":81,"86":86,"87":87,"88":88,"9":9,"93":93,"94":94}],84:[function(_dereq_,module,exports){
15787// Copyright Joyent, Inc. and other Node contributors.
15788//
15789// Permission is hereby granted, free of charge, to any person obtaining a
15790// copy of this software and associated documentation files (the
15791// "Software"), to deal in the Software without restriction, including
15792// without limitation the rights to use, copy, modify, merge, publish,
15793// distribute, sublicense, and/or sell copies of the Software, and to permit
15794// persons to whom the Software is furnished to do so, subject to the
15795// following conditions:
15796//
15797// The above copyright notice and this permission notice shall be included
15798// in all copies or substantial portions of the Software.
15799//
15800// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15801// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15802// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15803// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15804// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15805// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15806// USE OR OTHER DEALINGS IN THE SOFTWARE.
15807
15808// a transform stream is a readable/writable stream where you do
15809// something with the data. Sometimes it's called a "filter",
15810// but that's not a great name for it, since that implies a thing where
15811// some bits pass through, and others are simply ignored. (That would
15812// be a valid example of a transform, of course.)
15813//
15814// While the output is causally related to the input, it's not a
15815// necessarily symmetric or synchronous transformation. For example,
15816// a zlib stream might take multiple plain-text writes(), and then
15817// emit a single compressed chunk some time in the future.
15818//
15819// Here's how this works:
15820//
15821// The Transform stream has all the aspects of the readable and writable
15822// stream classes. When you write(chunk), that calls _write(chunk,cb)
15823// internally, and returns false if there's a lot of pending writes
15824// buffered up. When you call read(), that calls _read(n) until
15825// there's enough pending readable data buffered up.
15826//
15827// In a transform stream, the written data is placed in a buffer. When
15828// _read(n) is called, it transforms the queued up data, calling the
15829// buffered _write cb's as it consumes chunks. If consuming a single
15830// written chunk would result in multiple output chunks, then the first
15831// outputted bit calls the readcb, and subsequent chunks just go into
15832// the read buffer, and will cause it to emit 'readable' if necessary.
15833//
15834// This way, back-pressure is actually determined by the reading side,
15835// since _read has to be called to start processing a new chunk. However,
15836// a pathological inflate type of transform can cause excessive buffering
15837// here. For example, imagine a stream where every byte of input is
15838// interpreted as an integer from 0-255, and then results in that many
15839// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
15840// 1kb of data being output. In this case, you could write a very small
15841// amount of input, and end up with a very large amount of output. In
15842// such a pathological inflating mechanism, there'd be no way to tell
15843// the system to stop doing the transform. A single 4MB write could
15844// cause the system to run out of memory.
15845//
15846// However, even in such a pathological case, only a single written chunk
15847// would be consumed, and then the rest would wait (un-transformed) until
15848// the results of the previous transformed chunk were consumed.
15849
15850'use strict';
15851
15852module.exports = Transform;
15853
15854var Duplex = _dereq_(81);
15855
15856/*<replacement>*/
15857var util = Object.create(_dereq_(9));
15858util.inherits = _dereq_(29);
15859/*</replacement>*/
15860
15861util.inherits(Transform, Duplex);
15862
15863function afterTransform(er, data) {
15864 var ts = this._transformState;
15865 ts.transforming = false;
15866
15867 var cb = ts.writecb;
15868
15869 if (!cb) {
15870 return this.emit('error', new Error('write callback called multiple times'));
15871 }
15872
15873 ts.writechunk = null;
15874 ts.writecb = null;
15875
15876 if (data != null) // single equals check for both `null` and `undefined`
15877 this.push(data);
15878
15879 cb(er);
15880
15881 var rs = this._readableState;
15882 rs.reading = false;
15883 if (rs.needReadable || rs.length < rs.highWaterMark) {
15884 this._read(rs.highWaterMark);
15885 }
15886}
15887
15888function Transform(options) {
15889 if (!(this instanceof Transform)) return new Transform(options);
15890
15891 Duplex.call(this, options);
15892
15893 this._transformState = {
15894 afterTransform: afterTransform.bind(this),
15895 needTransform: false,
15896 transforming: false,
15897 writecb: null,
15898 writechunk: null,
15899 writeencoding: null
15900 };
15901
15902 // start out asking for a readable event once data is transformed.
15903 this._readableState.needReadable = true;
15904
15905 // we have implemented the _read method, and done the other things
15906 // that Readable wants before the first _read call, so unset the
15907 // sync guard flag.
15908 this._readableState.sync = false;
15909
15910 if (options) {
15911 if (typeof options.transform === 'function') this._transform = options.transform;
15912
15913 if (typeof options.flush === 'function') this._flush = options.flush;
15914 }
15915
15916 // When the writable side finishes, then flush out anything remaining.
15917 this.on('prefinish', prefinish);
15918}
15919
15920function prefinish() {
15921 var _this = this;
15922
15923 if (typeof this._flush === 'function') {
15924 this._flush(function (er, data) {
15925 done(_this, er, data);
15926 });
15927 } else {
15928 done(this, null, null);
15929 }
15930}
15931
15932Transform.prototype.push = function (chunk, encoding) {
15933 this._transformState.needTransform = false;
15934 return Duplex.prototype.push.call(this, chunk, encoding);
15935};
15936
15937// This is the part where you do stuff!
15938// override this function in implementation classes.
15939// 'chunk' is an input chunk.
15940//
15941// Call `push(newChunk)` to pass along transformed output
15942// to the readable side. You may call 'push' zero or more times.
15943//
15944// Call `cb(err)` when you are done with this chunk. If you pass
15945// an error, then that'll put the hurt on the whole operation. If you
15946// never call cb(), then you'll never get another chunk.
15947Transform.prototype._transform = function (chunk, encoding, cb) {
15948 throw new Error('_transform() is not implemented');
15949};
15950
15951Transform.prototype._write = function (chunk, encoding, cb) {
15952 var ts = this._transformState;
15953 ts.writecb = cb;
15954 ts.writechunk = chunk;
15955 ts.writeencoding = encoding;
15956 if (!ts.transforming) {
15957 var rs = this._readableState;
15958 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
15959 }
15960};
15961
15962// Doesn't matter what the args are here.
15963// _transform does all the work.
15964// That we got here means that the readable side wants more data.
15965Transform.prototype._read = function (n) {
15966 var ts = this._transformState;
15967
15968 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
15969 ts.transforming = true;
15970 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
15971 } else {
15972 // mark that we need a transform, so that any data that comes in
15973 // will get processed, now that we've asked for it.
15974 ts.needTransform = true;
15975 }
15976};
15977
15978Transform.prototype._destroy = function (err, cb) {
15979 var _this2 = this;
15980
15981 Duplex.prototype._destroy.call(this, err, function (err2) {
15982 cb(err2);
15983 _this2.emit('close');
15984 });
15985};
15986
15987function done(stream, er, data) {
15988 if (er) return stream.emit('error', er);
15989
15990 if (data != null) // single equals check for both `null` and `undefined`
15991 stream.push(data);
15992
15993 // if there's nothing in the write buffer, then that means
15994 // that nothing more will ever be provided
15995 if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
15996
15997 if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
15998
15999 return stream.push(null);
16000}
16001},{"29":29,"81":81,"9":9}],85:[function(_dereq_,module,exports){
16002(function (process,global,setImmediate){(function (){
16003// Copyright Joyent, Inc. and other Node contributors.
16004//
16005// Permission is hereby granted, free of charge, to any person obtaining a
16006// copy of this software and associated documentation files (the
16007// "Software"), to deal in the Software without restriction, including
16008// without limitation the rights to use, copy, modify, merge, publish,
16009// distribute, sublicense, and/or sell copies of the Software, and to permit
16010// persons to whom the Software is furnished to do so, subject to the
16011// following conditions:
16012//
16013// The above copyright notice and this permission notice shall be included
16014// in all copies or substantial portions of the Software.
16015//
16016// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16017// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16018// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
16019// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
16020// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16021// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
16022// USE OR OTHER DEALINGS IN THE SOFTWARE.
16023
16024// A bit simpler than readable streams.
16025// Implement an async ._write(chunk, encoding, cb), and it'll handle all
16026// the drain event emission and buffering.
16027
16028'use strict';
16029
16030/*<replacement>*/
16031
16032var pna = _dereq_(65);
16033/*</replacement>*/
16034
16035module.exports = Writable;
16036
16037/* <replacement> */
16038function WriteReq(chunk, encoding, cb) {
16039 this.chunk = chunk;
16040 this.encoding = encoding;
16041 this.callback = cb;
16042 this.next = null;
16043}
16044
16045// It seems a linked list but it is not
16046// there will be only 2 of these for each stream
16047function CorkedRequest(state) {
16048 var _this = this;
16049
16050 this.next = null;
16051 this.entry = null;
16052 this.finish = function () {
16053 onCorkedFinish(_this, state);
16054 };
16055}
16056/* </replacement> */
16057
16058/*<replacement>*/
16059var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
16060/*</replacement>*/
16061
16062/*<replacement>*/
16063var Duplex;
16064/*</replacement>*/
16065
16066Writable.WritableState = WritableState;
16067
16068/*<replacement>*/
16069var util = Object.create(_dereq_(9));
16070util.inherits = _dereq_(29);
16071/*</replacement>*/
16072
16073/*<replacement>*/
16074var internalUtil = {
16075 deprecate: _dereq_(113)
16076};
16077/*</replacement>*/
16078
16079/*<replacement>*/
16080var Stream = _dereq_(88);
16081/*</replacement>*/
16082
16083/*<replacement>*/
16084
16085var Buffer = _dereq_(93).Buffer;
16086var OurUint8Array = global.Uint8Array || function () {};
16087function _uint8ArrayToBuffer(chunk) {
16088 return Buffer.from(chunk);
16089}
16090function _isUint8Array(obj) {
16091 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
16092}
16093
16094/*</replacement>*/
16095
16096var destroyImpl = _dereq_(87);
16097
16098util.inherits(Writable, Stream);
16099
16100function nop() {}
16101
16102function WritableState(options, stream) {
16103 Duplex = Duplex || _dereq_(81);
16104
16105 options = options || {};
16106
16107 // Duplex streams are both readable and writable, but share
16108 // the same options object.
16109 // However, some cases require setting options to different
16110 // values for the readable and the writable sides of the duplex stream.
16111 // These options can be provided separately as readableXXX and writableXXX.
16112 var isDuplex = stream instanceof Duplex;
16113
16114 // object stream flag to indicate whether or not this stream
16115 // contains buffers or objects.
16116 this.objectMode = !!options.objectMode;
16117
16118 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
16119
16120 // the point at which write() starts returning false
16121 // Note: 0 is a valid value, means that we always return false if
16122 // the entire buffer is not flushed immediately on write()
16123 var hwm = options.highWaterMark;
16124 var writableHwm = options.writableHighWaterMark;
16125 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
16126
16127 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
16128
16129 // cast to ints.
16130 this.highWaterMark = Math.floor(this.highWaterMark);
16131
16132 // if _final has been called
16133 this.finalCalled = false;
16134
16135 // drain event flag.
16136 this.needDrain = false;
16137 // at the start of calling end()
16138 this.ending = false;
16139 // when end() has been called, and returned
16140 this.ended = false;
16141 // when 'finish' is emitted
16142 this.finished = false;
16143
16144 // has it been destroyed
16145 this.destroyed = false;
16146
16147 // should we decode strings into buffers before passing to _write?
16148 // this is here so that some node-core streams can optimize string
16149 // handling at a lower level.
16150 var noDecode = options.decodeStrings === false;
16151 this.decodeStrings = !noDecode;
16152
16153 // Crypto is kind of old and crusty. Historically, its default string
16154 // encoding is 'binary' so we have to make this configurable.
16155 // Everything else in the universe uses 'utf8', though.
16156 this.defaultEncoding = options.defaultEncoding || 'utf8';
16157
16158 // not an actual buffer we keep track of, but a measurement
16159 // of how much we're waiting to get pushed to some underlying
16160 // socket or file.
16161 this.length = 0;
16162
16163 // a flag to see when we're in the middle of a write.
16164 this.writing = false;
16165
16166 // when true all writes will be buffered until .uncork() call
16167 this.corked = 0;
16168
16169 // a flag to be able to tell if the onwrite cb is called immediately,
16170 // or on a later tick. We set this to true at first, because any
16171 // actions that shouldn't happen until "later" should generally also
16172 // not happen before the first write call.
16173 this.sync = true;
16174
16175 // a flag to know if we're processing previously buffered items, which
16176 // may call the _write() callback in the same tick, so that we don't
16177 // end up in an overlapped onwrite situation.
16178 this.bufferProcessing = false;
16179
16180 // the callback that's passed to _write(chunk,cb)
16181 this.onwrite = function (er) {
16182 onwrite(stream, er);
16183 };
16184
16185 // the callback that the user supplies to write(chunk,encoding,cb)
16186 this.writecb = null;
16187
16188 // the amount that is being written when _write is called.
16189 this.writelen = 0;
16190
16191 this.bufferedRequest = null;
16192 this.lastBufferedRequest = null;
16193
16194 // number of pending user-supplied write callbacks
16195 // this must be 0 before 'finish' can be emitted
16196 this.pendingcb = 0;
16197
16198 // emit prefinish if the only thing we're waiting for is _write cbs
16199 // This is relevant for synchronous Transform streams
16200 this.prefinished = false;
16201
16202 // True if the error was already emitted and should not be thrown again
16203 this.errorEmitted = false;
16204
16205 // count buffered requests
16206 this.bufferedRequestCount = 0;
16207
16208 // allocate the first CorkedRequest, there is always
16209 // one allocated and free to use, and we maintain at most two
16210 this.corkedRequestsFree = new CorkedRequest(this);
16211}
16212
16213WritableState.prototype.getBuffer = function getBuffer() {
16214 var current = this.bufferedRequest;
16215 var out = [];
16216 while (current) {
16217 out.push(current);
16218 current = current.next;
16219 }
16220 return out;
16221};
16222
16223(function () {
16224 try {
16225 Object.defineProperty(WritableState.prototype, 'buffer', {
16226 get: internalUtil.deprecate(function () {
16227 return this.getBuffer();
16228 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
16229 });
16230 } catch (_) {}
16231})();
16232
16233// Test _writableState for inheritance to account for Duplex streams,
16234// whose prototype chain only points to Readable.
16235var realHasInstance;
16236if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
16237 realHasInstance = Function.prototype[Symbol.hasInstance];
16238 Object.defineProperty(Writable, Symbol.hasInstance, {
16239 value: function (object) {
16240 if (realHasInstance.call(this, object)) return true;
16241 if (this !== Writable) return false;
16242
16243 return object && object._writableState instanceof WritableState;
16244 }
16245 });
16246} else {
16247 realHasInstance = function (object) {
16248 return object instanceof this;
16249 };
16250}
16251
16252function Writable(options) {
16253 Duplex = Duplex || _dereq_(81);
16254
16255 // Writable ctor is applied to Duplexes, too.
16256 // `realHasInstance` is necessary because using plain `instanceof`
16257 // would return false, as no `_writableState` property is attached.
16258
16259 // Trying to use the custom `instanceof` for Writable here will also break the
16260 // Node.js LazyTransform implementation, which has a non-trivial getter for
16261 // `_writableState` that would lead to infinite recursion.
16262 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
16263 return new Writable(options);
16264 }
16265
16266 this._writableState = new WritableState(options, this);
16267
16268 // legacy.
16269 this.writable = true;
16270
16271 if (options) {
16272 if (typeof options.write === 'function') this._write = options.write;
16273
16274 if (typeof options.writev === 'function') this._writev = options.writev;
16275
16276 if (typeof options.destroy === 'function') this._destroy = options.destroy;
16277
16278 if (typeof options.final === 'function') this._final = options.final;
16279 }
16280
16281 Stream.call(this);
16282}
16283
16284// Otherwise people can pipe Writable streams, which is just wrong.
16285Writable.prototype.pipe = function () {
16286 this.emit('error', new Error('Cannot pipe, not readable'));
16287};
16288
16289function writeAfterEnd(stream, cb) {
16290 var er = new Error('write after end');
16291 // TODO: defer error events consistently everywhere, not just the cb
16292 stream.emit('error', er);
16293 pna.nextTick(cb, er);
16294}
16295
16296// Checks that a user-supplied chunk is valid, especially for the particular
16297// mode the stream is in. Currently this means that `null` is never accepted
16298// and undefined/non-string values are only allowed in object mode.
16299function validChunk(stream, state, chunk, cb) {
16300 var valid = true;
16301 var er = false;
16302
16303 if (chunk === null) {
16304 er = new TypeError('May not write null values to stream');
16305 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
16306 er = new TypeError('Invalid non-string/buffer chunk');
16307 }
16308 if (er) {
16309 stream.emit('error', er);
16310 pna.nextTick(cb, er);
16311 valid = false;
16312 }
16313 return valid;
16314}
16315
16316Writable.prototype.write = function (chunk, encoding, cb) {
16317 var state = this._writableState;
16318 var ret = false;
16319 var isBuf = !state.objectMode && _isUint8Array(chunk);
16320
16321 if (isBuf && !Buffer.isBuffer(chunk)) {
16322 chunk = _uint8ArrayToBuffer(chunk);
16323 }
16324
16325 if (typeof encoding === 'function') {
16326 cb = encoding;
16327 encoding = null;
16328 }
16329
16330 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
16331
16332 if (typeof cb !== 'function') cb = nop;
16333
16334 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
16335 state.pendingcb++;
16336 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
16337 }
16338
16339 return ret;
16340};
16341
16342Writable.prototype.cork = function () {
16343 var state = this._writableState;
16344
16345 state.corked++;
16346};
16347
16348Writable.prototype.uncork = function () {
16349 var state = this._writableState;
16350
16351 if (state.corked) {
16352 state.corked--;
16353
16354 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
16355 }
16356};
16357
16358Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
16359 // node::ParseEncoding() requires lower case.
16360 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
16361 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);
16362 this._writableState.defaultEncoding = encoding;
16363 return this;
16364};
16365
16366function decodeChunk(state, chunk, encoding) {
16367 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
16368 chunk = Buffer.from(chunk, encoding);
16369 }
16370 return chunk;
16371}
16372
16373Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
16374 // making it explicit this property is not enumerable
16375 // because otherwise some prototype manipulation in
16376 // userland will fail
16377 enumerable: false,
16378 get: function () {
16379 return this._writableState.highWaterMark;
16380 }
16381});
16382
16383// if we're already writing something, then just put this
16384// in the queue, and wait our turn. Otherwise, call _write
16385// If we return false, then we need a drain event, so set that flag.
16386function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
16387 if (!isBuf) {
16388 var newChunk = decodeChunk(state, chunk, encoding);
16389 if (chunk !== newChunk) {
16390 isBuf = true;
16391 encoding = 'buffer';
16392 chunk = newChunk;
16393 }
16394 }
16395 var len = state.objectMode ? 1 : chunk.length;
16396
16397 state.length += len;
16398
16399 var ret = state.length < state.highWaterMark;
16400 // we must ensure that previous needDrain will not be reset to false.
16401 if (!ret) state.needDrain = true;
16402
16403 if (state.writing || state.corked) {
16404 var last = state.lastBufferedRequest;
16405 state.lastBufferedRequest = {
16406 chunk: chunk,
16407 encoding: encoding,
16408 isBuf: isBuf,
16409 callback: cb,
16410 next: null
16411 };
16412 if (last) {
16413 last.next = state.lastBufferedRequest;
16414 } else {
16415 state.bufferedRequest = state.lastBufferedRequest;
16416 }
16417 state.bufferedRequestCount += 1;
16418 } else {
16419 doWrite(stream, state, false, len, chunk, encoding, cb);
16420 }
16421
16422 return ret;
16423}
16424
16425function doWrite(stream, state, writev, len, chunk, encoding, cb) {
16426 state.writelen = len;
16427 state.writecb = cb;
16428 state.writing = true;
16429 state.sync = true;
16430 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
16431 state.sync = false;
16432}
16433
16434function onwriteError(stream, state, sync, er, cb) {
16435 --state.pendingcb;
16436
16437 if (sync) {
16438 // defer the callback if we are being called synchronously
16439 // to avoid piling up things on the stack
16440 pna.nextTick(cb, er);
16441 // this can emit finish, and it will always happen
16442 // after error
16443 pna.nextTick(finishMaybe, stream, state);
16444 stream._writableState.errorEmitted = true;
16445 stream.emit('error', er);
16446 } else {
16447 // the caller expect this to happen before if
16448 // it is async
16449 cb(er);
16450 stream._writableState.errorEmitted = true;
16451 stream.emit('error', er);
16452 // this can emit finish, but finish must
16453 // always follow error
16454 finishMaybe(stream, state);
16455 }
16456}
16457
16458function onwriteStateUpdate(state) {
16459 state.writing = false;
16460 state.writecb = null;
16461 state.length -= state.writelen;
16462 state.writelen = 0;
16463}
16464
16465function onwrite(stream, er) {
16466 var state = stream._writableState;
16467 var sync = state.sync;
16468 var cb = state.writecb;
16469
16470 onwriteStateUpdate(state);
16471
16472 if (er) onwriteError(stream, state, sync, er, cb);else {
16473 // Check if we're actually ready to finish, but don't emit yet
16474 var finished = needFinish(state);
16475
16476 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
16477 clearBuffer(stream, state);
16478 }
16479
16480 if (sync) {
16481 /*<replacement>*/
16482 asyncWrite(afterWrite, stream, state, finished, cb);
16483 /*</replacement>*/
16484 } else {
16485 afterWrite(stream, state, finished, cb);
16486 }
16487 }
16488}
16489
16490function afterWrite(stream, state, finished, cb) {
16491 if (!finished) onwriteDrain(stream, state);
16492 state.pendingcb--;
16493 cb();
16494 finishMaybe(stream, state);
16495}
16496
16497// Must force callback to be called on nextTick, so that we don't
16498// emit 'drain' before the write() consumer gets the 'false' return
16499// value, and has a chance to attach a 'drain' listener.
16500function onwriteDrain(stream, state) {
16501 if (state.length === 0 && state.needDrain) {
16502 state.needDrain = false;
16503 stream.emit('drain');
16504 }
16505}
16506
16507// if there's something in the buffer waiting, then process it
16508function clearBuffer(stream, state) {
16509 state.bufferProcessing = true;
16510 var entry = state.bufferedRequest;
16511
16512 if (stream._writev && entry && entry.next) {
16513 // Fast case, write everything using _writev()
16514 var l = state.bufferedRequestCount;
16515 var buffer = new Array(l);
16516 var holder = state.corkedRequestsFree;
16517 holder.entry = entry;
16518
16519 var count = 0;
16520 var allBuffers = true;
16521 while (entry) {
16522 buffer[count] = entry;
16523 if (!entry.isBuf) allBuffers = false;
16524 entry = entry.next;
16525 count += 1;
16526 }
16527 buffer.allBuffers = allBuffers;
16528
16529 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
16530
16531 // doWrite is almost always async, defer these to save a bit of time
16532 // as the hot path ends with doWrite
16533 state.pendingcb++;
16534 state.lastBufferedRequest = null;
16535 if (holder.next) {
16536 state.corkedRequestsFree = holder.next;
16537 holder.next = null;
16538 } else {
16539 state.corkedRequestsFree = new CorkedRequest(state);
16540 }
16541 state.bufferedRequestCount = 0;
16542 } else {
16543 // Slow case, write chunks one-by-one
16544 while (entry) {
16545 var chunk = entry.chunk;
16546 var encoding = entry.encoding;
16547 var cb = entry.callback;
16548 var len = state.objectMode ? 1 : chunk.length;
16549
16550 doWrite(stream, state, false, len, chunk, encoding, cb);
16551 entry = entry.next;
16552 state.bufferedRequestCount--;
16553 // if we didn't call the onwrite immediately, then
16554 // it means that we need to wait until it does.
16555 // also, that means that the chunk and cb are currently
16556 // being processed, so move the buffer counter past them.
16557 if (state.writing) {
16558 break;
16559 }
16560 }
16561
16562 if (entry === null) state.lastBufferedRequest = null;
16563 }
16564
16565 state.bufferedRequest = entry;
16566 state.bufferProcessing = false;
16567}
16568
16569Writable.prototype._write = function (chunk, encoding, cb) {
16570 cb(new Error('_write() is not implemented'));
16571};
16572
16573Writable.prototype._writev = null;
16574
16575Writable.prototype.end = function (chunk, encoding, cb) {
16576 var state = this._writableState;
16577
16578 if (typeof chunk === 'function') {
16579 cb = chunk;
16580 chunk = null;
16581 encoding = null;
16582 } else if (typeof encoding === 'function') {
16583 cb = encoding;
16584 encoding = null;
16585 }
16586
16587 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
16588
16589 // .end() fully uncorks
16590 if (state.corked) {
16591 state.corked = 1;
16592 this.uncork();
16593 }
16594
16595 // ignore unnecessary end() calls.
16596 if (!state.ending && !state.finished) endWritable(this, state, cb);
16597};
16598
16599function needFinish(state) {
16600 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
16601}
16602function callFinal(stream, state) {
16603 stream._final(function (err) {
16604 state.pendingcb--;
16605 if (err) {
16606 stream.emit('error', err);
16607 }
16608 state.prefinished = true;
16609 stream.emit('prefinish');
16610 finishMaybe(stream, state);
16611 });
16612}
16613function prefinish(stream, state) {
16614 if (!state.prefinished && !state.finalCalled) {
16615 if (typeof stream._final === 'function') {
16616 state.pendingcb++;
16617 state.finalCalled = true;
16618 pna.nextTick(callFinal, stream, state);
16619 } else {
16620 state.prefinished = true;
16621 stream.emit('prefinish');
16622 }
16623 }
16624}
16625
16626function finishMaybe(stream, state) {
16627 var need = needFinish(state);
16628 if (need) {
16629 prefinish(stream, state);
16630 if (state.pendingcb === 0) {
16631 state.finished = true;
16632 stream.emit('finish');
16633 }
16634 }
16635 return need;
16636}
16637
16638function endWritable(stream, state, cb) {
16639 state.ending = true;
16640 finishMaybe(stream, state);
16641 if (cb) {
16642 if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
16643 }
16644 state.ended = true;
16645 stream.writable = false;
16646}
16647
16648function onCorkedFinish(corkReq, state, err) {
16649 var entry = corkReq.entry;
16650 corkReq.entry = null;
16651 while (entry) {
16652 var cb = entry.callback;
16653 state.pendingcb--;
16654 cb(err);
16655 entry = entry.next;
16656 }
16657 if (state.corkedRequestsFree) {
16658 state.corkedRequestsFree.next = corkReq;
16659 } else {
16660 state.corkedRequestsFree = corkReq;
16661 }
16662}
16663
16664Object.defineProperty(Writable.prototype, 'destroyed', {
16665 get: function () {
16666 if (this._writableState === undefined) {
16667 return false;
16668 }
16669 return this._writableState.destroyed;
16670 },
16671 set: function (value) {
16672 // we ignore the value if the stream
16673 // has not been initialized yet
16674 if (!this._writableState) {
16675 return;
16676 }
16677
16678 // backward compatibility, the user is explicitly
16679 // managing destroyed
16680 this._writableState.destroyed = value;
16681 }
16682});
16683
16684Writable.prototype.destroy = destroyImpl.destroy;
16685Writable.prototype._undestroy = destroyImpl.undestroy;
16686Writable.prototype._destroy = function (err, cb) {
16687 this.end();
16688 cb(err);
16689};
16690}).call(this)}).call(this,_dereq_(66),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_(112).setImmediate)
16691},{"112":112,"113":113,"29":29,"65":65,"66":66,"81":81,"87":87,"88":88,"9":9,"93":93}],86:[function(_dereq_,module,exports){
16692'use strict';
16693
16694function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
16695
16696var Buffer = _dereq_(93).Buffer;
16697var util = _dereq_(6);
16698
16699function copyBuffer(src, target, offset) {
16700 src.copy(target, offset);
16701}
16702
16703module.exports = function () {
16704 function BufferList() {
16705 _classCallCheck(this, BufferList);
16706
16707 this.head = null;
16708 this.tail = null;
16709 this.length = 0;
16710 }
16711
16712 BufferList.prototype.push = function push(v) {
16713 var entry = { data: v, next: null };
16714 if (this.length > 0) this.tail.next = entry;else this.head = entry;
16715 this.tail = entry;
16716 ++this.length;
16717 };
16718
16719 BufferList.prototype.unshift = function unshift(v) {
16720 var entry = { data: v, next: this.head };
16721 if (this.length === 0) this.tail = entry;
16722 this.head = entry;
16723 ++this.length;
16724 };
16725
16726 BufferList.prototype.shift = function shift() {
16727 if (this.length === 0) return;
16728 var ret = this.head.data;
16729 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
16730 --this.length;
16731 return ret;
16732 };
16733
16734 BufferList.prototype.clear = function clear() {
16735 this.head = this.tail = null;
16736 this.length = 0;
16737 };
16738
16739 BufferList.prototype.join = function join(s) {
16740 if (this.length === 0) return '';
16741 var p = this.head;
16742 var ret = '' + p.data;
16743 while (p = p.next) {
16744 ret += s + p.data;
16745 }return ret;
16746 };
16747
16748 BufferList.prototype.concat = function concat(n) {
16749 if (this.length === 0) return Buffer.alloc(0);
16750 if (this.length === 1) return this.head.data;
16751 var ret = Buffer.allocUnsafe(n >>> 0);
16752 var p = this.head;
16753 var i = 0;
16754 while (p) {
16755 copyBuffer(p.data, ret, i);
16756 i += p.data.length;
16757 p = p.next;
16758 }
16759 return ret;
16760 };
16761
16762 return BufferList;
16763}();
16764
16765if (util && util.inspect && util.inspect.custom) {
16766 module.exports.prototype[util.inspect.custom] = function () {
16767 var obj = util.inspect({ length: this.length });
16768 return this.constructor.name + ' ' + obj;
16769 };
16770}
16771},{"6":6,"93":93}],87:[function(_dereq_,module,exports){
16772'use strict';
16773
16774/*<replacement>*/
16775
16776var pna = _dereq_(65);
16777/*</replacement>*/
16778
16779// undocumented cb() API, needed for core, not for public API
16780function destroy(err, cb) {
16781 var _this = this;
16782
16783 var readableDestroyed = this._readableState && this._readableState.destroyed;
16784 var writableDestroyed = this._writableState && this._writableState.destroyed;
16785
16786 if (readableDestroyed || writableDestroyed) {
16787 if (cb) {
16788 cb(err);
16789 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
16790 pna.nextTick(emitErrorNT, this, err);
16791 }
16792 return this;
16793 }
16794
16795 // we set destroyed to true before firing error callbacks in order
16796 // to make it re-entrance safe in case destroy() is called within callbacks
16797
16798 if (this._readableState) {
16799 this._readableState.destroyed = true;
16800 }
16801
16802 // if this is a duplex stream mark the writable part as destroyed as well
16803 if (this._writableState) {
16804 this._writableState.destroyed = true;
16805 }
16806
16807 this._destroy(err || null, function (err) {
16808 if (!cb && err) {
16809 pna.nextTick(emitErrorNT, _this, err);
16810 if (_this._writableState) {
16811 _this._writableState.errorEmitted = true;
16812 }
16813 } else if (cb) {
16814 cb(err);
16815 }
16816 });
16817
16818 return this;
16819}
16820
16821function undestroy() {
16822 if (this._readableState) {
16823 this._readableState.destroyed = false;
16824 this._readableState.reading = false;
16825 this._readableState.ended = false;
16826 this._readableState.endEmitted = false;
16827 }
16828
16829 if (this._writableState) {
16830 this._writableState.destroyed = false;
16831 this._writableState.ended = false;
16832 this._writableState.ending = false;
16833 this._writableState.finished = false;
16834 this._writableState.errorEmitted = false;
16835 }
16836}
16837
16838function emitErrorNT(self, err) {
16839 self.emit('error', err);
16840}
16841
16842module.exports = {
16843 destroy: destroy,
16844 undestroy: undestroy
16845};
16846},{"65":65}],88:[function(_dereq_,module,exports){
16847arguments[4][48][0].apply(exports,arguments)
16848},{"20":20,"48":48}],89:[function(_dereq_,module,exports){
16849module.exports = _dereq_(90).PassThrough
16850
16851},{"90":90}],90:[function(_dereq_,module,exports){
16852exports = module.exports = _dereq_(83);
16853exports.Stream = exports;
16854exports.Readable = exports;
16855exports.Writable = _dereq_(85);
16856exports.Duplex = _dereq_(81);
16857exports.Transform = _dereq_(84);
16858exports.PassThrough = _dereq_(82);
16859
16860},{"81":81,"82":82,"83":83,"84":84,"85":85}],91:[function(_dereq_,module,exports){
16861module.exports = _dereq_(90).Transform
16862
16863},{"90":90}],92:[function(_dereq_,module,exports){
16864module.exports = _dereq_(85);
16865
16866},{"85":85}],93:[function(_dereq_,module,exports){
16867arguments[4][63][0].apply(exports,arguments)
16868},{"63":63,"8":8}],94:[function(_dereq_,module,exports){
16869// Copyright Joyent, Inc. and other Node contributors.
16870//
16871// Permission is hereby granted, free of charge, to any person obtaining a
16872// copy of this software and associated documentation files (the
16873// "Software"), to deal in the Software without restriction, including
16874// without limitation the rights to use, copy, modify, merge, publish,
16875// distribute, sublicense, and/or sell copies of the Software, and to permit
16876// persons to whom the Software is furnished to do so, subject to the
16877// following conditions:
16878//
16879// The above copyright notice and this permission notice shall be included
16880// in all copies or substantial portions of the Software.
16881//
16882// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16883// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16884// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
16885// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
16886// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16887// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
16888// USE OR OTHER DEALINGS IN THE SOFTWARE.
16889
16890'use strict';
16891
16892/*<replacement>*/
16893
16894var Buffer = _dereq_(93).Buffer;
16895/*</replacement>*/
16896
16897var isEncoding = Buffer.isEncoding || function (encoding) {
16898 encoding = '' + encoding;
16899 switch (encoding && encoding.toLowerCase()) {
16900 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':
16901 return true;
16902 default:
16903 return false;
16904 }
16905};
16906
16907function _normalizeEncoding(enc) {
16908 if (!enc) return 'utf8';
16909 var retried;
16910 while (true) {
16911 switch (enc) {
16912 case 'utf8':
16913 case 'utf-8':
16914 return 'utf8';
16915 case 'ucs2':
16916 case 'ucs-2':
16917 case 'utf16le':
16918 case 'utf-16le':
16919 return 'utf16le';
16920 case 'latin1':
16921 case 'binary':
16922 return 'latin1';
16923 case 'base64':
16924 case 'ascii':
16925 case 'hex':
16926 return enc;
16927 default:
16928 if (retried) return; // undefined
16929 enc = ('' + enc).toLowerCase();
16930 retried = true;
16931 }
16932 }
16933};
16934
16935// Do not cache `Buffer.isEncoding` when checking encoding names as some
16936// modules monkey-patch it to support additional encodings
16937function normalizeEncoding(enc) {
16938 var nenc = _normalizeEncoding(enc);
16939 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
16940 return nenc || enc;
16941}
16942
16943// StringDecoder provides an interface for efficiently splitting a series of
16944// buffers into a series of JS strings without breaking apart multi-byte
16945// characters.
16946exports.StringDecoder = StringDecoder;
16947function StringDecoder(encoding) {
16948 this.encoding = normalizeEncoding(encoding);
16949 var nb;
16950 switch (this.encoding) {
16951 case 'utf16le':
16952 this.text = utf16Text;
16953 this.end = utf16End;
16954 nb = 4;
16955 break;
16956 case 'utf8':
16957 this.fillLast = utf8FillLast;
16958 nb = 4;
16959 break;
16960 case 'base64':
16961 this.text = base64Text;
16962 this.end = base64End;
16963 nb = 3;
16964 break;
16965 default:
16966 this.write = simpleWrite;
16967 this.end = simpleEnd;
16968 return;
16969 }
16970 this.lastNeed = 0;
16971 this.lastTotal = 0;
16972 this.lastChar = Buffer.allocUnsafe(nb);
16973}
16974
16975StringDecoder.prototype.write = function (buf) {
16976 if (buf.length === 0) return '';
16977 var r;
16978 var i;
16979 if (this.lastNeed) {
16980 r = this.fillLast(buf);
16981 if (r === undefined) return '';
16982 i = this.lastNeed;
16983 this.lastNeed = 0;
16984 } else {
16985 i = 0;
16986 }
16987 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
16988 return r || '';
16989};
16990
16991StringDecoder.prototype.end = utf8End;
16992
16993// Returns only complete characters in a Buffer
16994StringDecoder.prototype.text = utf8Text;
16995
16996// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
16997StringDecoder.prototype.fillLast = function (buf) {
16998 if (this.lastNeed <= buf.length) {
16999 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
17000 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
17001 }
17002 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
17003 this.lastNeed -= buf.length;
17004};
17005
17006// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
17007// continuation byte. If an invalid byte is detected, -2 is returned.
17008function utf8CheckByte(byte) {
17009 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;
17010 return byte >> 6 === 0x02 ? -1 : -2;
17011}
17012
17013// Checks at most 3 bytes at the end of a Buffer in order to detect an
17014// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
17015// needed to complete the UTF-8 character (if applicable) are returned.
17016function utf8CheckIncomplete(self, buf, i) {
17017 var j = buf.length - 1;
17018 if (j < i) return 0;
17019 var nb = utf8CheckByte(buf[j]);
17020 if (nb >= 0) {
17021 if (nb > 0) self.lastNeed = nb - 1;
17022 return nb;
17023 }
17024 if (--j < i || nb === -2) return 0;
17025 nb = utf8CheckByte(buf[j]);
17026 if (nb >= 0) {
17027 if (nb > 0) self.lastNeed = nb - 2;
17028 return nb;
17029 }
17030 if (--j < i || nb === -2) return 0;
17031 nb = utf8CheckByte(buf[j]);
17032 if (nb >= 0) {
17033 if (nb > 0) {
17034 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
17035 }
17036 return nb;
17037 }
17038 return 0;
17039}
17040
17041// Validates as many continuation bytes for a multi-byte UTF-8 character as
17042// needed or are available. If we see a non-continuation byte where we expect
17043// one, we "replace" the validated continuation bytes we've seen so far with
17044// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
17045// behavior. The continuation byte check is included three times in the case
17046// where all of the continuation bytes for a character exist in the same buffer.
17047// It is also done this way as a slight performance increase instead of using a
17048// loop.
17049function utf8CheckExtraBytes(self, buf, p) {
17050 if ((buf[0] & 0xC0) !== 0x80) {
17051 self.lastNeed = 0;
17052 return '\ufffd';
17053 }
17054 if (self.lastNeed > 1 && buf.length > 1) {
17055 if ((buf[1] & 0xC0) !== 0x80) {
17056 self.lastNeed = 1;
17057 return '\ufffd';
17058 }
17059 if (self.lastNeed > 2 && buf.length > 2) {
17060 if ((buf[2] & 0xC0) !== 0x80) {
17061 self.lastNeed = 2;
17062 return '\ufffd';
17063 }
17064 }
17065 }
17066}
17067
17068// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
17069function utf8FillLast(buf) {
17070 var p = this.lastTotal - this.lastNeed;
17071 var r = utf8CheckExtraBytes(this, buf, p);
17072 if (r !== undefined) return r;
17073 if (this.lastNeed <= buf.length) {
17074 buf.copy(this.lastChar, p, 0, this.lastNeed);
17075 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
17076 }
17077 buf.copy(this.lastChar, p, 0, buf.length);
17078 this.lastNeed -= buf.length;
17079}
17080
17081// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
17082// partial character, the character's bytes are buffered until the required
17083// number of bytes are available.
17084function utf8Text(buf, i) {
17085 var total = utf8CheckIncomplete(this, buf, i);
17086 if (!this.lastNeed) return buf.toString('utf8', i);
17087 this.lastTotal = total;
17088 var end = buf.length - (total - this.lastNeed);
17089 buf.copy(this.lastChar, 0, end);
17090 return buf.toString('utf8', i, end);
17091}
17092
17093// For UTF-8, a replacement character is added when ending on a partial
17094// character.
17095function utf8End(buf) {
17096 var r = buf && buf.length ? this.write(buf) : '';
17097 if (this.lastNeed) return r + '\ufffd';
17098 return r;
17099}
17100
17101// UTF-16LE typically needs two bytes per character, but even if we have an even
17102// number of bytes available, we need to check if we end on a leading/high
17103// surrogate. In that case, we need to wait for the next two bytes in order to
17104// decode the last character properly.
17105function utf16Text(buf, i) {
17106 if ((buf.length - i) % 2 === 0) {
17107 var r = buf.toString('utf16le', i);
17108 if (r) {
17109 var c = r.charCodeAt(r.length - 1);
17110 if (c >= 0xD800 && c <= 0xDBFF) {
17111 this.lastNeed = 2;
17112 this.lastTotal = 4;
17113 this.lastChar[0] = buf[buf.length - 2];
17114 this.lastChar[1] = buf[buf.length - 1];
17115 return r.slice(0, -1);
17116 }
17117 }
17118 return r;
17119 }
17120 this.lastNeed = 1;
17121 this.lastTotal = 2;
17122 this.lastChar[0] = buf[buf.length - 1];
17123 return buf.toString('utf16le', i, buf.length - 1);
17124}
17125
17126// For UTF-16LE we do not explicitly append special replacement characters if we
17127// end on a partial character, we simply let v8 handle that.
17128function utf16End(buf) {
17129 var r = buf && buf.length ? this.write(buf) : '';
17130 if (this.lastNeed) {
17131 var end = this.lastTotal - this.lastNeed;
17132 return r + this.lastChar.toString('utf16le', 0, end);
17133 }
17134 return r;
17135}
17136
17137function base64Text(buf, i) {
17138 var n = (buf.length - i) % 3;
17139 if (n === 0) return buf.toString('base64', i);
17140 this.lastNeed = 3 - n;
17141 this.lastTotal = 3;
17142 if (n === 1) {
17143 this.lastChar[0] = buf[buf.length - 1];
17144 } else {
17145 this.lastChar[0] = buf[buf.length - 2];
17146 this.lastChar[1] = buf[buf.length - 1];
17147 }
17148 return buf.toString('base64', i, buf.length - n);
17149}
17150
17151function base64End(buf) {
17152 var r = buf && buf.length ? this.write(buf) : '';
17153 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
17154 return r;
17155}
17156
17157// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
17158function simpleWrite(buf) {
17159 return buf.toString(this.encoding);
17160}
17161
17162function simpleEnd(buf) {
17163 return buf && buf.length ? this.write(buf) : '';
17164}
17165},{"93":93}],95:[function(_dereq_,module,exports){
17166arguments[4][94][0].apply(exports,arguments)
17167},{"76":76,"94":94}],96:[function(_dereq_,module,exports){
17168arguments[4][35][0].apply(exports,arguments)
17169},{"35":35}],97:[function(_dereq_,module,exports){
17170arguments[4][36][0].apply(exports,arguments)
17171},{"101":101,"29":29,"36":36,"66":66,"99":99}],98:[function(_dereq_,module,exports){
17172arguments[4][37][0].apply(exports,arguments)
17173},{"100":100,"29":29,"37":37}],99:[function(_dereq_,module,exports){
17174arguments[4][38][0].apply(exports,arguments)
17175},{"102":102,"103":103,"104":104,"106":106,"108":108,"109":109,"20":20,"29":29,"38":38,"6":6,"66":66,"8":8,"95":95,"96":96,"97":97}],100:[function(_dereq_,module,exports){
17176arguments[4][39][0].apply(exports,arguments)
17177},{"29":29,"39":39,"96":96,"97":97}],101:[function(_dereq_,module,exports){
17178arguments[4][40][0].apply(exports,arguments)
17179},{"104":104,"108":108,"109":109,"113":113,"29":29,"40":40,"66":66,"8":8,"96":96,"97":97}],102:[function(_dereq_,module,exports){
17180arguments[4][41][0].apply(exports,arguments)
17181},{"105":105,"41":41,"66":66}],103:[function(_dereq_,module,exports){
17182arguments[4][42][0].apply(exports,arguments)
17183},{"42":42,"6":6,"8":8}],104:[function(_dereq_,module,exports){
17184arguments[4][43][0].apply(exports,arguments)
17185},{"43":43,"66":66}],105:[function(_dereq_,module,exports){
17186arguments[4][44][0].apply(exports,arguments)
17187},{"44":44,"96":96}],106:[function(_dereq_,module,exports){
17188arguments[4][45][0].apply(exports,arguments)
17189},{"45":45}],107:[function(_dereq_,module,exports){
17190arguments[4][46][0].apply(exports,arguments)
17191},{"105":105,"46":46,"96":96}],108:[function(_dereq_,module,exports){
17192arguments[4][47][0].apply(exports,arguments)
17193},{"47":47,"96":96}],109:[function(_dereq_,module,exports){
17194arguments[4][48][0].apply(exports,arguments)
17195},{"20":20,"48":48}],110:[function(_dereq_,module,exports){
17196arguments[4][49][0].apply(exports,arguments)
17197},{"100":100,"101":101,"105":105,"107":107,"49":49,"97":97,"98":98,"99":99}],111:[function(_dereq_,module,exports){
17198(function (process){(function (){
17199var Transform = _dereq_(110).Transform
17200 , inherits = _dereq_(29)
17201
17202function DestroyableTransform(opts) {
17203 Transform.call(this, opts)
17204 this._destroyed = false
17205}
17206
17207inherits(DestroyableTransform, Transform)
17208
17209DestroyableTransform.prototype.destroy = function(err) {
17210 if (this._destroyed) return
17211 this._destroyed = true
17212
17213 var self = this
17214 process.nextTick(function() {
17215 if (err)
17216 self.emit('error', err)
17217 self.emit('close')
17218 })
17219}
17220
17221// a noop _transform function
17222function noop (chunk, enc, callback) {
17223 callback(null, chunk)
17224}
17225
17226
17227// create a new export function, used by both the main export and
17228// the .ctor export, contains common logic for dealing with arguments
17229function through2 (construct) {
17230 return function (options, transform, flush) {
17231 if (typeof options == 'function') {
17232 flush = transform
17233 transform = options
17234 options = {}
17235 }
17236
17237 if (typeof transform != 'function')
17238 transform = noop
17239
17240 if (typeof flush != 'function')
17241 flush = null
17242
17243 return construct(options, transform, flush)
17244 }
17245}
17246
17247
17248// main export, just make me a transform stream!
17249module.exports = through2(function (options, transform, flush) {
17250 var t2 = new DestroyableTransform(options)
17251
17252 t2._transform = transform
17253
17254 if (flush)
17255 t2._flush = flush
17256
17257 return t2
17258})
17259
17260
17261// make me a reusable prototype that I can `new`, or implicitly `new`
17262// with a constructor call
17263module.exports.ctor = through2(function (options, transform, flush) {
17264 function Through2 (override) {
17265 if (!(this instanceof Through2))
17266 return new Through2(override)
17267
17268 this.options = Object.assign({}, options, override)
17269
17270 DestroyableTransform.call(this, this.options)
17271 }
17272
17273 inherits(Through2, DestroyableTransform)
17274
17275 Through2.prototype._transform = transform
17276
17277 if (flush)
17278 Through2.prototype._flush = flush
17279
17280 return Through2
17281})
17282
17283
17284module.exports.obj = through2(function (options, transform, flush) {
17285 var t2 = new DestroyableTransform(Object.assign({ objectMode: true, highWaterMark: 16 }, options))
17286
17287 t2._transform = transform
17288
17289 if (flush)
17290 t2._flush = flush
17291
17292 return t2
17293})
17294
17295}).call(this)}).call(this,_dereq_(66))
17296},{"110":110,"29":29,"66":66}],112:[function(_dereq_,module,exports){
17297(function (setImmediate,clearImmediate){(function (){
17298var nextTick = _dereq_(66).nextTick;
17299var apply = Function.prototype.apply;
17300var slice = Array.prototype.slice;
17301var immediateIds = {};
17302var nextImmediateId = 0;
17303
17304// DOM APIs, for completeness
17305
17306exports.setTimeout = function() {
17307 return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
17308};
17309exports.setInterval = function() {
17310 return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
17311};
17312exports.clearTimeout =
17313exports.clearInterval = function(timeout) { timeout.close(); };
17314
17315function Timeout(id, clearFn) {
17316 this._id = id;
17317 this._clearFn = clearFn;
17318}
17319Timeout.prototype.unref = Timeout.prototype.ref = function() {};
17320Timeout.prototype.close = function() {
17321 this._clearFn.call(window, this._id);
17322};
17323
17324// Does not start the time, just sets up the members needed.
17325exports.enroll = function(item, msecs) {
17326 clearTimeout(item._idleTimeoutId);
17327 item._idleTimeout = msecs;
17328};
17329
17330exports.unenroll = function(item) {
17331 clearTimeout(item._idleTimeoutId);
17332 item._idleTimeout = -1;
17333};
17334
17335exports._unrefActive = exports.active = function(item) {
17336 clearTimeout(item._idleTimeoutId);
17337
17338 var msecs = item._idleTimeout;
17339 if (msecs >= 0) {
17340 item._idleTimeoutId = setTimeout(function onTimeout() {
17341 if (item._onTimeout)
17342 item._onTimeout();
17343 }, msecs);
17344 }
17345};
17346
17347// That's not how node.js implements it but the exposed api is the same.
17348exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
17349 var id = nextImmediateId++;
17350 var args = arguments.length < 2 ? false : slice.call(arguments, 1);
17351
17352 immediateIds[id] = true;
17353
17354 nextTick(function onNextTick() {
17355 if (immediateIds[id]) {
17356 // fn.call() is faster so we optimize for the common use-case
17357 // @see http://jsperf.com/call-apply-segu
17358 if (args) {
17359 fn.apply(null, args);
17360 } else {
17361 fn.call(null);
17362 }
17363 // Prevent ids from leaking
17364 exports.clearImmediate(id);
17365 }
17366 });
17367
17368 return id;
17369};
17370
17371exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
17372 delete immediateIds[id];
17373};
17374}).call(this)}).call(this,_dereq_(112).setImmediate,_dereq_(112).clearImmediate)
17375},{"112":112,"66":66}],113:[function(_dereq_,module,exports){
17376(function (global){(function (){
17377
17378/**
17379 * Module exports.
17380 */
17381
17382module.exports = deprecate;
17383
17384/**
17385 * Mark that a method should not be used.
17386 * Returns a modified function which warns once by default.
17387 *
17388 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
17389 *
17390 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
17391 * will throw an Error when invoked.
17392 *
17393 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
17394 * will invoke `console.trace()` instead of `console.error()`.
17395 *
17396 * @param {Function} fn - the function to deprecate
17397 * @param {String} msg - the string to print to the console when `fn` is invoked
17398 * @returns {Function} a new "deprecated" version of `fn`
17399 * @api public
17400 */
17401
17402function deprecate (fn, msg) {
17403 if (config('noDeprecation')) {
17404 return fn;
17405 }
17406
17407 var warned = false;
17408 function deprecated() {
17409 if (!warned) {
17410 if (config('throwDeprecation')) {
17411 throw new Error(msg);
17412 } else if (config('traceDeprecation')) {
17413 console.trace(msg);
17414 } else {
17415 console.warn(msg);
17416 }
17417 warned = true;
17418 }
17419 return fn.apply(this, arguments);
17420 }
17421
17422 return deprecated;
17423}
17424
17425/**
17426 * Checks `localStorage` for boolean values for the given `name`.
17427 *
17428 * @param {String} name
17429 * @returns {Boolean}
17430 * @api private
17431 */
17432
17433function config (name) {
17434 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
17435 try {
17436 if (!global.localStorage) return false;
17437 } catch (_) {
17438 return false;
17439 }
17440 var val = global.localStorage[name];
17441 if (null == val) return false;
17442 return String(val).toLowerCase() === 'true';
17443}
17444
17445}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
17446},{}],114:[function(_dereq_,module,exports){
17447arguments[4][2][0].apply(exports,arguments)
17448},{"2":2}],115:[function(_dereq_,module,exports){
17449arguments[4][3][0].apply(exports,arguments)
17450},{"3":3}],116:[function(_dereq_,module,exports){
17451arguments[4][4][0].apply(exports,arguments)
17452},{"114":114,"115":115,"4":4,"66":66}],117:[function(_dereq_,module,exports){
17453"use strict";
17454
17455Object.defineProperty(exports, "__esModule", {
17456 value: true
17457});
17458Object.defineProperty(exports, "v1", {
17459 enumerable: true,
17460 get: function () {
17461 return _v.default;
17462 }
17463});
17464Object.defineProperty(exports, "v3", {
17465 enumerable: true,
17466 get: function () {
17467 return _v2.default;
17468 }
17469});
17470Object.defineProperty(exports, "v4", {
17471 enumerable: true,
17472 get: function () {
17473 return _v3.default;
17474 }
17475});
17476Object.defineProperty(exports, "v5", {
17477 enumerable: true,
17478 get: function () {
17479 return _v4.default;
17480 }
17481});
17482Object.defineProperty(exports, "NIL", {
17483 enumerable: true,
17484 get: function () {
17485 return _nil.default;
17486 }
17487});
17488Object.defineProperty(exports, "version", {
17489 enumerable: true,
17490 get: function () {
17491 return _version.default;
17492 }
17493});
17494Object.defineProperty(exports, "validate", {
17495 enumerable: true,
17496 get: function () {
17497 return _validate.default;
17498 }
17499});
17500Object.defineProperty(exports, "stringify", {
17501 enumerable: true,
17502 get: function () {
17503 return _stringify.default;
17504 }
17505});
17506Object.defineProperty(exports, "parse", {
17507 enumerable: true,
17508 get: function () {
17509 return _parse.default;
17510 }
17511});
17512
17513var _v = _interopRequireDefault(_dereq_(125));
17514
17515var _v2 = _interopRequireDefault(_dereq_(126));
17516
17517var _v3 = _interopRequireDefault(_dereq_(128));
17518
17519var _v4 = _interopRequireDefault(_dereq_(129));
17520
17521var _nil = _interopRequireDefault(_dereq_(119));
17522
17523var _version = _interopRequireDefault(_dereq_(131));
17524
17525var _validate = _interopRequireDefault(_dereq_(130));
17526
17527var _stringify = _interopRequireDefault(_dereq_(124));
17528
17529var _parse = _interopRequireDefault(_dereq_(120));
17530
17531function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17532},{"119":119,"120":120,"124":124,"125":125,"126":126,"128":128,"129":129,"130":130,"131":131}],118:[function(_dereq_,module,exports){
17533"use strict";
17534
17535Object.defineProperty(exports, "__esModule", {
17536 value: true
17537});
17538exports.default = void 0;
17539
17540/*
17541 * Browser-compatible JavaScript MD5
17542 *
17543 * Modification of JavaScript MD5
17544 * https://github.com/blueimp/JavaScript-MD5
17545 *
17546 * Copyright 2011, Sebastian Tschan
17547 * https://blueimp.net
17548 *
17549 * Licensed under the MIT license:
17550 * https://opensource.org/licenses/MIT
17551 *
17552 * Based on
17553 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
17554 * Digest Algorithm, as defined in RFC 1321.
17555 * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
17556 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
17557 * Distributed under the BSD License
17558 * See http://pajhome.org.uk/crypt/md5 for more info.
17559 */
17560function md5(bytes) {
17561 if (typeof bytes === 'string') {
17562 const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
17563
17564 bytes = new Uint8Array(msg.length);
17565
17566 for (let i = 0; i < msg.length; ++i) {
17567 bytes[i] = msg.charCodeAt(i);
17568 }
17569 }
17570
17571 return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));
17572}
17573/*
17574 * Convert an array of little-endian words to an array of bytes
17575 */
17576
17577
17578function md5ToHexEncodedArray(input) {
17579 const output = [];
17580 const length32 = input.length * 32;
17581 const hexTab = '0123456789abcdef';
17582
17583 for (let i = 0; i < length32; i += 8) {
17584 const x = input[i >> 5] >>> i % 32 & 0xff;
17585 const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);
17586 output.push(hex);
17587 }
17588
17589 return output;
17590}
17591/**
17592 * Calculate output length with padding and bit length
17593 */
17594
17595
17596function getOutputLength(inputLength8) {
17597 return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
17598}
17599/*
17600 * Calculate the MD5 of an array of little-endian words, and a bit length.
17601 */
17602
17603
17604function wordsToMd5(x, len) {
17605 /* append padding */
17606 x[len >> 5] |= 0x80 << len % 32;
17607 x[getOutputLength(len) - 1] = len;
17608 let a = 1732584193;
17609 let b = -271733879;
17610 let c = -1732584194;
17611 let d = 271733878;
17612
17613 for (let i = 0; i < x.length; i += 16) {
17614 const olda = a;
17615 const oldb = b;
17616 const oldc = c;
17617 const oldd = d;
17618 a = md5ff(a, b, c, d, x[i], 7, -680876936);
17619 d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
17620 c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
17621 b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
17622 a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
17623 d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
17624 c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
17625 b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
17626 a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
17627 d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
17628 c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
17629 b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
17630 a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
17631 d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
17632 c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
17633 b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
17634 a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
17635 d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
17636 c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
17637 b = md5gg(b, c, d, a, x[i], 20, -373897302);
17638 a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
17639 d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
17640 c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
17641 b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
17642 a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
17643 d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
17644 c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
17645 b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
17646 a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
17647 d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
17648 c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
17649 b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
17650 a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
17651 d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
17652 c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
17653 b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
17654 a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
17655 d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
17656 c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
17657 b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
17658 a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
17659 d = md5hh(d, a, b, c, x[i], 11, -358537222);
17660 c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
17661 b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
17662 a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
17663 d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
17664 c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
17665 b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
17666 a = md5ii(a, b, c, d, x[i], 6, -198630844);
17667 d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
17668 c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
17669 b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
17670 a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
17671 d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
17672 c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
17673 b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
17674 a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
17675 d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
17676 c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
17677 b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
17678 a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
17679 d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
17680 c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
17681 b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
17682 a = safeAdd(a, olda);
17683 b = safeAdd(b, oldb);
17684 c = safeAdd(c, oldc);
17685 d = safeAdd(d, oldd);
17686 }
17687
17688 return [a, b, c, d];
17689}
17690/*
17691 * Convert an array bytes to an array of little-endian words
17692 * Characters >255 have their high-byte silently ignored.
17693 */
17694
17695
17696function bytesToWords(input) {
17697 if (input.length === 0) {
17698 return [];
17699 }
17700
17701 const length8 = input.length * 8;
17702 const output = new Uint32Array(getOutputLength(length8));
17703
17704 for (let i = 0; i < length8; i += 8) {
17705 output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;
17706 }
17707
17708 return output;
17709}
17710/*
17711 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
17712 * to work around bugs in some JS interpreters.
17713 */
17714
17715
17716function safeAdd(x, y) {
17717 const lsw = (x & 0xffff) + (y & 0xffff);
17718 const msw = (x >> 16) + (y >> 16) + (lsw >> 16);
17719 return msw << 16 | lsw & 0xffff;
17720}
17721/*
17722 * Bitwise rotate a 32-bit number to the left.
17723 */
17724
17725
17726function bitRotateLeft(num, cnt) {
17727 return num << cnt | num >>> 32 - cnt;
17728}
17729/*
17730 * These functions implement the four basic operations the algorithm uses.
17731 */
17732
17733
17734function md5cmn(q, a, b, x, s, t) {
17735 return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
17736}
17737
17738function md5ff(a, b, c, d, x, s, t) {
17739 return md5cmn(b & c | ~b & d, a, b, x, s, t);
17740}
17741
17742function md5gg(a, b, c, d, x, s, t) {
17743 return md5cmn(b & d | c & ~d, a, b, x, s, t);
17744}
17745
17746function md5hh(a, b, c, d, x, s, t) {
17747 return md5cmn(b ^ c ^ d, a, b, x, s, t);
17748}
17749
17750function md5ii(a, b, c, d, x, s, t) {
17751 return md5cmn(c ^ (b | ~d), a, b, x, s, t);
17752}
17753
17754var _default = md5;
17755exports.default = _default;
17756},{}],119:[function(_dereq_,module,exports){
17757"use strict";
17758
17759Object.defineProperty(exports, "__esModule", {
17760 value: true
17761});
17762exports.default = void 0;
17763var _default = '00000000-0000-0000-0000-000000000000';
17764exports.default = _default;
17765},{}],120:[function(_dereq_,module,exports){
17766"use strict";
17767
17768Object.defineProperty(exports, "__esModule", {
17769 value: true
17770});
17771exports.default = void 0;
17772
17773var _validate = _interopRequireDefault(_dereq_(130));
17774
17775function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17776
17777function parse(uuid) {
17778 if (!(0, _validate.default)(uuid)) {
17779 throw TypeError('Invalid UUID');
17780 }
17781
17782 let v;
17783 const arr = new Uint8Array(16); // Parse ########-....-....-....-............
17784
17785 arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
17786 arr[1] = v >>> 16 & 0xff;
17787 arr[2] = v >>> 8 & 0xff;
17788 arr[3] = v & 0xff; // Parse ........-####-....-....-............
17789
17790 arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
17791 arr[5] = v & 0xff; // Parse ........-....-####-....-............
17792
17793 arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
17794 arr[7] = v & 0xff; // Parse ........-....-....-####-............
17795
17796 arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
17797 arr[9] = v & 0xff; // Parse ........-....-....-....-############
17798 // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
17799
17800 arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
17801 arr[11] = v / 0x100000000 & 0xff;
17802 arr[12] = v >>> 24 & 0xff;
17803 arr[13] = v >>> 16 & 0xff;
17804 arr[14] = v >>> 8 & 0xff;
17805 arr[15] = v & 0xff;
17806 return arr;
17807}
17808
17809var _default = parse;
17810exports.default = _default;
17811},{"130":130}],121:[function(_dereq_,module,exports){
17812"use strict";
17813
17814Object.defineProperty(exports, "__esModule", {
17815 value: true
17816});
17817exports.default = void 0;
17818var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
17819exports.default = _default;
17820},{}],122:[function(_dereq_,module,exports){
17821"use strict";
17822
17823Object.defineProperty(exports, "__esModule", {
17824 value: true
17825});
17826exports.default = rng;
17827// Unique ID creation requires a high quality random # generator. In the browser we therefore
17828// require the crypto API and do not support built-in fallback to lower quality random number
17829// generators (like Math.random()).
17830let getRandomValues;
17831const rnds8 = new Uint8Array(16);
17832
17833function rng() {
17834 // lazy load so that environments that need to polyfill have a chance to do so
17835 if (!getRandomValues) {
17836 // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
17837 // find the complete implementation of crypto (msCrypto) on IE11.
17838 getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
17839
17840 if (!getRandomValues) {
17841 throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
17842 }
17843 }
17844
17845 return getRandomValues(rnds8);
17846}
17847},{}],123:[function(_dereq_,module,exports){
17848"use strict";
17849
17850Object.defineProperty(exports, "__esModule", {
17851 value: true
17852});
17853exports.default = void 0;
17854
17855// Adapted from Chris Veness' SHA1 code at
17856// http://www.movable-type.co.uk/scripts/sha1.html
17857function f(s, x, y, z) {
17858 switch (s) {
17859 case 0:
17860 return x & y ^ ~x & z;
17861
17862 case 1:
17863 return x ^ y ^ z;
17864
17865 case 2:
17866 return x & y ^ x & z ^ y & z;
17867
17868 case 3:
17869 return x ^ y ^ z;
17870 }
17871}
17872
17873function ROTL(x, n) {
17874 return x << n | x >>> 32 - n;
17875}
17876
17877function sha1(bytes) {
17878 const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
17879 const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
17880
17881 if (typeof bytes === 'string') {
17882 const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
17883
17884 bytes = [];
17885
17886 for (let i = 0; i < msg.length; ++i) {
17887 bytes.push(msg.charCodeAt(i));
17888 }
17889 } else if (!Array.isArray(bytes)) {
17890 // Convert Array-like to Array
17891 bytes = Array.prototype.slice.call(bytes);
17892 }
17893
17894 bytes.push(0x80);
17895 const l = bytes.length / 4 + 2;
17896 const N = Math.ceil(l / 16);
17897 const M = new Array(N);
17898
17899 for (let i = 0; i < N; ++i) {
17900 const arr = new Uint32Array(16);
17901
17902 for (let j = 0; j < 16; ++j) {
17903 arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3];
17904 }
17905
17906 M[i] = arr;
17907 }
17908
17909 M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
17910 M[N - 1][14] = Math.floor(M[N - 1][14]);
17911 M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;
17912
17913 for (let i = 0; i < N; ++i) {
17914 const W = new Uint32Array(80);
17915
17916 for (let t = 0; t < 16; ++t) {
17917 W[t] = M[i][t];
17918 }
17919
17920 for (let t = 16; t < 80; ++t) {
17921 W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);
17922 }
17923
17924 let a = H[0];
17925 let b = H[1];
17926 let c = H[2];
17927 let d = H[3];
17928 let e = H[4];
17929
17930 for (let t = 0; t < 80; ++t) {
17931 const s = Math.floor(t / 20);
17932 const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0;
17933 e = d;
17934 d = c;
17935 c = ROTL(b, 30) >>> 0;
17936 b = a;
17937 a = T;
17938 }
17939
17940 H[0] = H[0] + a >>> 0;
17941 H[1] = H[1] + b >>> 0;
17942 H[2] = H[2] + c >>> 0;
17943 H[3] = H[3] + d >>> 0;
17944 H[4] = H[4] + e >>> 0;
17945 }
17946
17947 return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];
17948}
17949
17950var _default = sha1;
17951exports.default = _default;
17952},{}],124:[function(_dereq_,module,exports){
17953"use strict";
17954
17955Object.defineProperty(exports, "__esModule", {
17956 value: true
17957});
17958exports.default = void 0;
17959
17960var _validate = _interopRequireDefault(_dereq_(130));
17961
17962function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17963
17964/**
17965 * Convert array of 16 byte values to UUID string format of the form:
17966 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
17967 */
17968const byteToHex = [];
17969
17970for (let i = 0; i < 256; ++i) {
17971 byteToHex.push((i + 0x100).toString(16).substr(1));
17972}
17973
17974function stringify(arr, offset = 0) {
17975 // Note: Be careful editing this code! It's been tuned for performance
17976 // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
17977 const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
17978 // of the following:
17979 // - One or more input array values don't map to a hex octet (leading to
17980 // "undefined" in the uuid)
17981 // - Invalid input values for the RFC `version` or `variant` fields
17982
17983 if (!(0, _validate.default)(uuid)) {
17984 throw TypeError('Stringified UUID is invalid');
17985 }
17986
17987 return uuid;
17988}
17989
17990var _default = stringify;
17991exports.default = _default;
17992},{"130":130}],125:[function(_dereq_,module,exports){
17993"use strict";
17994
17995Object.defineProperty(exports, "__esModule", {
17996 value: true
17997});
17998exports.default = void 0;
17999
18000var _rng = _interopRequireDefault(_dereq_(122));
18001
18002var _stringify = _interopRequireDefault(_dereq_(124));
18003
18004function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18005
18006// **`v1()` - Generate time-based UUID**
18007//
18008// Inspired by https://github.com/LiosK/UUID.js
18009// and http://docs.python.org/library/uuid.html
18010let _nodeId;
18011
18012let _clockseq; // Previous uuid creation time
18013
18014
18015let _lastMSecs = 0;
18016let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details
18017
18018function v1(options, buf, offset) {
18019 let i = buf && offset || 0;
18020 const b = buf || new Array(16);
18021 options = options || {};
18022 let node = options.node || _nodeId;
18023 let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not
18024 // specified. We do this lazily to minimize issues related to insufficient
18025 // system entropy. See #189
18026
18027 if (node == null || clockseq == null) {
18028 const seedBytes = options.random || (options.rng || _rng.default)();
18029
18030 if (node == null) {
18031 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
18032 node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
18033 }
18034
18035 if (clockseq == null) {
18036 // Per 4.2.2, randomize (14 bit) clockseq
18037 clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
18038 }
18039 } // UUID timestamps are 100 nano-second units since the Gregorian epoch,
18040 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
18041 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
18042 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
18043
18044
18045 let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock
18046 // cycle to simulate higher resolution clock
18047
18048 let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)
18049
18050 const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression
18051
18052 if (dt < 0 && options.clockseq === undefined) {
18053 clockseq = clockseq + 1 & 0x3fff;
18054 } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
18055 // time interval
18056
18057
18058 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
18059 nsecs = 0;
18060 } // Per 4.2.1.2 Throw error if too many uuids are requested
18061
18062
18063 if (nsecs >= 10000) {
18064 throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
18065 }
18066
18067 _lastMSecs = msecs;
18068 _lastNSecs = nsecs;
18069 _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
18070
18071 msecs += 12219292800000; // `time_low`
18072
18073 const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
18074 b[i++] = tl >>> 24 & 0xff;
18075 b[i++] = tl >>> 16 & 0xff;
18076 b[i++] = tl >>> 8 & 0xff;
18077 b[i++] = tl & 0xff; // `time_mid`
18078
18079 const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
18080 b[i++] = tmh >>> 8 & 0xff;
18081 b[i++] = tmh & 0xff; // `time_high_and_version`
18082
18083 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
18084
18085 b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
18086
18087 b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`
18088
18089 b[i++] = clockseq & 0xff; // `node`
18090
18091 for (let n = 0; n < 6; ++n) {
18092 b[i + n] = node[n];
18093 }
18094
18095 return buf || (0, _stringify.default)(b);
18096}
18097
18098var _default = v1;
18099exports.default = _default;
18100},{"122":122,"124":124}],126:[function(_dereq_,module,exports){
18101"use strict";
18102
18103Object.defineProperty(exports, "__esModule", {
18104 value: true
18105});
18106exports.default = void 0;
18107
18108var _v = _interopRequireDefault(_dereq_(127));
18109
18110var _md = _interopRequireDefault(_dereq_(118));
18111
18112function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18113
18114const v3 = (0, _v.default)('v3', 0x30, _md.default);
18115var _default = v3;
18116exports.default = _default;
18117},{"118":118,"127":127}],127:[function(_dereq_,module,exports){
18118"use strict";
18119
18120Object.defineProperty(exports, "__esModule", {
18121 value: true
18122});
18123exports.default = _default;
18124exports.URL = exports.DNS = void 0;
18125
18126var _stringify = _interopRequireDefault(_dereq_(124));
18127
18128var _parse = _interopRequireDefault(_dereq_(120));
18129
18130function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18131
18132function stringToBytes(str) {
18133 str = unescape(encodeURIComponent(str)); // UTF8 escape
18134
18135 const bytes = [];
18136
18137 for (let i = 0; i < str.length; ++i) {
18138 bytes.push(str.charCodeAt(i));
18139 }
18140
18141 return bytes;
18142}
18143
18144const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
18145exports.DNS = DNS;
18146const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
18147exports.URL = URL;
18148
18149function _default(name, version, hashfunc) {
18150 function generateUUID(value, namespace, buf, offset) {
18151 if (typeof value === 'string') {
18152 value = stringToBytes(value);
18153 }
18154
18155 if (typeof namespace === 'string') {
18156 namespace = (0, _parse.default)(namespace);
18157 }
18158
18159 if (namespace.length !== 16) {
18160 throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
18161 } // Compute hash of namespace and value, Per 4.3
18162 // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
18163 // hashfunc([...namespace, ... value])`
18164
18165
18166 let bytes = new Uint8Array(16 + value.length);
18167 bytes.set(namespace);
18168 bytes.set(value, namespace.length);
18169 bytes = hashfunc(bytes);
18170 bytes[6] = bytes[6] & 0x0f | version;
18171 bytes[8] = bytes[8] & 0x3f | 0x80;
18172
18173 if (buf) {
18174 offset = offset || 0;
18175
18176 for (let i = 0; i < 16; ++i) {
18177 buf[offset + i] = bytes[i];
18178 }
18179
18180 return buf;
18181 }
18182
18183 return (0, _stringify.default)(bytes);
18184 } // Function#name is not settable on some platforms (#270)
18185
18186
18187 try {
18188 generateUUID.name = name; // eslint-disable-next-line no-empty
18189 } catch (err) {} // For CommonJS default export support
18190
18191
18192 generateUUID.DNS = DNS;
18193 generateUUID.URL = URL;
18194 return generateUUID;
18195}
18196},{"120":120,"124":124}],128:[function(_dereq_,module,exports){
18197"use strict";
18198
18199Object.defineProperty(exports, "__esModule", {
18200 value: true
18201});
18202exports.default = void 0;
18203
18204var _rng = _interopRequireDefault(_dereq_(122));
18205
18206var _stringify = _interopRequireDefault(_dereq_(124));
18207
18208function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18209
18210function v4(options, buf, offset) {
18211 options = options || {};
18212
18213 const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
18214
18215
18216 rnds[6] = rnds[6] & 0x0f | 0x40;
18217 rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
18218
18219 if (buf) {
18220 offset = offset || 0;
18221
18222 for (let i = 0; i < 16; ++i) {
18223 buf[offset + i] = rnds[i];
18224 }
18225
18226 return buf;
18227 }
18228
18229 return (0, _stringify.default)(rnds);
18230}
18231
18232var _default = v4;
18233exports.default = _default;
18234},{"122":122,"124":124}],129:[function(_dereq_,module,exports){
18235"use strict";
18236
18237Object.defineProperty(exports, "__esModule", {
18238 value: true
18239});
18240exports.default = void 0;
18241
18242var _v = _interopRequireDefault(_dereq_(127));
18243
18244var _sha = _interopRequireDefault(_dereq_(123));
18245
18246function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18247
18248const v5 = (0, _v.default)('v5', 0x50, _sha.default);
18249var _default = v5;
18250exports.default = _default;
18251},{"123":123,"127":127}],130:[function(_dereq_,module,exports){
18252"use strict";
18253
18254Object.defineProperty(exports, "__esModule", {
18255 value: true
18256});
18257exports.default = void 0;
18258
18259var _regex = _interopRequireDefault(_dereq_(121));
18260
18261function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18262
18263function validate(uuid) {
18264 return typeof uuid === 'string' && _regex.default.test(uuid);
18265}
18266
18267var _default = validate;
18268exports.default = _default;
18269},{"121":121}],131:[function(_dereq_,module,exports){
18270"use strict";
18271
18272Object.defineProperty(exports, "__esModule", {
18273 value: true
18274});
18275exports.default = void 0;
18276
18277var _validate = _interopRequireDefault(_dereq_(130));
18278
18279function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18280
18281function version(uuid) {
18282 if (!(0, _validate.default)(uuid)) {
18283 throw TypeError('Invalid UUID');
18284 }
18285
18286 return parseInt(uuid.substr(14, 1), 16);
18287}
18288
18289var _default = version;
18290exports.default = _default;
18291},{"130":130}],132:[function(_dereq_,module,exports){
18292'use strict';
18293
18294/**
18295 * Stringify/parse functions that don't operate
18296 * recursively, so they avoid call stack exceeded
18297 * errors.
18298 */
18299exports.stringify = function stringify(input) {
18300 var queue = [];
18301 queue.push({obj: input});
18302
18303 var res = '';
18304 var next, obj, prefix, val, i, arrayPrefix, keys, k, key, value, objPrefix;
18305 while ((next = queue.pop())) {
18306 obj = next.obj;
18307 prefix = next.prefix || '';
18308 val = next.val || '';
18309 res += prefix;
18310 if (val) {
18311 res += val;
18312 } else if (typeof obj !== 'object') {
18313 res += typeof obj === 'undefined' ? null : JSON.stringify(obj);
18314 } else if (obj === null) {
18315 res += 'null';
18316 } else if (Array.isArray(obj)) {
18317 queue.push({val: ']'});
18318 for (i = obj.length - 1; i >= 0; i--) {
18319 arrayPrefix = i === 0 ? '' : ',';
18320 queue.push({obj: obj[i], prefix: arrayPrefix});
18321 }
18322 queue.push({val: '['});
18323 } else { // object
18324 keys = [];
18325 for (k in obj) {
18326 if (obj.hasOwnProperty(k)) {
18327 keys.push(k);
18328 }
18329 }
18330 queue.push({val: '}'});
18331 for (i = keys.length - 1; i >= 0; i--) {
18332 key = keys[i];
18333 value = obj[key];
18334 objPrefix = (i > 0 ? ',' : '');
18335 objPrefix += JSON.stringify(key) + ':';
18336 queue.push({obj: value, prefix: objPrefix});
18337 }
18338 queue.push({val: '{'});
18339 }
18340 }
18341 return res;
18342};
18343
18344// Convenience function for the parse function.
18345// This pop function is basically copied from
18346// pouchCollate.parseIndexableString
18347function pop(obj, stack, metaStack) {
18348 var lastMetaElement = metaStack[metaStack.length - 1];
18349 if (obj === lastMetaElement.element) {
18350 // popping a meta-element, e.g. an object whose value is another object
18351 metaStack.pop();
18352 lastMetaElement = metaStack[metaStack.length - 1];
18353 }
18354 var element = lastMetaElement.element;
18355 var lastElementIndex = lastMetaElement.index;
18356 if (Array.isArray(element)) {
18357 element.push(obj);
18358 } else if (lastElementIndex === stack.length - 2) { // obj with key+value
18359 var key = stack.pop();
18360 element[key] = obj;
18361 } else {
18362 stack.push(obj); // obj with key only
18363 }
18364}
18365
18366exports.parse = function (str) {
18367 var stack = [];
18368 var metaStack = []; // stack for arrays and objects
18369 var i = 0;
18370 var collationIndex,parsedNum,numChar;
18371 var parsedString,lastCh,numConsecutiveSlashes,ch;
18372 var arrayElement, objElement;
18373 while (true) {
18374 collationIndex = str[i++];
18375 if (collationIndex === '}' ||
18376 collationIndex === ']' ||
18377 typeof collationIndex === 'undefined') {
18378 if (stack.length === 1) {
18379 return stack.pop();
18380 } else {
18381 pop(stack.pop(), stack, metaStack);
18382 continue;
18383 }
18384 }
18385 switch (collationIndex) {
18386 case ' ':
18387 case '\t':
18388 case '\n':
18389 case ':':
18390 case ',':
18391 break;
18392 case 'n':
18393 i += 3; // 'ull'
18394 pop(null, stack, metaStack);
18395 break;
18396 case 't':
18397 i += 3; // 'rue'
18398 pop(true, stack, metaStack);
18399 break;
18400 case 'f':
18401 i += 4; // 'alse'
18402 pop(false, stack, metaStack);
18403 break;
18404 case '0':
18405 case '1':
18406 case '2':
18407 case '3':
18408 case '4':
18409 case '5':
18410 case '6':
18411 case '7':
18412 case '8':
18413 case '9':
18414 case '-':
18415 parsedNum = '';
18416 i--;
18417 while (true) {
18418 numChar = str[i++];
18419 if (/[\d\.\-e\+]/.test(numChar)) {
18420 parsedNum += numChar;
18421 } else {
18422 i--;
18423 break;
18424 }
18425 }
18426 pop(parseFloat(parsedNum), stack, metaStack);
18427 break;
18428 case '"':
18429 parsedString = '';
18430 lastCh = void 0;
18431 numConsecutiveSlashes = 0;
18432 while (true) {
18433 ch = str[i++];
18434 if (ch !== '"' || (lastCh === '\\' &&
18435 numConsecutiveSlashes % 2 === 1)) {
18436 parsedString += ch;
18437 lastCh = ch;
18438 if (lastCh === '\\') {
18439 numConsecutiveSlashes++;
18440 } else {
18441 numConsecutiveSlashes = 0;
18442 }
18443 } else {
18444 break;
18445 }
18446 }
18447 pop(JSON.parse('"' + parsedString + '"'), stack, metaStack);
18448 break;
18449 case '[':
18450 arrayElement = { element: [], index: stack.length };
18451 stack.push(arrayElement.element);
18452 metaStack.push(arrayElement);
18453 break;
18454 case '{':
18455 objElement = { element: {}, index: stack.length };
18456 stack.push(objElement.element);
18457 metaStack.push(objElement);
18458 break;
18459 default:
18460 throw new Error(
18461 'unexpectedly reached end of input: ' + collationIndex);
18462 }
18463 }
18464};
18465
18466},{}],133:[function(_dereq_,module,exports){
18467module.exports = extend
18468
18469var hasOwnProperty = Object.prototype.hasOwnProperty;
18470
18471function extend() {
18472 var target = {}
18473
18474 for (var i = 0; i < arguments.length; i++) {
18475 var source = arguments[i]
18476
18477 for (var key in source) {
18478 if (hasOwnProperty.call(source, key)) {
18479 target[key] = source[key]
18480 }
18481 }
18482 }
18483
18484 return target
18485}
18486
18487},{}],134:[function(_dereq_,module,exports){
18488module.exports = extend
18489
18490var hasOwnProperty = Object.prototype.hasOwnProperty;
18491
18492function extend(target) {
18493 for (var i = 1; i < arguments.length; i++) {
18494 var source = arguments[i]
18495
18496 for (var key in source) {
18497 if (hasOwnProperty.call(source, key)) {
18498 target[key] = source[key]
18499 }
18500 }
18501 }
18502
18503 return target
18504}
18505
18506},{}],135:[function(_dereq_,module,exports){
18507'use strict';
18508
18509function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
18510
18511var immediate = _interopDefault(_dereq_(23));
18512var Md5 = _interopDefault(_dereq_(77));
18513var levelup = _interopDefault(_dereq_(53));
18514var ltgt = _interopDefault(_dereq_(55));
18515var Codec = _interopDefault(_dereq_(31));
18516var ReadableStreamCore = _interopDefault(_dereq_(75));
18517var through2 = _dereq_(111);
18518var Deque = _interopDefault(_dereq_(17));
18519var bufferFrom = _interopDefault(_dereq_(7));
18520var EE = _interopDefault(_dereq_(20));
18521var uuid = _dereq_(117);
18522var vuvuzela = _interopDefault(_dereq_(132));
18523var memdown = _interopDefault(_dereq_(57));
18524
18525function isBinaryObject(object) {
18526 return (typeof ArrayBuffer !== 'undefined' && object instanceof ArrayBuffer) ||
18527 (typeof Blob !== 'undefined' && object instanceof Blob);
18528}
18529
18530function cloneArrayBuffer(buff) {
18531 if (typeof buff.slice === 'function') {
18532 return buff.slice(0);
18533 }
18534 // IE10-11 slice() polyfill
18535 var target = new ArrayBuffer(buff.byteLength);
18536 var targetArray = new Uint8Array(target);
18537 var sourceArray = new Uint8Array(buff);
18538 targetArray.set(sourceArray);
18539 return target;
18540}
18541
18542function cloneBinaryObject(object) {
18543 if (object instanceof ArrayBuffer) {
18544 return cloneArrayBuffer(object);
18545 }
18546 var size = object.size;
18547 var type = object.type;
18548 // Blob
18549 if (typeof object.slice === 'function') {
18550 return object.slice(0, size, type);
18551 }
18552 // PhantomJS slice() replacement
18553 return object.webkitSlice(0, size, type);
18554}
18555
18556// most of this is borrowed from lodash.isPlainObject:
18557// https://github.com/fis-components/lodash.isplainobject/
18558// blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js
18559
18560var funcToString = Function.prototype.toString;
18561var objectCtorString = funcToString.call(Object);
18562
18563function isPlainObject(value) {
18564 var proto = Object.getPrototypeOf(value);
18565 /* istanbul ignore if */
18566 if (proto === null) { // not sure when this happens, but I guess it can
18567 return true;
18568 }
18569 var Ctor = proto.constructor;
18570 return (typeof Ctor == 'function' &&
18571 Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
18572}
18573
18574function clone(object) {
18575 var newObject;
18576 var i;
18577 var len;
18578
18579 if (!object || typeof object !== 'object') {
18580 return object;
18581 }
18582
18583 if (Array.isArray(object)) {
18584 newObject = [];
18585 for (i = 0, len = object.length; i < len; i++) {
18586 newObject[i] = clone(object[i]);
18587 }
18588 return newObject;
18589 }
18590
18591 // special case: to avoid inconsistencies between IndexedDB
18592 // and other backends, we automatically stringify Dates
18593 if (object instanceof Date && isFinite(object)) {
18594 return object.toISOString();
18595 }
18596
18597 if (isBinaryObject(object)) {
18598 return cloneBinaryObject(object);
18599 }
18600
18601 if (!isPlainObject(object)) {
18602 return object; // don't clone objects like Workers
18603 }
18604
18605 newObject = {};
18606 for (i in object) {
18607 /* istanbul ignore else */
18608 if (Object.prototype.hasOwnProperty.call(object, i)) {
18609 var value = clone(object[i]);
18610 if (typeof value !== 'undefined') {
18611 newObject[i] = value;
18612 }
18613 }
18614 }
18615 return newObject;
18616}
18617
18618function once(fun) {
18619 var called = false;
18620 return function (...args) {
18621 /* istanbul ignore if */
18622 if (called) {
18623 // this is a smoke test and should never actually happen
18624 throw new Error('once called more than once');
18625 } else {
18626 called = true;
18627 fun.apply(this, args);
18628 }
18629 };
18630}
18631
18632function toPromise(func) {
18633 //create the function we will be returning
18634 return function (...args) {
18635 // Clone arguments
18636 args = clone(args);
18637 var self = this;
18638 // if the last argument is a function, assume its a callback
18639 var usedCB = (typeof args[args.length - 1] === 'function') ? args.pop() : false;
18640 var promise = new Promise(function (fulfill, reject) {
18641 var resp;
18642 try {
18643 var callback = once(function (err, mesg) {
18644 if (err) {
18645 reject(err);
18646 } else {
18647 fulfill(mesg);
18648 }
18649 });
18650 // create a callback for this invocation
18651 // apply the function in the orig context
18652 args.push(callback);
18653 resp = func.apply(self, args);
18654 if (resp && typeof resp.then === 'function') {
18655 fulfill(resp);
18656 }
18657 } catch (e) {
18658 reject(e);
18659 }
18660 });
18661 // if there is a callback, call it back
18662 if (usedCB) {
18663 promise.then(function (result) {
18664 usedCB(null, result);
18665 }, usedCB);
18666 }
18667 return promise;
18668 };
18669}
18670
18671function logApiCall(self, name, args) {
18672 /* istanbul ignore if */
18673 if (self.constructor.listeners('debug').length) {
18674 var logArgs = ['api', self.name, name];
18675 for (var i = 0; i < args.length - 1; i++) {
18676 logArgs.push(args[i]);
18677 }
18678 self.constructor.emit('debug', logArgs);
18679
18680 // override the callback itself to log the response
18681 var origCallback = args[args.length - 1];
18682 args[args.length - 1] = function (err, res) {
18683 var responseArgs = ['api', self.name, name];
18684 responseArgs = responseArgs.concat(
18685 err ? ['error', err] : ['success', res]
18686 );
18687 self.constructor.emit('debug', responseArgs);
18688 origCallback(err, res);
18689 };
18690 }
18691}
18692
18693function adapterFun(name, callback) {
18694 return toPromise(function (...args) {
18695 if (this._closed) {
18696 return Promise.reject(new Error('database is closed'));
18697 }
18698 if (this._destroyed) {
18699 return Promise.reject(new Error('database is destroyed'));
18700 }
18701 var self = this;
18702 logApiCall(self, name, args);
18703 if (!this.taskqueue.isReady) {
18704 return new Promise(function (fulfill, reject) {
18705 self.taskqueue.addTask(function (failed) {
18706 if (failed) {
18707 reject(failed);
18708 } else {
18709 fulfill(self[name].apply(self, args));
18710 }
18711 });
18712 });
18713 }
18714 return callback.apply(this, args);
18715 });
18716}
18717
18718function mangle(key) {
18719 return '$' + key;
18720}
18721function unmangle(key) {
18722 return key.substring(1);
18723}
18724function Map$1() {
18725 this._store = {};
18726}
18727Map$1.prototype.get = function (key) {
18728 var mangled = mangle(key);
18729 return this._store[mangled];
18730};
18731Map$1.prototype.set = function (key, value) {
18732 var mangled = mangle(key);
18733 this._store[mangled] = value;
18734 return true;
18735};
18736Map$1.prototype.has = function (key) {
18737 var mangled = mangle(key);
18738 return mangled in this._store;
18739};
18740Map$1.prototype.keys = function () {
18741 return Object.keys(this._store).map(k => unmangle(k));
18742};
18743Map$1.prototype["delete"] = function (key) {
18744 var mangled = mangle(key);
18745 var res = mangled in this._store;
18746 delete this._store[mangled];
18747 return res;
18748};
18749Map$1.prototype.forEach = function (cb) {
18750 var keys = Object.keys(this._store);
18751 for (var i = 0, len = keys.length; i < len; i++) {
18752 var key = keys[i];
18753 var value = this._store[key];
18754 key = unmangle(key);
18755 cb(value, key);
18756 }
18757};
18758Object.defineProperty(Map$1.prototype, 'size', {
18759 get: function () {
18760 return Object.keys(this._store).length;
18761 }
18762});
18763
18764function Set$1(array) {
18765 this._store = new Map$1();
18766
18767 // init with an array
18768 if (array && Array.isArray(array)) {
18769 for (var i = 0, len = array.length; i < len; i++) {
18770 this.add(array[i]);
18771 }
18772 }
18773}
18774Set$1.prototype.add = function (key) {
18775 return this._store.set(key, true);
18776};
18777Set$1.prototype.has = function (key) {
18778 return this._store.has(key);
18779};
18780Set$1.prototype.forEach = function (cb) {
18781 this._store.forEach(function (value, key) {
18782 cb(key);
18783 });
18784};
18785Object.defineProperty(Set$1.prototype, 'size', {
18786 get: function () {
18787 return this._store.size;
18788 }
18789});
18790
18791// Based on https://kangax.github.io/compat-table/es6/ we can sniff out
18792// incomplete Map/Set implementations which would otherwise cause our tests to fail.
18793// Notably they fail in IE11 and iOS 8.4, which this prevents.
18794function supportsMapAndSet() {
18795 if (typeof Symbol === 'undefined' || typeof Map === 'undefined' || typeof Set === 'undefined') {
18796 return false;
18797 }
18798 var prop = Object.getOwnPropertyDescriptor(Map, Symbol.species);
18799 return prop && 'get' in prop && Map[Symbol.species] === Map;
18800}
18801
18802// based on https://github.com/montagejs/collections
18803
18804var ExportedSet;
18805var ExportedMap;
18806
18807{
18808 if (supportsMapAndSet()) { // prefer built-in Map/Set
18809 ExportedSet = Set;
18810 ExportedMap = Map;
18811 } else { // fall back to our polyfill
18812 ExportedSet = Set$1;
18813 ExportedMap = Map$1;
18814 }
18815}
18816
18817// like underscore/lodash _.pick()
18818function pick(obj, arr) {
18819 var res = {};
18820 for (var i = 0, len = arr.length; i < len; i++) {
18821 var prop = arr[i];
18822 if (prop in obj) {
18823 res[prop] = obj[prop];
18824 }
18825 }
18826 return res;
18827}
18828
18829// Most browsers throttle concurrent requests at 6, so it's silly
18830// to shim _bulk_get by trying to launch potentially hundreds of requests
18831// and then letting the majority time out. We can handle this ourselves.
18832var MAX_NUM_CONCURRENT_REQUESTS = 6;
18833
18834function identityFunction(x) {
18835 return x;
18836}
18837
18838function formatResultForOpenRevsGet(result) {
18839 return [{
18840 ok: result
18841 }];
18842}
18843
18844// shim for P/CouchDB adapters that don't directly implement _bulk_get
18845function bulkGet(db, opts, callback) {
18846 var requests = opts.docs;
18847
18848 // consolidate into one request per doc if possible
18849 var requestsById = new ExportedMap();
18850 requests.forEach(function (request) {
18851 if (requestsById.has(request.id)) {
18852 requestsById.get(request.id).push(request);
18853 } else {
18854 requestsById.set(request.id, [request]);
18855 }
18856 });
18857
18858 var numDocs = requestsById.size;
18859 var numDone = 0;
18860 var perDocResults = new Array(numDocs);
18861
18862 function collapseResultsAndFinish() {
18863 var results = [];
18864 perDocResults.forEach(function (res) {
18865 res.docs.forEach(function (info) {
18866 results.push({
18867 id: res.id,
18868 docs: [info]
18869 });
18870 });
18871 });
18872 callback(null, {results: results});
18873 }
18874
18875 function checkDone() {
18876 if (++numDone === numDocs) {
18877 collapseResultsAndFinish();
18878 }
18879 }
18880
18881 function gotResult(docIndex, id, docs) {
18882 perDocResults[docIndex] = {id: id, docs: docs};
18883 checkDone();
18884 }
18885
18886 var allRequests = [];
18887 requestsById.forEach(function (value, key) {
18888 allRequests.push(key);
18889 });
18890
18891 var i = 0;
18892
18893 function nextBatch() {
18894
18895 if (i >= allRequests.length) {
18896 return;
18897 }
18898
18899 var upTo = Math.min(i + MAX_NUM_CONCURRENT_REQUESTS, allRequests.length);
18900 var batch = allRequests.slice(i, upTo);
18901 processBatch(batch, i);
18902 i += batch.length;
18903 }
18904
18905 function processBatch(batch, offset) {
18906 batch.forEach(function (docId, j) {
18907 var docIdx = offset + j;
18908 var docRequests = requestsById.get(docId);
18909
18910 // just use the first request as the "template"
18911 // TODO: The _bulk_get API allows for more subtle use cases than this,
18912 // but for now it is unlikely that there will be a mix of different
18913 // "atts_since" or "attachments" in the same request, since it's just
18914 // replicate.js that is using this for the moment.
18915 // Also, atts_since is aspirational, since we don't support it yet.
18916 var docOpts = pick(docRequests[0], ['atts_since', 'attachments']);
18917 docOpts.open_revs = docRequests.map(function (request) {
18918 // rev is optional, open_revs disallowed
18919 return request.rev;
18920 });
18921
18922 // remove falsey / undefined revisions
18923 docOpts.open_revs = docOpts.open_revs.filter(identityFunction);
18924
18925 var formatResult = identityFunction;
18926
18927 if (docOpts.open_revs.length === 0) {
18928 delete docOpts.open_revs;
18929
18930 // when fetching only the "winning" leaf,
18931 // transform the result so it looks like an open_revs
18932 // request
18933 formatResult = formatResultForOpenRevsGet;
18934 }
18935
18936 // globally-supplied options
18937 ['revs', 'attachments', 'binary', 'ajax', 'latest'].forEach(function (param) {
18938 if (param in opts) {
18939 docOpts[param] = opts[param];
18940 }
18941 });
18942 db.get(docId, docOpts, function (err, res) {
18943 var result;
18944 /* istanbul ignore if */
18945 if (err) {
18946 result = [{error: err}];
18947 } else {
18948 result = formatResult(res);
18949 }
18950 gotResult(docIdx, docId, result);
18951 nextBatch();
18952 });
18953 });
18954 }
18955
18956 nextBatch();
18957
18958}
18959
18960var hasLocal;
18961
18962try {
18963 localStorage.setItem('_pouch_check_localstorage', 1);
18964 hasLocal = !!localStorage.getItem('_pouch_check_localstorage');
18965} catch (e) {
18966 hasLocal = false;
18967}
18968
18969function hasLocalStorage() {
18970 return hasLocal;
18971}
18972
18973// Custom nextTick() shim for browsers. In node, this will just be process.nextTick(). We
18974
18975class Changes extends EE {
18976 constructor() {
18977 super();
18978
18979 this._listeners = {};
18980
18981 if (hasLocalStorage()) {
18982 addEventListener("storage", function (e) {
18983 this.emit(e.key);
18984 });
18985 }
18986 }
18987
18988 addListener(dbName, id, db, opts) {
18989 if (this._listeners[id]) {
18990 return;
18991 }
18992 var inprogress = false;
18993 var self = this;
18994 function eventFunction() {
18995 if (!self._listeners[id]) {
18996 return;
18997 }
18998 if (inprogress) {
18999 inprogress = 'waiting';
19000 return;
19001 }
19002 inprogress = true;
19003 var changesOpts = pick(opts, [
19004 'style', 'include_docs', 'attachments', 'conflicts', 'filter',
19005 'doc_ids', 'view', 'since', 'query_params', 'binary', 'return_docs'
19006 ]);
19007
19008 function onError() {
19009 inprogress = false;
19010 }
19011
19012 db.changes(changesOpts).on('change', function (c) {
19013 if (c.seq > opts.since && !opts.cancelled) {
19014 opts.since = c.seq;
19015 opts.onChange(c);
19016 }
19017 }).on('complete', function () {
19018 if (inprogress === 'waiting') {
19019 immediate(eventFunction);
19020 }
19021 inprogress = false;
19022 }).on('error', onError);
19023 }
19024 this._listeners[id] = eventFunction;
19025 this.on(dbName, eventFunction);
19026 }
19027
19028 removeListener(dbName, id) {
19029 if (!(id in this._listeners)) {
19030 return;
19031 }
19032 super.removeListener(dbName, this._listeners[id]);
19033 delete this._listeners[id];
19034 }
19035
19036 notifyLocalWindows(dbName) {
19037 //do a useless change on a storage thing
19038 //in order to get other windows's listeners to activate
19039 if (hasLocalStorage()) {
19040 localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a";
19041 }
19042 }
19043
19044 notify(dbName) {
19045 this.emit(dbName);
19046 this.notifyLocalWindows(dbName);
19047 }
19048}
19049
19050function guardedConsole(method) {
19051 /* istanbul ignore else */
19052 if (typeof console !== 'undefined' && typeof console[method] === 'function') {
19053 var args = Array.prototype.slice.call(arguments, 1);
19054 console[method].apply(console, args);
19055 }
19056}
19057
19058var assign;
19059{
19060 if (typeof Object.assign === 'function') {
19061 assign = Object.assign;
19062 } else {
19063 // lite Object.assign polyfill based on
19064 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
19065 assign = function (target) {
19066 var to = Object(target);
19067
19068 for (var index = 1; index < arguments.length; index++) {
19069 var nextSource = arguments[index];
19070
19071 if (nextSource != null) { // Skip over if undefined or null
19072 for (var nextKey in nextSource) {
19073 // Avoid bugs when hasOwnProperty is shadowed
19074 if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
19075 to[nextKey] = nextSource[nextKey];
19076 }
19077 }
19078 }
19079 }
19080 return to;
19081 };
19082 }
19083}
19084
19085var $inject_Object_assign = assign;
19086
19087class PouchError extends Error {
19088 constructor(status, error, reason) {
19089 super();
19090 this.status = status;
19091 this.name = error;
19092 this.message = reason;
19093 this.error = true;
19094 }
19095
19096 toString() {
19097 return JSON.stringify({
19098 status: this.status,
19099 name: this.name,
19100 message: this.message,
19101 reason: this.reason
19102 });
19103 }
19104}
19105
19106var UNAUTHORIZED = new PouchError(401, 'unauthorized', "Name or password is incorrect.");
19107var MISSING_BULK_DOCS = new PouchError(400, 'bad_request', "Missing JSON list of 'docs'");
19108var MISSING_DOC = new PouchError(404, 'not_found', 'missing');
19109var REV_CONFLICT = new PouchError(409, 'conflict', 'Document update conflict');
19110var INVALID_ID = new PouchError(400, 'bad_request', '_id field must contain a string');
19111var MISSING_ID = new PouchError(412, 'missing_id', '_id is required for puts');
19112var RESERVED_ID = new PouchError(400, 'bad_request', 'Only reserved document ids may start with underscore.');
19113var NOT_OPEN = new PouchError(412, 'precondition_failed', 'Database not open');
19114var UNKNOWN_ERROR = new PouchError(500, 'unknown_error', 'Database encountered an unknown error');
19115var BAD_ARG = new PouchError(500, 'badarg', 'Some query argument is invalid');
19116var INVALID_REQUEST = new PouchError(400, 'invalid_request', 'Request was invalid');
19117var QUERY_PARSE_ERROR = new PouchError(400, 'query_parse_error', 'Some query parameter is invalid');
19118var DOC_VALIDATION = new PouchError(500, 'doc_validation', 'Bad special document member');
19119var BAD_REQUEST = new PouchError(400, 'bad_request', 'Something wrong with the request');
19120var NOT_AN_OBJECT = new PouchError(400, 'bad_request', 'Document must be a JSON object');
19121var DB_MISSING = new PouchError(404, 'not_found', 'Database not found');
19122var IDB_ERROR = new PouchError(500, 'indexed_db_went_bad', 'unknown');
19123var WSQ_ERROR = new PouchError(500, 'web_sql_went_bad', 'unknown');
19124var LDB_ERROR = new PouchError(500, 'levelDB_went_went_bad', 'unknown');
19125var FORBIDDEN = new PouchError(403, 'forbidden', 'Forbidden by design doc validate_doc_update function');
19126var INVALID_REV = new PouchError(400, 'bad_request', 'Invalid rev format');
19127var FILE_EXISTS = new PouchError(412, 'file_exists', 'The database could not be created, the file already exists.');
19128var MISSING_STUB = new PouchError(412, 'missing_stub', 'A pre-existing attachment stub wasn\'t found');
19129var INVALID_URL = new PouchError(413, 'invalid_url', 'Provided URL is invalid');
19130
19131function createError(error, reason) {
19132 function CustomPouchError(reason) {
19133 // inherit error properties from our parent error manually
19134 // so as to allow proper JSON parsing.
19135 /* jshint ignore:start */
19136 var names = Object.getOwnPropertyNames(error);
19137 for (var i = 0, len = names.length; i < len; i++) {
19138 if (typeof error[names[i]] !== 'function') {
19139 this[names[i]] = error[names[i]];
19140 }
19141 }
19142
19143 if (this.stack === undefined) {
19144 this.stack = (new Error()).stack;
19145 }
19146
19147 /* jshint ignore:end */
19148 if (reason !== undefined) {
19149 this.reason = reason;
19150 }
19151 }
19152 CustomPouchError.prototype = PouchError.prototype;
19153 return new CustomPouchError(reason);
19154}
19155
19156function generateErrorFromResponse(err) {
19157
19158 if (typeof err !== 'object') {
19159 var data = err;
19160 err = UNKNOWN_ERROR;
19161 err.data = data;
19162 }
19163
19164 if ('error' in err && err.error === 'conflict') {
19165 err.name = 'conflict';
19166 err.status = 409;
19167 }
19168
19169 if (!('name' in err)) {
19170 err.name = err.error || 'unknown';
19171 }
19172
19173 if (!('status' in err)) {
19174 err.status = 500;
19175 }
19176
19177 if (!('message' in err)) {
19178 err.message = err.message || err.reason;
19179 }
19180
19181 if (!('stack' in err)) {
19182 err.stack = (new Error()).stack;
19183 }
19184
19185 return err;
19186}
19187
19188function tryFilter(filter, doc, req) {
19189 try {
19190 return !filter(doc, req);
19191 } catch (err) {
19192 var msg = 'Filter function threw: ' + err.toString();
19193 return createError(BAD_REQUEST, msg);
19194 }
19195}
19196
19197function filterChange(opts) {
19198 var req = {};
19199 var hasFilter = opts.filter && typeof opts.filter === 'function';
19200 req.query = opts.query_params;
19201
19202 return function filter(change) {
19203 if (!change.doc) {
19204 // CSG sends events on the changes feed that don't have documents,
19205 // this hack makes a whole lot of existing code robust.
19206 change.doc = {};
19207 }
19208
19209 var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req);
19210
19211 if (typeof filterReturn === 'object') {
19212 return filterReturn;
19213 }
19214
19215 if (filterReturn) {
19216 return false;
19217 }
19218
19219 if (!opts.include_docs) {
19220 delete change.doc;
19221 } else if (!opts.attachments) {
19222 for (var att in change.doc._attachments) {
19223 /* istanbul ignore else */
19224 if (Object.prototype.hasOwnProperty.call(change.doc._attachments, att)) {
19225 change.doc._attachments[att].stub = true;
19226 }
19227 }
19228 }
19229 return true;
19230 };
19231}
19232
19233// shim for Function.prototype.name,
19234// for browsers that don't support it like IE
19235
19236/* istanbul ignore next */
19237function f() {}
19238
19239var hasName = f.name;
19240var res;
19241
19242// We dont run coverage in IE
19243/* istanbul ignore else */
19244if (hasName) {
19245 res = function (fun) {
19246 return fun.name;
19247 };
19248} else {
19249 res = function (fun) {
19250 var match = fun.toString().match(/^\s*function\s*(?:(\S+)\s*)?\(/);
19251 if (match && match[1]) {
19252 return match[1];
19253 }
19254 else {
19255 return '';
19256 }
19257 };
19258}
19259
19260var functionName = res;
19261
19262// Determine id an ID is valid
19263// - invalid IDs begin with an underescore that does not begin '_design' or
19264// '_local'
19265// - any other string value is a valid id
19266// Returns the specific error object for each case
19267function invalidIdError(id) {
19268 var err;
19269 if (!id) {
19270 err = createError(MISSING_ID);
19271 } else if (typeof id !== 'string') {
19272 err = createError(INVALID_ID);
19273 } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {
19274 err = createError(RESERVED_ID);
19275 }
19276 if (err) {
19277 throw err;
19278 }
19279}
19280
19281// Checks if a PouchDB object is "remote" or not. This is
19282
19283function isRemote(db) {
19284 if (typeof db._remote === 'boolean') {
19285 return db._remote;
19286 }
19287 /* istanbul ignore next */
19288 if (typeof db.type === 'function') {
19289 guardedConsole('warn',
19290 'db.type() is deprecated and will be removed in ' +
19291 'a future version of PouchDB');
19292 return db.type() === 'http';
19293 }
19294 /* istanbul ignore next */
19295 return false;
19296}
19297
19298function listenerCount(ee, type) {
19299 return 'listenerCount' in ee ? ee.listenerCount(type) :
19300 EE.listenerCount(ee, type);
19301}
19302
19303function parseDesignDocFunctionName(s) {
19304 if (!s) {
19305 return null;
19306 }
19307 var parts = s.split('/');
19308 if (parts.length === 2) {
19309 return parts;
19310 }
19311 if (parts.length === 1) {
19312 return [s, s];
19313 }
19314 return null;
19315}
19316
19317function normalizeDesignDocFunctionName(s) {
19318 var normalized = parseDesignDocFunctionName(s);
19319 return normalized ? normalized.join('/') : null;
19320}
19321
19322// originally parseUri 1.2.2, now patched by us
19323
19324// Based on https://github.com/alexdavid/scope-eval v0.0.3
19325// (source: https://unpkg.com/scope-eval@0.0.3/scope_eval.js)
19326// This is basically just a wrapper around new Function()
19327
19328function scopeEval(source, scope) {
19329 var keys = [];
19330 var values = [];
19331 for (var key in scope) {
19332 if (Object.prototype.hasOwnProperty.call(scope, key)) {
19333 keys.push(key);
19334 values.push(scope[key]);
19335 }
19336 }
19337 keys.push(source);
19338 return Function.apply(null, keys).apply(null, values);
19339}
19340
19341// this is essentially the "update sugar" function from daleharvey/pouchdb#1388
19342// the diffFun tells us what delta to apply to the doc. it either returns
19343// the doc, or false if it doesn't need to do an update after all
19344function upsert(db, docId, diffFun) {
19345 return db.get(docId)[
19346 "catch"](function (err) {
19347 /* istanbul ignore next */
19348 if (err.status !== 404) {
19349 throw err;
19350 }
19351 return {};
19352 })
19353 .then(function (doc) {
19354 // the user might change the _rev, so save it for posterity
19355 var docRev = doc._rev;
19356 var newDoc = diffFun(doc);
19357
19358 if (!newDoc) {
19359 // if the diffFun returns falsy, we short-circuit as
19360 // an optimization
19361 return {updated: false, rev: docRev};
19362 }
19363
19364 // users aren't allowed to modify these values,
19365 // so reset them here
19366 newDoc._id = docId;
19367 newDoc._rev = docRev;
19368 return tryAndPut(db, newDoc, diffFun);
19369 });
19370}
19371
19372function tryAndPut(db, doc, diffFun) {
19373 return db.put(doc).then(function (res) {
19374 return {
19375 updated: true,
19376 rev: res.rev
19377 };
19378 }, function (err) {
19379 /* istanbul ignore next */
19380 if (err.status !== 409) {
19381 throw err;
19382 }
19383 return upsert(db, doc._id, diffFun);
19384 });
19385}
19386
19387var thisAtob = function (str) {
19388 return atob(str);
19389};
19390
19391var thisBtoa = function (str) {
19392 return btoa(str);
19393};
19394
19395// Abstracts constructing a Blob object, so it also works in older
19396// browsers that don't support the native Blob constructor (e.g.
19397// old QtWebKit versions, Android < 4.4).
19398function createBlob(parts, properties) {
19399 /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
19400 parts = parts || [];
19401 properties = properties || {};
19402 try {
19403 return new Blob(parts, properties);
19404 } catch (e) {
19405 if (e.name !== "TypeError") {
19406 throw e;
19407 }
19408 var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
19409 typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
19410 typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
19411 WebKitBlobBuilder;
19412 var builder = new Builder();
19413 for (var i = 0; i < parts.length; i += 1) {
19414 builder.append(parts[i]);
19415 }
19416 return builder.getBlob(properties.type);
19417 }
19418}
19419
19420// From http://stackoverflow.com/questions/14967647/ (continues on next line)
19421// encode-decode-image-with-base64-breaks-image (2013-04-21)
19422function binaryStringToArrayBuffer(bin) {
19423 var length = bin.length;
19424 var buf = new ArrayBuffer(length);
19425 var arr = new Uint8Array(buf);
19426 for (var i = 0; i < length; i++) {
19427 arr[i] = bin.charCodeAt(i);
19428 }
19429 return buf;
19430}
19431
19432function binStringToBluffer(binString, type) {
19433 return createBlob([binaryStringToArrayBuffer(binString)], {type: type});
19434}
19435
19436//Can't find original post, but this is close
19437//http://stackoverflow.com/questions/6965107/ (continues on next line)
19438//converting-between-strings-and-arraybuffers
19439function arrayBufferToBinaryString(buffer) {
19440 var binary = '';
19441 var bytes = new Uint8Array(buffer);
19442 var length = bytes.byteLength;
19443 for (var i = 0; i < length; i++) {
19444 binary += String.fromCharCode(bytes[i]);
19445 }
19446 return binary;
19447}
19448
19449// shim for browsers that don't support it
19450function readAsBinaryString(blob, callback) {
19451 var reader = new FileReader();
19452 var hasBinaryString = typeof reader.readAsBinaryString === 'function';
19453 reader.onloadend = function (e) {
19454 var result = e.target.result || '';
19455 if (hasBinaryString) {
19456 return callback(result);
19457 }
19458 callback(arrayBufferToBinaryString(result));
19459 };
19460 if (hasBinaryString) {
19461 reader.readAsBinaryString(blob);
19462 } else {
19463 reader.readAsArrayBuffer(blob);
19464 }
19465}
19466
19467// simplified API. universal browser support is assumed
19468function readAsArrayBuffer(blob, callback) {
19469 var reader = new FileReader();
19470 reader.onloadend = function (e) {
19471 var result = e.target.result || new ArrayBuffer(0);
19472 callback(result);
19473 };
19474 reader.readAsArrayBuffer(blob);
19475}
19476
19477// this is not used in the browser
19478
19479var setImmediateShim = self.setImmediate || self.setTimeout;
19480var MD5_CHUNK_SIZE = 32768;
19481
19482function rawToBase64(raw) {
19483 return thisBtoa(raw);
19484}
19485
19486function sliceBlob(blob, start, end) {
19487 if (blob.webkitSlice) {
19488 return blob.webkitSlice(start, end);
19489 }
19490 return blob.slice(start, end);
19491}
19492
19493function appendBlob(buffer, blob, start, end, callback) {
19494 if (start > 0 || end < blob.size) {
19495 // only slice blob if we really need to
19496 blob = sliceBlob(blob, start, end);
19497 }
19498 readAsArrayBuffer(blob, function (arrayBuffer) {
19499 buffer.append(arrayBuffer);
19500 callback();
19501 });
19502}
19503
19504function appendString(buffer, string, start, end, callback) {
19505 if (start > 0 || end < string.length) {
19506 // only create a substring if we really need to
19507 string = string.substring(start, end);
19508 }
19509 buffer.appendBinary(string);
19510 callback();
19511}
19512
19513function binaryMd5(data, callback) {
19514 var inputIsString = typeof data === 'string';
19515 var len = inputIsString ? data.length : data.size;
19516 var chunkSize = Math.min(MD5_CHUNK_SIZE, len);
19517 var chunks = Math.ceil(len / chunkSize);
19518 var currentChunk = 0;
19519 var buffer = inputIsString ? new Md5() : new Md5.ArrayBuffer();
19520
19521 var append = inputIsString ? appendString : appendBlob;
19522
19523 function next() {
19524 setImmediateShim(loadNextChunk);
19525 }
19526
19527 function done() {
19528 var raw = buffer.end(true);
19529 var base64 = rawToBase64(raw);
19530 callback(base64);
19531 buffer.destroy();
19532 }
19533
19534 function loadNextChunk() {
19535 var start = currentChunk * chunkSize;
19536 var end = start + chunkSize;
19537 currentChunk++;
19538 if (currentChunk < chunks) {
19539 append(buffer, data, start, end, next);
19540 } else {
19541 append(buffer, data, start, end, done);
19542 }
19543 }
19544 loadNextChunk();
19545}
19546
19547function stringMd5(string) {
19548 return Md5.hash(string);
19549}
19550
19551/**
19552 * Creates a new revision string that does NOT include the revision height
19553 * For example '56649f1b0506c6ca9fda0746eb0cacdf'
19554 */
19555function rev$$1(doc, deterministic_revs) {
19556 if (!deterministic_revs) {
19557 return uuid.v4().replace(/-/g, '').toLowerCase();
19558 }
19559
19560 var mutateableDoc = $inject_Object_assign({}, doc);
19561 delete mutateableDoc._rev_tree;
19562 return stringMd5(JSON.stringify(mutateableDoc));
19563}
19564
19565var uuid$1 = uuid.v4; // mimic old import, only v4 is ever used elsewhere
19566
19567function isFunction(f) {
19568 return 'function' === typeof f;
19569}
19570
19571function getPrefix(db) {
19572 if (isFunction(db.prefix)) {
19573 return db.prefix();
19574 }
19575 return db;
19576}
19577
19578function clone$1(_obj) {
19579 var obj = {};
19580 for (var k in _obj) {
19581 obj[k] = _obj[k];
19582 }
19583 return obj;
19584}
19585
19586function nut(db, precodec, codec) {
19587 function encodePrefix(prefix, key, opts1, opts2) {
19588 return precodec.encode([ prefix, codec.encodeKey(key, opts1, opts2 ) ]);
19589 }
19590
19591 function addEncodings(op, prefix) {
19592 if (prefix && prefix.options) {
19593 op.keyEncoding =
19594 op.keyEncoding || prefix.options.keyEncoding;
19595 op.valueEncoding =
19596 op.valueEncoding || prefix.options.valueEncoding;
19597 }
19598 return op;
19599 }
19600
19601 db.open(function () { /* no-op */});
19602
19603 return {
19604 apply: function (ops, opts, cb) {
19605 opts = opts || {};
19606
19607 var batch = [];
19608 var i = -1;
19609 var len = ops.length;
19610
19611 while (++i < len) {
19612 var op = ops[i];
19613 addEncodings(op, op.prefix);
19614 op.prefix = getPrefix(op.prefix);
19615 batch.push({
19616 key: encodePrefix(op.prefix, op.key, opts, op),
19617 value: op.type !== 'del' && codec.encodeValue(op.value, opts, op),
19618 type: op.type
19619 });
19620 }
19621 db.db.batch(batch, opts, cb);
19622 },
19623 get: function (key, prefix, opts, cb) {
19624 opts.asBuffer = codec.valueAsBuffer(opts);
19625 return db.db.get(
19626 encodePrefix(prefix, key, opts),
19627 opts,
19628 function (err, value) {
19629 if (err) {
19630 cb(err);
19631 } else {
19632 cb(null, codec.decodeValue(value, opts));
19633 }
19634 }
19635 );
19636 },
19637 createDecoder: function (opts) {
19638 return function (key, value) {
19639 return {
19640 key: codec.decodeKey(precodec.decode(key)[1], opts),
19641 value: codec.decodeValue(value, opts)
19642 };
19643 };
19644 },
19645 isClosed: function isClosed() {
19646 return db.isClosed();
19647 },
19648 close: function close(cb) {
19649 return db.close(cb);
19650 },
19651 iterator: function (_opts) {
19652 var opts = clone$1(_opts || {});
19653 var prefix = _opts.prefix || [];
19654
19655 function encodeKey(key) {
19656 return encodePrefix(prefix, key, opts, {});
19657 }
19658
19659 ltgt.toLtgt(_opts, opts, encodeKey, precodec.lowerBound, precodec.upperBound);
19660
19661 // if these legacy values are in the options, remove them
19662
19663 opts.prefix = null;
19664
19665 //************************************************
19666 //hard coded defaults, for now...
19667 //TODO: pull defaults and encoding out of levelup.
19668 opts.keyAsBuffer = opts.valueAsBuffer = false;
19669 //************************************************
19670
19671
19672 //this is vital, otherwise limit: undefined will
19673 //create an empty stream.
19674 /* istanbul ignore next */
19675 if ('number' !== typeof opts.limit) {
19676 opts.limit = -1;
19677 }
19678
19679 opts.keyAsBuffer = precodec.buffer;
19680 opts.valueAsBuffer = codec.valueAsBuffer(opts);
19681
19682 function wrapIterator(iterator) {
19683 return {
19684 next: function (cb) {
19685 return iterator.next(cb);
19686 },
19687 end: function (cb) {
19688 iterator.end(cb);
19689 }
19690 };
19691 }
19692
19693 return wrapIterator(db.db.iterator(opts));
19694 }
19695 };
19696}
19697
19698class NotFoundError extends Error {
19699 constructor() {
19700 super();
19701 this.name = 'NotFoundError';
19702 }
19703}
19704
19705var EventEmitter = EE.EventEmitter;
19706var version = "6.5.4";
19707
19708var NOT_FOUND_ERROR = new NotFoundError();
19709
19710var sublevel = function (nut, prefix, createStream, options) {
19711 var emitter = new EventEmitter();
19712 emitter.sublevels = {};
19713 emitter.options = options;
19714
19715 emitter.version = version;
19716
19717 emitter.methods = {};
19718 prefix = prefix || [];
19719
19720 function mergeOpts(opts) {
19721 var o = {};
19722 var k;
19723 if (options) {
19724 for (k in options) {
19725 if (typeof options[k] !== 'undefined') {
19726 o[k] = options[k];
19727 }
19728 }
19729 }
19730 if (opts) {
19731 for (k in opts) {
19732 if (typeof opts[k] !== 'undefined') {
19733 o[k] = opts[k];
19734 }
19735 }
19736 }
19737 return o;
19738 }
19739
19740 emitter.put = function (key, value, opts, cb) {
19741 if ('function' === typeof opts) {
19742 cb = opts;
19743 opts = {};
19744 }
19745
19746 nut.apply([{
19747 key: key, value: value,
19748 prefix: prefix.slice(), type: 'put'
19749 }], mergeOpts(opts), function (err) {
19750 /* istanbul ignore next */
19751 if (err) {
19752 return cb(err);
19753 }
19754 emitter.emit('put', key, value);
19755 cb(null);
19756 });
19757 };
19758
19759 emitter.prefix = function () {
19760 return prefix.slice();
19761 };
19762
19763 emitter.batch = function (ops, opts, cb) {
19764 if ('function' === typeof opts) {
19765 cb = opts;
19766 opts = {};
19767 }
19768
19769 ops = ops.map(function (op) {
19770 return {
19771 key: op.key,
19772 value: op.value,
19773 prefix: op.prefix || prefix,
19774 keyEncoding: op.keyEncoding, // *
19775 valueEncoding: op.valueEncoding, // * (TODO: encodings on sublevel)
19776 type: op.type
19777 };
19778 });
19779
19780 nut.apply(ops, mergeOpts(opts), function (err) {
19781 /* istanbul ignore next */
19782 if (err) {
19783 return cb(err);
19784 }
19785 emitter.emit('batch', ops);
19786 cb(null);
19787 });
19788 };
19789
19790 emitter.get = function (key, opts, cb) {
19791 /* istanbul ignore else */
19792 if ('function' === typeof opts) {
19793 cb = opts;
19794 opts = {};
19795 }
19796 nut.get(key, prefix, mergeOpts(opts), function (err, value) {
19797 if (err) {
19798 cb(NOT_FOUND_ERROR);
19799 } else {
19800 cb(null, value);
19801 }
19802 });
19803 };
19804
19805 emitter.sublevel = function (name, opts) {
19806 return emitter.sublevels[name] =
19807 emitter.sublevels[name] || sublevel(nut, prefix.concat(name), createStream, mergeOpts(opts));
19808 };
19809
19810 emitter.readStream = emitter.createReadStream = function (opts) {
19811 opts = mergeOpts(opts);
19812 opts.prefix = prefix;
19813 var stream;
19814 var it = nut.iterator(opts);
19815
19816 stream = createStream(opts, nut.createDecoder(opts));
19817 stream.setIterator(it);
19818
19819 return stream;
19820 };
19821
19822 emitter.close = function (cb) {
19823 nut.close(cb);
19824 };
19825
19826 emitter.isOpen = nut.isOpen;
19827 emitter.isClosed = nut.isClosed;
19828
19829 return emitter;
19830};
19831
19832/* Copyright (c) 2012-2014 LevelUP contributors
19833 * See list at <https://github.com/rvagg/node-levelup#contributing>
19834 * MIT License <https://github.com/rvagg/node-levelup/blob/master/LICENSE.md>
19835 */
19836
19837var Readable = ReadableStreamCore.Readable;
19838
19839function createClass(parent, init) {
19840 let klass = function (...args) {
19841 if (!(this instanceof klass)) {
19842 return new klass(...args);
19843 }
19844 init.apply(this, args);
19845 };
19846 klass.prototype = Object.create(parent.prototype, {
19847 constructor: { value: klass }
19848 });
19849 return klass;
19850}
19851
19852class ReadStreamInternal extends Readable {
19853 constructor(options, makeData) {
19854 super({ objectMode: true, highWaterMark: options.highWaterMark });
19855 this._setup(options, makeData);
19856 }
19857
19858 _setup(options, makeData) {
19859 super.constructor({ objectMode: true, highWaterMark: options.highWaterMark });
19860
19861 // purely to keep `db` around until we're done so it's not GCed if the user doesn't keep a ref
19862 this._waiting = false;
19863 this._options = options;
19864 this._makeData = makeData;
19865 }
19866
19867 setIterator(it) {
19868 this._iterator = it;
19869 /* istanbul ignore if */
19870 if (this._destroyed) {
19871 return it.end(function () {});
19872 }
19873 /* istanbul ignore if */
19874 if (this._waiting) {
19875 this._waiting = false;
19876 return this._read();
19877 }
19878 return this;
19879 }
19880
19881 _cleanup(err) {
19882 if (this._destroyed) {
19883 return;
19884 }
19885
19886 this._destroyed = true;
19887
19888 var self = this;
19889 /* istanbul ignore if */
19890 if (err && err.message !== 'iterator has ended') {
19891 self.emit('error', err);
19892 }
19893
19894 /* istanbul ignore else */
19895 if (self._iterator) {
19896 self._iterator.end(function () {
19897 self._iterator = null;
19898 self.emit('close');
19899 });
19900 } else {
19901 self.emit('close');
19902 }
19903 }
19904
19905 destroy() {
19906 this._cleanup();
19907 }
19908
19909 _read() {
19910 var self = this;
19911 /* istanbul ignore if */
19912 if (self._destroyed) {
19913 return;
19914 }
19915 /* istanbul ignore if */
19916 if (!self._iterator) {
19917 return this._waiting = true;
19918 }
19919
19920 self._iterator.next(function (err, key, value) {
19921 if (err || (key === undefined && value === undefined)) {
19922 if (!err && !self._destroyed) {
19923 self.push(null);
19924 }
19925 return self._cleanup(err);
19926 }
19927
19928
19929 value = self._makeData(key, value);
19930 if (!self._destroyed) {
19931 self.push(value);
19932 }
19933 });
19934 }
19935}
19936
19937const ReadStream = createClass(ReadStreamInternal, function (options, makeData) {
19938 ReadStreamInternal.prototype._setup.call(this, options, makeData);
19939});
19940
19941var precodec = {
19942 encode: function (decodedKey) {
19943 return '\xff' + decodedKey[0] + '\xff' + decodedKey[1];
19944 },
19945 decode: function (encodedKeyAsBuffer) {
19946 var str = encodedKeyAsBuffer.toString();
19947 var idx = str.indexOf('\xff', 1);
19948 return [str.substring(1, idx), str.substring(idx + 1)];
19949 },
19950 lowerBound: '\x00',
19951 upperBound: '\xff'
19952};
19953
19954var codec = new Codec();
19955
19956function sublevelPouch(db) {
19957 return sublevel(nut(db, precodec, codec), [], ReadStream, db.options);
19958}
19959
19960// We fetch all leafs of the revision tree, and sort them based on tree length
19961// and whether they were deleted, undeleted documents with the longest revision
19962// tree (most edits) win
19963// The final sort algorithm is slightly documented in a sidebar here:
19964// http://guide.couchdb.org/draft/conflicts.html
19965function winningRev(metadata) {
19966 var winningId;
19967 var winningPos;
19968 var winningDeleted;
19969 var toVisit = metadata.rev_tree.slice();
19970 var node;
19971 while ((node = toVisit.pop())) {
19972 var tree = node.ids;
19973 var branches = tree[2];
19974 var pos = node.pos;
19975 if (branches.length) { // non-leaf
19976 for (var i = 0, len = branches.length; i < len; i++) {
19977 toVisit.push({pos: pos + 1, ids: branches[i]});
19978 }
19979 continue;
19980 }
19981 var deleted = !!tree[1].deleted;
19982 var id = tree[0];
19983 // sort by deleted, then pos, then id
19984 if (!winningId || (winningDeleted !== deleted ? winningDeleted :
19985 winningPos !== pos ? winningPos < pos : winningId < id)) {
19986 winningId = id;
19987 winningPos = pos;
19988 winningDeleted = deleted;
19989 }
19990 }
19991
19992 return winningPos + '-' + winningId;
19993}
19994
19995// Pretty much all below can be combined into a higher order function to
19996// traverse revisions
19997// The return value from the callback will be passed as context to all
19998// children of that node
19999function traverseRevTree(revs, callback) {
20000 var toVisit = revs.slice();
20001
20002 var node;
20003 while ((node = toVisit.pop())) {
20004 var pos = node.pos;
20005 var tree = node.ids;
20006 var branches = tree[2];
20007 var newCtx =
20008 callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]);
20009 for (var i = 0, len = branches.length; i < len; i++) {
20010 toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx});
20011 }
20012 }
20013}
20014
20015function sortByPos(a, b) {
20016 return a.pos - b.pos;
20017}
20018
20019function collectLeaves(revs) {
20020 var leaves = [];
20021 traverseRevTree(revs, function (isLeaf, pos, id, acc, opts) {
20022 if (isLeaf) {
20023 leaves.push({rev: pos + "-" + id, pos: pos, opts: opts});
20024 }
20025 });
20026 leaves.sort(sortByPos).reverse();
20027 for (var i = 0, len = leaves.length; i < len; i++) {
20028 delete leaves[i].pos;
20029 }
20030 return leaves;
20031}
20032
20033// returns revs of all conflicts that is leaves such that
20034// 1. are not deleted and
20035// 2. are different than winning revision
20036function collectConflicts(metadata) {
20037 var win = winningRev(metadata);
20038 var leaves = collectLeaves(metadata.rev_tree);
20039 var conflicts = [];
20040 for (var i = 0, len = leaves.length; i < len; i++) {
20041 var leaf = leaves[i];
20042 if (leaf.rev !== win && !leaf.opts.deleted) {
20043 conflicts.push(leaf.rev);
20044 }
20045 }
20046 return conflicts;
20047}
20048
20049// compact a tree by marking its non-leafs as missing,
20050// and return a list of revs to delete
20051function compactTree(metadata) {
20052 var revs = [];
20053 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
20054 revHash, ctx, opts) {
20055 if (opts.status === 'available' && !isLeaf) {
20056 revs.push(pos + '-' + revHash);
20057 opts.status = 'missing';
20058 }
20059 });
20060 return revs;
20061}
20062
20063// `findPathToLeaf()` returns an array of revs that goes from the specified
20064// leaf rev to the root of that leaf’s branch.
20065//
20066// eg. for this rev tree:
20067// 1-9692 ▶ 2-37aa ▶ 3-df22 ▶ 4-6e94 ▶ 5-df4a ▶ 6-6a3a ▶ 7-57e5
20068// ┃ ┗━━━━━━▶ 5-8d8c ▶ 6-65e0
20069// ┗━━━━━━▶ 3-43f6 ▶ 4-a3b4
20070//
20071// For a `targetRev` of '7-57e5', `findPathToLeaf()` would return ['7-57e5', '6-6a3a', '5-df4a']
20072// The `revs` arument has the same structure as what `revs_tree` has on e.g.
20073// the IndexedDB representation of the rev tree datastructure. Please refer to
20074// tests/unit/test.purge.js for examples of what these look like.
20075//
20076// This function will throw an error if:
20077// - The requested revision does not exist
20078// - The requested revision is not a leaf
20079function findPathToLeaf(revs, targetRev) {
20080 let path = [];
20081 const toVisit = revs.slice();
20082
20083 let node;
20084 while ((node = toVisit.pop())) {
20085 const { pos, ids: tree } = node;
20086 const rev = `${pos}-${tree[0]}`;
20087 const branches = tree[2];
20088
20089 // just assuming we're already working on the path up towards our desired leaf.
20090 path.push(rev);
20091
20092 // we've reached the leaf of our dreams, so return the computed path.
20093 if (rev === targetRev) {
20094 //…unleeeeess
20095 if (branches.length !== 0) {
20096 throw new Error('The requested revision is not a leaf');
20097 }
20098 return path.reverse();
20099 }
20100
20101 // this is based on the assumption that after we have a leaf (`branches.length == 0`), we handle the next
20102 // branch. this is true for all branches other than the path leading to the winning rev (which is 7-57e5 in
20103 // the example above. i've added a reset condition for branching nodes (`branches.length > 1`) as well.
20104 if (branches.length === 0 || branches.length > 1) {
20105 path = [];
20106 }
20107
20108 // as a next step, we push the branches of this node to `toVisit` for visiting it during the next iteration
20109 for (let i = 0, len = branches.length; i < len; i++) {
20110 toVisit.push({ pos: pos + 1, ids: branches[i] });
20111 }
20112 }
20113 if (path.length === 0) {
20114 throw new Error('The requested revision does not exist');
20115 }
20116 return path.reverse();
20117}
20118
20119// build up a list of all the paths to the leafs in this revision tree
20120function rootToLeaf(revs) {
20121 var paths = [];
20122 var toVisit = revs.slice();
20123 var node;
20124 while ((node = toVisit.pop())) {
20125 var pos = node.pos;
20126 var tree = node.ids;
20127 var id = tree[0];
20128 var opts = tree[1];
20129 var branches = tree[2];
20130 var isLeaf = branches.length === 0;
20131
20132 var history = node.history ? node.history.slice() : [];
20133 history.push({id: id, opts: opts});
20134 if (isLeaf) {
20135 paths.push({pos: (pos + 1 - history.length), ids: history});
20136 }
20137 for (var i = 0, len = branches.length; i < len; i++) {
20138 toVisit.push({pos: pos + 1, ids: branches[i], history: history});
20139 }
20140 }
20141 return paths.reverse();
20142}
20143
20144// for a better overview of what this is doing, read:
20145
20146function sortByPos$1(a, b) {
20147 return a.pos - b.pos;
20148}
20149
20150// classic binary search
20151function binarySearch(arr, item, comparator) {
20152 var low = 0;
20153 var high = arr.length;
20154 var mid;
20155 while (low < high) {
20156 mid = (low + high) >>> 1;
20157 if (comparator(arr[mid], item) < 0) {
20158 low = mid + 1;
20159 } else {
20160 high = mid;
20161 }
20162 }
20163 return low;
20164}
20165
20166// assuming the arr is sorted, insert the item in the proper place
20167function insertSorted(arr, item, comparator) {
20168 var idx = binarySearch(arr, item, comparator);
20169 arr.splice(idx, 0, item);
20170}
20171
20172// Turn a path as a flat array into a tree with a single branch.
20173// If any should be stemmed from the beginning of the array, that's passed
20174// in as the second argument
20175function pathToTree(path, numStemmed) {
20176 var root;
20177 var leaf;
20178 for (var i = numStemmed, len = path.length; i < len; i++) {
20179 var node = path[i];
20180 var currentLeaf = [node.id, node.opts, []];
20181 if (leaf) {
20182 leaf[2].push(currentLeaf);
20183 leaf = currentLeaf;
20184 } else {
20185 root = leaf = currentLeaf;
20186 }
20187 }
20188 return root;
20189}
20190
20191// compare the IDs of two trees
20192function compareTree(a, b) {
20193 return a[0] < b[0] ? -1 : 1;
20194}
20195
20196// Merge two trees together
20197// The roots of tree1 and tree2 must be the same revision
20198function mergeTree(in_tree1, in_tree2) {
20199 var queue = [{tree1: in_tree1, tree2: in_tree2}];
20200 var conflicts = false;
20201 while (queue.length > 0) {
20202 var item = queue.pop();
20203 var tree1 = item.tree1;
20204 var tree2 = item.tree2;
20205
20206 if (tree1[1].status || tree2[1].status) {
20207 tree1[1].status =
20208 (tree1[1].status === 'available' ||
20209 tree2[1].status === 'available') ? 'available' : 'missing';
20210 }
20211
20212 for (var i = 0; i < tree2[2].length; i++) {
20213 if (!tree1[2][0]) {
20214 conflicts = 'new_leaf';
20215 tree1[2][0] = tree2[2][i];
20216 continue;
20217 }
20218
20219 var merged = false;
20220 for (var j = 0; j < tree1[2].length; j++) {
20221 if (tree1[2][j][0] === tree2[2][i][0]) {
20222 queue.push({tree1: tree1[2][j], tree2: tree2[2][i]});
20223 merged = true;
20224 }
20225 }
20226 if (!merged) {
20227 conflicts = 'new_branch';
20228 insertSorted(tree1[2], tree2[2][i], compareTree);
20229 }
20230 }
20231 }
20232 return {conflicts: conflicts, tree: in_tree1};
20233}
20234
20235function doMerge(tree, path, dontExpand) {
20236 var restree = [];
20237 var conflicts = false;
20238 var merged = false;
20239 var res;
20240
20241 if (!tree.length) {
20242 return {tree: [path], conflicts: 'new_leaf'};
20243 }
20244
20245 for (var i = 0, len = tree.length; i < len; i++) {
20246 var branch = tree[i];
20247 if (branch.pos === path.pos && branch.ids[0] === path.ids[0]) {
20248 // Paths start at the same position and have the same root, so they need
20249 // merged
20250 res = mergeTree(branch.ids, path.ids);
20251 restree.push({pos: branch.pos, ids: res.tree});
20252 conflicts = conflicts || res.conflicts;
20253 merged = true;
20254 } else if (dontExpand !== true) {
20255 // The paths start at a different position, take the earliest path and
20256 // traverse up until it as at the same point from root as the path we
20257 // want to merge. If the keys match we return the longer path with the
20258 // other merged After stemming we dont want to expand the trees
20259
20260 var t1 = branch.pos < path.pos ? branch : path;
20261 var t2 = branch.pos < path.pos ? path : branch;
20262 var diff = t2.pos - t1.pos;
20263
20264 var candidateParents = [];
20265
20266 var trees = [];
20267 trees.push({ids: t1.ids, diff: diff, parent: null, parentIdx: null});
20268 while (trees.length > 0) {
20269 var item = trees.pop();
20270 if (item.diff === 0) {
20271 if (item.ids[0] === t2.ids[0]) {
20272 candidateParents.push(item);
20273 }
20274 continue;
20275 }
20276 var elements = item.ids[2];
20277 for (var j = 0, elementsLen = elements.length; j < elementsLen; j++) {
20278 trees.push({
20279 ids: elements[j],
20280 diff: item.diff - 1,
20281 parent: item.ids,
20282 parentIdx: j
20283 });
20284 }
20285 }
20286
20287 var el = candidateParents[0];
20288
20289 if (!el) {
20290 restree.push(branch);
20291 } else {
20292 res = mergeTree(el.ids, t2.ids);
20293 el.parent[2][el.parentIdx] = res.tree;
20294 restree.push({pos: t1.pos, ids: t1.ids});
20295 conflicts = conflicts || res.conflicts;
20296 merged = true;
20297 }
20298 } else {
20299 restree.push(branch);
20300 }
20301 }
20302
20303 // We didnt find
20304 if (!merged) {
20305 restree.push(path);
20306 }
20307
20308 restree.sort(sortByPos$1);
20309
20310 return {
20311 tree: restree,
20312 conflicts: conflicts || 'internal_node'
20313 };
20314}
20315
20316// To ensure we dont grow the revision tree infinitely, we stem old revisions
20317function stem(tree, depth) {
20318 // First we break out the tree into a complete list of root to leaf paths
20319 var paths = rootToLeaf(tree);
20320 var stemmedRevs;
20321
20322 var result;
20323 for (var i = 0, len = paths.length; i < len; i++) {
20324 // Then for each path, we cut off the start of the path based on the
20325 // `depth` to stem to, and generate a new set of flat trees
20326 var path = paths[i];
20327 var stemmed = path.ids;
20328 var node;
20329 if (stemmed.length > depth) {
20330 // only do the stemming work if we actually need to stem
20331 if (!stemmedRevs) {
20332 stemmedRevs = {}; // avoid allocating this object unnecessarily
20333 }
20334 var numStemmed = stemmed.length - depth;
20335 node = {
20336 pos: path.pos + numStemmed,
20337 ids: pathToTree(stemmed, numStemmed)
20338 };
20339
20340 for (var s = 0; s < numStemmed; s++) {
20341 var rev = (path.pos + s) + '-' + stemmed[s].id;
20342 stemmedRevs[rev] = true;
20343 }
20344 } else { // no need to actually stem
20345 node = {
20346 pos: path.pos,
20347 ids: pathToTree(stemmed, 0)
20348 };
20349 }
20350
20351 // Then we remerge all those flat trees together, ensuring that we dont
20352 // connect trees that would go beyond the depth limit
20353 if (result) {
20354 result = doMerge(result, node, true).tree;
20355 } else {
20356 result = [node];
20357 }
20358 }
20359
20360 // this is memory-heavy per Chrome profiler, avoid unless we actually stemmed
20361 if (stemmedRevs) {
20362 traverseRevTree(result, function (isLeaf, pos, revHash) {
20363 // some revisions may have been removed in a branch but not in another
20364 delete stemmedRevs[pos + '-' + revHash];
20365 });
20366 }
20367
20368 return {
20369 tree: result,
20370 revs: stemmedRevs ? Object.keys(stemmedRevs) : []
20371 };
20372}
20373
20374function merge(tree, path, depth) {
20375 var newTree = doMerge(tree, path);
20376 var stemmed = stem(newTree.tree, depth);
20377 return {
20378 tree: stemmed.tree,
20379 stemmedRevs: stemmed.revs,
20380 conflicts: newTree.conflicts
20381 };
20382}
20383
20384// return true if a rev exists in the rev tree, false otherwise
20385function revExists(revs, rev) {
20386 var toVisit = revs.slice();
20387 var splitRev = rev.split('-');
20388 var targetPos = parseInt(splitRev[0], 10);
20389 var targetId = splitRev[1];
20390
20391 var node;
20392 while ((node = toVisit.pop())) {
20393 if (node.pos === targetPos && node.ids[0] === targetId) {
20394 return true;
20395 }
20396 var branches = node.ids[2];
20397 for (var i = 0, len = branches.length; i < len; i++) {
20398 toVisit.push({pos: node.pos + 1, ids: branches[i]});
20399 }
20400 }
20401 return false;
20402}
20403
20404function getTrees(node) {
20405 return node.ids;
20406}
20407
20408// check if a specific revision of a doc has been deleted
20409// - metadata: the metadata object from the doc store
20410// - rev: (optional) the revision to check. defaults to winning revision
20411function isDeleted(metadata, rev) {
20412 if (!rev) {
20413 rev = winningRev(metadata);
20414 }
20415 var id = rev.substring(rev.indexOf('-') + 1);
20416 var toVisit = metadata.rev_tree.map(getTrees);
20417
20418 var tree;
20419 while ((tree = toVisit.pop())) {
20420 if (tree[0] === id) {
20421 return !!tree[1].deleted;
20422 }
20423 toVisit = toVisit.concat(tree[2]);
20424 }
20425}
20426
20427function isLocalId(id) {
20428 return (/^_local/).test(id);
20429}
20430
20431// returns the current leaf node for a given revision
20432function latest(rev, metadata) {
20433 var toVisit = metadata.rev_tree.slice();
20434 var node;
20435 while ((node = toVisit.pop())) {
20436 var pos = node.pos;
20437 var tree = node.ids;
20438 var id = tree[0];
20439 var opts = tree[1];
20440 var branches = tree[2];
20441 var isLeaf = branches.length === 0;
20442
20443 var history = node.history ? node.history.slice() : [];
20444 history.push({id: id, pos: pos, opts: opts});
20445
20446 if (isLeaf) {
20447 for (var i = 0, len = history.length; i < len; i++) {
20448 var historyNode = history[i];
20449 var historyRev = historyNode.pos + '-' + historyNode.id;
20450
20451 if (historyRev === rev) {
20452 // return the rev of this leaf
20453 return pos + '-' + id;
20454 }
20455 }
20456 }
20457
20458 for (var j = 0, l = branches.length; j < l; j++) {
20459 toVisit.push({pos: pos + 1, ids: branches[j], history: history});
20460 }
20461 }
20462
20463 /* istanbul ignore next */
20464 throw new Error('Unable to resolve latest revision for id ' + metadata.id + ', rev ' + rev);
20465}
20466
20467function tryCatchInChangeListener(self, change, pending, lastSeq) {
20468 // isolate try/catches to avoid V8 deoptimizations
20469 try {
20470 self.emit('change', change, pending, lastSeq);
20471 } catch (e) {
20472 guardedConsole('error', 'Error in .on("change", function):', e);
20473 }
20474}
20475
20476function processChange(doc, metadata, opts) {
20477 var changeList = [{rev: doc._rev}];
20478 if (opts.style === 'all_docs') {
20479 changeList = collectLeaves(metadata.rev_tree)
20480 .map(function (x) { return {rev: x.rev}; });
20481 }
20482 var change = {
20483 id: metadata.id,
20484 changes: changeList,
20485 doc: doc
20486 };
20487
20488 if (isDeleted(metadata, doc._rev)) {
20489 change.deleted = true;
20490 }
20491 if (opts.conflicts) {
20492 change.doc._conflicts = collectConflicts(metadata);
20493 if (!change.doc._conflicts.length) {
20494 delete change.doc._conflicts;
20495 }
20496 }
20497 return change;
20498}
20499
20500class Changes$1 extends EE {
20501 constructor(db, opts, callback) {
20502 super();
20503 this.db = db;
20504 opts = opts ? clone(opts) : {};
20505 var complete = opts.complete = once((err, resp) => {
20506 if (err) {
20507 if (listenerCount(this, 'error') > 0) {
20508 this.emit('error', err);
20509 }
20510 } else {
20511 this.emit('complete', resp);
20512 }
20513 this.removeAllListeners();
20514 db.removeListener('destroyed', onDestroy);
20515 });
20516 if (callback) {
20517 this.on('complete', function (resp) {
20518 callback(null, resp);
20519 });
20520 this.on('error', callback);
20521 }
20522 const onDestroy = () => {
20523 this.cancel();
20524 };
20525 db.once('destroyed', onDestroy);
20526
20527 opts.onChange = (change, pending, lastSeq) => {
20528 /* istanbul ignore if */
20529 if (this.isCancelled) {
20530 return;
20531 }
20532 tryCatchInChangeListener(this, change, pending, lastSeq);
20533 };
20534
20535 var promise = new Promise(function (fulfill, reject) {
20536 opts.complete = function (err, res) {
20537 if (err) {
20538 reject(err);
20539 } else {
20540 fulfill(res);
20541 }
20542 };
20543 });
20544 this.once('cancel', function () {
20545 db.removeListener('destroyed', onDestroy);
20546 opts.complete(null, {status: 'cancelled'});
20547 });
20548 this.then = promise.then.bind(promise);
20549 this['catch'] = promise['catch'].bind(promise);
20550 this.then(function (result) {
20551 complete(null, result);
20552 }, complete);
20553
20554
20555
20556 if (!db.taskqueue.isReady) {
20557 db.taskqueue.addTask((failed) => {
20558 if (failed) {
20559 opts.complete(failed);
20560 } else if (this.isCancelled) {
20561 this.emit('cancel');
20562 } else {
20563 this.validateChanges(opts);
20564 }
20565 });
20566 } else {
20567 this.validateChanges(opts);
20568 }
20569 }
20570
20571 cancel() {
20572 this.isCancelled = true;
20573 if (this.db.taskqueue.isReady) {
20574 this.emit('cancel');
20575 }
20576 }
20577
20578 validateChanges(opts) {
20579 var callback = opts.complete;
20580
20581 /* istanbul ignore else */
20582 if (PouchDB$1._changesFilterPlugin) {
20583 PouchDB$1._changesFilterPlugin.validate(opts, (err) => {
20584 if (err) {
20585 return callback(err);
20586 }
20587 this.doChanges(opts);
20588 });
20589 } else {
20590 this.doChanges(opts);
20591 }
20592 }
20593
20594 doChanges(opts) {
20595 var callback = opts.complete;
20596
20597 opts = clone(opts);
20598 if ('live' in opts && !('continuous' in opts)) {
20599 opts.continuous = opts.live;
20600 }
20601 opts.processChange = processChange;
20602
20603 if (opts.since === 'latest') {
20604 opts.since = 'now';
20605 }
20606 if (!opts.since) {
20607 opts.since = 0;
20608 }
20609 if (opts.since === 'now') {
20610 this.db.info().then((info) => {
20611 /* istanbul ignore if */
20612 if (this.isCancelled) {
20613 callback(null, {status: 'cancelled'});
20614 return;
20615 }
20616 opts.since = info.update_seq;
20617 this.doChanges(opts);
20618 }, callback);
20619 return;
20620 }
20621
20622 /* istanbul ignore else */
20623 if (PouchDB$1._changesFilterPlugin) {
20624 PouchDB$1._changesFilterPlugin.normalize(opts);
20625 if (PouchDB$1._changesFilterPlugin.shouldFilter(this, opts)) {
20626 return PouchDB$1._changesFilterPlugin.filter(this, opts);
20627 }
20628 } else {
20629 ['doc_ids', 'filter', 'selector', 'view'].forEach(function (key) {
20630 if (key in opts) {
20631 guardedConsole('warn',
20632 'The "' + key + '" option was passed in to changes/replicate, ' +
20633 'but pouchdb-changes-filter plugin is not installed, so it ' +
20634 'was ignored. Please install the plugin to enable filtering.'
20635 );
20636 }
20637 });
20638 }
20639
20640 if (!('descending' in opts)) {
20641 opts.descending = false;
20642 }
20643
20644 // 0 and 1 should return 1 document
20645 opts.limit = opts.limit === 0 ? 1 : opts.limit;
20646 opts.complete = callback;
20647 var newPromise = this.db._changes(opts);
20648 /* istanbul ignore else */
20649 if (newPromise && typeof newPromise.cancel === 'function') {
20650 const cancel = this.cancel;
20651 this.cancel = (...args) => {
20652 newPromise.cancel();
20653 cancel.apply(this, args);
20654 };
20655 }
20656 }
20657}
20658
20659/*
20660 * A generic pouch adapter
20661 */
20662
20663function compare(left, right) {
20664 return left < right ? -1 : left > right ? 1 : 0;
20665}
20666
20667// Wrapper for functions that call the bulkdocs api with a single doc,
20668// if the first result is an error, return an error
20669function yankError(callback, docId) {
20670 return function (err, results) {
20671 if (err || (results[0] && results[0].error)) {
20672 err = err || results[0];
20673 err.docId = docId;
20674 callback(err);
20675 } else {
20676 callback(null, results.length ? results[0] : results);
20677 }
20678 };
20679}
20680
20681// clean docs given to us by the user
20682function cleanDocs(docs) {
20683 for (var i = 0; i < docs.length; i++) {
20684 var doc = docs[i];
20685 if (doc._deleted) {
20686 delete doc._attachments; // ignore atts for deleted docs
20687 } else if (doc._attachments) {
20688 // filter out extraneous keys from _attachments
20689 var atts = Object.keys(doc._attachments);
20690 for (var j = 0; j < atts.length; j++) {
20691 var att = atts[j];
20692 doc._attachments[att] = pick(doc._attachments[att],
20693 ['data', 'digest', 'content_type', 'length', 'revpos', 'stub']);
20694 }
20695 }
20696 }
20697}
20698
20699// compare two docs, first by _id then by _rev
20700function compareByIdThenRev(a, b) {
20701 var idCompare = compare(a._id, b._id);
20702 if (idCompare !== 0) {
20703 return idCompare;
20704 }
20705 var aStart = a._revisions ? a._revisions.start : 0;
20706 var bStart = b._revisions ? b._revisions.start : 0;
20707 return compare(aStart, bStart);
20708}
20709
20710// for every node in a revision tree computes its distance from the closest
20711// leaf
20712function computeHeight(revs) {
20713 var height = {};
20714 var edges = [];
20715 traverseRevTree(revs, function (isLeaf, pos, id, prnt) {
20716 var rev = pos + "-" + id;
20717 if (isLeaf) {
20718 height[rev] = 0;
20719 }
20720 if (prnt !== undefined) {
20721 edges.push({from: prnt, to: rev});
20722 }
20723 return rev;
20724 });
20725
20726 edges.reverse();
20727 edges.forEach(function (edge) {
20728 if (height[edge.from] === undefined) {
20729 height[edge.from] = 1 + height[edge.to];
20730 } else {
20731 height[edge.from] = Math.min(height[edge.from], 1 + height[edge.to]);
20732 }
20733 });
20734 return height;
20735}
20736
20737function allDocsKeysParse(opts) {
20738 var keys = ('limit' in opts) ?
20739 opts.keys.slice(opts.skip, opts.limit + opts.skip) :
20740 (opts.skip > 0) ? opts.keys.slice(opts.skip) : opts.keys;
20741 opts.keys = keys;
20742 opts.skip = 0;
20743 delete opts.limit;
20744 if (opts.descending) {
20745 keys.reverse();
20746 opts.descending = false;
20747 }
20748}
20749
20750// all compaction is done in a queue, to avoid attaching
20751// too many listeners at once
20752function doNextCompaction(self) {
20753 var task = self._compactionQueue[0];
20754 var opts = task.opts;
20755 var callback = task.callback;
20756 self.get('_local/compaction')["catch"](function () {
20757 return false;
20758 }).then(function (doc) {
20759 if (doc && doc.last_seq) {
20760 opts.last_seq = doc.last_seq;
20761 }
20762 self._compact(opts, function (err, res) {
20763 /* istanbul ignore if */
20764 if (err) {
20765 callback(err);
20766 } else {
20767 callback(null, res);
20768 }
20769 immediate(function () {
20770 self._compactionQueue.shift();
20771 if (self._compactionQueue.length) {
20772 doNextCompaction(self);
20773 }
20774 });
20775 });
20776 });
20777}
20778
20779function appendPurgeSeq(db, docId, rev) {
20780 return db.get('_local/purges').then(function (doc) {
20781 const purgeSeq = doc.purgeSeq + 1;
20782 doc.purges.push({
20783 docId,
20784 rev,
20785 purgeSeq
20786 });
20787 if (doc.purges.length > self.purged_infos_limit) {
20788 doc.purges.splice(0, doc.purges.length - self.purged_infos_limit);
20789 }
20790 doc.purgeSeq = purgeSeq;
20791 return doc;
20792 })["catch"](function (err) {
20793 if (err.status !== 404) {
20794 throw err;
20795 }
20796 return {
20797 _id: '_local/purges',
20798 purges: [{
20799 docId,
20800 rev,
20801 purgeSeq: 0
20802 }],
20803 purgeSeq: 0
20804 };
20805 }).then(function (doc) {
20806 return db.put(doc);
20807 });
20808}
20809
20810function attachmentNameError(name) {
20811 if (name.charAt(0) === '_') {
20812 return name + ' is not a valid attachment name, attachment ' +
20813 'names cannot start with \'_\'';
20814 }
20815 return false;
20816}
20817
20818class AbstractPouchDB extends EE {
20819 _setup() {
20820 this.post = adapterFun('post', function (doc, opts, callback) {
20821 if (typeof opts === 'function') {
20822 callback = opts;
20823 opts = {};
20824 }
20825 if (typeof doc !== 'object' || Array.isArray(doc)) {
20826 return callback(createError(NOT_AN_OBJECT));
20827 }
20828 this.bulkDocs({docs: [doc]}, opts, yankError(callback, doc._id));
20829 }).bind(this);
20830
20831 this.put = adapterFun('put', function (doc, opts, cb) {
20832 if (typeof opts === 'function') {
20833 cb = opts;
20834 opts = {};
20835 }
20836 if (typeof doc !== 'object' || Array.isArray(doc)) {
20837 return cb(createError(NOT_AN_OBJECT));
20838 }
20839 invalidIdError(doc._id);
20840 if (isLocalId(doc._id) && typeof this._putLocal === 'function') {
20841 if (doc._deleted) {
20842 return this._removeLocal(doc, cb);
20843 } else {
20844 return this._putLocal(doc, cb);
20845 }
20846 }
20847
20848 const putDoc = (next) => {
20849 if (typeof this._put === 'function' && opts.new_edits !== false) {
20850 this._put(doc, opts, next);
20851 } else {
20852 this.bulkDocs({docs: [doc]}, opts, yankError(next, doc._id));
20853 }
20854 };
20855
20856 if (opts.force && doc._rev) {
20857 transformForceOptionToNewEditsOption();
20858 putDoc(function (err) {
20859 var result = err ? null : {ok: true, id: doc._id, rev: doc._rev};
20860 cb(err, result);
20861 });
20862 } else {
20863 putDoc(cb);
20864 }
20865
20866 function transformForceOptionToNewEditsOption() {
20867 var parts = doc._rev.split('-');
20868 var oldRevId = parts[1];
20869 var oldRevNum = parseInt(parts[0], 10);
20870
20871 var newRevNum = oldRevNum + 1;
20872 var newRevId = rev$$1();
20873
20874 doc._revisions = {
20875 start: newRevNum,
20876 ids: [newRevId, oldRevId]
20877 };
20878 doc._rev = newRevNum + '-' + newRevId;
20879 opts.new_edits = false;
20880 }
20881 }).bind(this);
20882
20883 this.putAttachment = adapterFun('putAttachment', function (docId, attachmentId, rev, blob, type) {
20884 var api = this;
20885 if (typeof type === 'function') {
20886 type = blob;
20887 blob = rev;
20888 rev = null;
20889 }
20890 // Lets fix in https://github.com/pouchdb/pouchdb/issues/3267
20891 /* istanbul ignore if */
20892 if (typeof type === 'undefined') {
20893 type = blob;
20894 blob = rev;
20895 rev = null;
20896 }
20897 if (!type) {
20898 guardedConsole('warn', 'Attachment', attachmentId, 'on document', docId, 'is missing content_type');
20899 }
20900
20901 function createAttachment(doc) {
20902 var prevrevpos = '_rev' in doc ? parseInt(doc._rev, 10) : 0;
20903 doc._attachments = doc._attachments || {};
20904 doc._attachments[attachmentId] = {
20905 content_type: type,
20906 data: blob,
20907 revpos: ++prevrevpos
20908 };
20909 return api.put(doc);
20910 }
20911
20912 return api.get(docId).then(function (doc) {
20913 if (doc._rev !== rev) {
20914 throw createError(REV_CONFLICT);
20915 }
20916
20917 return createAttachment(doc);
20918 }, function (err) {
20919 // create new doc
20920 /* istanbul ignore else */
20921 if (err.reason === MISSING_DOC.message) {
20922 return createAttachment({_id: docId});
20923 } else {
20924 throw err;
20925 }
20926 });
20927 }).bind(this);
20928
20929 this.removeAttachment = adapterFun('removeAttachment', function (docId, attachmentId, rev, callback) {
20930 this.get(docId, (err, obj) => {
20931 /* istanbul ignore if */
20932 if (err) {
20933 callback(err);
20934 return;
20935 }
20936 if (obj._rev !== rev) {
20937 callback(createError(REV_CONFLICT));
20938 return;
20939 }
20940 /* istanbul ignore if */
20941 if (!obj._attachments) {
20942 return callback();
20943 }
20944 delete obj._attachments[attachmentId];
20945 if (Object.keys(obj._attachments).length === 0) {
20946 delete obj._attachments;
20947 }
20948 this.put(obj, callback);
20949 });
20950 }).bind(this);
20951
20952 this.remove = adapterFun('remove', function (docOrId, optsOrRev, opts, callback) {
20953 var doc;
20954 if (typeof optsOrRev === 'string') {
20955 // id, rev, opts, callback style
20956 doc = {
20957 _id: docOrId,
20958 _rev: optsOrRev
20959 };
20960 if (typeof opts === 'function') {
20961 callback = opts;
20962 opts = {};
20963 }
20964 } else {
20965 // doc, opts, callback style
20966 doc = docOrId;
20967 if (typeof optsOrRev === 'function') {
20968 callback = optsOrRev;
20969 opts = {};
20970 } else {
20971 callback = opts;
20972 opts = optsOrRev;
20973 }
20974 }
20975 opts = opts || {};
20976 opts.was_delete = true;
20977 var newDoc = {_id: doc._id, _rev: (doc._rev || opts.rev)};
20978 newDoc._deleted = true;
20979 if (isLocalId(newDoc._id) && typeof this._removeLocal === 'function') {
20980 return this._removeLocal(doc, callback);
20981 }
20982 this.bulkDocs({docs: [newDoc]}, opts, yankError(callback, newDoc._id));
20983 }).bind(this);
20984
20985 this.revsDiff = adapterFun('revsDiff', function (req, opts, callback) {
20986 if (typeof opts === 'function') {
20987 callback = opts;
20988 opts = {};
20989 }
20990 var ids = Object.keys(req);
20991
20992 if (!ids.length) {
20993 return callback(null, {});
20994 }
20995
20996 var count = 0;
20997 var missing = new ExportedMap();
20998
20999 function addToMissing(id, revId) {
21000 if (!missing.has(id)) {
21001 missing.set(id, {missing: []});
21002 }
21003 missing.get(id).missing.push(revId);
21004 }
21005
21006 function processDoc(id, rev_tree) {
21007 // Is this fast enough? Maybe we should switch to a set simulated by a map
21008 var missingForId = req[id].slice(0);
21009 traverseRevTree(rev_tree, function (isLeaf, pos, revHash, ctx,
21010 opts) {
21011 var rev = pos + '-' + revHash;
21012 var idx = missingForId.indexOf(rev);
21013 if (idx === -1) {
21014 return;
21015 }
21016
21017 missingForId.splice(idx, 1);
21018 /* istanbul ignore if */
21019 if (opts.status !== 'available') {
21020 addToMissing(id, rev);
21021 }
21022 });
21023
21024 // Traversing the tree is synchronous, so now `missingForId` contains
21025 // revisions that were not found in the tree
21026 missingForId.forEach(function (rev) {
21027 addToMissing(id, rev);
21028 });
21029 }
21030
21031 ids.map(function (id) {
21032 this._getRevisionTree(id, function (err, rev_tree) {
21033 if (err && err.status === 404 && err.message === 'missing') {
21034 missing.set(id, {missing: req[id]});
21035 } else if (err) {
21036 /* istanbul ignore next */
21037 return callback(err);
21038 } else {
21039 processDoc(id, rev_tree);
21040 }
21041
21042 if (++count === ids.length) {
21043 // convert LazyMap to object
21044 var missingObj = {};
21045 missing.forEach(function (value, key) {
21046 missingObj[key] = value;
21047 });
21048 return callback(null, missingObj);
21049 }
21050 });
21051 }, this);
21052 }).bind(this);
21053
21054 // _bulk_get API for faster replication, as described in
21055 // https://github.com/apache/couchdb-chttpd/pull/33
21056 // At the "abstract" level, it will just run multiple get()s in
21057 // parallel, because this isn't much of a performance cost
21058 // for local databases (except the cost of multiple transactions, which is
21059 // small). The http adapter overrides this in order
21060 // to do a more efficient single HTTP request.
21061 this.bulkGet = adapterFun('bulkGet', function (opts, callback) {
21062 bulkGet(this, opts, callback);
21063 }).bind(this);
21064
21065 // compact one document and fire callback
21066 // by compacting we mean removing all revisions which
21067 // are further from the leaf in revision tree than max_height
21068 this.compactDocument = adapterFun('compactDocument', function (docId, maxHeight, callback) {
21069 this._getRevisionTree(docId, (err, revTree) => {
21070 /* istanbul ignore if */
21071 if (err) {
21072 return callback(err);
21073 }
21074 var height = computeHeight(revTree);
21075 var candidates = [];
21076 var revs = [];
21077 Object.keys(height).forEach(function (rev) {
21078 if (height[rev] > maxHeight) {
21079 candidates.push(rev);
21080 }
21081 });
21082
21083 traverseRevTree(revTree, function (isLeaf, pos, revHash, ctx, opts) {
21084 var rev = pos + '-' + revHash;
21085 if (opts.status === 'available' && candidates.indexOf(rev) !== -1) {
21086 revs.push(rev);
21087 }
21088 });
21089 this._doCompaction(docId, revs, callback);
21090 });
21091 }).bind(this);
21092
21093 // compact the whole database using single document
21094 // compaction
21095 this.compact = adapterFun('compact', function (opts, callback) {
21096 if (typeof opts === 'function') {
21097 callback = opts;
21098 opts = {};
21099 }
21100
21101 opts = opts || {};
21102
21103 this._compactionQueue = this._compactionQueue || [];
21104 this._compactionQueue.push({opts: opts, callback: callback});
21105 if (this._compactionQueue.length === 1) {
21106 doNextCompaction(this);
21107 }
21108 }).bind(this);
21109
21110 /* Begin api wrappers. Specific functionality to storage belongs in the _[method] */
21111 this.get = adapterFun('get', function (id, opts, cb) {
21112 if (typeof opts === 'function') {
21113 cb = opts;
21114 opts = {};
21115 }
21116 if (typeof id !== 'string') {
21117 return cb(createError(INVALID_ID));
21118 }
21119 if (isLocalId(id) && typeof this._getLocal === 'function') {
21120 return this._getLocal(id, cb);
21121 }
21122 var leaves = [];
21123
21124 const finishOpenRevs = () => {
21125 var result = [];
21126 var count = leaves.length;
21127 /* istanbul ignore if */
21128 if (!count) {
21129 return cb(null, result);
21130 }
21131
21132 // order with open_revs is unspecified
21133 leaves.forEach((leaf) => {
21134 this.get(id, {
21135 rev: leaf,
21136 revs: opts.revs,
21137 latest: opts.latest,
21138 attachments: opts.attachments,
21139 binary: opts.binary
21140 }, function (err, doc) {
21141 if (!err) {
21142 // using latest=true can produce duplicates
21143 var existing;
21144 for (var i = 0, l = result.length; i < l; i++) {
21145 if (result[i].ok && result[i].ok._rev === doc._rev) {
21146 existing = true;
21147 break;
21148 }
21149 }
21150 if (!existing) {
21151 result.push({ok: doc});
21152 }
21153 } else {
21154 result.push({missing: leaf});
21155 }
21156 count--;
21157 if (!count) {
21158 cb(null, result);
21159 }
21160 });
21161 });
21162 };
21163
21164 if (opts.open_revs) {
21165 if (opts.open_revs === "all") {
21166 this._getRevisionTree(id, function (err, rev_tree) {
21167 /* istanbul ignore if */
21168 if (err) {
21169 return cb(err);
21170 }
21171 leaves = collectLeaves(rev_tree).map(function (leaf) {
21172 return leaf.rev;
21173 });
21174 finishOpenRevs();
21175 });
21176 } else {
21177 if (Array.isArray(opts.open_revs)) {
21178 leaves = opts.open_revs;
21179 for (var i = 0; i < leaves.length; i++) {
21180 var l = leaves[i];
21181 // looks like it's the only thing couchdb checks
21182 if (!(typeof (l) === "string" && /^\d+-/.test(l))) {
21183 return cb(createError(INVALID_REV));
21184 }
21185 }
21186 finishOpenRevs();
21187 } else {
21188 return cb(createError(UNKNOWN_ERROR, 'function_clause'));
21189 }
21190 }
21191 return; // open_revs does not like other options
21192 }
21193
21194 return this._get(id, opts, (err, result) => {
21195 if (err) {
21196 err.docId = id;
21197 return cb(err);
21198 }
21199
21200 var doc = result.doc;
21201 var metadata = result.metadata;
21202 var ctx = result.ctx;
21203
21204 if (opts.conflicts) {
21205 var conflicts = collectConflicts(metadata);
21206 if (conflicts.length) {
21207 doc._conflicts = conflicts;
21208 }
21209 }
21210
21211 if (isDeleted(metadata, doc._rev)) {
21212 doc._deleted = true;
21213 }
21214
21215 if (opts.revs || opts.revs_info) {
21216 var splittedRev = doc._rev.split('-');
21217 var revNo = parseInt(splittedRev[0], 10);
21218 var revHash = splittedRev[1];
21219
21220 var paths = rootToLeaf(metadata.rev_tree);
21221 var path = null;
21222
21223 for (var i = 0; i < paths.length; i++) {
21224 var currentPath = paths[i];
21225 var hashIndex = currentPath.ids.map(function (x) { return x.id; })
21226 .indexOf(revHash);
21227 var hashFoundAtRevPos = hashIndex === (revNo - 1);
21228
21229 if (hashFoundAtRevPos || (!path && hashIndex !== -1)) {
21230 path = currentPath;
21231 }
21232 }
21233
21234 /* istanbul ignore if */
21235 if (!path) {
21236 err = new Error('invalid rev tree');
21237 err.docId = id;
21238 return cb(err);
21239 }
21240
21241 var indexOfRev = path.ids.map(function (x) { return x.id; })
21242 .indexOf(doc._rev.split('-')[1]) + 1;
21243 var howMany = path.ids.length - indexOfRev;
21244 path.ids.splice(indexOfRev, howMany);
21245 path.ids.reverse();
21246
21247 if (opts.revs) {
21248 doc._revisions = {
21249 start: (path.pos + path.ids.length) - 1,
21250 ids: path.ids.map(function (rev) {
21251 return rev.id;
21252 })
21253 };
21254 }
21255 if (opts.revs_info) {
21256 var pos = path.pos + path.ids.length;
21257 doc._revs_info = path.ids.map(function (rev) {
21258 pos--;
21259 return {
21260 rev: pos + '-' + rev.id,
21261 status: rev.opts.status
21262 };
21263 });
21264 }
21265 }
21266
21267 if (opts.attachments && doc._attachments) {
21268 var attachments = doc._attachments;
21269 var count = Object.keys(attachments).length;
21270 if (count === 0) {
21271 return cb(null, doc);
21272 }
21273 Object.keys(attachments).forEach((key) => {
21274 this._getAttachment(doc._id, key, attachments[key], {
21275 // Previously the revision handling was done in adapter.js
21276 // getAttachment, however since idb-next doesnt we need to
21277 // pass the rev through
21278 rev: doc._rev,
21279 binary: opts.binary,
21280 ctx: ctx
21281 }, function (err, data) {
21282 var att = doc._attachments[key];
21283 att.data = data;
21284 delete att.stub;
21285 delete att.length;
21286 if (!--count) {
21287 cb(null, doc);
21288 }
21289 });
21290 });
21291 } else {
21292 if (doc._attachments) {
21293 for (var key in doc._attachments) {
21294 /* istanbul ignore else */
21295 if (Object.prototype.hasOwnProperty.call(doc._attachments, key)) {
21296 doc._attachments[key].stub = true;
21297 }
21298 }
21299 }
21300 cb(null, doc);
21301 }
21302 });
21303 }).bind(this);
21304
21305 // TODO: I dont like this, it forces an extra read for every
21306 // attachment read and enforces a confusing api between
21307 // adapter.js and the adapter implementation
21308 this.getAttachment = adapterFun('getAttachment', function (docId, attachmentId, opts, callback) {
21309 if (opts instanceof Function) {
21310 callback = opts;
21311 opts = {};
21312 }
21313 this._get(docId, opts, (err, res) => {
21314 if (err) {
21315 return callback(err);
21316 }
21317 if (res.doc._attachments && res.doc._attachments[attachmentId]) {
21318 opts.ctx = res.ctx;
21319 opts.binary = true;
21320 this._getAttachment(docId, attachmentId,
21321 res.doc._attachments[attachmentId], opts, callback);
21322 } else {
21323 return callback(createError(MISSING_DOC));
21324 }
21325 });
21326 }).bind(this);
21327
21328 this.allDocs = adapterFun('allDocs', function (opts, callback) {
21329 if (typeof opts === 'function') {
21330 callback = opts;
21331 opts = {};
21332 }
21333 opts.skip = typeof opts.skip !== 'undefined' ? opts.skip : 0;
21334 if (opts.start_key) {
21335 opts.startkey = opts.start_key;
21336 }
21337 if (opts.end_key) {
21338 opts.endkey = opts.end_key;
21339 }
21340 if ('keys' in opts) {
21341 if (!Array.isArray(opts.keys)) {
21342 return callback(new TypeError('options.keys must be an array'));
21343 }
21344 var incompatibleOpt =
21345 ['startkey', 'endkey', 'key'].filter(function (incompatibleOpt) {
21346 return incompatibleOpt in opts;
21347 })[0];
21348 if (incompatibleOpt) {
21349 callback(createError(QUERY_PARSE_ERROR,
21350 'Query parameter `' + incompatibleOpt +
21351 '` is not compatible with multi-get'
21352 ));
21353 return;
21354 }
21355 if (!isRemote(this)) {
21356 allDocsKeysParse(opts);
21357 if (opts.keys.length === 0) {
21358 return this._allDocs({limit: 0}, callback);
21359 }
21360 }
21361 }
21362
21363 return this._allDocs(opts, callback);
21364 }).bind(this);
21365
21366 this.close = adapterFun('close', function (callback) {
21367 this._closed = true;
21368 this.emit('closed');
21369 return this._close(callback);
21370 }).bind(this);
21371
21372 this.info = adapterFun('info', function (callback) {
21373 this._info((err, info) => {
21374 if (err) {
21375 return callback(err);
21376 }
21377 // assume we know better than the adapter, unless it informs us
21378 info.db_name = info.db_name || this.name;
21379 info.auto_compaction = !!(this.auto_compaction && !isRemote(this));
21380 info.adapter = this.adapter;
21381 callback(null, info);
21382 });
21383 }).bind(this);
21384
21385 this.id = adapterFun('id', function (callback) {
21386 return this._id(callback);
21387 }).bind(this);
21388
21389 this.bulkDocs = adapterFun('bulkDocs', function (req, opts, callback) {
21390 if (typeof opts === 'function') {
21391 callback = opts;
21392 opts = {};
21393 }
21394
21395 opts = opts || {};
21396
21397 if (Array.isArray(req)) {
21398 req = {
21399 docs: req
21400 };
21401 }
21402
21403 if (!req || !req.docs || !Array.isArray(req.docs)) {
21404 return callback(createError(MISSING_BULK_DOCS));
21405 }
21406
21407 for (var i = 0; i < req.docs.length; ++i) {
21408 if (typeof req.docs[i] !== 'object' || Array.isArray(req.docs[i])) {
21409 return callback(createError(NOT_AN_OBJECT));
21410 }
21411 }
21412
21413 var attachmentError;
21414 req.docs.forEach(function (doc) {
21415 if (doc._attachments) {
21416 Object.keys(doc._attachments).forEach(function (name) {
21417 attachmentError = attachmentError || attachmentNameError(name);
21418 if (!doc._attachments[name].content_type) {
21419 guardedConsole('warn', 'Attachment', name, 'on document', doc._id, 'is missing content_type');
21420 }
21421 });
21422 }
21423 });
21424
21425 if (attachmentError) {
21426 return callback(createError(BAD_REQUEST, attachmentError));
21427 }
21428
21429 if (!('new_edits' in opts)) {
21430 if ('new_edits' in req) {
21431 opts.new_edits = req.new_edits;
21432 } else {
21433 opts.new_edits = true;
21434 }
21435 }
21436
21437 var adapter = this;
21438 if (!opts.new_edits && !isRemote(adapter)) {
21439 // ensure revisions of the same doc are sorted, so that
21440 // the local adapter processes them correctly (#2935)
21441 req.docs.sort(compareByIdThenRev);
21442 }
21443
21444 cleanDocs(req.docs);
21445
21446 // in the case of conflicts, we want to return the _ids to the user
21447 // however, the underlying adapter may destroy the docs array, so
21448 // create a copy here
21449 var ids = req.docs.map(function (doc) {
21450 return doc._id;
21451 });
21452
21453 this._bulkDocs(req, opts, function (err, res) {
21454 if (err) {
21455 return callback(err);
21456 }
21457 if (!opts.new_edits) {
21458 // this is what couch does when new_edits is false
21459 res = res.filter(function (x) {
21460 return x.error;
21461 });
21462 }
21463 // add ids for error/conflict responses (not required for CouchDB)
21464 if (!isRemote(adapter)) {
21465 for (var i = 0, l = res.length; i < l; i++) {
21466 res[i].id = res[i].id || ids[i];
21467 }
21468 }
21469
21470 callback(null, res);
21471 });
21472 }).bind(this);
21473
21474 this.registerDependentDatabase = adapterFun('registerDependentDatabase', function (dependentDb, callback) {
21475 var dbOptions = clone(this.__opts);
21476 if (this.__opts.view_adapter) {
21477 dbOptions.adapter = this.__opts.view_adapter;
21478 }
21479
21480 var depDB = new this.constructor(dependentDb, dbOptions);
21481
21482 function diffFun(doc) {
21483 doc.dependentDbs = doc.dependentDbs || {};
21484 if (doc.dependentDbs[dependentDb]) {
21485 return false; // no update required
21486 }
21487 doc.dependentDbs[dependentDb] = true;
21488 return doc;
21489 }
21490 upsert(this, '_local/_pouch_dependentDbs', diffFun).then(function () {
21491 callback(null, {db: depDB});
21492 })["catch"](callback);
21493 }).bind(this);
21494
21495 this.destroy = adapterFun('destroy', function (opts, callback) {
21496
21497 if (typeof opts === 'function') {
21498 callback = opts;
21499 opts = {};
21500 }
21501
21502 var usePrefix = 'use_prefix' in this ? this.use_prefix : true;
21503
21504 const destroyDb = () => {
21505 // call destroy method of the particular adaptor
21506 this._destroy(opts, (err, resp) => {
21507 if (err) {
21508 return callback(err);
21509 }
21510 this._destroyed = true;
21511 this.emit('destroyed');
21512 callback(null, resp || { 'ok': true });
21513 });
21514 };
21515
21516 if (isRemote(this)) {
21517 // no need to check for dependent DBs if it's a remote DB
21518 return destroyDb();
21519 }
21520
21521 this.get('_local/_pouch_dependentDbs', (err, localDoc) => {
21522 if (err) {
21523 /* istanbul ignore if */
21524 if (err.status !== 404) {
21525 return callback(err);
21526 } else { // no dependencies
21527 return destroyDb();
21528 }
21529 }
21530 var dependentDbs = localDoc.dependentDbs;
21531 var PouchDB = this.constructor;
21532 var deletedMap = Object.keys(dependentDbs).map((name) => {
21533 // use_prefix is only false in the browser
21534 /* istanbul ignore next */
21535 var trueName = usePrefix ?
21536 name.replace(new RegExp('^' + PouchDB.prefix), '') : name;
21537 return new PouchDB(trueName, this.__opts).destroy();
21538 });
21539 Promise.all(deletedMap).then(destroyDb, callback);
21540 });
21541 }).bind(this);
21542 }
21543
21544 _compact(opts, callback) {
21545 var changesOpts = {
21546 return_docs: false,
21547 last_seq: opts.last_seq || 0
21548 };
21549 var promises = [];
21550
21551 var taskId;
21552 var compactedDocs = 0;
21553
21554 const onChange = (row) => {
21555 this.activeTasks.update(taskId, {
21556 completed_items: ++compactedDocs
21557 });
21558 promises.push(this.compactDocument(row.id, 0));
21559 };
21560 const onError = (err) => {
21561 this.activeTasks.remove(taskId, err);
21562 callback(err);
21563 };
21564 const onComplete = (resp) => {
21565 var lastSeq = resp.last_seq;
21566 Promise.all(promises).then(() => {
21567 return upsert(this, '_local/compaction', (doc) => {
21568 if (!doc.last_seq || doc.last_seq < lastSeq) {
21569 doc.last_seq = lastSeq;
21570 return doc;
21571 }
21572 return false; // somebody else got here first, don't update
21573 });
21574 }).then(() => {
21575 this.activeTasks.remove(taskId);
21576 callback(null, {ok: true});
21577 })["catch"](onError);
21578 };
21579
21580 this.info().then((info) => {
21581 taskId = this.activeTasks.add({
21582 name: 'database_compaction',
21583 total_items: info.update_seq - changesOpts.last_seq
21584 });
21585
21586 this.changes(changesOpts)
21587 .on('change', onChange)
21588 .on('complete', onComplete)
21589 .on('error', onError);
21590 });
21591 }
21592
21593 changes(opts, callback) {
21594 if (typeof opts === 'function') {
21595 callback = opts;
21596 opts = {};
21597 }
21598
21599 opts = opts || {};
21600
21601 // By default set return_docs to false if the caller has opts.live = true,
21602 // this will prevent us from collecting the set of changes indefinitely
21603 // resulting in growing memory
21604 opts.return_docs = ('return_docs' in opts) ? opts.return_docs : !opts.live;
21605
21606 return new Changes$1(this, opts, callback);
21607 }
21608
21609 type() {
21610 return (typeof this._type === 'function') ? this._type() : this.adapter;
21611 }
21612}
21613
21614// The abstract purge implementation expects a doc id and the rev of a leaf node in that doc.
21615// It will return errors if the rev doesn’t exist or isn’t a leaf.
21616AbstractPouchDB.prototype.purge = adapterFun('_purge', function (docId, rev, callback) {
21617 if (typeof this._purge === 'undefined') {
21618 return callback(createError(UNKNOWN_ERROR, 'Purge is not implemented in the ' + this.adapter + ' adapter.'));
21619 }
21620 var self = this;
21621
21622 self._getRevisionTree(docId, (error, revs) => {
21623 if (error) {
21624 return callback(error);
21625 }
21626 if (!revs) {
21627 return callback(createError(MISSING_DOC));
21628 }
21629 let path;
21630 try {
21631 path = findPathToLeaf(revs, rev);
21632 } catch (error) {
21633 return callback(error.message || error);
21634 }
21635 self._purge(docId, path, (error, result) => {
21636 if (error) {
21637 return callback(error);
21638 } else {
21639 appendPurgeSeq(self, docId, rev).then(function () {
21640 return callback(null, result);
21641 });
21642 }
21643 });
21644 });
21645});
21646
21647class TaskQueue {
21648 constructor() {
21649 this.isReady = false;
21650 this.failed = false;
21651 this.queue = [];
21652 }
21653
21654 execute() {
21655 var fun;
21656 if (this.failed) {
21657 while ((fun = this.queue.shift())) {
21658 fun(this.failed);
21659 }
21660 } else {
21661 while ((fun = this.queue.shift())) {
21662 fun();
21663 }
21664 }
21665 }
21666
21667 fail(err) {
21668 this.failed = err;
21669 this.execute();
21670 }
21671
21672 ready(db) {
21673 this.isReady = true;
21674 this.db = db;
21675 this.execute();
21676 }
21677
21678 addTask(fun) {
21679 this.queue.push(fun);
21680 if (this.failed) {
21681 this.execute();
21682 }
21683 }
21684}
21685
21686function parseAdapter(name, opts) {
21687 var match = name.match(/([a-z-]*):\/\/(.*)/);
21688 if (match) {
21689 // the http adapter expects the fully qualified name
21690 return {
21691 name: /https?/.test(match[1]) ? match[1] + '://' + match[2] : match[2],
21692 adapter: match[1]
21693 };
21694 }
21695
21696 var adapters = PouchDB$1.adapters;
21697 var preferredAdapters = PouchDB$1.preferredAdapters;
21698 var prefix = PouchDB$1.prefix;
21699 var adapterName = opts.adapter;
21700
21701 if (!adapterName) { // automatically determine adapter
21702 for (var i = 0; i < preferredAdapters.length; ++i) {
21703 adapterName = preferredAdapters[i];
21704 // check for browsers that have been upgraded from websql-only to websql+idb
21705 /* istanbul ignore if */
21706 if (adapterName === 'idb' && 'websql' in adapters &&
21707 hasLocalStorage() && localStorage['_pouch__websqldb_' + prefix + name]) {
21708 // log it, because this can be confusing during development
21709 guardedConsole('log', 'PouchDB is downgrading "' + name + '" to WebSQL to' +
21710 ' avoid data loss, because it was already opened with WebSQL.');
21711 continue; // keep using websql to avoid user data loss
21712 }
21713 break;
21714 }
21715 }
21716
21717 var adapter = adapters[adapterName];
21718
21719 // if adapter is invalid, then an error will be thrown later
21720 var usePrefix = (adapter && 'use_prefix' in adapter) ?
21721 adapter.use_prefix : true;
21722
21723 return {
21724 name: usePrefix ? (prefix + name) : name,
21725 adapter: adapterName
21726 };
21727}
21728
21729function inherits(A, B) {
21730 A.prototype = Object.create(B.prototype, {
21731 constructor: { value: A }
21732 });
21733}
21734
21735function createClass$1(parent, init) {
21736 let klass = function (...args) {
21737 if (!(this instanceof klass)) {
21738 return new klass(...args);
21739 }
21740 init.apply(this, args);
21741 };
21742 inherits(klass, parent);
21743 return klass;
21744}
21745
21746// OK, so here's the deal. Consider this code:
21747// var db1 = new PouchDB('foo');
21748// var db2 = new PouchDB('foo');
21749// db1.destroy();
21750// ^ these two both need to emit 'destroyed' events,
21751// as well as the PouchDB constructor itself.
21752// So we have one db object (whichever one got destroy() called on it)
21753// responsible for emitting the initial event, which then gets emitted
21754// by the constructor, which then broadcasts it to any other dbs
21755// that may have been created with the same name.
21756function prepareForDestruction(self) {
21757
21758 function onDestroyed(from_constructor) {
21759 self.removeListener('closed', onClosed);
21760 if (!from_constructor) {
21761 self.constructor.emit('destroyed', self.name);
21762 }
21763 }
21764
21765 function onClosed() {
21766 self.removeListener('destroyed', onDestroyed);
21767 self.constructor.emit('unref', self);
21768 }
21769
21770 self.once('destroyed', onDestroyed);
21771 self.once('closed', onClosed);
21772 self.constructor.emit('ref', self);
21773}
21774
21775class PouchInternal extends AbstractPouchDB {
21776 constructor(name, opts) {
21777 super();
21778 this._setup(name, opts);
21779 }
21780
21781 _setup(name, opts) {
21782 super._setup();
21783 opts = opts || {};
21784
21785 if (name && typeof name === 'object') {
21786 opts = name;
21787 name = opts.name;
21788 delete opts.name;
21789 }
21790
21791 if (opts.deterministic_revs === undefined) {
21792 opts.deterministic_revs = true;
21793 }
21794
21795 this.__opts = opts = clone(opts);
21796
21797 this.auto_compaction = opts.auto_compaction;
21798 this.purged_infos_limit = opts.purged_infos_limit || 1000;
21799 this.prefix = PouchDB$1.prefix;
21800
21801 if (typeof name !== 'string') {
21802 throw new Error('Missing/invalid DB name');
21803 }
21804
21805 var prefixedName = (opts.prefix || '') + name;
21806 var backend = parseAdapter(prefixedName, opts);
21807
21808 opts.name = backend.name;
21809 opts.adapter = opts.adapter || backend.adapter;
21810
21811 this.name = name;
21812 this._adapter = opts.adapter;
21813 PouchDB$1.emit('debug', ['adapter', 'Picked adapter: ', opts.adapter]);
21814
21815 if (!PouchDB$1.adapters[opts.adapter] ||
21816 !PouchDB$1.adapters[opts.adapter].valid()) {
21817 throw new Error('Invalid Adapter: ' + opts.adapter);
21818 }
21819
21820 if (opts.view_adapter) {
21821 if (!PouchDB$1.adapters[opts.view_adapter] ||
21822 !PouchDB$1.adapters[opts.view_adapter].valid()) {
21823 throw new Error('Invalid View Adapter: ' + opts.view_adapter);
21824 }
21825 }
21826
21827 this.taskqueue = new TaskQueue();
21828
21829 this.adapter = opts.adapter;
21830
21831 PouchDB$1.adapters[opts.adapter].call(this, opts, (err) => {
21832 if (err) {
21833 return this.taskqueue.fail(err);
21834 }
21835 prepareForDestruction(this);
21836
21837 this.emit('created', this);
21838 PouchDB$1.emit('created', this.name);
21839 this.taskqueue.ready(this);
21840 });
21841 }
21842}
21843
21844const PouchDB$1 = createClass$1(PouchInternal, function (name, opts) {
21845 PouchInternal.prototype._setup.call(this, name, opts);
21846});
21847
21848var f$1 = fetch;
21849
21850class ActiveTasks {
21851 constructor() {
21852 this.tasks = {};
21853 }
21854
21855 list() {
21856 return Object.values(this.tasks);
21857 }
21858
21859 add(task) {
21860 const id = uuid.v4();
21861 this.tasks[id] = {
21862 id,
21863 name: task.name,
21864 total_items: task.total_items,
21865 created_at: new Date().toJSON()
21866 };
21867 return id;
21868 }
21869
21870 get(id) {
21871 return this.tasks[id];
21872 }
21873
21874 /* eslint-disable no-unused-vars */
21875 remove(id, reason) {
21876 delete this.tasks[id];
21877 return this.tasks;
21878 }
21879
21880 update(id, updatedTask) {
21881 const task = this.tasks[id];
21882 if (typeof task !== 'undefined') {
21883 const mergedTask = {
21884 id: task.id,
21885 name: task.name,
21886 created_at: task.created_at,
21887 total_items: updatedTask.total_items || task.total_items,
21888 completed_items: updatedTask.completed_items || task.completed_items,
21889 updated_at: new Date().toJSON()
21890 };
21891 this.tasks[id] = mergedTask;
21892 }
21893 return this.tasks;
21894 }
21895}
21896
21897PouchDB$1.adapters = {};
21898PouchDB$1.preferredAdapters = [];
21899
21900PouchDB$1.prefix = '_pouch_';
21901
21902var eventEmitter = new EE();
21903
21904function setUpEventEmitter(Pouch) {
21905 Object.keys(EE.prototype).forEach(function (key) {
21906 if (typeof EE.prototype[key] === 'function') {
21907 Pouch[key] = eventEmitter[key].bind(eventEmitter);
21908 }
21909 });
21910
21911 // these are created in constructor.js, and allow us to notify each DB with
21912 // the same name that it was destroyed, via the constructor object
21913 var destructListeners = Pouch._destructionListeners = new ExportedMap();
21914
21915 Pouch.on('ref', function onConstructorRef(db) {
21916 if (!destructListeners.has(db.name)) {
21917 destructListeners.set(db.name, []);
21918 }
21919 destructListeners.get(db.name).push(db);
21920 });
21921
21922 Pouch.on('unref', function onConstructorUnref(db) {
21923 if (!destructListeners.has(db.name)) {
21924 return;
21925 }
21926 var dbList = destructListeners.get(db.name);
21927 var pos = dbList.indexOf(db);
21928 if (pos < 0) {
21929 /* istanbul ignore next */
21930 return;
21931 }
21932 dbList.splice(pos, 1);
21933 if (dbList.length > 1) {
21934 /* istanbul ignore next */
21935 destructListeners.set(db.name, dbList);
21936 } else {
21937 destructListeners["delete"](db.name);
21938 }
21939 });
21940
21941 Pouch.on('destroyed', function onConstructorDestroyed(name) {
21942 if (!destructListeners.has(name)) {
21943 return;
21944 }
21945 var dbList = destructListeners.get(name);
21946 destructListeners["delete"](name);
21947 dbList.forEach(function (db) {
21948 db.emit('destroyed',true);
21949 });
21950 });
21951}
21952
21953setUpEventEmitter(PouchDB$1);
21954
21955PouchDB$1.adapter = function (id, obj, addToPreferredAdapters) {
21956 /* istanbul ignore else */
21957 if (obj.valid()) {
21958 PouchDB$1.adapters[id] = obj;
21959 if (addToPreferredAdapters) {
21960 PouchDB$1.preferredAdapters.push(id);
21961 }
21962 }
21963};
21964
21965PouchDB$1.plugin = function (obj) {
21966 if (typeof obj === 'function') { // function style for plugins
21967 obj(PouchDB$1);
21968 } else if (typeof obj !== 'object' || Object.keys(obj).length === 0) {
21969 throw new Error('Invalid plugin: got "' + obj + '", expected an object or a function');
21970 } else {
21971 Object.keys(obj).forEach(function (id) { // object style for plugins
21972 PouchDB$1.prototype[id] = obj[id];
21973 });
21974 }
21975 if (this.__defaults) {
21976 PouchDB$1.__defaults = $inject_Object_assign({}, this.__defaults);
21977 }
21978 return PouchDB$1;
21979};
21980
21981PouchDB$1.defaults = function (defaultOpts) {
21982 let PouchWithDefaults = createClass$1(PouchDB$1, function (name, opts) {
21983 opts = opts || {};
21984
21985 if (name && typeof name === 'object') {
21986 opts = name;
21987 name = opts.name;
21988 delete opts.name;
21989 }
21990
21991 opts = $inject_Object_assign({}, PouchWithDefaults.__defaults, opts);
21992 PouchDB$1.call(this, name, opts);
21993 });
21994
21995 PouchWithDefaults.preferredAdapters = PouchDB$1.preferredAdapters.slice();
21996 Object.keys(PouchDB$1).forEach(function (key) {
21997 if (!(key in PouchWithDefaults)) {
21998 PouchWithDefaults[key] = PouchDB$1[key];
21999 }
22000 });
22001
22002 // make default options transitive
22003 // https://github.com/pouchdb/pouchdb/issues/5922
22004 PouchWithDefaults.__defaults = $inject_Object_assign({}, this.__defaults, defaultOpts);
22005
22006 return PouchWithDefaults;
22007};
22008
22009PouchDB$1.fetch = function (url, opts) {
22010 return f$1(url, opts);
22011};
22012
22013PouchDB$1.prototype.activeTasks = PouchDB$1.activeTasks = new ActiveTasks();
22014
22015// managed automatically by set-version.js
22016var version$1 = "8.0.0";
22017
22018// this would just be "return doc[field]", but fields
22019// can be "deep" due to dot notation
22020function getFieldFromDoc(doc, parsedField) {
22021 var value = doc;
22022 for (var i = 0, len = parsedField.length; i < len; i++) {
22023 var key = parsedField[i];
22024 value = value[key];
22025 if (!value) {
22026 break;
22027 }
22028 }
22029 return value;
22030}
22031
22032function compare$1(left, right) {
22033 return left < right ? -1 : left > right ? 1 : 0;
22034}
22035
22036// Converts a string in dot notation to an array of its components, with backslash escaping
22037function parseField(fieldName) {
22038 // fields may be deep (e.g. "foo.bar.baz"), so parse
22039 var fields = [];
22040 var current = '';
22041 for (var i = 0, len = fieldName.length; i < len; i++) {
22042 var ch = fieldName[i];
22043 if (i > 0 && fieldName[i - 1] === '\\' && (ch === '$' || ch === '.')) {
22044 // escaped delimiter
22045 current = current.substring(0, current.length - 1) + ch;
22046 } else if (ch === '.') {
22047 // When `.` is not escaped (above), it is a field delimiter
22048 fields.push(current);
22049 current = '';
22050 } else { // normal character
22051 current += ch;
22052 }
22053 }
22054 fields.push(current);
22055 return fields;
22056}
22057
22058var combinationFields = ['$or', '$nor', '$not'];
22059function isCombinationalField(field) {
22060 return combinationFields.indexOf(field) > -1;
22061}
22062
22063function getKey(obj) {
22064 return Object.keys(obj)[0];
22065}
22066
22067function getValue(obj) {
22068 return obj[getKey(obj)];
22069}
22070
22071
22072// flatten an array of selectors joined by an $and operator
22073function mergeAndedSelectors(selectors) {
22074
22075 // sort to ensure that e.g. if the user specified
22076 // $and: [{$gt: 'a'}, {$gt: 'b'}], then it's collapsed into
22077 // just {$gt: 'b'}
22078 var res = {};
22079 var first = {$or: true, $nor: true};
22080
22081 selectors.forEach(function (selector) {
22082 Object.keys(selector).forEach(function (field) {
22083 var matcher = selector[field];
22084 if (typeof matcher !== 'object') {
22085 matcher = {$eq: matcher};
22086 }
22087
22088 if (isCombinationalField(field)) {
22089 // or, nor
22090 if (matcher instanceof Array) {
22091 if (first[field]) {
22092 first[field] = false;
22093 res[field] = matcher;
22094 return;
22095 }
22096
22097 var entries = [];
22098 res[field].forEach(function (existing) {
22099 Object.keys(matcher).forEach(function (key) {
22100 var m = matcher[key];
22101 var longest = Math.max(Object.keys(existing).length, Object.keys(m).length);
22102 var merged = mergeAndedSelectors([existing, m]);
22103 if (Object.keys(merged).length <= longest) {
22104 // we have a situation like: (a :{$eq :1} || ...) && (a {$eq: 2} || ...)
22105 // merging would produce a $eq 2 when actually we shouldn't ever match against these merged conditions
22106 // merged should always contain more values to be valid
22107 return;
22108 }
22109 entries.push(merged);
22110 });
22111 });
22112 res[field] = entries;
22113 } else {
22114 // not
22115 res[field] = mergeAndedSelectors([matcher]);
22116 }
22117 } else {
22118 var fieldMatchers = res[field] = res[field] || {};
22119 Object.keys(matcher).forEach(function (operator) {
22120 var value = matcher[operator];
22121
22122 if (operator === '$gt' || operator === '$gte') {
22123 return mergeGtGte(operator, value, fieldMatchers);
22124 } else if (operator === '$lt' || operator === '$lte') {
22125 return mergeLtLte(operator, value, fieldMatchers);
22126 } else if (operator === '$ne') {
22127 return mergeNe(value, fieldMatchers);
22128 } else if (operator === '$eq') {
22129 return mergeEq(value, fieldMatchers);
22130 } else if (operator === "$regex") {
22131 return mergeRegex(value, fieldMatchers);
22132 }
22133 fieldMatchers[operator] = value;
22134 });
22135 }
22136 });
22137 });
22138
22139 return res;
22140}
22141
22142
22143
22144// collapse logically equivalent gt/gte values
22145function mergeGtGte(operator, value, fieldMatchers) {
22146 if (typeof fieldMatchers.$eq !== 'undefined') {
22147 return; // do nothing
22148 }
22149 if (typeof fieldMatchers.$gte !== 'undefined') {
22150 if (operator === '$gte') {
22151 if (value > fieldMatchers.$gte) { // more specificity
22152 fieldMatchers.$gte = value;
22153 }
22154 } else { // operator === '$gt'
22155 if (value >= fieldMatchers.$gte) { // more specificity
22156 delete fieldMatchers.$gte;
22157 fieldMatchers.$gt = value;
22158 }
22159 }
22160 } else if (typeof fieldMatchers.$gt !== 'undefined') {
22161 if (operator === '$gte') {
22162 if (value > fieldMatchers.$gt) { // more specificity
22163 delete fieldMatchers.$gt;
22164 fieldMatchers.$gte = value;
22165 }
22166 } else { // operator === '$gt'
22167 if (value > fieldMatchers.$gt) { // more specificity
22168 fieldMatchers.$gt = value;
22169 }
22170 }
22171 } else {
22172 fieldMatchers[operator] = value;
22173 }
22174}
22175
22176// collapse logically equivalent lt/lte values
22177function mergeLtLte(operator, value, fieldMatchers) {
22178 if (typeof fieldMatchers.$eq !== 'undefined') {
22179 return; // do nothing
22180 }
22181 if (typeof fieldMatchers.$lte !== 'undefined') {
22182 if (operator === '$lte') {
22183 if (value < fieldMatchers.$lte) { // more specificity
22184 fieldMatchers.$lte = value;
22185 }
22186 } else { // operator === '$gt'
22187 if (value <= fieldMatchers.$lte) { // more specificity
22188 delete fieldMatchers.$lte;
22189 fieldMatchers.$lt = value;
22190 }
22191 }
22192 } else if (typeof fieldMatchers.$lt !== 'undefined') {
22193 if (operator === '$lte') {
22194 if (value < fieldMatchers.$lt) { // more specificity
22195 delete fieldMatchers.$lt;
22196 fieldMatchers.$lte = value;
22197 }
22198 } else { // operator === '$gt'
22199 if (value < fieldMatchers.$lt) { // more specificity
22200 fieldMatchers.$lt = value;
22201 }
22202 }
22203 } else {
22204 fieldMatchers[operator] = value;
22205 }
22206}
22207
22208// combine $ne values into one array
22209function mergeNe(value, fieldMatchers) {
22210 if ('$ne' in fieldMatchers) {
22211 // there are many things this could "not" be
22212 fieldMatchers.$ne.push(value);
22213 } else { // doesn't exist yet
22214 fieldMatchers.$ne = [value];
22215 }
22216}
22217
22218// add $eq into the mix
22219function mergeEq(value, fieldMatchers) {
22220 // these all have less specificity than the $eq
22221 // TODO: check for user errors here
22222 delete fieldMatchers.$gt;
22223 delete fieldMatchers.$gte;
22224 delete fieldMatchers.$lt;
22225 delete fieldMatchers.$lte;
22226 delete fieldMatchers.$ne;
22227 fieldMatchers.$eq = value;
22228}
22229
22230// combine $regex values into one array
22231function mergeRegex(value, fieldMatchers) {
22232 if ('$regex' in fieldMatchers) {
22233 // a value could match multiple regexes
22234 fieldMatchers.$regex.push(value);
22235 } else { // doesn't exist yet
22236 fieldMatchers.$regex = [value];
22237 }
22238}
22239
22240//#7458: execute function mergeAndedSelectors on nested $and
22241function mergeAndedSelectorsNested(obj) {
22242 for (var prop in obj) {
22243 if (Array.isArray(obj)) {
22244 for (var i in obj) {
22245 if (obj[i]['$and']) {
22246 obj[i] = mergeAndedSelectors(obj[i]['$and']);
22247 }
22248 }
22249 }
22250 var value = obj[prop];
22251 if (typeof value === 'object') {
22252 mergeAndedSelectorsNested(value); // <- recursive call
22253 }
22254 }
22255 return obj;
22256}
22257
22258//#7458: determine id $and is present in selector (at any level)
22259function isAndInSelector(obj, isAnd) {
22260 for (var prop in obj) {
22261 if (prop === '$and') {
22262 isAnd = true;
22263 }
22264 var value = obj[prop];
22265 if (typeof value === 'object') {
22266 isAnd = isAndInSelector(value, isAnd); // <- recursive call
22267 }
22268 }
22269 return isAnd;
22270}
22271
22272//
22273// normalize the selector
22274//
22275function massageSelector(input) {
22276 var result = clone(input);
22277
22278 //#7458: if $and is present in selector (at any level) merge nested $and
22279 if (isAndInSelector(result, false)) {
22280 result = mergeAndedSelectorsNested(result);
22281 if ('$and' in result) {
22282 result = mergeAndedSelectors(result['$and']);
22283 }
22284 }
22285
22286 ['$or', '$nor'].forEach(function (orOrNor) {
22287 if (orOrNor in result) {
22288 // message each individual selector
22289 // e.g. {foo: 'bar'} becomes {foo: {$eq: 'bar'}}
22290 result[orOrNor].forEach(function (subSelector) {
22291 var fields = Object.keys(subSelector);
22292 for (var i = 0; i < fields.length; i++) {
22293 var field = fields[i];
22294 var matcher = subSelector[field];
22295 if (typeof matcher !== 'object' || matcher === null) {
22296 subSelector[field] = {$eq: matcher};
22297 }
22298 }
22299 });
22300 }
22301 });
22302
22303 if ('$not' in result) {
22304 //This feels a little like forcing, but it will work for now,
22305 //I would like to come back to this and make the merging of selectors a little more generic
22306 result['$not'] = mergeAndedSelectors([result['$not']]);
22307 }
22308
22309 var fields = Object.keys(result);
22310
22311 for (var i = 0; i < fields.length; i++) {
22312 var field = fields[i];
22313 var matcher = result[field];
22314
22315 if (typeof matcher !== 'object' || matcher === null) {
22316 matcher = {$eq: matcher};
22317 }
22318 result[field] = matcher;
22319 }
22320
22321 normalizeArrayOperators(result);
22322
22323 return result;
22324}
22325
22326//
22327// The $ne and $regex values must be placed in an array because these operators can be used multiple times on the same field.
22328// When $and is used, mergeAndedSelectors takes care of putting some of them into arrays, otherwise it's done here.
22329//
22330function normalizeArrayOperators(selector) {
22331 Object.keys(selector).forEach(function (field) {
22332 var matcher = selector[field];
22333
22334 if (Array.isArray(matcher)) {
22335 matcher.forEach(function (matcherItem) {
22336 if (matcherItem && typeof matcherItem === 'object') {
22337 normalizeArrayOperators(matcherItem);
22338 }
22339 });
22340 } else if (field === '$ne') {
22341 selector.$ne = [matcher];
22342 } else if (field === '$regex') {
22343 selector.$regex = [matcher];
22344 } else if (matcher && typeof matcher === 'object') {
22345 normalizeArrayOperators(matcher);
22346 }
22347 });
22348}
22349
22350function collate(a, b) {
22351
22352 if (a === b) {
22353 return 0;
22354 }
22355
22356 a = normalizeKey(a);
22357 b = normalizeKey(b);
22358
22359 var ai = collationIndex(a);
22360 var bi = collationIndex(b);
22361 if ((ai - bi) !== 0) {
22362 return ai - bi;
22363 }
22364 switch (typeof a) {
22365 case 'number':
22366 return a - b;
22367 case 'boolean':
22368 return a < b ? -1 : 1;
22369 case 'string':
22370 return stringCollate(a, b);
22371 }
22372 return Array.isArray(a) ? arrayCollate(a, b) : objectCollate(a, b);
22373}
22374
22375// couch considers null/NaN/Infinity/-Infinity === undefined,
22376// for the purposes of mapreduce indexes. also, dates get stringified.
22377function normalizeKey(key) {
22378 switch (typeof key) {
22379 case 'undefined':
22380 return null;
22381 case 'number':
22382 if (key === Infinity || key === -Infinity || isNaN(key)) {
22383 return null;
22384 }
22385 return key;
22386 case 'object':
22387 var origKey = key;
22388 if (Array.isArray(key)) {
22389 var len = key.length;
22390 key = new Array(len);
22391 for (var i = 0; i < len; i++) {
22392 key[i] = normalizeKey(origKey[i]);
22393 }
22394 /* istanbul ignore next */
22395 } else if (key instanceof Date) {
22396 return key.toJSON();
22397 } else if (key !== null) { // generic object
22398 key = {};
22399 for (var k in origKey) {
22400 if (Object.prototype.hasOwnProperty.call(origKey, k)) {
22401 var val = origKey[k];
22402 if (typeof val !== 'undefined') {
22403 key[k] = normalizeKey(val);
22404 }
22405 }
22406 }
22407 }
22408 }
22409 return key;
22410}
22411
22412function arrayCollate(a, b) {
22413 var len = Math.min(a.length, b.length);
22414 for (var i = 0; i < len; i++) {
22415 var sort = collate(a[i], b[i]);
22416 if (sort !== 0) {
22417 return sort;
22418 }
22419 }
22420 return (a.length === b.length) ? 0 :
22421 (a.length > b.length) ? 1 : -1;
22422}
22423function stringCollate(a, b) {
22424 // See: https://github.com/daleharvey/pouchdb/issues/40
22425 // This is incompatible with the CouchDB implementation, but its the
22426 // best we can do for now
22427 return (a === b) ? 0 : ((a > b) ? 1 : -1);
22428}
22429function objectCollate(a, b) {
22430 var ak = Object.keys(a), bk = Object.keys(b);
22431 var len = Math.min(ak.length, bk.length);
22432 for (var i = 0; i < len; i++) {
22433 // First sort the keys
22434 var sort = collate(ak[i], bk[i]);
22435 if (sort !== 0) {
22436 return sort;
22437 }
22438 // if the keys are equal sort the values
22439 sort = collate(a[ak[i]], b[bk[i]]);
22440 if (sort !== 0) {
22441 return sort;
22442 }
22443
22444 }
22445 return (ak.length === bk.length) ? 0 :
22446 (ak.length > bk.length) ? 1 : -1;
22447}
22448// The collation is defined by erlangs ordered terms
22449// the atoms null, true, false come first, then numbers, strings,
22450// arrays, then objects
22451// null/undefined/NaN/Infinity/-Infinity are all considered null
22452function collationIndex(x) {
22453 var id = ['boolean', 'number', 'string', 'object'];
22454 var idx = id.indexOf(typeof x);
22455 //false if -1 otherwise true, but fast!!!!1
22456 if (~idx) {
22457 if (x === null) {
22458 return 1;
22459 }
22460 if (Array.isArray(x)) {
22461 return 5;
22462 }
22463 return idx < 3 ? (idx + 2) : (idx + 3);
22464 }
22465 /* istanbul ignore next */
22466 if (Array.isArray(x)) {
22467 return 5;
22468 }
22469}
22470
22471// create a comparator based on the sort object
22472function createFieldSorter(sort) {
22473
22474 function getFieldValuesAsArray(doc) {
22475 return sort.map(function (sorting) {
22476 var fieldName = getKey(sorting);
22477 var parsedField = parseField(fieldName);
22478 var docFieldValue = getFieldFromDoc(doc, parsedField);
22479 return docFieldValue;
22480 });
22481 }
22482
22483 return function (aRow, bRow) {
22484 var aFieldValues = getFieldValuesAsArray(aRow.doc);
22485 var bFieldValues = getFieldValuesAsArray(bRow.doc);
22486 var collation = collate(aFieldValues, bFieldValues);
22487 if (collation !== 0) {
22488 return collation;
22489 }
22490 // this is what mango seems to do
22491 return compare$1(aRow.doc._id, bRow.doc._id);
22492 };
22493}
22494
22495function filterInMemoryFields(rows, requestDef, inMemoryFields) {
22496 rows = rows.filter(function (row) {
22497 return rowFilter(row.doc, requestDef.selector, inMemoryFields);
22498 });
22499
22500 if (requestDef.sort) {
22501 // in-memory sort
22502 var fieldSorter = createFieldSorter(requestDef.sort);
22503 rows = rows.sort(fieldSorter);
22504 if (typeof requestDef.sort[0] !== 'string' &&
22505 getValue(requestDef.sort[0]) === 'desc') {
22506 rows = rows.reverse();
22507 }
22508 }
22509
22510 if ('limit' in requestDef || 'skip' in requestDef) {
22511 // have to do the limit in-memory
22512 var skip = requestDef.skip || 0;
22513 var limit = ('limit' in requestDef ? requestDef.limit : rows.length) + skip;
22514 rows = rows.slice(skip, limit);
22515 }
22516 return rows;
22517}
22518
22519function rowFilter(doc, selector, inMemoryFields) {
22520 return inMemoryFields.every(function (field) {
22521 var matcher = selector[field];
22522 var parsedField = parseField(field);
22523 var docFieldValue = getFieldFromDoc(doc, parsedField);
22524 if (isCombinationalField(field)) {
22525 return matchCominationalSelector(field, matcher, doc);
22526 }
22527
22528 return matchSelector(matcher, doc, parsedField, docFieldValue);
22529 });
22530}
22531
22532function matchSelector(matcher, doc, parsedField, docFieldValue) {
22533 if (!matcher) {
22534 // no filtering necessary; this field is just needed for sorting
22535 return true;
22536 }
22537
22538 // is matcher an object, if so continue recursion
22539 if (typeof matcher === 'object') {
22540 return Object.keys(matcher).every(function (maybeUserOperator) {
22541 var userValue = matcher[ maybeUserOperator ];
22542 // explicit operator
22543 if (maybeUserOperator.indexOf("$") === 0) {
22544 return match(maybeUserOperator, doc, userValue, parsedField, docFieldValue);
22545 } else {
22546 var subParsedField = parseField(maybeUserOperator);
22547
22548 if (
22549 docFieldValue === undefined &&
22550 typeof userValue !== "object" &&
22551 subParsedField.length > 0
22552 ) {
22553 // the field does not exist, return or getFieldFromDoc will throw
22554 return false;
22555 }
22556
22557 var subDocFieldValue = getFieldFromDoc(docFieldValue, subParsedField);
22558
22559 if (typeof userValue === "object") {
22560 // field value is an object that might contain more operators
22561 return matchSelector(userValue, doc, parsedField, subDocFieldValue);
22562 }
22563
22564 // implicit operator
22565 return match("$eq", doc, userValue, subParsedField, subDocFieldValue);
22566 }
22567 });
22568 }
22569
22570 // no more depth, No need to recurse further
22571 return matcher === docFieldValue;
22572}
22573
22574function matchCominationalSelector(field, matcher, doc) {
22575
22576 if (field === '$or') {
22577 return matcher.some(function (orMatchers) {
22578 return rowFilter(doc, orMatchers, Object.keys(orMatchers));
22579 });
22580 }
22581
22582 if (field === '$not') {
22583 return !rowFilter(doc, matcher, Object.keys(matcher));
22584 }
22585
22586 //`$nor`
22587 return !matcher.find(function (orMatchers) {
22588 return rowFilter(doc, orMatchers, Object.keys(orMatchers));
22589 });
22590
22591}
22592
22593function match(userOperator, doc, userValue, parsedField, docFieldValue) {
22594 if (!matchers[userOperator]) {
22595 /* istanbul ignore next */
22596 throw new Error('unknown operator "' + userOperator +
22597 '" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, ' +
22598 '$nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all');
22599 }
22600 return matchers[userOperator](doc, userValue, parsedField, docFieldValue);
22601}
22602
22603function fieldExists(docFieldValue) {
22604 return typeof docFieldValue !== 'undefined' && docFieldValue !== null;
22605}
22606
22607function fieldIsNotUndefined(docFieldValue) {
22608 return typeof docFieldValue !== 'undefined';
22609}
22610
22611function modField(docFieldValue, userValue) {
22612 if (typeof docFieldValue !== "number" ||
22613 parseInt(docFieldValue, 10) !== docFieldValue) {
22614 return false;
22615 }
22616
22617 var divisor = userValue[0];
22618 var mod = userValue[1];
22619
22620 return docFieldValue % divisor === mod;
22621}
22622
22623function arrayContainsValue(docFieldValue, userValue) {
22624 return userValue.some(function (val) {
22625 if (docFieldValue instanceof Array) {
22626 return docFieldValue.some(function (docFieldValueItem) {
22627 return collate(val, docFieldValueItem) === 0;
22628 });
22629 }
22630
22631 return collate(val, docFieldValue) === 0;
22632 });
22633}
22634
22635function arrayContainsAllValues(docFieldValue, userValue) {
22636 return userValue.every(function (val) {
22637 return docFieldValue.some(function (docFieldValueItem) {
22638 return collate(val, docFieldValueItem) === 0;
22639 });
22640 });
22641}
22642
22643function arraySize(docFieldValue, userValue) {
22644 return docFieldValue.length === userValue;
22645}
22646
22647function regexMatch(docFieldValue, userValue) {
22648 var re = new RegExp(userValue);
22649
22650 return re.test(docFieldValue);
22651}
22652
22653function typeMatch(docFieldValue, userValue) {
22654
22655 switch (userValue) {
22656 case 'null':
22657 return docFieldValue === null;
22658 case 'boolean':
22659 return typeof (docFieldValue) === 'boolean';
22660 case 'number':
22661 return typeof (docFieldValue) === 'number';
22662 case 'string':
22663 return typeof (docFieldValue) === 'string';
22664 case 'array':
22665 return docFieldValue instanceof Array;
22666 case 'object':
22667 return ({}).toString.call(docFieldValue) === '[object Object]';
22668 }
22669}
22670
22671var matchers = {
22672
22673 '$elemMatch': function (doc, userValue, parsedField, docFieldValue) {
22674 if (!Array.isArray(docFieldValue)) {
22675 return false;
22676 }
22677
22678 if (docFieldValue.length === 0) {
22679 return false;
22680 }
22681
22682 if (typeof docFieldValue[0] === 'object' && docFieldValue[0] !== null) {
22683 return docFieldValue.some(function (val) {
22684 return rowFilter(val, userValue, Object.keys(userValue));
22685 });
22686 }
22687
22688 return docFieldValue.some(function (val) {
22689 return matchSelector(userValue, doc, parsedField, val);
22690 });
22691 },
22692
22693 '$allMatch': function (doc, userValue, parsedField, docFieldValue) {
22694 if (!Array.isArray(docFieldValue)) {
22695 return false;
22696 }
22697
22698 /* istanbul ignore next */
22699 if (docFieldValue.length === 0) {
22700 return false;
22701 }
22702
22703 if (typeof docFieldValue[0] === 'object' && docFieldValue[0] !== null) {
22704 return docFieldValue.every(function (val) {
22705 return rowFilter(val, userValue, Object.keys(userValue));
22706 });
22707 }
22708
22709 return docFieldValue.every(function (val) {
22710 return matchSelector(userValue, doc, parsedField, val);
22711 });
22712 },
22713
22714 '$eq': function (doc, userValue, parsedField, docFieldValue) {
22715 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) === 0;
22716 },
22717
22718 '$gte': function (doc, userValue, parsedField, docFieldValue) {
22719 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) >= 0;
22720 },
22721
22722 '$gt': function (doc, userValue, parsedField, docFieldValue) {
22723 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) > 0;
22724 },
22725
22726 '$lte': function (doc, userValue, parsedField, docFieldValue) {
22727 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) <= 0;
22728 },
22729
22730 '$lt': function (doc, userValue, parsedField, docFieldValue) {
22731 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) < 0;
22732 },
22733
22734 '$exists': function (doc, userValue, parsedField, docFieldValue) {
22735 //a field that is null is still considered to exist
22736 if (userValue) {
22737 return fieldIsNotUndefined(docFieldValue);
22738 }
22739
22740 return !fieldIsNotUndefined(docFieldValue);
22741 },
22742
22743 '$mod': function (doc, userValue, parsedField, docFieldValue) {
22744 return fieldExists(docFieldValue) && modField(docFieldValue, userValue);
22745 },
22746
22747 '$ne': function (doc, userValue, parsedField, docFieldValue) {
22748 return userValue.every(function (neValue) {
22749 return collate(docFieldValue, neValue) !== 0;
22750 });
22751 },
22752 '$in': function (doc, userValue, parsedField, docFieldValue) {
22753 return fieldExists(docFieldValue) && arrayContainsValue(docFieldValue, userValue);
22754 },
22755
22756 '$nin': function (doc, userValue, parsedField, docFieldValue) {
22757 return fieldExists(docFieldValue) && !arrayContainsValue(docFieldValue, userValue);
22758 },
22759
22760 '$size': function (doc, userValue, parsedField, docFieldValue) {
22761 return fieldExists(docFieldValue) &&
22762 Array.isArray(docFieldValue) &&
22763 arraySize(docFieldValue, userValue);
22764 },
22765
22766 '$all': function (doc, userValue, parsedField, docFieldValue) {
22767 return Array.isArray(docFieldValue) && arrayContainsAllValues(docFieldValue, userValue);
22768 },
22769
22770 '$regex': function (doc, userValue, parsedField, docFieldValue) {
22771 return fieldExists(docFieldValue) &&
22772 typeof docFieldValue == "string" &&
22773 userValue.every(function (regexValue) {
22774 return regexMatch(docFieldValue, regexValue);
22775 });
22776 },
22777
22778 '$type': function (doc, userValue, parsedField, docFieldValue) {
22779 return typeMatch(docFieldValue, userValue);
22780 }
22781};
22782
22783// return true if the given doc matches the supplied selector
22784function matchesSelector(doc, selector) {
22785 /* istanbul ignore if */
22786 if (typeof selector !== 'object') {
22787 // match the CouchDB error message
22788 throw new Error('Selector error: expected a JSON object');
22789 }
22790
22791 selector = massageSelector(selector);
22792 var row = {
22793 'doc': doc
22794 };
22795
22796 var rowsMatched = filterInMemoryFields([row], { 'selector': selector }, Object.keys(selector));
22797 return rowsMatched && rowsMatched.length === 1;
22798}
22799
22800function evalFilter(input) {
22801 return scopeEval('"use strict";\nreturn ' + input + ';', {});
22802}
22803
22804function evalView(input) {
22805 var code = [
22806 'return function(doc) {',
22807 ' "use strict";',
22808 ' var emitted = false;',
22809 ' var emit = function (a, b) {',
22810 ' emitted = true;',
22811 ' };',
22812 ' var view = ' + input + ';',
22813 ' view(doc);',
22814 ' if (emitted) {',
22815 ' return true;',
22816 ' }',
22817 '};'
22818 ].join('\n');
22819
22820 return scopeEval(code, {});
22821}
22822
22823function validate(opts, callback) {
22824 if (opts.selector) {
22825 if (opts.filter && opts.filter !== '_selector') {
22826 var filterName = typeof opts.filter === 'string' ?
22827 opts.filter : 'function';
22828 return callback(new Error('selector invalid for filter "' + filterName + '"'));
22829 }
22830 }
22831 callback();
22832}
22833
22834function normalize(opts) {
22835 if (opts.view && !opts.filter) {
22836 opts.filter = '_view';
22837 }
22838
22839 if (opts.selector && !opts.filter) {
22840 opts.filter = '_selector';
22841 }
22842
22843 if (opts.filter && typeof opts.filter === 'string') {
22844 if (opts.filter === '_view') {
22845 opts.view = normalizeDesignDocFunctionName(opts.view);
22846 } else {
22847 opts.filter = normalizeDesignDocFunctionName(opts.filter);
22848 }
22849 }
22850}
22851
22852function shouldFilter(changesHandler, opts) {
22853 return opts.filter && typeof opts.filter === 'string' &&
22854 !opts.doc_ids && !isRemote(changesHandler.db);
22855}
22856
22857function filter(changesHandler, opts) {
22858 var callback = opts.complete;
22859 if (opts.filter === '_view') {
22860 if (!opts.view || typeof opts.view !== 'string') {
22861 var err = createError(BAD_REQUEST,
22862 '`view` filter parameter not found or invalid.');
22863 return callback(err);
22864 }
22865 // fetch a view from a design doc, make it behave like a filter
22866 var viewName = parseDesignDocFunctionName(opts.view);
22867 changesHandler.db.get('_design/' + viewName[0], function (err, ddoc) {
22868 /* istanbul ignore if */
22869 if (changesHandler.isCancelled) {
22870 return callback(null, {status: 'cancelled'});
22871 }
22872 /* istanbul ignore next */
22873 if (err) {
22874 return callback(generateErrorFromResponse(err));
22875 }
22876 var mapFun = ddoc && ddoc.views && ddoc.views[viewName[1]] &&
22877 ddoc.views[viewName[1]].map;
22878 if (!mapFun) {
22879 return callback(createError(MISSING_DOC,
22880 (ddoc.views ? 'missing json key: ' + viewName[1] :
22881 'missing json key: views')));
22882 }
22883 opts.filter = evalView(mapFun);
22884 changesHandler.doChanges(opts);
22885 });
22886 } else if (opts.selector) {
22887 opts.filter = function (doc) {
22888 return matchesSelector(doc, opts.selector);
22889 };
22890 changesHandler.doChanges(opts);
22891 } else {
22892 // fetch a filter from a design doc
22893 var filterName = parseDesignDocFunctionName(opts.filter);
22894 changesHandler.db.get('_design/' + filterName[0], function (err, ddoc) {
22895 /* istanbul ignore if */
22896 if (changesHandler.isCancelled) {
22897 return callback(null, {status: 'cancelled'});
22898 }
22899 /* istanbul ignore next */
22900 if (err) {
22901 return callback(generateErrorFromResponse(err));
22902 }
22903 var filterFun = ddoc && ddoc.filters && ddoc.filters[filterName[1]];
22904 if (!filterFun) {
22905 return callback(createError(MISSING_DOC,
22906 ((ddoc && ddoc.filters) ? 'missing json key: ' + filterName[1]
22907 : 'missing json key: filters')));
22908 }
22909 opts.filter = evalFilter(filterFun);
22910 changesHandler.doChanges(opts);
22911 });
22912 }
22913}
22914
22915function applyChangesFilterPlugin(PouchDB) {
22916 PouchDB._changesFilterPlugin = {
22917 validate: validate,
22918 normalize: normalize,
22919 shouldFilter: shouldFilter,
22920 filter: filter
22921 };
22922}
22923
22924// TODO: remove from pouchdb-core (breaking)
22925PouchDB$1.plugin(applyChangesFilterPlugin);
22926
22927PouchDB$1.version = version$1;
22928
22929function allDocsKeysQuery(api, opts) {
22930 var keys = opts.keys;
22931 var finalResults = {
22932 offset: opts.skip
22933 };
22934 return Promise.all(keys.map(function (key) {
22935 var subOpts = $inject_Object_assign({key: key, deleted: 'ok'}, opts);
22936 ['limit', 'skip', 'keys'].forEach(function (optKey) {
22937 delete subOpts[optKey];
22938 });
22939 return new Promise(function (resolve, reject) {
22940 api._allDocs(subOpts, function (err, res) {
22941 /* istanbul ignore if */
22942 if (err) {
22943 return reject(err);
22944 }
22945 /* istanbul ignore if */
22946 if (opts.update_seq && res.update_seq !== undefined) {
22947 finalResults.update_seq = res.update_seq;
22948 }
22949 finalResults.total_rows = res.total_rows;
22950 resolve(res.rows[0] || {key: key, error: 'not_found'});
22951 });
22952 });
22953 })).then(function (results) {
22954 finalResults.rows = results;
22955 return finalResults;
22956 });
22957}
22958
22959function toObject(array) {
22960 return array.reduce(function (obj, item) {
22961 obj[item] = true;
22962 return obj;
22963 }, {});
22964}
22965// List of top level reserved words for doc
22966var reservedWords = toObject([
22967 '_id',
22968 '_rev',
22969 '_access',
22970 '_attachments',
22971 '_deleted',
22972 '_revisions',
22973 '_revs_info',
22974 '_conflicts',
22975 '_deleted_conflicts',
22976 '_local_seq',
22977 '_rev_tree',
22978 // replication documents
22979 '_replication_id',
22980 '_replication_state',
22981 '_replication_state_time',
22982 '_replication_state_reason',
22983 '_replication_stats',
22984 // Specific to Couchbase Sync Gateway
22985 '_removed'
22986]);
22987
22988// List of reserved words that should end up in the document
22989var dataWords = toObject([
22990 '_access',
22991 '_attachments',
22992 // replication documents
22993 '_replication_id',
22994 '_replication_state',
22995 '_replication_state_time',
22996 '_replication_state_reason',
22997 '_replication_stats'
22998]);
22999
23000function parseRevisionInfo(rev) {
23001 if (!/^\d+-/.test(rev)) {
23002 return createError(INVALID_REV);
23003 }
23004 var idx = rev.indexOf('-');
23005 var left = rev.substring(0, idx);
23006 var right = rev.substring(idx + 1);
23007 return {
23008 prefix: parseInt(left, 10),
23009 id: right
23010 };
23011}
23012
23013function makeRevTreeFromRevisions(revisions, opts) {
23014 var pos = revisions.start - revisions.ids.length + 1;
23015
23016 var revisionIds = revisions.ids;
23017 var ids = [revisionIds[0], opts, []];
23018
23019 for (var i = 1, len = revisionIds.length; i < len; i++) {
23020 ids = [revisionIds[i], {status: 'missing'}, [ids]];
23021 }
23022
23023 return [{
23024 pos: pos,
23025 ids: ids
23026 }];
23027}
23028
23029// Preprocess documents, parse their revisions, assign an id and a
23030// revision for new writes that are missing them, etc
23031function parseDoc(doc, newEdits, dbOpts) {
23032 if (!dbOpts) {
23033 dbOpts = {
23034 deterministic_revs: true
23035 };
23036 }
23037
23038 var nRevNum;
23039 var newRevId;
23040 var revInfo;
23041 var opts = {status: 'available'};
23042 if (doc._deleted) {
23043 opts.deleted = true;
23044 }
23045
23046 if (newEdits) {
23047 if (!doc._id) {
23048 doc._id = uuid$1();
23049 }
23050 newRevId = rev$$1(doc, dbOpts.deterministic_revs);
23051 if (doc._rev) {
23052 revInfo = parseRevisionInfo(doc._rev);
23053 if (revInfo.error) {
23054 return revInfo;
23055 }
23056 doc._rev_tree = [{
23057 pos: revInfo.prefix,
23058 ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]]
23059 }];
23060 nRevNum = revInfo.prefix + 1;
23061 } else {
23062 doc._rev_tree = [{
23063 pos: 1,
23064 ids : [newRevId, opts, []]
23065 }];
23066 nRevNum = 1;
23067 }
23068 } else {
23069 if (doc._revisions) {
23070 doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts);
23071 nRevNum = doc._revisions.start;
23072 newRevId = doc._revisions.ids[0];
23073 }
23074 if (!doc._rev_tree) {
23075 revInfo = parseRevisionInfo(doc._rev);
23076 if (revInfo.error) {
23077 return revInfo;
23078 }
23079 nRevNum = revInfo.prefix;
23080 newRevId = revInfo.id;
23081 doc._rev_tree = [{
23082 pos: nRevNum,
23083 ids: [newRevId, opts, []]
23084 }];
23085 }
23086 }
23087
23088 invalidIdError(doc._id);
23089
23090 doc._rev = nRevNum + '-' + newRevId;
23091
23092 var result = {metadata : {}, data : {}};
23093 for (var key in doc) {
23094 /* istanbul ignore else */
23095 if (Object.prototype.hasOwnProperty.call(doc, key)) {
23096 var specialKey = key[0] === '_';
23097 if (specialKey && !reservedWords[key]) {
23098 var error = createError(DOC_VALIDATION, key);
23099 error.message = DOC_VALIDATION.message + ': ' + key;
23100 throw error;
23101 } else if (specialKey && !dataWords[key]) {
23102 result.metadata[key.slice(1)] = doc[key];
23103 } else {
23104 result.data[key] = doc[key];
23105 }
23106 }
23107 }
23108 return result;
23109}
23110
23111function updateDoc(revLimit, prev, docInfo, results,
23112 i, cb, writeDoc, newEdits) {
23113
23114 if (revExists(prev.rev_tree, docInfo.metadata.rev) && !newEdits) {
23115 results[i] = docInfo;
23116 return cb();
23117 }
23118
23119 // sometimes this is pre-calculated. historically not always
23120 var previousWinningRev = prev.winningRev || winningRev(prev);
23121 var previouslyDeleted = 'deleted' in prev ? prev.deleted :
23122 isDeleted(prev, previousWinningRev);
23123 var deleted = 'deleted' in docInfo.metadata ? docInfo.metadata.deleted :
23124 isDeleted(docInfo.metadata);
23125 var isRoot = /^1-/.test(docInfo.metadata.rev);
23126
23127 if (previouslyDeleted && !deleted && newEdits && isRoot) {
23128 var newDoc = docInfo.data;
23129 newDoc._rev = previousWinningRev;
23130 newDoc._id = docInfo.metadata.id;
23131 docInfo = parseDoc(newDoc, newEdits);
23132 }
23133
23134 var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit);
23135
23136 var inConflict = newEdits && ((
23137 (previouslyDeleted && deleted && merged.conflicts !== 'new_leaf') ||
23138 (!previouslyDeleted && merged.conflicts !== 'new_leaf') ||
23139 (previouslyDeleted && !deleted && merged.conflicts === 'new_branch')));
23140
23141 if (inConflict) {
23142 var err = createError(REV_CONFLICT);
23143 results[i] = err;
23144 return cb();
23145 }
23146
23147 var newRev = docInfo.metadata.rev;
23148 docInfo.metadata.rev_tree = merged.tree;
23149 docInfo.stemmedRevs = merged.stemmedRevs || [];
23150 /* istanbul ignore else */
23151 if (prev.rev_map) {
23152 docInfo.metadata.rev_map = prev.rev_map; // used only by leveldb
23153 }
23154
23155 // recalculate
23156 var winningRev$$1 = winningRev(docInfo.metadata);
23157 var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev$$1);
23158
23159 // calculate the total number of documents that were added/removed,
23160 // from the perspective of total_rows/doc_count
23161 var delta = (previouslyDeleted === winningRevIsDeleted) ? 0 :
23162 previouslyDeleted < winningRevIsDeleted ? -1 : 1;
23163
23164 var newRevIsDeleted;
23165 if (newRev === winningRev$$1) {
23166 // if the new rev is the same as the winning rev, we can reuse that value
23167 newRevIsDeleted = winningRevIsDeleted;
23168 } else {
23169 // if they're not the same, then we need to recalculate
23170 newRevIsDeleted = isDeleted(docInfo.metadata, newRev);
23171 }
23172
23173 writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
23174 true, delta, i, cb);
23175}
23176
23177function rootIsMissing(docInfo) {
23178 return docInfo.metadata.rev_tree[0].ids[1].status === 'missing';
23179}
23180
23181function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results,
23182 writeDoc, opts, overallCallback) {
23183
23184 // Default to 1000 locally
23185 revLimit = revLimit || 1000;
23186
23187 function insertDoc(docInfo, resultsIdx, callback) {
23188 // Cant insert new deleted documents
23189 var winningRev$$1 = winningRev(docInfo.metadata);
23190 var deleted = isDeleted(docInfo.metadata, winningRev$$1);
23191 if ('was_delete' in opts && deleted) {
23192 results[resultsIdx] = createError(MISSING_DOC, 'deleted');
23193 return callback();
23194 }
23195
23196 // 4712 - detect whether a new document was inserted with a _rev
23197 var inConflict = newEdits && rootIsMissing(docInfo);
23198
23199 if (inConflict) {
23200 var err = createError(REV_CONFLICT);
23201 results[resultsIdx] = err;
23202 return callback();
23203 }
23204
23205 var delta = deleted ? 0 : 1;
23206
23207 writeDoc(docInfo, winningRev$$1, deleted, deleted, false,
23208 delta, resultsIdx, callback);
23209 }
23210
23211 var newEdits = opts.new_edits;
23212 var idsToDocs = new ExportedMap();
23213
23214 var docsDone = 0;
23215 var docsToDo = docInfos.length;
23216
23217 function checkAllDocsDone() {
23218 if (++docsDone === docsToDo && overallCallback) {
23219 overallCallback();
23220 }
23221 }
23222
23223 docInfos.forEach(function (currentDoc, resultsIdx) {
23224
23225 if (currentDoc._id && isLocalId(currentDoc._id)) {
23226 var fun = currentDoc._deleted ? '_removeLocal' : '_putLocal';
23227 api[fun](currentDoc, {ctx: tx}, function (err, res) {
23228 results[resultsIdx] = err || res;
23229 checkAllDocsDone();
23230 });
23231 return;
23232 }
23233
23234 var id = currentDoc.metadata.id;
23235 if (idsToDocs.has(id)) {
23236 docsToDo--; // duplicate
23237 idsToDocs.get(id).push([currentDoc, resultsIdx]);
23238 } else {
23239 idsToDocs.set(id, [[currentDoc, resultsIdx]]);
23240 }
23241 });
23242
23243 // in the case of new_edits, the user can provide multiple docs
23244 // with the same id. these need to be processed sequentially
23245 idsToDocs.forEach(function (docs, id) {
23246 var numDone = 0;
23247
23248 function docWritten() {
23249 if (++numDone < docs.length) {
23250 nextDoc();
23251 } else {
23252 checkAllDocsDone();
23253 }
23254 }
23255 function nextDoc() {
23256 var value = docs[numDone];
23257 var currentDoc = value[0];
23258 var resultsIdx = value[1];
23259
23260 if (fetchedDocs.has(id)) {
23261 updateDoc(revLimit, fetchedDocs.get(id), currentDoc, results,
23262 resultsIdx, docWritten, writeDoc, newEdits);
23263 } else {
23264 // Ensure stemming applies to new writes as well
23265 var merged = merge([], currentDoc.metadata.rev_tree[0], revLimit);
23266 currentDoc.metadata.rev_tree = merged.tree;
23267 currentDoc.stemmedRevs = merged.stemmedRevs || [];
23268 insertDoc(currentDoc, resultsIdx, docWritten);
23269 }
23270 }
23271 nextDoc();
23272 });
23273}
23274
23275function safeJsonParse(str) {
23276 // This try/catch guards against stack overflow errors.
23277 // JSON.parse() is faster than vuvuzela.parse() but vuvuzela
23278 // cannot overflow.
23279 try {
23280 return JSON.parse(str);
23281 } catch (e) {
23282 /* istanbul ignore next */
23283 return vuvuzela.parse(str);
23284 }
23285}
23286
23287function safeJsonStringify(json) {
23288 try {
23289 return JSON.stringify(json);
23290 } catch (e) {
23291 /* istanbul ignore next */
23292 return vuvuzela.stringify(json);
23293 }
23294}
23295
23296function readAsBlobOrBuffer(storedObject, type) {
23297 // In the browser, we've stored a binary string. This now comes back as a
23298 // browserified Node-style Buffer (implemented as a typed array),
23299 // but we want a Blob instead.
23300 var byteArray = new Uint8Array(storedObject);
23301 return createBlob([byteArray], {type: type});
23302}
23303
23304// In the browser, we store a binary string
23305function prepareAttachmentForStorage(attData, cb) {
23306 readAsBinaryString(attData, cb);
23307}
23308
23309function createEmptyBlobOrBuffer(type) {
23310 return createBlob([''], {type: type});
23311}
23312
23313function getCacheFor(transaction, store) {
23314 var prefix = store.prefix()[0];
23315 var cache = transaction._cache;
23316 var subCache = cache.get(prefix);
23317 if (!subCache) {
23318 subCache = new ExportedMap();
23319 cache.set(prefix, subCache);
23320 }
23321 return subCache;
23322}
23323
23324class LevelTransaction {
23325 constructor() {
23326 this._batch = [];
23327 this._cache = new ExportedMap();
23328 }
23329
23330 get(store, key, callback) {
23331 var cache = getCacheFor(this, store);
23332 var exists = cache.get(key);
23333 if (exists) {
23334 return immediate(function () {
23335 callback(null, exists);
23336 });
23337 } else if (exists === null) { // deleted marker
23338 /* istanbul ignore next */
23339 return immediate(function () {
23340 callback({name: 'NotFoundError'});
23341 });
23342 }
23343 store.get(key, function (err, res) {
23344 if (err) {
23345 /* istanbul ignore else */
23346 if (err.name === 'NotFoundError') {
23347 cache.set(key, null);
23348 }
23349 return callback(err);
23350 }
23351 cache.set(key, res);
23352 callback(null, res);
23353 });
23354 }
23355
23356 batch(batch) {
23357 for (var i = 0, len = batch.length; i < len; i++) {
23358 var operation = batch[i];
23359
23360 var cache = getCacheFor(this, operation.prefix);
23361
23362 if (operation.type === 'put') {
23363 cache.set(operation.key, operation.value);
23364 } else {
23365 cache.set(operation.key, null);
23366 }
23367 }
23368 this._batch = this._batch.concat(batch);
23369 }
23370
23371 execute(db, callback) {
23372 var keys = new ExportedSet();
23373 var uniqBatches = [];
23374
23375 // remove duplicates; last one wins
23376 for (var i = this._batch.length - 1; i >= 0; i--) {
23377 var operation = this._batch[i];
23378 var lookupKey = operation.prefix.prefix()[0] + '\xff' + operation.key;
23379 if (keys.has(lookupKey)) {
23380 continue;
23381 }
23382 keys.add(lookupKey);
23383 uniqBatches.push(operation);
23384 }
23385
23386 db.batch(uniqBatches, callback);
23387 }
23388}
23389
23390var DOC_STORE = 'document-store';
23391var BY_SEQ_STORE = 'by-sequence';
23392var ATTACHMENT_STORE = 'attach-store';
23393var BINARY_STORE = 'attach-binary-store';
23394var LOCAL_STORE = 'local-store';
23395var META_STORE = 'meta-store';
23396
23397// leveldb barks if we try to open a db multiple times
23398// so we cache opened connections here for initstore()
23399var dbStores = new ExportedMap();
23400
23401// store the value of update_seq in the by-sequence store the key name will
23402// never conflict, since the keys in the by-sequence store are integers
23403var UPDATE_SEQ_KEY = '_local_last_update_seq';
23404var DOC_COUNT_KEY = '_local_doc_count';
23405var UUID_KEY = '_local_uuid';
23406
23407var MD5_PREFIX = 'md5-';
23408
23409var safeJsonEncoding = {
23410 encode: safeJsonStringify,
23411 decode: safeJsonParse,
23412 buffer: false,
23413 type: 'cheap-json'
23414};
23415
23416var levelChanges = new Changes();
23417
23418// winningRev and deleted are performance-killers, but
23419// in newer versions of PouchDB, they are cached on the metadata
23420function getWinningRev(metadata) {
23421 return 'winningRev' in metadata ?
23422 metadata.winningRev : winningRev(metadata);
23423}
23424
23425function getIsDeleted(metadata, winningRev$$1) {
23426 return 'deleted' in metadata ?
23427 metadata.deleted : isDeleted(metadata, winningRev$$1);
23428}
23429
23430function fetchAttachment(att, stores, opts) {
23431 var type = att.content_type;
23432 return new Promise(function (resolve, reject) {
23433 stores.binaryStore.get(att.digest, function (err, buffer) {
23434 var data;
23435 if (err) {
23436 /* istanbul ignore if */
23437 if (err.name !== 'NotFoundError') {
23438 return reject(err);
23439 } else {
23440 // empty
23441 if (!opts.binary) {
23442 data = '';
23443 } else {
23444 data = binStringToBluffer('', type);
23445 }
23446 }
23447 } else { // non-empty
23448 if (opts.binary) {
23449 data = readAsBlobOrBuffer(buffer, type);
23450 } else {
23451 data = buffer.toString('base64');
23452 }
23453 }
23454 delete att.stub;
23455 delete att.length;
23456 att.data = data;
23457 resolve();
23458 });
23459 });
23460}
23461
23462function fetchAttachments(results, stores, opts) {
23463 var atts = [];
23464 results.forEach(function (row) {
23465 if (!(row.doc && row.doc._attachments)) {
23466 return;
23467 }
23468 var attNames = Object.keys(row.doc._attachments);
23469 attNames.forEach(function (attName) {
23470 var att = row.doc._attachments[attName];
23471 if (!('data' in att)) {
23472 atts.push(att);
23473 }
23474 });
23475 });
23476
23477 return Promise.all(atts.map(function (att) {
23478 return fetchAttachment(att, stores, opts);
23479 }));
23480}
23481
23482function LevelPouch(opts, callback) {
23483 opts = clone(opts);
23484 var api = this;
23485 var instanceId;
23486 var stores = {};
23487 var revLimit = opts.revs_limit;
23488 var db;
23489 var name = opts.name;
23490 // TODO: this is undocumented and unused probably
23491 /* istanbul ignore else */
23492 if (typeof opts.createIfMissing === 'undefined') {
23493 opts.createIfMissing = true;
23494 }
23495
23496 var leveldown = opts.db;
23497
23498 var dbStore;
23499 var leveldownName = functionName(leveldown);
23500 if (dbStores.has(leveldownName)) {
23501 dbStore = dbStores.get(leveldownName);
23502 } else {
23503 dbStore = new ExportedMap();
23504 dbStores.set(leveldownName, dbStore);
23505 }
23506 if (dbStore.has(name)) {
23507 db = dbStore.get(name);
23508 afterDBCreated();
23509 } else {
23510 dbStore.set(name, sublevelPouch(levelup(leveldown(name), opts, function (err) {
23511 /* istanbul ignore if */
23512 if (err) {
23513 dbStore["delete"](name);
23514 return callback(err);
23515 }
23516 db = dbStore.get(name);
23517 db._docCount = -1;
23518 db._queue = new Deque();
23519 /* istanbul ignore else */
23520 if (typeof opts.migrate === 'object') { // migration for leveldown
23521 opts.migrate.doMigrationOne(name, db, afterDBCreated);
23522 } else {
23523 afterDBCreated();
23524 }
23525 })));
23526 }
23527
23528 function afterDBCreated() {
23529 stores.docStore = db.sublevel(DOC_STORE, {valueEncoding: safeJsonEncoding});
23530 stores.bySeqStore = db.sublevel(BY_SEQ_STORE, {valueEncoding: 'json'});
23531 stores.attachmentStore =
23532 db.sublevel(ATTACHMENT_STORE, {valueEncoding: 'json'});
23533 stores.binaryStore = db.sublevel(BINARY_STORE, {valueEncoding: 'binary'});
23534 stores.localStore = db.sublevel(LOCAL_STORE, {valueEncoding: 'json'});
23535 stores.metaStore = db.sublevel(META_STORE, {valueEncoding: 'json'});
23536 /* istanbul ignore else */
23537 if (typeof opts.migrate === 'object') { // migration for leveldown
23538 opts.migrate.doMigrationTwo(db, stores, afterLastMigration);
23539 } else {
23540 afterLastMigration();
23541 }
23542 }
23543
23544 function afterLastMigration() {
23545 stores.metaStore.get(UPDATE_SEQ_KEY, function (err, value) {
23546 if (typeof db._updateSeq === 'undefined') {
23547 db._updateSeq = value || 0;
23548 }
23549 stores.metaStore.get(DOC_COUNT_KEY, function (err, value) {
23550 db._docCount = !err ? value : 0;
23551 stores.metaStore.get(UUID_KEY, function (err, value) {
23552 instanceId = !err ? value : uuid$1();
23553 stores.metaStore.put(UUID_KEY, instanceId, function () {
23554 immediate(function () {
23555 callback(null, api);
23556 });
23557 });
23558 });
23559 });
23560 });
23561 }
23562
23563 function countDocs(callback) {
23564 /* istanbul ignore if */
23565 if (db.isClosed()) {
23566 return callback(new Error('database is closed'));
23567 }
23568 return callback(null, db._docCount); // use cached value
23569 }
23570
23571 api._remote = false;
23572 /* istanbul ignore next */
23573 api.type = function () {
23574 return 'leveldb';
23575 };
23576
23577 api._id = function (callback) {
23578 callback(null, instanceId);
23579 };
23580
23581 api._info = function (callback) {
23582 var res = {
23583 doc_count: db._docCount,
23584 update_seq: db._updateSeq,
23585 backend_adapter: functionName(leveldown)
23586 };
23587 return immediate(function () {
23588 callback(null, res);
23589 });
23590 };
23591
23592 function tryCode(fun, args) {
23593 try {
23594 fun.apply(null, args);
23595 } catch (err) {
23596 args[args.length - 1](err);
23597 }
23598 }
23599
23600 function executeNext() {
23601 var firstTask = db._queue.peekFront();
23602
23603 if (firstTask.type === 'read') {
23604 runReadOperation(firstTask);
23605 } else { // write, only do one at a time
23606 runWriteOperation(firstTask);
23607 }
23608 }
23609
23610 function runReadOperation(firstTask) {
23611 // do multiple reads at once simultaneously, because it's safe
23612
23613 var readTasks = [firstTask];
23614 var i = 1;
23615 var nextTask = db._queue.get(i);
23616 while (typeof nextTask !== 'undefined' && nextTask.type === 'read') {
23617 readTasks.push(nextTask);
23618 i++;
23619 nextTask = db._queue.get(i);
23620 }
23621
23622 var numDone = 0;
23623
23624 readTasks.forEach(function (readTask) {
23625 var args = readTask.args;
23626 var callback = args[args.length - 1];
23627 args[args.length - 1] = function (...cbArgs) {
23628 callback.apply(null, cbArgs);
23629 if (++numDone === readTasks.length) {
23630 immediate(function () {
23631 // all read tasks have finished
23632 readTasks.forEach(function () {
23633 db._queue.shift();
23634 });
23635 if (db._queue.length) {
23636 executeNext();
23637 }
23638 });
23639 }
23640 };
23641 tryCode(readTask.fun, args);
23642 });
23643 }
23644
23645 function runWriteOperation(firstTask) {
23646 var args = firstTask.args;
23647 var callback = args[args.length - 1];
23648 args[args.length - 1] = function (...cbArgs) {
23649 callback.apply(null, cbArgs);
23650 immediate(function () {
23651 db._queue.shift();
23652 if (db._queue.length) {
23653 executeNext();
23654 }
23655 });
23656 };
23657 tryCode(firstTask.fun, args);
23658 }
23659
23660 // all read/write operations to the database are done in a queue,
23661 // similar to how websql/idb works. this avoids problems such
23662 // as e.g. compaction needing to have a lock on the database while
23663 // it updates stuff. in the future we can revisit this.
23664 function writeLock(fun) {
23665 return function (...args) {
23666 db._queue.push({
23667 fun: fun,
23668 args: args,
23669 type: 'write'
23670 });
23671
23672 if (db._queue.length === 1) {
23673 immediate(executeNext);
23674 }
23675 };
23676 }
23677
23678 // same as the writelock, but multiple can run at once
23679 function readLock(fun) {
23680 return function (...args) {
23681 db._queue.push({
23682 fun: fun,
23683 args: args,
23684 type: 'read'
23685 });
23686
23687 if (db._queue.length === 1) {
23688 immediate(executeNext);
23689 }
23690 };
23691 }
23692
23693 function formatSeq(n) {
23694 return ('0000000000000000' + n).slice(-16);
23695 }
23696
23697 function parseSeq(s) {
23698 return parseInt(s, 10);
23699 }
23700
23701 api._get = readLock(function (id, opts, callback) {
23702 opts = clone(opts);
23703
23704 stores.docStore.get(id, function (err, metadata) {
23705
23706 if (err || !metadata) {
23707 return callback(createError(MISSING_DOC, 'missing'));
23708 }
23709
23710 var rev;
23711 if (!opts.rev) {
23712 rev = getWinningRev(metadata);
23713 var deleted = getIsDeleted(metadata, rev);
23714 if (deleted) {
23715 return callback(createError(MISSING_DOC, "deleted"));
23716 }
23717 } else {
23718 rev = opts.latest ? latest(opts.rev, metadata) : opts.rev;
23719 }
23720
23721 var seq = metadata.rev_map[rev];
23722
23723 stores.bySeqStore.get(formatSeq(seq), function (err, doc) {
23724 if (!doc) {
23725 return callback(createError(MISSING_DOC));
23726 }
23727 /* istanbul ignore if */
23728 if ('_id' in doc && doc._id !== metadata.id) {
23729 // this failing implies something very wrong
23730 return callback(new Error('wrong doc returned'));
23731 }
23732 doc._id = metadata.id;
23733 if ('_rev' in doc) {
23734 /* istanbul ignore if */
23735 if (doc._rev !== rev) {
23736 // this failing implies something very wrong
23737 return callback(new Error('wrong doc returned'));
23738 }
23739 } else {
23740 // we didn't always store this
23741 doc._rev = rev;
23742 }
23743 return callback(null, {doc: doc, metadata: metadata});
23744 });
23745 });
23746 });
23747
23748 // not technically part of the spec, but if putAttachment has its own
23749 // method...
23750 api._getAttachment = function (docId, attachId, attachment, opts, callback) {
23751 var digest = attachment.digest;
23752 var type = attachment.content_type;
23753
23754 stores.binaryStore.get(digest, function (err, attach) {
23755 if (err) {
23756 /* istanbul ignore if */
23757 if (err.name !== 'NotFoundError') {
23758 return callback(err);
23759 }
23760 // Empty attachment
23761 return callback(null, opts.binary ? createEmptyBlobOrBuffer(type) : '');
23762 }
23763
23764 if (opts.binary) {
23765 callback(null, readAsBlobOrBuffer(attach, type));
23766 } else {
23767 callback(null, attach.toString('base64'));
23768 }
23769 });
23770 };
23771
23772 api._bulkDocs = writeLock(function (req, opts, callback) {
23773 var newEdits = opts.new_edits;
23774 var results = new Array(req.docs.length);
23775 var fetchedDocs = new ExportedMap();
23776 var stemmedRevs = new ExportedMap();
23777
23778 var txn = new LevelTransaction();
23779 var docCountDelta = 0;
23780 var newUpdateSeq = db._updateSeq;
23781
23782 // parse the docs and give each a sequence number
23783 var userDocs = req.docs;
23784 var docInfos = userDocs.map(function (doc) {
23785 if (doc._id && isLocalId(doc._id)) {
23786 return doc;
23787 }
23788 var newDoc = parseDoc(doc, newEdits, api.__opts);
23789
23790 if (newDoc.metadata && !newDoc.metadata.rev_map) {
23791 newDoc.metadata.rev_map = {};
23792 }
23793
23794 return newDoc;
23795 });
23796 var infoErrors = docInfos.filter(function (doc) {
23797 return doc.error;
23798 });
23799
23800 if (infoErrors.length) {
23801 return callback(infoErrors[0]);
23802 }
23803
23804 // verify any stub attachments as a precondition test
23805
23806 function verifyAttachment(digest, callback) {
23807 txn.get(stores.attachmentStore, digest, function (levelErr) {
23808 if (levelErr) {
23809 var err = createError(MISSING_STUB,
23810 'unknown stub attachment with digest ' +
23811 digest);
23812 callback(err);
23813 } else {
23814 callback();
23815 }
23816 });
23817 }
23818
23819 function verifyAttachments(finish) {
23820 var digests = [];
23821 userDocs.forEach(function (doc) {
23822 if (doc && doc._attachments) {
23823 Object.keys(doc._attachments).forEach(function (filename) {
23824 var att = doc._attachments[filename];
23825 if (att.stub) {
23826 digests.push(att.digest);
23827 }
23828 });
23829 }
23830 });
23831 if (!digests.length) {
23832 return finish();
23833 }
23834 var numDone = 0;
23835 var err;
23836
23837 digests.forEach(function (digest) {
23838 verifyAttachment(digest, function (attErr) {
23839 if (attErr && !err) {
23840 err = attErr;
23841 }
23842
23843 if (++numDone === digests.length) {
23844 finish(err);
23845 }
23846 });
23847 });
23848 }
23849
23850 function fetchExistingDocs(finish) {
23851 var numDone = 0;
23852 var overallErr;
23853 function checkDone() {
23854 if (++numDone === userDocs.length) {
23855 return finish(overallErr);
23856 }
23857 }
23858
23859 userDocs.forEach(function (doc) {
23860 if (doc._id && isLocalId(doc._id)) {
23861 // skip local docs
23862 return checkDone();
23863 }
23864 txn.get(stores.docStore, doc._id, function (err, info) {
23865 if (err) {
23866 /* istanbul ignore if */
23867 if (err.name !== 'NotFoundError') {
23868 overallErr = err;
23869 }
23870 } else {
23871 fetchedDocs.set(doc._id, info);
23872 }
23873 checkDone();
23874 });
23875 });
23876 }
23877
23878 function compact(revsMap, callback) {
23879 var promise = Promise.resolve();
23880 revsMap.forEach(function (revs, docId) {
23881 // TODO: parallelize, for now need to be sequential to
23882 // pass orphaned attachment tests
23883 promise = promise.then(function () {
23884 return new Promise(function (resolve, reject) {
23885 api._doCompactionNoLock(docId, revs, {ctx: txn}, function (err) {
23886 /* istanbul ignore if */
23887 if (err) {
23888 return reject(err);
23889 }
23890 resolve();
23891 });
23892 });
23893 });
23894 });
23895
23896 promise.then(function () {
23897 callback();
23898 }, callback);
23899 }
23900
23901 function autoCompact(callback) {
23902 var revsMap = new ExportedMap();
23903 fetchedDocs.forEach(function (metadata, docId) {
23904 revsMap.set(docId, compactTree(metadata));
23905 });
23906 compact(revsMap, callback);
23907 }
23908
23909 function finish() {
23910 compact(stemmedRevs, function (error) {
23911 /* istanbul ignore if */
23912 if (error) {
23913 complete(error);
23914 }
23915 if (api.auto_compaction) {
23916 return autoCompact(complete);
23917 }
23918 complete();
23919 });
23920 }
23921
23922 function writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
23923 isUpdate, delta, resultsIdx, callback2) {
23924 docCountDelta += delta;
23925
23926 var err = null;
23927 var recv = 0;
23928
23929 docInfo.metadata.winningRev = winningRev$$1;
23930 docInfo.metadata.deleted = winningRevIsDeleted;
23931
23932 docInfo.data._id = docInfo.metadata.id;
23933 docInfo.data._rev = docInfo.metadata.rev;
23934
23935 if (newRevIsDeleted) {
23936 docInfo.data._deleted = true;
23937 }
23938
23939 if (docInfo.stemmedRevs.length) {
23940 stemmedRevs.set(docInfo.metadata.id, docInfo.stemmedRevs);
23941 }
23942
23943 var attachments = docInfo.data._attachments ?
23944 Object.keys(docInfo.data._attachments) :
23945 [];
23946
23947 function attachmentSaved(attachmentErr) {
23948 recv++;
23949 if (!err) {
23950 /* istanbul ignore if */
23951 if (attachmentErr) {
23952 err = attachmentErr;
23953 callback2(err);
23954 } else if (recv === attachments.length) {
23955 finish();
23956 }
23957 }
23958 }
23959
23960 function onMD5Load(doc, key, data, attachmentSaved) {
23961 return function (result) {
23962 saveAttachment(doc, MD5_PREFIX + result, key, data, attachmentSaved);
23963 };
23964 }
23965
23966 function doMD5(doc, key, attachmentSaved) {
23967 return function (data) {
23968 binaryMd5(data, onMD5Load(doc, key, data, attachmentSaved));
23969 };
23970 }
23971
23972 for (var i = 0; i < attachments.length; i++) {
23973 var key = attachments[i];
23974 var att = docInfo.data._attachments[key];
23975
23976 if (att.stub) {
23977 // still need to update the refs mapping
23978 var id = docInfo.data._id;
23979 var rev = docInfo.data._rev;
23980 saveAttachmentRefs(id, rev, att.digest, attachmentSaved);
23981 continue;
23982 }
23983 var data;
23984 if (typeof att.data === 'string') {
23985 // input is assumed to be a base64 string
23986 try {
23987 data = thisAtob(att.data);
23988 } catch (e) {
23989 callback(createError(BAD_ARG,
23990 'Attachment is not a valid base64 string'));
23991 return;
23992 }
23993 doMD5(docInfo, key, attachmentSaved)(data);
23994 } else {
23995 prepareAttachmentForStorage(att.data,
23996 doMD5(docInfo, key, attachmentSaved));
23997 }
23998 }
23999
24000 function finish() {
24001 var seq = docInfo.metadata.rev_map[docInfo.metadata.rev];
24002 /* istanbul ignore if */
24003 if (seq) {
24004 // check that there aren't any existing revisions with the same
24005 // revision id, else we shouldn't do anything
24006 return callback2();
24007 }
24008 seq = ++newUpdateSeq;
24009 docInfo.metadata.rev_map[docInfo.metadata.rev] =
24010 docInfo.metadata.seq = seq;
24011 var seqKey = formatSeq(seq);
24012 var batch = [{
24013 key: seqKey,
24014 value: docInfo.data,
24015 prefix: stores.bySeqStore,
24016 type: 'put'
24017 }, {
24018 key: docInfo.metadata.id,
24019 value: docInfo.metadata,
24020 prefix: stores.docStore,
24021 type: 'put'
24022 }];
24023 txn.batch(batch);
24024 results[resultsIdx] = {
24025 ok: true,
24026 id: docInfo.metadata.id,
24027 rev: docInfo.metadata.rev
24028 };
24029 fetchedDocs.set(docInfo.metadata.id, docInfo.metadata);
24030 callback2();
24031 }
24032
24033 if (!attachments.length) {
24034 finish();
24035 }
24036 }
24037
24038 // attachments are queued per-digest, otherwise the refs could be
24039 // overwritten by concurrent writes in the same bulkDocs session
24040 var attachmentQueues = {};
24041
24042 function saveAttachmentRefs(id, rev, digest, callback) {
24043
24044 function fetchAtt() {
24045 return new Promise(function (resolve, reject) {
24046 txn.get(stores.attachmentStore, digest, function (err, oldAtt) {
24047 /* istanbul ignore if */
24048 if (err && err.name !== 'NotFoundError') {
24049 return reject(err);
24050 }
24051 resolve(oldAtt);
24052 });
24053 });
24054 }
24055
24056 function saveAtt(oldAtt) {
24057 var ref = [id, rev].join('@');
24058 var newAtt = {};
24059
24060 if (oldAtt) {
24061 if (oldAtt.refs) {
24062 // only update references if this attachment already has them
24063 // since we cannot migrate old style attachments here without
24064 // doing a full db scan for references
24065 newAtt.refs = oldAtt.refs;
24066 newAtt.refs[ref] = true;
24067 }
24068 } else {
24069 newAtt.refs = {};
24070 newAtt.refs[ref] = true;
24071 }
24072
24073 return new Promise(function (resolve) {
24074 txn.batch([{
24075 type: 'put',
24076 prefix: stores.attachmentStore,
24077 key: digest,
24078 value: newAtt
24079 }]);
24080 resolve(!oldAtt);
24081 });
24082 }
24083
24084 // put attachments in a per-digest queue, to avoid two docs with the same
24085 // attachment overwriting each other
24086 var queue = attachmentQueues[digest] || Promise.resolve();
24087 attachmentQueues[digest] = queue.then(function () {
24088 return fetchAtt().then(saveAtt).then(function (isNewAttachment) {
24089 callback(null, isNewAttachment);
24090 }, callback);
24091 });
24092 }
24093
24094 function saveAttachment(docInfo, digest, key, data, callback) {
24095 var att = docInfo.data._attachments[key];
24096 delete att.data;
24097 att.digest = digest;
24098 att.length = data.length;
24099 var id = docInfo.metadata.id;
24100 var rev = docInfo.metadata.rev;
24101 att.revpos = parseInt(rev, 10);
24102
24103 saveAttachmentRefs(id, rev, digest, function (err, isNewAttachment) {
24104 /* istanbul ignore if */
24105 if (err) {
24106 return callback(err);
24107 }
24108 // do not try to store empty attachments
24109 if (data.length === 0) {
24110 return callback(err);
24111 }
24112 if (!isNewAttachment) {
24113 // small optimization - don't bother writing it again
24114 return callback(err);
24115 }
24116 txn.batch([{
24117 type: 'put',
24118 prefix: stores.binaryStore,
24119 key: digest,
24120 value: bufferFrom(data, 'binary')
24121 }]);
24122 callback();
24123 });
24124 }
24125
24126 function complete(err) {
24127 /* istanbul ignore if */
24128 if (err) {
24129 return immediate(function () {
24130 callback(err);
24131 });
24132 }
24133 txn.batch([
24134 {
24135 prefix: stores.metaStore,
24136 type: 'put',
24137 key: UPDATE_SEQ_KEY,
24138 value: newUpdateSeq
24139 },
24140 {
24141 prefix: stores.metaStore,
24142 type: 'put',
24143 key: DOC_COUNT_KEY,
24144 value: db._docCount + docCountDelta
24145 }
24146 ]);
24147 txn.execute(db, function (err) {
24148 /* istanbul ignore if */
24149 if (err) {
24150 return callback(err);
24151 }
24152 db._docCount += docCountDelta;
24153 db._updateSeq = newUpdateSeq;
24154 levelChanges.notify(name);
24155 immediate(function () {
24156 callback(null, results);
24157 });
24158 });
24159 }
24160
24161 if (!docInfos.length) {
24162 return callback(null, []);
24163 }
24164
24165 verifyAttachments(function (err) {
24166 if (err) {
24167 return callback(err);
24168 }
24169 fetchExistingDocs(function (err) {
24170 /* istanbul ignore if */
24171 if (err) {
24172 return callback(err);
24173 }
24174 processDocs(revLimit, docInfos, api, fetchedDocs, txn, results,
24175 writeDoc, opts, finish);
24176 });
24177 });
24178 });
24179 api._allDocs = function (opts, callback) {
24180 if ('keys' in opts) {
24181 return allDocsKeysQuery(this, opts);
24182 }
24183 return readLock(function (opts, callback) {
24184 opts = clone(opts);
24185 countDocs(function (err, docCount) {
24186 /* istanbul ignore if */
24187 if (err) {
24188 return callback(err);
24189 }
24190 var readstreamOpts = {};
24191 var skip = opts.skip || 0;
24192 if (opts.startkey) {
24193 readstreamOpts.gte = opts.startkey;
24194 }
24195 if (opts.endkey) {
24196 readstreamOpts.lte = opts.endkey;
24197 }
24198 if (opts.key) {
24199 readstreamOpts.gte = readstreamOpts.lte = opts.key;
24200 }
24201 if (opts.descending) {
24202 readstreamOpts.reverse = true;
24203 // switch start and ends
24204 var tmp = readstreamOpts.lte;
24205 readstreamOpts.lte = readstreamOpts.gte;
24206 readstreamOpts.gte = tmp;
24207 }
24208 var limit;
24209 if (typeof opts.limit === 'number') {
24210 limit = opts.limit;
24211 }
24212 if (limit === 0 ||
24213 ('gte' in readstreamOpts && 'lte' in readstreamOpts &&
24214 readstreamOpts.gte > readstreamOpts.lte)) {
24215 // should return 0 results when start is greater than end.
24216 // normally level would "fix" this for us by reversing the order,
24217 // so short-circuit instead
24218 var returnVal = {
24219 total_rows: docCount,
24220 offset: opts.skip,
24221 rows: []
24222 };
24223 /* istanbul ignore if */
24224 if (opts.update_seq) {
24225 returnVal.update_seq = db._updateSeq;
24226 }
24227 return callback(null, returnVal);
24228 }
24229 var results = [];
24230 var docstream = stores.docStore.readStream(readstreamOpts);
24231
24232 var throughStream = through2.obj(function (entry, _, next) {
24233 var metadata = entry.value;
24234 // winningRev and deleted are performance-killers, but
24235 // in newer versions of PouchDB, they are cached on the metadata
24236 var winningRev$$1 = getWinningRev(metadata);
24237 var deleted = getIsDeleted(metadata, winningRev$$1);
24238 if (!deleted) {
24239 if (skip-- > 0) {
24240 next();
24241 return;
24242 } else if (typeof limit === 'number' && limit-- <= 0) {
24243 docstream.unpipe();
24244 docstream.destroy();
24245 next();
24246 return;
24247 }
24248 } else if (opts.deleted !== 'ok') {
24249 next();
24250 return;
24251 }
24252 function allDocsInner(data) {
24253 var doc = {
24254 id: metadata.id,
24255 key: metadata.id,
24256 value: {
24257 rev: winningRev$$1
24258 }
24259 };
24260 if (opts.include_docs) {
24261 doc.doc = data;
24262 doc.doc._rev = doc.value.rev;
24263 if (opts.conflicts) {
24264 var conflicts = collectConflicts(metadata);
24265 if (conflicts.length) {
24266 doc.doc._conflicts = conflicts;
24267 }
24268 }
24269 for (var att in doc.doc._attachments) {
24270 if (Object.prototype.hasOwnProperty.call(doc.doc._attachments, att)) {
24271 doc.doc._attachments[att].stub = true;
24272 }
24273 }
24274 }
24275 if (opts.inclusive_end === false && metadata.id === opts.endkey) {
24276 return next();
24277 } else if (deleted) {
24278 if (opts.deleted === 'ok') {
24279 doc.value.deleted = true;
24280 doc.doc = null;
24281 } else {
24282 /* istanbul ignore next */
24283 return next();
24284 }
24285 }
24286 results.push(doc);
24287 next();
24288 }
24289 if (opts.include_docs) {
24290 var seq = metadata.rev_map[winningRev$$1];
24291 stores.bySeqStore.get(formatSeq(seq), function (err, data) {
24292 allDocsInner(data);
24293 });
24294 }
24295 else {
24296 allDocsInner();
24297 }
24298 }, function (next) {
24299 Promise.resolve().then(function () {
24300 if (opts.include_docs && opts.attachments) {
24301 return fetchAttachments(results, stores, opts);
24302 }
24303 }).then(function () {
24304 var returnVal = {
24305 total_rows: docCount,
24306 offset: opts.skip,
24307 rows: results
24308 };
24309
24310 /* istanbul ignore if */
24311 if (opts.update_seq) {
24312 returnVal.update_seq = db._updateSeq;
24313 }
24314 callback(null, returnVal);
24315 }, callback);
24316 next();
24317 }).on('unpipe', function () {
24318 throughStream.end();
24319 });
24320
24321 docstream.on('error', callback);
24322
24323 docstream.pipe(throughStream);
24324 });
24325 })(opts, callback);
24326 };
24327
24328 api._changes = function (opts) {
24329 opts = clone(opts);
24330
24331 if (opts.continuous) {
24332 var id = name + ':' + uuid$1();
24333 levelChanges.addListener(name, id, api, opts);
24334 levelChanges.notify(name);
24335 return {
24336 cancel: function () {
24337 levelChanges.removeListener(name, id);
24338 }
24339 };
24340 }
24341
24342 var descending = opts.descending;
24343 var results = [];
24344 var lastSeq = opts.since || 0;
24345 var called = 0;
24346 var streamOpts = {
24347 reverse: descending
24348 };
24349 var limit;
24350 if ('limit' in opts && opts.limit > 0) {
24351 limit = opts.limit;
24352 }
24353 if (!streamOpts.reverse) {
24354 streamOpts.start = formatSeq(opts.since || 0);
24355 }
24356
24357 var docIds = opts.doc_ids && new ExportedSet(opts.doc_ids);
24358 var filter = filterChange(opts);
24359 var docIdsToMetadata = new ExportedMap();
24360
24361 function complete() {
24362 opts.done = true;
24363 if (opts.return_docs && opts.limit) {
24364 /* istanbul ignore if */
24365 if (opts.limit < results.length) {
24366 results.length = opts.limit;
24367 }
24368 }
24369 changeStream.unpipe(throughStream);
24370 changeStream.destroy();
24371 if (!opts.continuous && !opts.cancelled) {
24372 if (opts.include_docs && opts.attachments && opts.return_docs) {
24373 fetchAttachments(results, stores, opts).then(function () {
24374 opts.complete(null, {results: results, last_seq: lastSeq});
24375 });
24376 } else {
24377 opts.complete(null, {results: results, last_seq: lastSeq});
24378 }
24379 }
24380 }
24381 var changeStream = stores.bySeqStore.readStream(streamOpts);
24382 var throughStream = through2.obj(function (data, _, next) {
24383 if (limit && called >= limit) {
24384 complete();
24385 return next();
24386 }
24387 if (opts.cancelled || opts.done) {
24388 return next();
24389 }
24390
24391 var seq = parseSeq(data.key);
24392 var doc = data.value;
24393
24394 if (seq === opts.since && !descending) {
24395 // couchdb ignores `since` if descending=true
24396 return next();
24397 }
24398
24399 if (docIds && !docIds.has(doc._id)) {
24400 return next();
24401 }
24402
24403 var metadata;
24404
24405 function onGetMetadata(metadata) {
24406 var winningRev$$1 = getWinningRev(metadata);
24407
24408 function onGetWinningDoc(winningDoc) {
24409
24410 var change = opts.processChange(winningDoc, metadata, opts);
24411 change.seq = metadata.seq;
24412
24413 var filtered = filter(change);
24414 if (typeof filtered === 'object') {
24415 return opts.complete(filtered);
24416 }
24417
24418 if (filtered) {
24419 called++;
24420
24421 if (opts.attachments && opts.include_docs) {
24422 // fetch attachment immediately for the benefit
24423 // of live listeners
24424 fetchAttachments([change], stores, opts).then(function () {
24425 opts.onChange(change);
24426 });
24427 } else {
24428 opts.onChange(change);
24429 }
24430
24431 if (opts.return_docs) {
24432 results.push(change);
24433 }
24434 }
24435 next();
24436 }
24437
24438 if (metadata.seq !== seq) {
24439 // some other seq is later
24440 return next();
24441 }
24442
24443 lastSeq = seq;
24444
24445 if (winningRev$$1 === doc._rev) {
24446 return onGetWinningDoc(doc);
24447 }
24448
24449 // fetch the winner
24450
24451 var winningSeq = metadata.rev_map[winningRev$$1];
24452
24453 stores.bySeqStore.get(formatSeq(winningSeq), function (err, doc) {
24454 onGetWinningDoc(doc);
24455 });
24456 }
24457
24458 metadata = docIdsToMetadata.get(doc._id);
24459 if (metadata) { // cached
24460 return onGetMetadata(metadata);
24461 }
24462 // metadata not cached, have to go fetch it
24463 stores.docStore.get(doc._id, function (err, metadata) {
24464 /* istanbul ignore if */
24465 if (opts.cancelled || opts.done || db.isClosed() ||
24466 isLocalId(metadata.id)) {
24467 return next();
24468 }
24469 docIdsToMetadata.set(doc._id, metadata);
24470 onGetMetadata(metadata);
24471 });
24472 }, function (next) {
24473 if (opts.cancelled) {
24474 return next();
24475 }
24476 if (opts.return_docs && opts.limit) {
24477 /* istanbul ignore if */
24478 if (opts.limit < results.length) {
24479 results.length = opts.limit;
24480 }
24481 }
24482
24483 next();
24484 }).on('unpipe', function () {
24485 throughStream.end();
24486 complete();
24487 });
24488 changeStream.pipe(throughStream);
24489 return {
24490 cancel: function () {
24491 opts.cancelled = true;
24492 complete();
24493 }
24494 };
24495 };
24496
24497 api._close = function (callback) {
24498 /* istanbul ignore if */
24499 if (db.isClosed()) {
24500 return callback(createError(NOT_OPEN));
24501 }
24502 db.close(function (err) {
24503 /* istanbul ignore if */
24504 if (err) {
24505 callback(err);
24506 } else {
24507 dbStore["delete"](name);
24508
24509 var adapterName = functionName(leveldown);
24510 var adapterStore = dbStores.get(adapterName);
24511 var viewNamePrefix = PouchDB$1.prefix + name + "-mrview-";
24512 var keys = [...adapterStore.keys()].filter(k => k.includes(viewNamePrefix));
24513 keys.forEach(key => {
24514 var eventEmitter = adapterStore.get(key);
24515 eventEmitter.removeAllListeners();
24516 eventEmitter.close();
24517 adapterStore["delete"](key);
24518 });
24519
24520 callback();
24521 }
24522 });
24523 };
24524
24525 api._getRevisionTree = function (docId, callback) {
24526 stores.docStore.get(docId, function (err, metadata) {
24527 if (err) {
24528 callback(createError(MISSING_DOC));
24529 } else {
24530 callback(null, metadata.rev_tree);
24531 }
24532 });
24533 };
24534
24535 api._doCompaction = writeLock(function (docId, revs, opts, callback) {
24536 api._doCompactionNoLock(docId, revs, opts, callback);
24537 });
24538
24539 // the NoLock version is for use by bulkDocs
24540 api._doCompactionNoLock = function (docId, revs, opts, callback) {
24541 if (typeof opts === 'function') {
24542 callback = opts;
24543 opts = {};
24544 }
24545
24546 if (!revs.length) {
24547 return callback();
24548 }
24549 var txn = opts.ctx || new LevelTransaction();
24550
24551 txn.get(stores.docStore, docId, function (err, metadata) {
24552 /* istanbul ignore if */
24553 if (err) {
24554 return callback(err);
24555 }
24556 var seqs = revs.map(function (rev) {
24557 var seq = metadata.rev_map[rev];
24558 delete metadata.rev_map[rev];
24559 return seq;
24560 });
24561 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
24562 revHash, ctx, opts) {
24563 var rev = pos + '-' + revHash;
24564 if (revs.indexOf(rev) !== -1) {
24565 opts.status = 'missing';
24566 }
24567 });
24568
24569 var batch = [];
24570 batch.push({
24571 key: metadata.id,
24572 value: metadata,
24573 type: 'put',
24574 prefix: stores.docStore
24575 });
24576
24577 var digestMap = {};
24578 var numDone = 0;
24579 var overallErr;
24580 function checkDone(err) {
24581 /* istanbul ignore if */
24582 if (err) {
24583 overallErr = err;
24584 }
24585 if (++numDone === revs.length) { // done
24586 /* istanbul ignore if */
24587 if (overallErr) {
24588 return callback(overallErr);
24589 }
24590 deleteOrphanedAttachments();
24591 }
24592 }
24593
24594 function finish(err) {
24595 /* istanbul ignore if */
24596 if (err) {
24597 return callback(err);
24598 }
24599 txn.batch(batch);
24600 if (opts.ctx) {
24601 // don't execute immediately
24602 return callback();
24603 }
24604 txn.execute(db, callback);
24605 }
24606
24607 function deleteOrphanedAttachments() {
24608 var possiblyOrphanedAttachments = Object.keys(digestMap);
24609 if (!possiblyOrphanedAttachments.length) {
24610 return finish();
24611 }
24612 var numDone = 0;
24613 var overallErr;
24614 function checkDone(err) {
24615 /* istanbul ignore if */
24616 if (err) {
24617 overallErr = err;
24618 }
24619 if (++numDone === possiblyOrphanedAttachments.length) {
24620 finish(overallErr);
24621 }
24622 }
24623 var refsToDelete = new ExportedMap();
24624 revs.forEach(function (rev) {
24625 refsToDelete.set(docId + '@' + rev, true);
24626 });
24627 possiblyOrphanedAttachments.forEach(function (digest) {
24628 txn.get(stores.attachmentStore, digest, function (err, attData) {
24629 /* istanbul ignore if */
24630 if (err) {
24631 if (err.name === 'NotFoundError') {
24632 return checkDone();
24633 } else {
24634 return checkDone(err);
24635 }
24636 }
24637 var refs = Object.keys(attData.refs || {}).filter(function (ref) {
24638 return !refsToDelete.has(ref);
24639 });
24640 var newRefs = {};
24641 refs.forEach(function (ref) {
24642 newRefs[ref] = true;
24643 });
24644 if (refs.length) { // not orphaned
24645 batch.push({
24646 key: digest,
24647 type: 'put',
24648 value: {refs: newRefs},
24649 prefix: stores.attachmentStore
24650 });
24651 } else { // orphaned, can safely delete
24652 batch = batch.concat([{
24653 key: digest,
24654 type: 'del',
24655 prefix: stores.attachmentStore
24656 }, {
24657 key: digest,
24658 type: 'del',
24659 prefix: stores.binaryStore
24660 }]);
24661 }
24662 checkDone();
24663 });
24664 });
24665 }
24666
24667 seqs.forEach(function (seq) {
24668 batch.push({
24669 key: formatSeq(seq),
24670 type: 'del',
24671 prefix: stores.bySeqStore
24672 });
24673 txn.get(stores.bySeqStore, formatSeq(seq), function (err, doc) {
24674 /* istanbul ignore if */
24675 if (err) {
24676 if (err.name === 'NotFoundError') {
24677 return checkDone();
24678 } else {
24679 return checkDone(err);
24680 }
24681 }
24682 var atts = Object.keys(doc._attachments || {});
24683 atts.forEach(function (attName) {
24684 var digest = doc._attachments[attName].digest;
24685 digestMap[digest] = true;
24686 });
24687 checkDone();
24688 });
24689 });
24690 });
24691 };
24692
24693 api._getLocal = function (id, callback) {
24694 stores.localStore.get(id, function (err, doc) {
24695 if (err) {
24696 callback(createError(MISSING_DOC));
24697 } else {
24698 callback(null, doc);
24699 }
24700 });
24701 };
24702
24703 api._putLocal = function (doc, opts, callback) {
24704 if (typeof opts === 'function') {
24705 callback = opts;
24706 opts = {};
24707 }
24708 if (opts.ctx) {
24709 api._putLocalNoLock(doc, opts, callback);
24710 } else {
24711 api._putLocalWithLock(doc, opts, callback);
24712 }
24713 };
24714
24715 api._putLocalWithLock = writeLock(function (doc, opts, callback) {
24716 api._putLocalNoLock(doc, opts, callback);
24717 });
24718
24719 // the NoLock version is for use by bulkDocs
24720 api._putLocalNoLock = function (doc, opts, callback) {
24721 delete doc._revisions; // ignore this, trust the rev
24722 var oldRev = doc._rev;
24723 var id = doc._id;
24724
24725 var txn = opts.ctx || new LevelTransaction();
24726
24727 txn.get(stores.localStore, id, function (err, resp) {
24728 if (err && oldRev) {
24729 return callback(createError(REV_CONFLICT));
24730 }
24731 if (resp && resp._rev !== oldRev) {
24732 return callback(createError(REV_CONFLICT));
24733 }
24734 doc._rev =
24735 oldRev ? '0-' + (parseInt(oldRev.split('-')[1], 10) + 1) : '0-1';
24736 var batch = [
24737 {
24738 type: 'put',
24739 prefix: stores.localStore,
24740 key: id,
24741 value: doc
24742 }
24743 ];
24744
24745 txn.batch(batch);
24746 var ret = {ok: true, id: doc._id, rev: doc._rev};
24747
24748 if (opts.ctx) {
24749 // don't execute immediately
24750 return callback(null, ret);
24751 }
24752 txn.execute(db, function (err) {
24753 /* istanbul ignore if */
24754 if (err) {
24755 return callback(err);
24756 }
24757 callback(null, ret);
24758 });
24759 });
24760 };
24761
24762 api._removeLocal = function (doc, opts, callback) {
24763 if (typeof opts === 'function') {
24764 callback = opts;
24765 opts = {};
24766 }
24767 if (opts.ctx) {
24768 api._removeLocalNoLock(doc, opts, callback);
24769 } else {
24770 api._removeLocalWithLock(doc, opts, callback);
24771 }
24772 };
24773
24774 api._removeLocalWithLock = writeLock(function (doc, opts, callback) {
24775 api._removeLocalNoLock(doc, opts, callback);
24776 });
24777
24778 // the NoLock version is for use by bulkDocs
24779 api._removeLocalNoLock = function (doc, opts, callback) {
24780 var txn = opts.ctx || new LevelTransaction();
24781 txn.get(stores.localStore, doc._id, function (err, resp) {
24782 if (err) {
24783 /* istanbul ignore if */
24784 if (err.name !== 'NotFoundError') {
24785 return callback(err);
24786 } else {
24787 return callback(createError(MISSING_DOC));
24788 }
24789 }
24790 if (resp._rev !== doc._rev) {
24791 return callback(createError(REV_CONFLICT));
24792 }
24793 txn.batch([{
24794 prefix: stores.localStore,
24795 type: 'del',
24796 key: doc._id
24797 }]);
24798 var ret = {ok: true, id: doc._id, rev: '0-0'};
24799 if (opts.ctx) {
24800 // don't execute immediately
24801 return callback(null, ret);
24802 }
24803 txn.execute(db, function (err) {
24804 /* istanbul ignore if */
24805 if (err) {
24806 return callback(err);
24807 }
24808 callback(null, ret);
24809 });
24810 });
24811 };
24812
24813 // close and delete open leveldb stores
24814 api._destroy = function (opts, callback) {
24815 var dbStore;
24816 var leveldownName = functionName(leveldown);
24817 /* istanbul ignore else */
24818 if (dbStores.has(leveldownName)) {
24819 dbStore = dbStores.get(leveldownName);
24820 } else {
24821 return callDestroy(name, callback);
24822 }
24823
24824 /* istanbul ignore else */
24825 if (dbStore.has(name)) {
24826 levelChanges.removeAllListeners(name);
24827
24828 dbStore.get(name).close(function () {
24829 dbStore["delete"](name);
24830 callDestroy(name, callback);
24831 });
24832 } else {
24833 callDestroy(name, callback);
24834 }
24835 };
24836 function callDestroy(name, cb) {
24837 // May not exist if leveldown is backed by memory adapter
24838 /* istanbul ignore else */
24839 if ('destroy' in leveldown) {
24840 leveldown.destroy(name, cb);
24841 } else {
24842 cb(null);
24843 }
24844 }
24845}
24846
24847function MemDownPouch(opts, callback) {
24848 var _opts = $inject_Object_assign({
24849 db: memdown
24850 }, opts);
24851
24852 LevelPouch.call(this, _opts, callback);
24853}
24854
24855// overrides for normal LevelDB behavior on Node
24856MemDownPouch.valid = function () {
24857 return true;
24858};
24859MemDownPouch.use_prefix = false;
24860
24861function MemoryPouchPlugin (PouchDB) {
24862 PouchDB.adapter('memory', MemDownPouch, true);
24863}
24864
24865// this code only runs in the browser, as its own dist/ script
24866
24867if (typeof PouchDB === 'undefined') {
24868 guardedConsole('error', 'memory adapter plugin error: ' +
24869 'Cannot find global "PouchDB" object! ' +
24870 'Did you remember to include pouchdb.js?');
24871} else {
24872 PouchDB.plugin(MemoryPouchPlugin);
24873}
24874
24875},{"111":111,"117":117,"132":132,"17":17,"20":20,"23":23,"31":31,"53":53,"55":55,"57":57,"7":7,"75":75,"77":77}]},{},[135]);
24876
\No newline at end of file