UNPKG

160 kBJavaScriptView Raw
1(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
2
3var request, cancel, root, delay;
4var isNative = true;
5
6function fakeRAF (fn) {
7 return root.setTimeout(fn, delay);
8}
9
10if (!(request && cancel)) {
11 root = (function () { return this; })();
12
13 request = (root.requestAnimationFrame || root.mozRequestAnimationFrame || root.webkitRequestAnimationFrame || fakeRAF);
14 cancel = root.cancelAnimationFrame || root.mozCancelAnimationFrame || root.webkitCancelAnimationFrame || root.webkitCancelRequestAnimationFrame || root.clearTimeout;
15
16
17 if (cancel === root.clearTimeout || request === fakeRAF) {
18 isNative = false;
19 delay = 8;
20 request = fakeRAF;
21 }
22
23}
24
25function iteratee(fn, ctx) {
26 return function _iteratee() {
27 request(fn.apply.bind(fn, ctx || this, arguments));
28 };
29}
30
31function sync(_delay) {
32 return typeof _delay === 'number' && (delay = _delay);
33}
34
35module.exports = {
36 isNative: isNative,
37 request: function (fn, ctx) {
38 if (arguments.length > 1) fn = fn.bind(ctx);
39 return request.call(root, fn);
40 },
41 iteratee: iteratee,
42 deferred: iteratee,
43 cancel: cancel.bind(root),
44 sync60Hz: sync.bind(root, 16),
45 sync30Hz: sync.bind(root, 33),
46 sync: sync
47};
48},{}],2:[function(require,module,exports){
49(function (process){
50var defined = require('defined');
51var createDefaultStream = require('./lib/default_stream');
52var Test = require('./lib/test');
53var createResult = require('./lib/results');
54var through = require('through');
55
56var canEmitExit = typeof process !== 'undefined' && process
57 && typeof process.on === 'function' && process.browser !== true
58;
59var canExit = typeof process !== 'undefined' && process
60 && typeof process.exit === 'function'
61;
62
63var nextTick = typeof setImmediate !== 'undefined'
64 ? setImmediate
65 : process.nextTick
66;
67
68exports = module.exports = (function () {
69 var harness;
70 var lazyLoad = function () {
71 return getHarness().apply(this, arguments);
72 };
73
74 lazyLoad.only = function () {
75 return getHarness().only.apply(this, arguments);
76 };
77
78 lazyLoad.createStream = function (opts) {
79 if (!opts) opts = {};
80 if (!harness) {
81 var output = through();
82 getHarness({ stream: output, objectMode: opts.objectMode });
83 return output;
84 }
85 return harness.createStream(opts);
86 };
87
88 return lazyLoad
89
90 function getHarness (opts) {
91 if (!opts) opts = {};
92 opts.autoclose = !canEmitExit;
93 if (!harness) harness = createExitHarness(opts);
94 return harness;
95 }
96})();
97
98function createExitHarness (conf) {
99 if (!conf) conf = {};
100 var harness = createHarness({
101 autoclose: defined(conf.autoclose, false)
102 });
103
104 var stream = harness.createStream({ objectMode: conf.objectMode });
105 var es = stream.pipe(conf.stream || createDefaultStream());
106 if (canEmitExit) {
107 es.on('error', function (err) { harness._exitCode = 1 });
108 }
109
110 var ended = false;
111 stream.on('end', function () { ended = true });
112
113 if (conf.exit === false) return harness;
114 if (!canEmitExit || !canExit) return harness;
115
116 var inErrorState = false;
117
118 process.on('exit', function (code) {
119 // let the process exit cleanly.
120 if (code !== 0) {
121 return
122 }
123
124 if (!ended) {
125 var only = harness._results._only;
126 for (var i = 0; i < harness._tests.length; i++) {
127 var t = harness._tests[i];
128 if (only && t.name !== only) continue;
129 t._exit();
130 }
131 }
132 harness.close();
133 process.exit(code || harness._exitCode);
134 });
135
136 return harness;
137}
138
139exports.createHarness = createHarness;
140exports.Test = Test;
141exports.test = exports; // tap compat
142exports.test.skip = Test.skip;
143
144var exitInterval;
145
146function createHarness (conf_) {
147 if (!conf_) conf_ = {};
148 var results = createResult();
149 if (conf_.autoclose !== false) {
150 results.once('done', function () { results.close() });
151 }
152
153 var test = function (name, conf, cb) {
154 var t = new Test(name, conf, cb);
155 test._tests.push(t);
156
157 (function inspectCode (st) {
158 st.on('test', function sub (st_) {
159 inspectCode(st_);
160 });
161 st.on('result', function (r) {
162 if (!r.ok) test._exitCode = 1
163 });
164 })(t);
165
166 results.push(t);
167 return t;
168 };
169 test._results = results;
170
171 test._tests = [];
172
173 test.createStream = function (opts) {
174 return results.createStream(opts);
175 };
176
177 var only = false;
178 test.only = function (name) {
179 if (only) throw new Error('there can only be one only test');
180 results.only(name);
181 only = true;
182 return test.apply(null, arguments);
183 };
184 test._exitCode = 0;
185
186 test.close = function () { results.close() };
187
188 return test;
189}
190
191}).call(this,require('_process'))
192},{"./lib/default_stream":3,"./lib/results":4,"./lib/test":5,"_process":24,"defined":9,"through":13}],3:[function(require,module,exports){
193(function (process){
194var through = require('through');
195var fs = require('fs');
196
197module.exports = function () {
198 var line = '';
199 var stream = through(write, flush);
200 return stream;
201
202 function write (buf) {
203 for (var i = 0; i < buf.length; i++) {
204 var c = typeof buf === 'string'
205 ? buf.charAt(i)
206 : String.fromCharCode(buf[i])
207 ;
208 if (c === '\n') flush();
209 else line += c;
210 }
211 }
212
213 function flush () {
214 if (fs.writeSync && /^win/.test(process.platform)) {
215 try { fs.writeSync(1, line + '\n'); }
216 catch (e) { stream.emit('error', e) }
217 }
218 else {
219 try { console.log(line) }
220 catch (e) { stream.emit('error', e) }
221 }
222 line = '';
223 }
224};
225
226}).call(this,require('_process'))
227},{"_process":24,"fs":15,"through":13}],4:[function(require,module,exports){
228(function (process){
229var EventEmitter = require('events').EventEmitter;
230var inherits = require('inherits');
231var through = require('through');
232var resumer = require('resumer');
233var inspect = require('object-inspect');
234var nextTick = typeof setImmediate !== 'undefined'
235 ? setImmediate
236 : process.nextTick
237;
238
239module.exports = Results;
240inherits(Results, EventEmitter);
241
242function Results () {
243 if (!(this instanceof Results)) return new Results;
244 this.count = 0;
245 this.fail = 0;
246 this.pass = 0;
247 this._stream = through();
248 this.tests = [];
249}
250
251Results.prototype.createStream = function (opts) {
252 if (!opts) opts = {};
253 var self = this;
254 var output, testId = 0;
255 if (opts.objectMode) {
256 output = through();
257 self.on('_push', function ontest (t, extra) {
258 if (!extra) extra = {};
259 var id = testId++;
260 t.once('prerun', function () {
261 var row = {
262 type: 'test',
263 name: t.name,
264 id: id
265 };
266 if (has(extra, 'parent')) {
267 row.parent = extra.parent;
268 }
269 output.queue(row);
270 });
271 t.on('test', function (st) {
272 ontest(st, { parent: id });
273 });
274 t.on('result', function (res) {
275 res.test = id;
276 res.type = 'assert';
277 output.queue(res);
278 });
279 t.on('end', function () {
280 output.queue({ type: 'end', test: id });
281 });
282 });
283 self.on('done', function () { output.queue(null) });
284 }
285 else {
286 output = resumer();
287 output.queue('TAP version 13\n');
288 self._stream.pipe(output);
289 }
290
291 nextTick(function next() {
292 var t;
293 while (t = getNextTest(self)) {
294 t.run();
295 if (!t.ended) return t.once('end', function(){ nextTick(next); });
296 }
297 self.emit('done');
298 });
299
300 return output;
301};
302
303Results.prototype.push = function (t) {
304 var self = this;
305 self.tests.push(t);
306 self._watch(t);
307 self.emit('_push', t);
308};
309
310Results.prototype.only = function (name) {
311 if (this._only) {
312 self.count ++;
313 self.fail ++;
314 write('not ok ' + self.count + ' already called .only()\n');
315 }
316 this._only = name;
317};
318
319Results.prototype._watch = function (t) {
320 var self = this;
321 var write = function (s) { self._stream.queue(s) };
322 t.once('prerun', function () {
323 write('# ' + t.name + '\n');
324 });
325
326 t.on('result', function (res) {
327 if (typeof res === 'string') {
328 write('# ' + res + '\n');
329 return;
330 }
331 write(encodeResult(res, self.count + 1));
332 self.count ++;
333
334 if (res.ok) self.pass ++
335 else self.fail ++
336 });
337
338 t.on('test', function (st) { self._watch(st) });
339};
340
341Results.prototype.close = function () {
342 var self = this;
343 if (self.closed) self._stream.emit('error', new Error('ALREADY CLOSED'));
344 self.closed = true;
345 var write = function (s) { self._stream.queue(s) };
346
347 write('\n1..' + self.count + '\n');
348 write('# tests ' + self.count + '\n');
349 write('# pass ' + self.pass + '\n');
350 if (self.fail) write('# fail ' + self.fail + '\n')
351 else write('\n# ok\n')
352
353 self._stream.queue(null);
354};
355
356function encodeResult (res, count) {
357 var output = '';
358 output += (res.ok ? 'ok ' : 'not ok ') + count;
359 output += res.name ? ' ' + res.name.toString().replace(/\s+/g, ' ') : '';
360
361 if (res.skip) output += ' # SKIP';
362 else if (res.todo) output += ' # TODO';
363
364 output += '\n';
365 if (res.ok) return output;
366
367 var outer = ' ';
368 var inner = outer + ' ';
369 output += outer + '---\n';
370 output += inner + 'operator: ' + res.operator + '\n';
371
372 if (has(res, 'expected') || has(res, 'actual')) {
373 var ex = inspect(res.expected);
374 var ac = inspect(res.actual);
375
376 if (Math.max(ex.length, ac.length) > 65) {
377 output += inner + 'expected:\n' + inner + ' ' + ex + '\n';
378 output += inner + 'actual:\n' + inner + ' ' + ac + '\n';
379 }
380 else {
381 output += inner + 'expected: ' + ex + '\n';
382 output += inner + 'actual: ' + ac + '\n';
383 }
384 }
385 if (res.at) {
386 output += inner + 'at: ' + res.at + '\n';
387 }
388 if (res.operator === 'error' && res.actual && res.actual.stack) {
389 var lines = String(res.actual.stack).split('\n');
390 output += inner + 'stack:\n';
391 output += inner + ' ' + lines[0] + '\n';
392 for (var i = 1; i < lines.length; i++) {
393 output += inner + lines[i] + '\n';
394 }
395 }
396
397 output += outer + '...\n';
398 return output;
399}
400
401function getNextTest (results) {
402 if (!results._only) {
403 return results.tests.shift();
404 }
405
406 do {
407 var t = results.tests.shift();
408 if (!t) continue;
409 if (results._only === t.name) {
410 return t;
411 }
412 } while (results.tests.length !== 0)
413}
414
415function has (obj, prop) {
416 return Object.prototype.hasOwnProperty.call(obj, prop);
417}
418
419}).call(this,require('_process'))
420},{"_process":24,"events":20,"inherits":10,"object-inspect":11,"resumer":12,"through":13}],5:[function(require,module,exports){
421(function (process,__dirname){
422var deepEqual = require('deep-equal');
423var defined = require('defined');
424var path = require('path');
425var inherits = require('inherits');
426var EventEmitter = require('events').EventEmitter;
427
428module.exports = Test;
429
430var nextTick = typeof setImmediate !== 'undefined'
431 ? setImmediate
432 : process.nextTick
433;
434
435inherits(Test, EventEmitter);
436
437var getTestArgs = function (name_, opts_, cb_) {
438 var name = '(anonymous)';
439 var opts = {};
440 var cb;
441
442 for (var i = 0; i < arguments.length; i++) {
443 var arg = arguments[i];
444 var t = typeof arg;
445 if (t === 'string') {
446 name = arg;
447 }
448 else if (t === 'object') {
449 opts = arg || opts;
450 }
451 else if (t === 'function') {
452 cb = arg;
453 }
454 }
455 return { name: name, opts: opts, cb: cb };
456};
457
458function Test (name_, opts_, cb_) {
459 if (! (this instanceof Test)) {
460 return new Test(name_, opts_, cb_);
461 }
462
463 var args = getTestArgs(name_, opts_, cb_);
464
465 this.readable = true;
466 this.name = args.name || '(anonymous)';
467 this.assertCount = 0;
468 this.pendingCount = 0;
469 this._skip = args.opts.skip || false;
470 this._plan = undefined;
471 this._cb = args.cb;
472 this._progeny = [];
473 this._ok = true;
474
475 if (args.opts.timeout !== undefined) {
476 this.timeoutAfter(args.opts.timeout);
477 }
478
479 for (var prop in this) {
480 this[prop] = (function bind(self, val) {
481 if (typeof val === 'function') {
482 return function bound() {
483 return val.apply(self, arguments);
484 };
485 }
486 else return val;
487 })(this, this[prop]);
488 }
489}
490
491Test.prototype.run = function () {
492 if (!this._cb || this._skip) {
493 return this._end();
494 }
495 this.emit('prerun');
496 this._cb(this);
497 this.emit('run');
498};
499
500Test.prototype.test = function (name, opts, cb) {
501 var self = this;
502 var t = new Test(name, opts, cb);
503 this._progeny.push(t);
504 this.pendingCount++;
505 this.emit('test', t);
506 t.on('prerun', function () {
507 self.assertCount++;
508 })
509
510 if (!self._pendingAsserts()) {
511 nextTick(function () {
512 self._end();
513 });
514 }
515
516 nextTick(function() {
517 if (!self._plan && self.pendingCount == self._progeny.length) {
518 self._end();
519 }
520 });
521};
522
523Test.prototype.comment = function (msg) {
524 this.emit('result', msg.trim().replace(/^#\s*/, ''));
525};
526
527Test.prototype.plan = function (n) {
528 this._plan = n;
529 this.emit('plan', n);
530};
531
532Test.prototype.timeoutAfter = function(ms) {
533 if (!ms) throw new Error('timeoutAfter requires a timespan');
534 var self = this;
535 var timeout = setTimeout(function() {
536 self.fail('test timed out after ' + ms + 'ms');
537 self.end();
538 }, ms);
539 this.once('end', function() {
540 clearTimeout(timeout);
541 });
542}
543
544Test.prototype.end = function (err) {
545 var self = this;
546 if (arguments.length >= 1) {
547 this.ifError(err);
548 }
549
550 if (this.calledEnd) {
551 this.fail('.end() called twice');
552 }
553 this.calledEnd = true;
554 this._end();
555};
556
557Test.prototype._end = function (err) {
558 var self = this;
559 if (this._progeny.length) {
560 var t = this._progeny.shift();
561 t.on('end', function () { self._end() });
562 t.run();
563 return;
564 }
565
566 if (!this.ended) this.emit('end');
567 var pendingAsserts = this._pendingAsserts();
568 if (!this._planError && this._plan !== undefined && pendingAsserts) {
569 this._planError = true;
570 this.fail('plan != count', {
571 expected : this._plan,
572 actual : this.assertCount
573 });
574 }
575 this.ended = true;
576};
577
578Test.prototype._exit = function () {
579 if (this._plan !== undefined &&
580 !this._planError && this.assertCount !== this._plan) {
581 this._planError = true;
582 this.fail('plan != count', {
583 expected : this._plan,
584 actual : this.assertCount,
585 exiting : true
586 });
587 }
588 else if (!this.ended) {
589 this.fail('test exited without ending', {
590 exiting: true
591 });
592 }
593};
594
595Test.prototype._pendingAsserts = function () {
596 if (this._plan === undefined) {
597 return 1;
598 }
599 else {
600 return this._plan - (this._progeny.length + this.assertCount);
601 }
602};
603
604Test.prototype._assert = function assert (ok, opts) {
605 var self = this;
606 var extra = opts.extra || {};
607
608 var res = {
609 id : self.assertCount ++,
610 ok : Boolean(ok),
611 skip : defined(extra.skip, opts.skip),
612 name : defined(extra.message, opts.message, '(unnamed assert)'),
613 operator : defined(extra.operator, opts.operator)
614 };
615 if (has(opts, 'actual') || has(extra, 'actual')) {
616 res.actual = defined(extra.actual, opts.actual);
617 }
618 if (has(opts, 'expected') || has(extra, 'expected')) {
619 res.expected = defined(extra.expected, opts.expected);
620 }
621 this._ok = Boolean(this._ok && ok);
622
623 if (!ok) {
624 res.error = defined(extra.error, opts.error, new Error(res.name));
625 }
626
627 if (!ok) {
628 var e = new Error('exception');
629 var err = (e.stack || '').split('\n');
630 var dir = path.dirname(__dirname) + '/';
631
632 for (var i = 0; i < err.length; i++) {
633 var m = /^[^\s]*\s*\bat\s+(.+)/.exec(err[i]);
634 if (!m) {
635 continue;
636 }
637
638 var s = m[1].split(/\s+/);
639 var filem = /(\/[^:\s]+:(\d+)(?::(\d+))?)/.exec(s[1]);
640 if (!filem) {
641 filem = /(\/[^:\s]+:(\d+)(?::(\d+))?)/.exec(s[2]);
642
643 if (!filem) {
644 filem = /(\/[^:\s]+:(\d+)(?::(\d+))?)/.exec(s[3]);
645
646 if (!filem) {
647 continue;
648 }
649 }
650 }
651
652 if (filem[1].slice(0, dir.length) === dir) {
653 continue;
654 }
655
656 res.functionName = s[0];
657 res.file = filem[1];
658 res.line = Number(filem[2]);
659 if (filem[3]) res.column = filem[3];
660
661 res.at = m[1];
662 break;
663 }
664 }
665
666 self.emit('result', res);
667
668 var pendingAsserts = self._pendingAsserts();
669 if (!pendingAsserts) {
670 if (extra.exiting) {
671 self._end();
672 } else {
673 nextTick(function () {
674 self._end();
675 });
676 }
677 }
678
679 if (!self._planError && pendingAsserts < 0) {
680 self._planError = true;
681 self.fail('plan != count', {
682 expected : self._plan,
683 actual : self._plan - pendingAsserts
684 });
685 }
686};
687
688Test.prototype.fail = function (msg, extra) {
689 this._assert(false, {
690 message : msg,
691 operator : 'fail',
692 extra : extra
693 });
694};
695
696Test.prototype.pass = function (msg, extra) {
697 this._assert(true, {
698 message : msg,
699 operator : 'pass',
700 extra : extra
701 });
702};
703
704Test.prototype.skip = function (msg, extra) {
705 this._assert(true, {
706 message : msg,
707 operator : 'skip',
708 skip : true,
709 extra : extra
710 });
711};
712
713Test.prototype.ok
714= Test.prototype['true']
715= Test.prototype.assert
716= function (value, msg, extra) {
717 this._assert(value, {
718 message : msg,
719 operator : 'ok',
720 expected : true,
721 actual : value,
722 extra : extra
723 });
724};
725
726Test.prototype.notOk
727= Test.prototype['false']
728= Test.prototype.notok
729= function (value, msg, extra) {
730 this._assert(!value, {
731 message : msg,
732 operator : 'notOk',
733 expected : false,
734 actual : value,
735 extra : extra
736 });
737};
738
739Test.prototype.error
740= Test.prototype.ifError
741= Test.prototype.ifErr
742= Test.prototype.iferror
743= function (err, msg, extra) {
744 this._assert(!err, {
745 message : defined(msg, String(err)),
746 operator : 'error',
747 actual : err,
748 extra : extra
749 });
750};
751
752Test.prototype.equal
753= Test.prototype.equals
754= Test.prototype.isEqual
755= Test.prototype.is
756= Test.prototype.strictEqual
757= Test.prototype.strictEquals
758= function (a, b, msg, extra) {
759 this._assert(a === b, {
760 message : defined(msg, 'should be equal'),
761 operator : 'equal',
762 actual : a,
763 expected : b,
764 extra : extra
765 });
766};
767
768Test.prototype.notEqual
769= Test.prototype.notEquals
770= Test.prototype.notStrictEqual
771= Test.prototype.notStrictEquals
772= Test.prototype.isNotEqual
773= Test.prototype.isNot
774= Test.prototype.not
775= Test.prototype.doesNotEqual
776= Test.prototype.isInequal
777= function (a, b, msg, extra) {
778 this._assert(a !== b, {
779 message : defined(msg, 'should not be equal'),
780 operator : 'notEqual',
781 actual : a,
782 notExpected : b,
783 extra : extra
784 });
785};
786
787Test.prototype.deepEqual
788= Test.prototype.deepEquals
789= Test.prototype.isEquivalent
790= Test.prototype.same
791= function (a, b, msg, extra) {
792 this._assert(deepEqual(a, b, { strict: true }), {
793 message : defined(msg, 'should be equivalent'),
794 operator : 'deepEqual',
795 actual : a,
796 expected : b,
797 extra : extra
798 });
799};
800
801Test.prototype.deepLooseEqual
802= Test.prototype.looseEqual
803= Test.prototype.looseEquals
804= function (a, b, msg, extra) {
805 this._assert(deepEqual(a, b), {
806 message : defined(msg, 'should be equivalent'),
807 operator : 'deepLooseEqual',
808 actual : a,
809 expected : b,
810 extra : extra
811 });
812};
813
814Test.prototype.notDeepEqual
815= Test.prototype.notEquivalent
816= Test.prototype.notDeeply
817= Test.prototype.notSame
818= Test.prototype.isNotDeepEqual
819= Test.prototype.isNotDeeply
820= Test.prototype.isNotEquivalent
821= Test.prototype.isInequivalent
822= function (a, b, msg, extra) {
823 this._assert(!deepEqual(a, b, { strict: true }), {
824 message : defined(msg, 'should not be equivalent'),
825 operator : 'notDeepEqual',
826 actual : a,
827 notExpected : b,
828 extra : extra
829 });
830};
831
832Test.prototype.notDeepLooseEqual
833= Test.prototype.notLooseEqual
834= Test.prototype.notLooseEquals
835= function (a, b, msg, extra) {
836 this._assert(!deepEqual(a, b), {
837 message : defined(msg, 'should be equivalent'),
838 operator : 'notDeepLooseEqual',
839 actual : a,
840 expected : b,
841 extra : extra
842 });
843};
844
845Test.prototype['throws'] = function (fn, expected, msg, extra) {
846 if (typeof expected === 'string') {
847 msg = expected;
848 expected = undefined;
849 }
850
851 var caught = undefined;
852
853 try {
854 fn();
855 } catch (err) {
856 caught = { error : err };
857 var message = err.message;
858 delete err.message;
859 err.message = message;
860 }
861
862 var passed = caught;
863
864 if (expected instanceof RegExp) {
865 passed = expected.test(caught && caught.error);
866 expected = String(expected);
867 }
868
869 if (typeof expected === 'function') {
870 passed = caught.error instanceof expected;
871 caught.error = caught.error.constructor;
872 }
873
874 this._assert(passed, {
875 message : defined(msg, 'should throw'),
876 operator : 'throws',
877 actual : caught && caught.error,
878 expected : expected,
879 error: !passed && caught && caught.error,
880 extra : extra
881 });
882};
883
884Test.prototype.doesNotThrow = function (fn, expected, msg, extra) {
885 if (typeof expected === 'string') {
886 msg = expected;
887 expected = undefined;
888 }
889 var caught = undefined;
890 try {
891 fn();
892 }
893 catch (err) {
894 caught = { error : err };
895 }
896 this._assert(!caught, {
897 message : defined(msg, 'should not throw'),
898 operator : 'throws',
899 actual : caught && caught.error,
900 expected : expected,
901 error : caught && caught.error,
902 extra : extra
903 });
904};
905
906function has (obj, prop) {
907 return Object.prototype.hasOwnProperty.call(obj, prop);
908}
909
910Test.skip = function (name_, _opts, _cb) {
911 var args = getTestArgs.apply(null, arguments);
912 args.opts.skip = true;
913 return Test(args.name, args.opts, args.cb);
914};
915
916// vim: set softtabstop=4 shiftwidth=4:
917
918
919}).call(this,require('_process'),"/node_modules/tape/lib")
920},{"_process":24,"deep-equal":6,"defined":9,"events":20,"inherits":10,"path":23}],6:[function(require,module,exports){
921var pSlice = Array.prototype.slice;
922var objectKeys = require('./lib/keys.js');
923var isArguments = require('./lib/is_arguments.js');
924
925var deepEqual = module.exports = function (actual, expected, opts) {
926 if (!opts) opts = {};
927 // 7.1. All identical values are equivalent, as determined by ===.
928 if (actual === expected) {
929 return true;
930
931 } else if (actual instanceof Date && expected instanceof Date) {
932 return actual.getTime() === expected.getTime();
933
934 // 7.3. Other pairs that do not both pass typeof value == 'object',
935 // equivalence is determined by ==.
936 } else if (typeof actual != 'object' && typeof expected != 'object') {
937 return opts.strict ? actual === expected : actual == expected;
938
939 // 7.4. For all other Object pairs, including Array objects, equivalence is
940 // determined by having the same number of owned properties (as verified
941 // with Object.prototype.hasOwnProperty.call), the same set of keys
942 // (although not necessarily the same order), equivalent values for every
943 // corresponding key, and an identical 'prototype' property. Note: this
944 // accounts for both named and indexed properties on Arrays.
945 } else {
946 return objEquiv(actual, expected, opts);
947 }
948}
949
950function isUndefinedOrNull(value) {
951 return value === null || value === undefined;
952}
953
954function isBuffer (x) {
955 if (!x || typeof x !== 'object' || typeof x.length !== 'number') return false;
956 if (typeof x.copy !== 'function' || typeof x.slice !== 'function') {
957 return false;
958 }
959 if (x.length > 0 && typeof x[0] !== 'number') return false;
960 return true;
961}
962
963function objEquiv(a, b, opts) {
964 var i, key;
965 if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
966 return false;
967 // an identical 'prototype' property.
968 if (a.prototype !== b.prototype) return false;
969 //~~~I've managed to break Object.keys through screwy arguments passing.
970 // Converting to array solves the problem.
971 if (isArguments(a)) {
972 if (!isArguments(b)) {
973 return false;
974 }
975 a = pSlice.call(a);
976 b = pSlice.call(b);
977 return deepEqual(a, b, opts);
978 }
979 if (isBuffer(a)) {
980 if (!isBuffer(b)) {
981 return false;
982 }
983 if (a.length !== b.length) return false;
984 for (i = 0; i < a.length; i++) {
985 if (a[i] !== b[i]) return false;
986 }
987 return true;
988 }
989 try {
990 var ka = objectKeys(a),
991 kb = objectKeys(b);
992 } catch (e) {//happens when one is a string literal and the other isn't
993 return false;
994 }
995 // having the same number of owned properties (keys incorporates
996 // hasOwnProperty)
997 if (ka.length != kb.length)
998 return false;
999 //the same set of keys (although not necessarily the same order),
1000 ka.sort();
1001 kb.sort();
1002 //~~~cheap key test
1003 for (i = ka.length - 1; i >= 0; i--) {
1004 if (ka[i] != kb[i])
1005 return false;
1006 }
1007 //equivalent values for every corresponding key, and
1008 //~~~possibly expensive deep test
1009 for (i = ka.length - 1; i >= 0; i--) {
1010 key = ka[i];
1011 if (!deepEqual(a[key], b[key], opts)) return false;
1012 }
1013 return typeof a === typeof b;
1014}
1015
1016},{"./lib/is_arguments.js":7,"./lib/keys.js":8}],7:[function(require,module,exports){
1017var supportsArgumentsClass = (function(){
1018 return Object.prototype.toString.call(arguments)
1019})() == '[object Arguments]';
1020
1021exports = module.exports = supportsArgumentsClass ? supported : unsupported;
1022
1023exports.supported = supported;
1024function supported(object) {
1025 return Object.prototype.toString.call(object) == '[object Arguments]';
1026};
1027
1028exports.unsupported = unsupported;
1029function unsupported(object){
1030 return object &&
1031 typeof object == 'object' &&
1032 typeof object.length == 'number' &&
1033 Object.prototype.hasOwnProperty.call(object, 'callee') &&
1034 !Object.prototype.propertyIsEnumerable.call(object, 'callee') ||
1035 false;
1036};
1037
1038},{}],8:[function(require,module,exports){
1039exports = module.exports = typeof Object.keys === 'function'
1040 ? Object.keys : shim;
1041
1042exports.shim = shim;
1043function shim (obj) {
1044 var keys = [];
1045 for (var key in obj) keys.push(key);
1046 return keys;
1047}
1048
1049},{}],9:[function(require,module,exports){
1050module.exports = function () {
1051 for (var i = 0; i < arguments.length; i++) {
1052 if (arguments[i] !== undefined) return arguments[i];
1053 }
1054};
1055
1056},{}],10:[function(require,module,exports){
1057if (typeof Object.create === 'function') {
1058 // implementation from standard node.js 'util' module
1059 module.exports = function inherits(ctor, superCtor) {
1060 ctor.super_ = superCtor
1061 ctor.prototype = Object.create(superCtor.prototype, {
1062 constructor: {
1063 value: ctor,
1064 enumerable: false,
1065 writable: true,
1066 configurable: true
1067 }
1068 });
1069 };
1070} else {
1071 // old school shim for old browsers
1072 module.exports = function inherits(ctor, superCtor) {
1073 ctor.super_ = superCtor
1074 var TempCtor = function () {}
1075 TempCtor.prototype = superCtor.prototype
1076 ctor.prototype = new TempCtor()
1077 ctor.prototype.constructor = ctor
1078 }
1079}
1080
1081},{}],11:[function(require,module,exports){
1082module.exports = function inspect_ (obj, opts, depth, seen) {
1083 if (!opts) opts = {};
1084
1085 var maxDepth = opts.depth === undefined ? 5 : opts.depth;
1086 if (depth === undefined) depth = 0;
1087 if (depth > maxDepth && maxDepth > 0) return '...';
1088
1089 if (seen === undefined) seen = [];
1090 else if (indexOf(seen, obj) >= 0) {
1091 return '[Circular]';
1092 }
1093
1094 function inspect (value, from) {
1095 if (from) {
1096 seen = seen.slice();
1097 seen.push(from);
1098 }
1099 return inspect_(value, opts, depth + 1, seen);
1100 }
1101
1102 if (typeof obj === 'string') {
1103 return inspectString(obj);
1104 }
1105 else if (typeof obj === 'function') {
1106 var name = nameOf(obj);
1107 return '[Function' + (name ? ': ' + name : '') + ']';
1108 }
1109 else if (obj === null) {
1110 return 'null';
1111 }
1112 else if (isElement(obj)) {
1113 var s = '<' + String(obj.nodeName).toLowerCase();
1114 var attrs = obj.attributes || [];
1115 for (var i = 0; i < attrs.length; i++) {
1116 s += ' ' + attrs[i].name + '="' + quote(attrs[i].value) + '"';
1117 }
1118 s += '>';
1119 if (obj.childNodes && obj.childNodes.length) s += '...';
1120 s += '</' + String(obj.tagName).toLowerCase() + '>';
1121 return s;
1122 }
1123 else if (isArray(obj)) {
1124 if (obj.length === 0) return '[]';
1125 var xs = Array(obj.length);
1126 for (var i = 0; i < obj.length; i++) {
1127 xs[i] = has(obj, i) ? inspect(obj[i], obj) : '';
1128 }
1129 return '[ ' + xs.join(', ') + ' ]';
1130 }
1131 else if (typeof obj === 'object' && typeof obj.inspect === 'function') {
1132 return obj.inspect();
1133 }
1134 else if (typeof obj === 'object' && !isDate(obj) && !isRegExp(obj)) {
1135 var xs = [], keys = [];
1136 for (var key in obj) {
1137 if (has(obj, key)) keys.push(key);
1138 }
1139 keys.sort();
1140 for (var i = 0; i < keys.length; i++) {
1141 var key = keys[i];
1142 if (/[^\w$]/.test(key)) {
1143 xs.push(inspect(key) + ': ' + inspect(obj[key], obj));
1144 }
1145 else xs.push(key + ': ' + inspect(obj[key], obj));
1146 }
1147 if (xs.length === 0) return '{}';
1148 return '{ ' + xs.join(', ') + ' }';
1149 }
1150 else return String(obj);
1151};
1152
1153function quote (s) {
1154 return String(s).replace(/"/g, '&quot;');
1155}
1156
1157function isArray (obj) {
1158 return {}.toString.call(obj) === '[object Array]';
1159}
1160
1161function isDate (obj) {
1162 return {}.toString.call(obj) === '[object Date]';
1163}
1164
1165function isRegExp (obj) {
1166 return {}.toString.call(obj) === '[object RegExp]';
1167}
1168
1169function has (obj, key) {
1170 if (!{}.hasOwnProperty) return key in obj;
1171 return {}.hasOwnProperty.call(obj, key);
1172}
1173
1174function nameOf (f) {
1175 if (f.name) return f.name;
1176 var m = f.toString().match(/^function\s*([\w$]+)/);
1177 if (m) return m[1];
1178}
1179
1180function indexOf (xs, x) {
1181 if (xs.indexOf) return xs.indexOf(x);
1182 for (var i = 0, l = xs.length; i < l; i++) {
1183 if (xs[i] === x) return i;
1184 }
1185 return -1;
1186}
1187
1188function isElement (x) {
1189 if (!x || typeof x !== 'object') return false;
1190 if (typeof HTMLElement !== 'undefined') {
1191 return x instanceof HTMLElement;
1192 }
1193 else return typeof x.nodeName === 'string'
1194 && typeof x.getAttribute === 'function'
1195 ;
1196}
1197
1198function inspectString (str) {
1199 var s = str.replace(/(['\\])/g, '\\$1').replace(/[\x00-\x1f]/g, lowbyte);
1200 return "'" + s + "'";
1201
1202 function lowbyte (c) {
1203 var n = c.charCodeAt(0);
1204 var x = { 8: 'b', 9: 't', 10: 'n', 12: 'f', 13: 'r' }[n];
1205 if (x) return '\\' + x;
1206 return '\\x' + (n < 0x10 ? '0' : '') + n.toString(16);
1207 }
1208}
1209
1210},{}],12:[function(require,module,exports){
1211(function (process){
1212var through = require('through');
1213var nextTick = typeof setImmediate !== 'undefined'
1214 ? setImmediate
1215 : process.nextTick
1216;
1217
1218module.exports = function (write, end) {
1219 var tr = through(write, end);
1220 tr.pause();
1221 var resume = tr.resume;
1222 var pause = tr.pause;
1223 var paused = false;
1224
1225 tr.pause = function () {
1226 paused = true;
1227 return pause.apply(this, arguments);
1228 };
1229
1230 tr.resume = function () {
1231 paused = false;
1232 return resume.apply(this, arguments);
1233 };
1234
1235 nextTick(function () {
1236 if (!paused) tr.resume();
1237 });
1238
1239 return tr;
1240};
1241
1242}).call(this,require('_process'))
1243},{"_process":24,"through":13}],13:[function(require,module,exports){
1244(function (process){
1245var Stream = require('stream')
1246
1247// through
1248//
1249// a stream that does nothing but re-emit the input.
1250// useful for aggregating a series of changing but not ending streams into one stream)
1251
1252exports = module.exports = through
1253through.through = through
1254
1255//create a readable writable stream.
1256
1257function through (write, end, opts) {
1258 write = write || function (data) { this.queue(data) }
1259 end = end || function () { this.queue(null) }
1260
1261 var ended = false, destroyed = false, buffer = [], _ended = false
1262 var stream = new Stream()
1263 stream.readable = stream.writable = true
1264 stream.paused = false
1265
1266// stream.autoPause = !(opts && opts.autoPause === false)
1267 stream.autoDestroy = !(opts && opts.autoDestroy === false)
1268
1269 stream.write = function (data) {
1270 write.call(this, data)
1271 return !stream.paused
1272 }
1273
1274 function drain() {
1275 while(buffer.length && !stream.paused) {
1276 var data = buffer.shift()
1277 if(null === data)
1278 return stream.emit('end')
1279 else
1280 stream.emit('data', data)
1281 }
1282 }
1283
1284 stream.queue = stream.push = function (data) {
1285// console.error(ended)
1286 if(_ended) return stream
1287 if(data == null) _ended = true
1288 buffer.push(data)
1289 drain()
1290 return stream
1291 }
1292
1293 //this will be registered as the first 'end' listener
1294 //must call destroy next tick, to make sure we're after any
1295 //stream piped from here.
1296 //this is only a problem if end is not emitted synchronously.
1297 //a nicer way to do this is to make sure this is the last listener for 'end'
1298
1299 stream.on('end', function () {
1300 stream.readable = false
1301 if(!stream.writable && stream.autoDestroy)
1302 process.nextTick(function () {
1303 stream.destroy()
1304 })
1305 })
1306
1307 function _end () {
1308 stream.writable = false
1309 end.call(stream)
1310 if(!stream.readable && stream.autoDestroy)
1311 stream.destroy()
1312 }
1313
1314 stream.end = function (data) {
1315 if(ended) return
1316 ended = true
1317 if(arguments.length) stream.write(data)
1318 _end() // will emit or queue
1319 return stream
1320 }
1321
1322 stream.destroy = function () {
1323 if(destroyed) return
1324 destroyed = true
1325 ended = true
1326 buffer.length = 0
1327 stream.writable = stream.readable = false
1328 stream.emit('close')
1329 return stream
1330 }
1331
1332 stream.pause = function () {
1333 if(stream.paused) return
1334 stream.paused = true
1335 return stream
1336 }
1337
1338 stream.resume = function () {
1339 if(stream.paused) {
1340 stream.paused = false
1341 stream.emit('resume')
1342 }
1343 drain()
1344 //may have become paused again,
1345 //as drain emits 'data'.
1346 if(!stream.paused)
1347 stream.emit('drain')
1348 return stream
1349 }
1350 return stream
1351}
1352
1353
1354}).call(this,require('_process'))
1355},{"_process":24,"stream":36}],14:[function(require,module,exports){
1356var test = require('tape');
1357var rifraf = require('../index');
1358
1359function get5() {
1360 var i = 0;
1361 var l = 5;
1362 var set = [];
1363 for (; i < l; i++) {
1364 set.push({index: i});
1365 }
1366 return set;
1367}
1368
1369if (rifraf.isNative) {
1370 test('request defers approximately 16ms by default', function (t) {
1371 t.plan(7);
1372 rifraf.request(function (start) {
1373 var set = get5();
1374 var i = 0;
1375
1376 function tick(dt) {
1377 var item = set[i++];
1378 item.time = dt;
1379 t.ok((dt - start) >= 0, 'time has passed: ' + (dt - start));
1380
1381 if (set[i]) {
1382 rifraf.request(tick);
1383 } else {
1384 t.ok((item.time - start) > 5 * 16, 'should take at least 5 (80ms) frames of clock time; actual: ' + (item.time - start));
1385 t.ok(set.every(function (item, index) {
1386 var next = set[index + 1];
1387 if (next) {
1388 return item.time < next.time;
1389 }
1390 return true;
1391 }), 'callbacks executed in order');
1392 t.end();
1393 }
1394 }
1395 rifraf.request(tick);
1396 });
1397 });
1398} else {
1399
1400 test('request defers approximately 8ms by default', function (t) {
1401 t.plan(2);
1402 var set = get5();
1403 var i = 0;
1404 var start = now();
1405
1406 function tick() {
1407 var item = set[i++];
1408 item.time = now();
1409
1410 if (item.index === 4) {
1411 t.ok((item.time - start) > 5 * 8, 'total time > 5 * 8ms; actual(' + (item.time - start) + ')');
1412 t.ok(set.every(function (item, index) {
1413 var next = set[index + 1];
1414 if (next) {
1415 return item.time < next.time;
1416 }
1417 return true;
1418 }), 'callbacks executed in order');
1419 t.end();
1420 }
1421
1422 if (set[i]) rifraf.request(tick);
1423 }
1424 rifraf.request(tick);
1425 });
1426
1427 test('request defers approximately 16ms when sync60Hz is called', function (t) {
1428 rifraf.sync60Hz();
1429 t.plan(2);
1430 var set = get5();
1431 var i = 0;
1432 var start = now();
1433
1434 function tick() {
1435 var item = set[i++];
1436 item.time = now();
1437 if (item.index === 4) {
1438 t.ok((item.time - start) > 5 * 16, 'total time > 5 * 16ms; actual(' + (item.time - start) + ')');
1439 t.ok(set.every(function (item, index) {
1440 var next = set[index + 1];
1441 if (next) {
1442 return item.time < next.time;
1443 }
1444 return true;
1445 }), 'callbacks executed in order');
1446 t.end();
1447 }
1448
1449 if (set[i]) rifraf.request(tick);
1450 }
1451 rifraf.request(tick);
1452 });
1453
1454 test('request defers approximately 33ms when sync30Hz is called', function (t) {
1455 rifraf.sync30Hz();
1456 t.plan(2);
1457 var set = get5();
1458 var i = 0;
1459 var start = now();
1460
1461 function tick() {
1462 var item = set[i++];
1463 item.time = now();
1464 if (item.index === 4) {
1465 t.ok((item.time - start) > 5 * 33, 'total time > 5 * 33ms; actual(' + (item.time - start) + ')');
1466 t.ok(set.every(function (item, index) {
1467 var next = set[index + 1];
1468 if (next) {
1469 return item.time < next.time;
1470 }
1471 return true;
1472 }), 'callbacks executed in order');
1473 t.end();
1474 }
1475
1476 if (set[i]) rifraf.request(tick);
1477 }
1478 rifraf.request(tick);
1479 });
1480}
1481
1482test('callbacks can be cancelled', function (t) {
1483
1484 function one() { one.called = true; }
1485 function two() { two.called = true; }
1486 function three() { three.called = true; }
1487
1488 one.handle = rifraf.request(one);
1489 two.handle = rifraf.request(two);
1490 three.handle = rifraf.request(three);
1491
1492 t.ok([one, two, three].every(function (fn) {
1493 return fn.handle;
1494 }), 'rifraf.request returns a handle');
1495
1496 rifraf.cancel(two.handle);
1497
1498 rifraf.request(function () {
1499 t.ok(one.called, 'callback one was called');
1500 t.notOk(two.called, 'callback two was not called');
1501 t.ok(three.called, 'callback three was called');
1502 t.end();
1503 });
1504});
1505},{"../index":1,"tape":2}],15:[function(require,module,exports){
1506
1507},{}],16:[function(require,module,exports){
1508/*!
1509 * The buffer module from node.js, for the browser.
1510 *
1511 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
1512 * @license MIT
1513 */
1514
1515var base64 = require('base64-js')
1516var ieee754 = require('ieee754')
1517var isArray = require('is-array')
1518
1519exports.Buffer = Buffer
1520exports.SlowBuffer = Buffer
1521exports.INSPECT_MAX_BYTES = 50
1522Buffer.poolSize = 8192 // not used by this implementation
1523
1524var kMaxLength = 0x3fffffff
1525
1526/**
1527 * If `Buffer.TYPED_ARRAY_SUPPORT`:
1528 * === true Use Uint8Array implementation (fastest)
1529 * === false Use Object implementation (most compatible, even IE6)
1530 *
1531 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
1532 * Opera 11.6+, iOS 4.2+.
1533 *
1534 * Note:
1535 *
1536 * - Implementation must support adding new properties to `Uint8Array` instances.
1537 * Firefox 4-29 lacked support, fixed in Firefox 30+.
1538 * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
1539 *
1540 * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
1541 *
1542 * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
1543 * incorrect length in some situations.
1544 *
1545 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will
1546 * get the Object implementation, which is slower but will work correctly.
1547 */
1548Buffer.TYPED_ARRAY_SUPPORT = (function () {
1549 try {
1550 var buf = new ArrayBuffer(0)
1551 var arr = new Uint8Array(buf)
1552 arr.foo = function () { return 42 }
1553 return 42 === arr.foo() && // typed array instances can be augmented
1554 typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
1555 new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
1556 } catch (e) {
1557 return false
1558 }
1559})()
1560
1561/**
1562 * Class: Buffer
1563 * =============
1564 *
1565 * The Buffer constructor returns instances of `Uint8Array` that are augmented
1566 * with function properties for all the node `Buffer` API functions. We use
1567 * `Uint8Array` so that square bracket notation works as expected -- it returns
1568 * a single octet.
1569 *
1570 * By augmenting the instances, we can avoid modifying the `Uint8Array`
1571 * prototype.
1572 */
1573function Buffer (subject, encoding, noZero) {
1574 if (!(this instanceof Buffer))
1575 return new Buffer(subject, encoding, noZero)
1576
1577 var type = typeof subject
1578
1579 // Find the length
1580 var length
1581 if (type === 'number')
1582 length = subject > 0 ? subject >>> 0 : 0
1583 else if (type === 'string') {
1584 if (encoding === 'base64')
1585 subject = base64clean(subject)
1586 length = Buffer.byteLength(subject, encoding)
1587 } else if (type === 'object' && subject !== null) { // assume object is array-like
1588 if (subject.type === 'Buffer' && isArray(subject.data))
1589 subject = subject.data
1590 length = +subject.length > 0 ? Math.floor(+subject.length) : 0
1591 } else
1592 throw new TypeError('must start with number, buffer, array or string')
1593
1594 if (this.length > kMaxLength)
1595 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
1596 'size: 0x' + kMaxLength.toString(16) + ' bytes')
1597
1598 var buf
1599 if (Buffer.TYPED_ARRAY_SUPPORT) {
1600 // Preferred: Return an augmented `Uint8Array` instance for best performance
1601 buf = Buffer._augment(new Uint8Array(length))
1602 } else {
1603 // Fallback: Return THIS instance of Buffer (created by `new`)
1604 buf = this
1605 buf.length = length
1606 buf._isBuffer = true
1607 }
1608
1609 var i
1610 if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') {
1611 // Speed optimization -- use set if we're copying from a typed array
1612 buf._set(subject)
1613 } else if (isArrayish(subject)) {
1614 // Treat array-ish objects as a byte array
1615 if (Buffer.isBuffer(subject)) {
1616 for (i = 0; i < length; i++)
1617 buf[i] = subject.readUInt8(i)
1618 } else {
1619 for (i = 0; i < length; i++)
1620 buf[i] = ((subject[i] % 256) + 256) % 256
1621 }
1622 } else if (type === 'string') {
1623 buf.write(subject, 0, encoding)
1624 } else if (type === 'number' && !Buffer.TYPED_ARRAY_SUPPORT && !noZero) {
1625 for (i = 0; i < length; i++) {
1626 buf[i] = 0
1627 }
1628 }
1629
1630 return buf
1631}
1632
1633Buffer.isBuffer = function (b) {
1634 return !!(b != null && b._isBuffer)
1635}
1636
1637Buffer.compare = function (a, b) {
1638 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b))
1639 throw new TypeError('Arguments must be Buffers')
1640
1641 var x = a.length
1642 var y = b.length
1643 for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {}
1644 if (i !== len) {
1645 x = a[i]
1646 y = b[i]
1647 }
1648 if (x < y) return -1
1649 if (y < x) return 1
1650 return 0
1651}
1652
1653Buffer.isEncoding = function (encoding) {
1654 switch (String(encoding).toLowerCase()) {
1655 case 'hex':
1656 case 'utf8':
1657 case 'utf-8':
1658 case 'ascii':
1659 case 'binary':
1660 case 'base64':
1661 case 'raw':
1662 case 'ucs2':
1663 case 'ucs-2':
1664 case 'utf16le':
1665 case 'utf-16le':
1666 return true
1667 default:
1668 return false
1669 }
1670}
1671
1672Buffer.concat = function (list, totalLength) {
1673 if (!isArray(list)) throw new TypeError('Usage: Buffer.concat(list[, length])')
1674
1675 if (list.length === 0) {
1676 return new Buffer(0)
1677 } else if (list.length === 1) {
1678 return list[0]
1679 }
1680
1681 var i
1682 if (totalLength === undefined) {
1683 totalLength = 0
1684 for (i = 0; i < list.length; i++) {
1685 totalLength += list[i].length
1686 }
1687 }
1688
1689 var buf = new Buffer(totalLength)
1690 var pos = 0
1691 for (i = 0; i < list.length; i++) {
1692 var item = list[i]
1693 item.copy(buf, pos)
1694 pos += item.length
1695 }
1696 return buf
1697}
1698
1699Buffer.byteLength = function (str, encoding) {
1700 var ret
1701 str = str + ''
1702 switch (encoding || 'utf8') {
1703 case 'ascii':
1704 case 'binary':
1705 case 'raw':
1706 ret = str.length
1707 break
1708 case 'ucs2':
1709 case 'ucs-2':
1710 case 'utf16le':
1711 case 'utf-16le':
1712 ret = str.length * 2
1713 break
1714 case 'hex':
1715 ret = str.length >>> 1
1716 break
1717 case 'utf8':
1718 case 'utf-8':
1719 ret = utf8ToBytes(str).length
1720 break
1721 case 'base64':
1722 ret = base64ToBytes(str).length
1723 break
1724 default:
1725 ret = str.length
1726 }
1727 return ret
1728}
1729
1730// pre-set for values that may exist in the future
1731Buffer.prototype.length = undefined
1732Buffer.prototype.parent = undefined
1733
1734// toString(encoding, start=0, end=buffer.length)
1735Buffer.prototype.toString = function (encoding, start, end) {
1736 var loweredCase = false
1737
1738 start = start >>> 0
1739 end = end === undefined || end === Infinity ? this.length : end >>> 0
1740
1741 if (!encoding) encoding = 'utf8'
1742 if (start < 0) start = 0
1743 if (end > this.length) end = this.length
1744 if (end <= start) return ''
1745
1746 while (true) {
1747 switch (encoding) {
1748 case 'hex':
1749 return hexSlice(this, start, end)
1750
1751 case 'utf8':
1752 case 'utf-8':
1753 return utf8Slice(this, start, end)
1754
1755 case 'ascii':
1756 return asciiSlice(this, start, end)
1757
1758 case 'binary':
1759 return binarySlice(this, start, end)
1760
1761 case 'base64':
1762 return base64Slice(this, start, end)
1763
1764 case 'ucs2':
1765 case 'ucs-2':
1766 case 'utf16le':
1767 case 'utf-16le':
1768 return utf16leSlice(this, start, end)
1769
1770 default:
1771 if (loweredCase)
1772 throw new TypeError('Unknown encoding: ' + encoding)
1773 encoding = (encoding + '').toLowerCase()
1774 loweredCase = true
1775 }
1776 }
1777}
1778
1779Buffer.prototype.equals = function (b) {
1780 if(!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
1781 return Buffer.compare(this, b) === 0
1782}
1783
1784Buffer.prototype.inspect = function () {
1785 var str = ''
1786 var max = exports.INSPECT_MAX_BYTES
1787 if (this.length > 0) {
1788 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
1789 if (this.length > max)
1790 str += ' ... '
1791 }
1792 return '<Buffer ' + str + '>'
1793}
1794
1795Buffer.prototype.compare = function (b) {
1796 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
1797 return Buffer.compare(this, b)
1798}
1799
1800// `get` will be removed in Node 0.13+
1801Buffer.prototype.get = function (offset) {
1802 console.log('.get() is deprecated. Access using array indexes instead.')
1803 return this.readUInt8(offset)
1804}
1805
1806// `set` will be removed in Node 0.13+
1807Buffer.prototype.set = function (v, offset) {
1808 console.log('.set() is deprecated. Access using array indexes instead.')
1809 return this.writeUInt8(v, offset)
1810}
1811
1812function hexWrite (buf, string, offset, length) {
1813 offset = Number(offset) || 0
1814 var remaining = buf.length - offset
1815 if (!length) {
1816 length = remaining
1817 } else {
1818 length = Number(length)
1819 if (length > remaining) {
1820 length = remaining
1821 }
1822 }
1823
1824 // must be an even number of digits
1825 var strLen = string.length
1826 if (strLen % 2 !== 0) throw new Error('Invalid hex string')
1827
1828 if (length > strLen / 2) {
1829 length = strLen / 2
1830 }
1831 for (var i = 0; i < length; i++) {
1832 var byte = parseInt(string.substr(i * 2, 2), 16)
1833 if (isNaN(byte)) throw new Error('Invalid hex string')
1834 buf[offset + i] = byte
1835 }
1836 return i
1837}
1838
1839function utf8Write (buf, string, offset, length) {
1840 var charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length)
1841 return charsWritten
1842}
1843
1844function asciiWrite (buf, string, offset, length) {
1845 var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length)
1846 return charsWritten
1847}
1848
1849function binaryWrite (buf, string, offset, length) {
1850 return asciiWrite(buf, string, offset, length)
1851}
1852
1853function base64Write (buf, string, offset, length) {
1854 var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length)
1855 return charsWritten
1856}
1857
1858function utf16leWrite (buf, string, offset, length) {
1859 var charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length)
1860 return charsWritten
1861}
1862
1863Buffer.prototype.write = function (string, offset, length, encoding) {
1864 // Support both (string, offset, length, encoding)
1865 // and the legacy (string, encoding, offset, length)
1866 if (isFinite(offset)) {
1867 if (!isFinite(length)) {
1868 encoding = length
1869 length = undefined
1870 }
1871 } else { // legacy
1872 var swap = encoding
1873 encoding = offset
1874 offset = length
1875 length = swap
1876 }
1877
1878 offset = Number(offset) || 0
1879 var remaining = this.length - offset
1880 if (!length) {
1881 length = remaining
1882 } else {
1883 length = Number(length)
1884 if (length > remaining) {
1885 length = remaining
1886 }
1887 }
1888 encoding = String(encoding || 'utf8').toLowerCase()
1889
1890 var ret
1891 switch (encoding) {
1892 case 'hex':
1893 ret = hexWrite(this, string, offset, length)
1894 break
1895 case 'utf8':
1896 case 'utf-8':
1897 ret = utf8Write(this, string, offset, length)
1898 break
1899 case 'ascii':
1900 ret = asciiWrite(this, string, offset, length)
1901 break
1902 case 'binary':
1903 ret = binaryWrite(this, string, offset, length)
1904 break
1905 case 'base64':
1906 ret = base64Write(this, string, offset, length)
1907 break
1908 case 'ucs2':
1909 case 'ucs-2':
1910 case 'utf16le':
1911 case 'utf-16le':
1912 ret = utf16leWrite(this, string, offset, length)
1913 break
1914 default:
1915 throw new TypeError('Unknown encoding: ' + encoding)
1916 }
1917 return ret
1918}
1919
1920Buffer.prototype.toJSON = function () {
1921 return {
1922 type: 'Buffer',
1923 data: Array.prototype.slice.call(this._arr || this, 0)
1924 }
1925}
1926
1927function base64Slice (buf, start, end) {
1928 if (start === 0 && end === buf.length) {
1929 return base64.fromByteArray(buf)
1930 } else {
1931 return base64.fromByteArray(buf.slice(start, end))
1932 }
1933}
1934
1935function utf8Slice (buf, start, end) {
1936 var res = ''
1937 var tmp = ''
1938 end = Math.min(buf.length, end)
1939
1940 for (var i = start; i < end; i++) {
1941 if (buf[i] <= 0x7F) {
1942 res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
1943 tmp = ''
1944 } else {
1945 tmp += '%' + buf[i].toString(16)
1946 }
1947 }
1948
1949 return res + decodeUtf8Char(tmp)
1950}
1951
1952function asciiSlice (buf, start, end) {
1953 var ret = ''
1954 end = Math.min(buf.length, end)
1955
1956 for (var i = start; i < end; i++) {
1957 ret += String.fromCharCode(buf[i])
1958 }
1959 return ret
1960}
1961
1962function binarySlice (buf, start, end) {
1963 return asciiSlice(buf, start, end)
1964}
1965
1966function hexSlice (buf, start, end) {
1967 var len = buf.length
1968
1969 if (!start || start < 0) start = 0
1970 if (!end || end < 0 || end > len) end = len
1971
1972 var out = ''
1973 for (var i = start; i < end; i++) {
1974 out += toHex(buf[i])
1975 }
1976 return out
1977}
1978
1979function utf16leSlice (buf, start, end) {
1980 var bytes = buf.slice(start, end)
1981 var res = ''
1982 for (var i = 0; i < bytes.length; i += 2) {
1983 res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
1984 }
1985 return res
1986}
1987
1988Buffer.prototype.slice = function (start, end) {
1989 var len = this.length
1990 start = ~~start
1991 end = end === undefined ? len : ~~end
1992
1993 if (start < 0) {
1994 start += len;
1995 if (start < 0)
1996 start = 0
1997 } else if (start > len) {
1998 start = len
1999 }
2000
2001 if (end < 0) {
2002 end += len
2003 if (end < 0)
2004 end = 0
2005 } else if (end > len) {
2006 end = len
2007 }
2008
2009 if (end < start)
2010 end = start
2011
2012 if (Buffer.TYPED_ARRAY_SUPPORT) {
2013 return Buffer._augment(this.subarray(start, end))
2014 } else {
2015 var sliceLen = end - start
2016 var newBuf = new Buffer(sliceLen, undefined, true)
2017 for (var i = 0; i < sliceLen; i++) {
2018 newBuf[i] = this[i + start]
2019 }
2020 return newBuf
2021 }
2022}
2023
2024/*
2025 * Need to make sure that buffer isn't trying to write out of bounds.
2026 */
2027function checkOffset (offset, ext, length) {
2028 if ((offset % 1) !== 0 || offset < 0)
2029 throw new RangeError('offset is not uint')
2030 if (offset + ext > length)
2031 throw new RangeError('Trying to access beyond buffer length')
2032}
2033
2034Buffer.prototype.readUInt8 = function (offset, noAssert) {
2035 if (!noAssert)
2036 checkOffset(offset, 1, this.length)
2037 return this[offset]
2038}
2039
2040Buffer.prototype.readUInt16LE = function (offset, noAssert) {
2041 if (!noAssert)
2042 checkOffset(offset, 2, this.length)
2043 return this[offset] | (this[offset + 1] << 8)
2044}
2045
2046Buffer.prototype.readUInt16BE = function (offset, noAssert) {
2047 if (!noAssert)
2048 checkOffset(offset, 2, this.length)
2049 return (this[offset] << 8) | this[offset + 1]
2050}
2051
2052Buffer.prototype.readUInt32LE = function (offset, noAssert) {
2053 if (!noAssert)
2054 checkOffset(offset, 4, this.length)
2055
2056 return ((this[offset]) |
2057 (this[offset + 1] << 8) |
2058 (this[offset + 2] << 16)) +
2059 (this[offset + 3] * 0x1000000)
2060}
2061
2062Buffer.prototype.readUInt32BE = function (offset, noAssert) {
2063 if (!noAssert)
2064 checkOffset(offset, 4, this.length)
2065
2066 return (this[offset] * 0x1000000) +
2067 ((this[offset + 1] << 16) |
2068 (this[offset + 2] << 8) |
2069 this[offset + 3])
2070}
2071
2072Buffer.prototype.readInt8 = function (offset, noAssert) {
2073 if (!noAssert)
2074 checkOffset(offset, 1, this.length)
2075 if (!(this[offset] & 0x80))
2076 return (this[offset])
2077 return ((0xff - this[offset] + 1) * -1)
2078}
2079
2080Buffer.prototype.readInt16LE = function (offset, noAssert) {
2081 if (!noAssert)
2082 checkOffset(offset, 2, this.length)
2083 var val = this[offset] | (this[offset + 1] << 8)
2084 return (val & 0x8000) ? val | 0xFFFF0000 : val
2085}
2086
2087Buffer.prototype.readInt16BE = function (offset, noAssert) {
2088 if (!noAssert)
2089 checkOffset(offset, 2, this.length)
2090 var val = this[offset + 1] | (this[offset] << 8)
2091 return (val & 0x8000) ? val | 0xFFFF0000 : val
2092}
2093
2094Buffer.prototype.readInt32LE = function (offset, noAssert) {
2095 if (!noAssert)
2096 checkOffset(offset, 4, this.length)
2097
2098 return (this[offset]) |
2099 (this[offset + 1] << 8) |
2100 (this[offset + 2] << 16) |
2101 (this[offset + 3] << 24)
2102}
2103
2104Buffer.prototype.readInt32BE = function (offset, noAssert) {
2105 if (!noAssert)
2106 checkOffset(offset, 4, this.length)
2107
2108 return (this[offset] << 24) |
2109 (this[offset + 1] << 16) |
2110 (this[offset + 2] << 8) |
2111 (this[offset + 3])
2112}
2113
2114Buffer.prototype.readFloatLE = function (offset, noAssert) {
2115 if (!noAssert)
2116 checkOffset(offset, 4, this.length)
2117 return ieee754.read(this, offset, true, 23, 4)
2118}
2119
2120Buffer.prototype.readFloatBE = function (offset, noAssert) {
2121 if (!noAssert)
2122 checkOffset(offset, 4, this.length)
2123 return ieee754.read(this, offset, false, 23, 4)
2124}
2125
2126Buffer.prototype.readDoubleLE = function (offset, noAssert) {
2127 if (!noAssert)
2128 checkOffset(offset, 8, this.length)
2129 return ieee754.read(this, offset, true, 52, 8)
2130}
2131
2132Buffer.prototype.readDoubleBE = function (offset, noAssert) {
2133 if (!noAssert)
2134 checkOffset(offset, 8, this.length)
2135 return ieee754.read(this, offset, false, 52, 8)
2136}
2137
2138function checkInt (buf, value, offset, ext, max, min) {
2139 if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
2140 if (value > max || value < min) throw new TypeError('value is out of bounds')
2141 if (offset + ext > buf.length) throw new TypeError('index out of range')
2142}
2143
2144Buffer.prototype.writeUInt8 = function (value, offset, noAssert) {
2145 value = +value
2146 offset = offset >>> 0
2147 if (!noAssert)
2148 checkInt(this, value, offset, 1, 0xff, 0)
2149 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
2150 this[offset] = value
2151 return offset + 1
2152}
2153
2154function objectWriteUInt16 (buf, value, offset, littleEndian) {
2155 if (value < 0) value = 0xffff + value + 1
2156 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
2157 buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
2158 (littleEndian ? i : 1 - i) * 8
2159 }
2160}
2161
2162Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) {
2163 value = +value
2164 offset = offset >>> 0
2165 if (!noAssert)
2166 checkInt(this, value, offset, 2, 0xffff, 0)
2167 if (Buffer.TYPED_ARRAY_SUPPORT) {
2168 this[offset] = value
2169 this[offset + 1] = (value >>> 8)
2170 } else objectWriteUInt16(this, value, offset, true)
2171 return offset + 2
2172}
2173
2174Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) {
2175 value = +value
2176 offset = offset >>> 0
2177 if (!noAssert)
2178 checkInt(this, value, offset, 2, 0xffff, 0)
2179 if (Buffer.TYPED_ARRAY_SUPPORT) {
2180 this[offset] = (value >>> 8)
2181 this[offset + 1] = value
2182 } else objectWriteUInt16(this, value, offset, false)
2183 return offset + 2
2184}
2185
2186function objectWriteUInt32 (buf, value, offset, littleEndian) {
2187 if (value < 0) value = 0xffffffff + value + 1
2188 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
2189 buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
2190 }
2191}
2192
2193Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) {
2194 value = +value
2195 offset = offset >>> 0
2196 if (!noAssert)
2197 checkInt(this, value, offset, 4, 0xffffffff, 0)
2198 if (Buffer.TYPED_ARRAY_SUPPORT) {
2199 this[offset + 3] = (value >>> 24)
2200 this[offset + 2] = (value >>> 16)
2201 this[offset + 1] = (value >>> 8)
2202 this[offset] = value
2203 } else objectWriteUInt32(this, value, offset, true)
2204 return offset + 4
2205}
2206
2207Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) {
2208 value = +value
2209 offset = offset >>> 0
2210 if (!noAssert)
2211 checkInt(this, value, offset, 4, 0xffffffff, 0)
2212 if (Buffer.TYPED_ARRAY_SUPPORT) {
2213 this[offset] = (value >>> 24)
2214 this[offset + 1] = (value >>> 16)
2215 this[offset + 2] = (value >>> 8)
2216 this[offset + 3] = value
2217 } else objectWriteUInt32(this, value, offset, false)
2218 return offset + 4
2219}
2220
2221Buffer.prototype.writeInt8 = function (value, offset, noAssert) {
2222 value = +value
2223 offset = offset >>> 0
2224 if (!noAssert)
2225 checkInt(this, value, offset, 1, 0x7f, -0x80)
2226 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
2227 if (value < 0) value = 0xff + value + 1
2228 this[offset] = value
2229 return offset + 1
2230}
2231
2232Buffer.prototype.writeInt16LE = function (value, offset, noAssert) {
2233 value = +value
2234 offset = offset >>> 0
2235 if (!noAssert)
2236 checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2237 if (Buffer.TYPED_ARRAY_SUPPORT) {
2238 this[offset] = value
2239 this[offset + 1] = (value >>> 8)
2240 } else objectWriteUInt16(this, value, offset, true)
2241 return offset + 2
2242}
2243
2244Buffer.prototype.writeInt16BE = function (value, offset, noAssert) {
2245 value = +value
2246 offset = offset >>> 0
2247 if (!noAssert)
2248 checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2249 if (Buffer.TYPED_ARRAY_SUPPORT) {
2250 this[offset] = (value >>> 8)
2251 this[offset + 1] = value
2252 } else objectWriteUInt16(this, value, offset, false)
2253 return offset + 2
2254}
2255
2256Buffer.prototype.writeInt32LE = function (value, offset, noAssert) {
2257 value = +value
2258 offset = offset >>> 0
2259 if (!noAssert)
2260 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2261 if (Buffer.TYPED_ARRAY_SUPPORT) {
2262 this[offset] = value
2263 this[offset + 1] = (value >>> 8)
2264 this[offset + 2] = (value >>> 16)
2265 this[offset + 3] = (value >>> 24)
2266 } else objectWriteUInt32(this, value, offset, true)
2267 return offset + 4
2268}
2269
2270Buffer.prototype.writeInt32BE = function (value, offset, noAssert) {
2271 value = +value
2272 offset = offset >>> 0
2273 if (!noAssert)
2274 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2275 if (value < 0) value = 0xffffffff + value + 1
2276 if (Buffer.TYPED_ARRAY_SUPPORT) {
2277 this[offset] = (value >>> 24)
2278 this[offset + 1] = (value >>> 16)
2279 this[offset + 2] = (value >>> 8)
2280 this[offset + 3] = value
2281 } else objectWriteUInt32(this, value, offset, false)
2282 return offset + 4
2283}
2284
2285function checkIEEE754 (buf, value, offset, ext, max, min) {
2286 if (value > max || value < min) throw new TypeError('value is out of bounds')
2287 if (offset + ext > buf.length) throw new TypeError('index out of range')
2288}
2289
2290function writeFloat (buf, value, offset, littleEndian, noAssert) {
2291 if (!noAssert)
2292 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
2293 ieee754.write(buf, value, offset, littleEndian, 23, 4)
2294 return offset + 4
2295}
2296
2297Buffer.prototype.writeFloatLE = function (value, offset, noAssert) {
2298 return writeFloat(this, value, offset, true, noAssert)
2299}
2300
2301Buffer.prototype.writeFloatBE = function (value, offset, noAssert) {
2302 return writeFloat(this, value, offset, false, noAssert)
2303}
2304
2305function writeDouble (buf, value, offset, littleEndian, noAssert) {
2306 if (!noAssert)
2307 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
2308 ieee754.write(buf, value, offset, littleEndian, 52, 8)
2309 return offset + 8
2310}
2311
2312Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) {
2313 return writeDouble(this, value, offset, true, noAssert)
2314}
2315
2316Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) {
2317 return writeDouble(this, value, offset, false, noAssert)
2318}
2319
2320// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
2321Buffer.prototype.copy = function (target, target_start, start, end) {
2322 var source = this
2323
2324 if (!start) start = 0
2325 if (!end && end !== 0) end = this.length
2326 if (!target_start) target_start = 0
2327
2328 // Copy 0 bytes; we're done
2329 if (end === start) return
2330 if (target.length === 0 || source.length === 0) return
2331
2332 // Fatal error conditions
2333 if (end < start) throw new TypeError('sourceEnd < sourceStart')
2334 if (target_start < 0 || target_start >= target.length)
2335 throw new TypeError('targetStart out of bounds')
2336 if (start < 0 || start >= source.length) throw new TypeError('sourceStart out of bounds')
2337 if (end < 0 || end > source.length) throw new TypeError('sourceEnd out of bounds')
2338
2339 // Are we oob?
2340 if (end > this.length)
2341 end = this.length
2342 if (target.length - target_start < end - start)
2343 end = target.length - target_start + start
2344
2345 var len = end - start
2346
2347 if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
2348 for (var i = 0; i < len; i++) {
2349 target[i + target_start] = this[i + start]
2350 }
2351 } else {
2352 target._set(this.subarray(start, start + len), target_start)
2353 }
2354}
2355
2356// fill(value, start=0, end=buffer.length)
2357Buffer.prototype.fill = function (value, start, end) {
2358 if (!value) value = 0
2359 if (!start) start = 0
2360 if (!end) end = this.length
2361
2362 if (end < start) throw new TypeError('end < start')
2363
2364 // Fill 0 bytes; we're done
2365 if (end === start) return
2366 if (this.length === 0) return
2367
2368 if (start < 0 || start >= this.length) throw new TypeError('start out of bounds')
2369 if (end < 0 || end > this.length) throw new TypeError('end out of bounds')
2370
2371 var i
2372 if (typeof value === 'number') {
2373 for (i = start; i < end; i++) {
2374 this[i] = value
2375 }
2376 } else {
2377 var bytes = utf8ToBytes(value.toString())
2378 var len = bytes.length
2379 for (i = start; i < end; i++) {
2380 this[i] = bytes[i % len]
2381 }
2382 }
2383
2384 return this
2385}
2386
2387/**
2388 * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
2389 * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
2390 */
2391Buffer.prototype.toArrayBuffer = function () {
2392 if (typeof Uint8Array !== 'undefined') {
2393 if (Buffer.TYPED_ARRAY_SUPPORT) {
2394 return (new Buffer(this)).buffer
2395 } else {
2396 var buf = new Uint8Array(this.length)
2397 for (var i = 0, len = buf.length; i < len; i += 1) {
2398 buf[i] = this[i]
2399 }
2400 return buf.buffer
2401 }
2402 } else {
2403 throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
2404 }
2405}
2406
2407// HELPER FUNCTIONS
2408// ================
2409
2410var BP = Buffer.prototype
2411
2412/**
2413 * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
2414 */
2415Buffer._augment = function (arr) {
2416 arr.constructor = Buffer
2417 arr._isBuffer = true
2418
2419 // save reference to original Uint8Array get/set methods before overwriting
2420 arr._get = arr.get
2421 arr._set = arr.set
2422
2423 // deprecated, will be removed in node 0.13+
2424 arr.get = BP.get
2425 arr.set = BP.set
2426
2427 arr.write = BP.write
2428 arr.toString = BP.toString
2429 arr.toLocaleString = BP.toString
2430 arr.toJSON = BP.toJSON
2431 arr.equals = BP.equals
2432 arr.compare = BP.compare
2433 arr.copy = BP.copy
2434 arr.slice = BP.slice
2435 arr.readUInt8 = BP.readUInt8
2436 arr.readUInt16LE = BP.readUInt16LE
2437 arr.readUInt16BE = BP.readUInt16BE
2438 arr.readUInt32LE = BP.readUInt32LE
2439 arr.readUInt32BE = BP.readUInt32BE
2440 arr.readInt8 = BP.readInt8
2441 arr.readInt16LE = BP.readInt16LE
2442 arr.readInt16BE = BP.readInt16BE
2443 arr.readInt32LE = BP.readInt32LE
2444 arr.readInt32BE = BP.readInt32BE
2445 arr.readFloatLE = BP.readFloatLE
2446 arr.readFloatBE = BP.readFloatBE
2447 arr.readDoubleLE = BP.readDoubleLE
2448 arr.readDoubleBE = BP.readDoubleBE
2449 arr.writeUInt8 = BP.writeUInt8
2450 arr.writeUInt16LE = BP.writeUInt16LE
2451 arr.writeUInt16BE = BP.writeUInt16BE
2452 arr.writeUInt32LE = BP.writeUInt32LE
2453 arr.writeUInt32BE = BP.writeUInt32BE
2454 arr.writeInt8 = BP.writeInt8
2455 arr.writeInt16LE = BP.writeInt16LE
2456 arr.writeInt16BE = BP.writeInt16BE
2457 arr.writeInt32LE = BP.writeInt32LE
2458 arr.writeInt32BE = BP.writeInt32BE
2459 arr.writeFloatLE = BP.writeFloatLE
2460 arr.writeFloatBE = BP.writeFloatBE
2461 arr.writeDoubleLE = BP.writeDoubleLE
2462 arr.writeDoubleBE = BP.writeDoubleBE
2463 arr.fill = BP.fill
2464 arr.inspect = BP.inspect
2465 arr.toArrayBuffer = BP.toArrayBuffer
2466
2467 return arr
2468}
2469
2470var INVALID_BASE64_RE = /[^+\/0-9A-z]/g
2471
2472function base64clean (str) {
2473 // Node strips out invalid characters like \n and \t from the string, base64-js does not
2474 str = stringtrim(str).replace(INVALID_BASE64_RE, '')
2475 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
2476 while (str.length % 4 !== 0) {
2477 str = str + '='
2478 }
2479 return str
2480}
2481
2482function stringtrim (str) {
2483 if (str.trim) return str.trim()
2484 return str.replace(/^\s+|\s+$/g, '')
2485}
2486
2487function isArrayish (subject) {
2488 return isArray(subject) || Buffer.isBuffer(subject) ||
2489 subject && typeof subject === 'object' &&
2490 typeof subject.length === 'number'
2491}
2492
2493function toHex (n) {
2494 if (n < 16) return '0' + n.toString(16)
2495 return n.toString(16)
2496}
2497
2498function utf8ToBytes (str) {
2499 var byteArray = []
2500 for (var i = 0; i < str.length; i++) {
2501 var b = str.charCodeAt(i)
2502 if (b <= 0x7F) {
2503 byteArray.push(b)
2504 } else {
2505 var start = i
2506 if (b >= 0xD800 && b <= 0xDFFF) i++
2507 var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%')
2508 for (var j = 0; j < h.length; j++) {
2509 byteArray.push(parseInt(h[j], 16))
2510 }
2511 }
2512 }
2513 return byteArray
2514}
2515
2516function asciiToBytes (str) {
2517 var byteArray = []
2518 for (var i = 0; i < str.length; i++) {
2519 // Node's code seems to be doing this and not & 0x7F..
2520 byteArray.push(str.charCodeAt(i) & 0xFF)
2521 }
2522 return byteArray
2523}
2524
2525function utf16leToBytes (str) {
2526 var c, hi, lo
2527 var byteArray = []
2528 for (var i = 0; i < str.length; i++) {
2529 c = str.charCodeAt(i)
2530 hi = c >> 8
2531 lo = c % 256
2532 byteArray.push(lo)
2533 byteArray.push(hi)
2534 }
2535
2536 return byteArray
2537}
2538
2539function base64ToBytes (str) {
2540 return base64.toByteArray(str)
2541}
2542
2543function blitBuffer (src, dst, offset, length) {
2544 for (var i = 0; i < length; i++) {
2545 if ((i + offset >= dst.length) || (i >= src.length))
2546 break
2547 dst[i + offset] = src[i]
2548 }
2549 return i
2550}
2551
2552function decodeUtf8Char (str) {
2553 try {
2554 return decodeURIComponent(str)
2555 } catch (err) {
2556 return String.fromCharCode(0xFFFD) // UTF 8 invalid char
2557 }
2558}
2559
2560},{"base64-js":17,"ieee754":18,"is-array":19}],17:[function(require,module,exports){
2561var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
2562
2563;(function (exports) {
2564 'use strict';
2565
2566 var Arr = (typeof Uint8Array !== 'undefined')
2567 ? Uint8Array
2568 : Array
2569
2570 var PLUS = '+'.charCodeAt(0)
2571 var SLASH = '/'.charCodeAt(0)
2572 var NUMBER = '0'.charCodeAt(0)
2573 var LOWER = 'a'.charCodeAt(0)
2574 var UPPER = 'A'.charCodeAt(0)
2575
2576 function decode (elt) {
2577 var code = elt.charCodeAt(0)
2578 if (code === PLUS)
2579 return 62 // '+'
2580 if (code === SLASH)
2581 return 63 // '/'
2582 if (code < NUMBER)
2583 return -1 //no match
2584 if (code < NUMBER + 10)
2585 return code - NUMBER + 26 + 26
2586 if (code < UPPER + 26)
2587 return code - UPPER
2588 if (code < LOWER + 26)
2589 return code - LOWER + 26
2590 }
2591
2592 function b64ToByteArray (b64) {
2593 var i, j, l, tmp, placeHolders, arr
2594
2595 if (b64.length % 4 > 0) {
2596 throw new Error('Invalid string. Length must be a multiple of 4')
2597 }
2598
2599 // the number of equal signs (place holders)
2600 // if there are two placeholders, than the two characters before it
2601 // represent one byte
2602 // if there is only one, then the three characters before it represent 2 bytes
2603 // this is just a cheap hack to not do indexOf twice
2604 var len = b64.length
2605 placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
2606
2607 // base64 is 4/3 + up to two characters of the original data
2608 arr = new Arr(b64.length * 3 / 4 - placeHolders)
2609
2610 // if there are placeholders, only get up to the last complete 4 chars
2611 l = placeHolders > 0 ? b64.length - 4 : b64.length
2612
2613 var L = 0
2614
2615 function push (v) {
2616 arr[L++] = v
2617 }
2618
2619 for (i = 0, j = 0; i < l; i += 4, j += 3) {
2620 tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
2621 push((tmp & 0xFF0000) >> 16)
2622 push((tmp & 0xFF00) >> 8)
2623 push(tmp & 0xFF)
2624 }
2625
2626 if (placeHolders === 2) {
2627 tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
2628 push(tmp & 0xFF)
2629 } else if (placeHolders === 1) {
2630 tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
2631 push((tmp >> 8) & 0xFF)
2632 push(tmp & 0xFF)
2633 }
2634
2635 return arr
2636 }
2637
2638 function uint8ToBase64 (uint8) {
2639 var i,
2640 extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
2641 output = "",
2642 temp, length
2643
2644 function encode (num) {
2645 return lookup.charAt(num)
2646 }
2647
2648 function tripletToBase64 (num) {
2649 return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
2650 }
2651
2652 // go through the array every three bytes, we'll deal with trailing stuff later
2653 for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
2654 temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
2655 output += tripletToBase64(temp)
2656 }
2657
2658 // pad the end with zeros, but make sure to not forget the extra bytes
2659 switch (extraBytes) {
2660 case 1:
2661 temp = uint8[uint8.length - 1]
2662 output += encode(temp >> 2)
2663 output += encode((temp << 4) & 0x3F)
2664 output += '=='
2665 break
2666 case 2:
2667 temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
2668 output += encode(temp >> 10)
2669 output += encode((temp >> 4) & 0x3F)
2670 output += encode((temp << 2) & 0x3F)
2671 output += '='
2672 break
2673 }
2674
2675 return output
2676 }
2677
2678 exports.toByteArray = b64ToByteArray
2679 exports.fromByteArray = uint8ToBase64
2680}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
2681
2682},{}],18:[function(require,module,exports){
2683exports.read = function(buffer, offset, isLE, mLen, nBytes) {
2684 var e, m,
2685 eLen = nBytes * 8 - mLen - 1,
2686 eMax = (1 << eLen) - 1,
2687 eBias = eMax >> 1,
2688 nBits = -7,
2689 i = isLE ? (nBytes - 1) : 0,
2690 d = isLE ? -1 : 1,
2691 s = buffer[offset + i];
2692
2693 i += d;
2694
2695 e = s & ((1 << (-nBits)) - 1);
2696 s >>= (-nBits);
2697 nBits += eLen;
2698 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
2699
2700 m = e & ((1 << (-nBits)) - 1);
2701 e >>= (-nBits);
2702 nBits += mLen;
2703 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
2704
2705 if (e === 0) {
2706 e = 1 - eBias;
2707 } else if (e === eMax) {
2708 return m ? NaN : ((s ? -1 : 1) * Infinity);
2709 } else {
2710 m = m + Math.pow(2, mLen);
2711 e = e - eBias;
2712 }
2713 return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
2714};
2715
2716exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
2717 var e, m, c,
2718 eLen = nBytes * 8 - mLen - 1,
2719 eMax = (1 << eLen) - 1,
2720 eBias = eMax >> 1,
2721 rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
2722 i = isLE ? 0 : (nBytes - 1),
2723 d = isLE ? 1 : -1,
2724 s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
2725
2726 value = Math.abs(value);
2727
2728 if (isNaN(value) || value === Infinity) {
2729 m = isNaN(value) ? 1 : 0;
2730 e = eMax;
2731 } else {
2732 e = Math.floor(Math.log(value) / Math.LN2);
2733 if (value * (c = Math.pow(2, -e)) < 1) {
2734 e--;
2735 c *= 2;
2736 }
2737 if (e + eBias >= 1) {
2738 value += rt / c;
2739 } else {
2740 value += rt * Math.pow(2, 1 - eBias);
2741 }
2742 if (value * c >= 2) {
2743 e++;
2744 c /= 2;
2745 }
2746
2747 if (e + eBias >= eMax) {
2748 m = 0;
2749 e = eMax;
2750 } else if (e + eBias >= 1) {
2751 m = (value * c - 1) * Math.pow(2, mLen);
2752 e = e + eBias;
2753 } else {
2754 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
2755 e = 0;
2756 }
2757 }
2758
2759 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);
2760
2761 e = (e << mLen) | m;
2762 eLen += mLen;
2763 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
2764
2765 buffer[offset + i - d] |= s * 128;
2766};
2767
2768},{}],19:[function(require,module,exports){
2769
2770/**
2771 * isArray
2772 */
2773
2774var isArray = Array.isArray;
2775
2776/**
2777 * toString
2778 */
2779
2780var str = Object.prototype.toString;
2781
2782/**
2783 * Whether or not the given `val`
2784 * is an array.
2785 *
2786 * example:
2787 *
2788 * isArray([]);
2789 * // > true
2790 * isArray(arguments);
2791 * // > false
2792 * isArray('');
2793 * // > false
2794 *
2795 * @param {mixed} val
2796 * @return {bool}
2797 */
2798
2799module.exports = isArray || function (val) {
2800 return !! val && '[object Array]' == str.call(val);
2801};
2802
2803},{}],20:[function(require,module,exports){
2804// Copyright Joyent, Inc. and other Node contributors.
2805//
2806// Permission is hereby granted, free of charge, to any person obtaining a
2807// copy of this software and associated documentation files (the
2808// "Software"), to deal in the Software without restriction, including
2809// without limitation the rights to use, copy, modify, merge, publish,
2810// distribute, sublicense, and/or sell copies of the Software, and to permit
2811// persons to whom the Software is furnished to do so, subject to the
2812// following conditions:
2813//
2814// The above copyright notice and this permission notice shall be included
2815// in all copies or substantial portions of the Software.
2816//
2817// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
2818// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2819// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
2820// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
2821// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
2822// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
2823// USE OR OTHER DEALINGS IN THE SOFTWARE.
2824
2825function EventEmitter() {
2826 this._events = this._events || {};
2827 this._maxListeners = this._maxListeners || undefined;
2828}
2829module.exports = EventEmitter;
2830
2831// Backwards-compat with node 0.10.x
2832EventEmitter.EventEmitter = EventEmitter;
2833
2834EventEmitter.prototype._events = undefined;
2835EventEmitter.prototype._maxListeners = undefined;
2836
2837// By default EventEmitters will print a warning if more than 10 listeners are
2838// added to it. This is a useful default which helps finding memory leaks.
2839EventEmitter.defaultMaxListeners = 10;
2840
2841// Obviously not all Emitters should be limited to 10. This function allows
2842// that to be increased. Set to zero for unlimited.
2843EventEmitter.prototype.setMaxListeners = function(n) {
2844 if (!isNumber(n) || n < 0 || isNaN(n))
2845 throw TypeError('n must be a positive number');
2846 this._maxListeners = n;
2847 return this;
2848};
2849
2850EventEmitter.prototype.emit = function(type) {
2851 var er, handler, len, args, i, listeners;
2852
2853 if (!this._events)
2854 this._events = {};
2855
2856 // If there is no 'error' event listener then throw.
2857 if (type === 'error') {
2858 if (!this._events.error ||
2859 (isObject(this._events.error) && !this._events.error.length)) {
2860 er = arguments[1];
2861 if (er instanceof Error) {
2862 throw er; // Unhandled 'error' event
2863 }
2864 throw TypeError('Uncaught, unspecified "error" event.');
2865 }
2866 }
2867
2868 handler = this._events[type];
2869
2870 if (isUndefined(handler))
2871 return false;
2872
2873 if (isFunction(handler)) {
2874 switch (arguments.length) {
2875 // fast cases
2876 case 1:
2877 handler.call(this);
2878 break;
2879 case 2:
2880 handler.call(this, arguments[1]);
2881 break;
2882 case 3:
2883 handler.call(this, arguments[1], arguments[2]);
2884 break;
2885 // slower
2886 default:
2887 len = arguments.length;
2888 args = new Array(len - 1);
2889 for (i = 1; i < len; i++)
2890 args[i - 1] = arguments[i];
2891 handler.apply(this, args);
2892 }
2893 } else if (isObject(handler)) {
2894 len = arguments.length;
2895 args = new Array(len - 1);
2896 for (i = 1; i < len; i++)
2897 args[i - 1] = arguments[i];
2898
2899 listeners = handler.slice();
2900 len = listeners.length;
2901 for (i = 0; i < len; i++)
2902 listeners[i].apply(this, args);
2903 }
2904
2905 return true;
2906};
2907
2908EventEmitter.prototype.addListener = function(type, listener) {
2909 var m;
2910
2911 if (!isFunction(listener))
2912 throw TypeError('listener must be a function');
2913
2914 if (!this._events)
2915 this._events = {};
2916
2917 // To avoid recursion in the case that type === "newListener"! Before
2918 // adding it to the listeners, first emit "newListener".
2919 if (this._events.newListener)
2920 this.emit('newListener', type,
2921 isFunction(listener.listener) ?
2922 listener.listener : listener);
2923
2924 if (!this._events[type])
2925 // Optimize the case of one listener. Don't need the extra array object.
2926 this._events[type] = listener;
2927 else if (isObject(this._events[type]))
2928 // If we've already got an array, just append.
2929 this._events[type].push(listener);
2930 else
2931 // Adding the second element, need to change to array.
2932 this._events[type] = [this._events[type], listener];
2933
2934 // Check for listener leak
2935 if (isObject(this._events[type]) && !this._events[type].warned) {
2936 var m;
2937 if (!isUndefined(this._maxListeners)) {
2938 m = this._maxListeners;
2939 } else {
2940 m = EventEmitter.defaultMaxListeners;
2941 }
2942
2943 if (m && m > 0 && this._events[type].length > m) {
2944 this._events[type].warned = true;
2945 console.error('(node) warning: possible EventEmitter memory ' +
2946 'leak detected. %d listeners added. ' +
2947 'Use emitter.setMaxListeners() to increase limit.',
2948 this._events[type].length);
2949 if (typeof console.trace === 'function') {
2950 // not supported in IE 10
2951 console.trace();
2952 }
2953 }
2954 }
2955
2956 return this;
2957};
2958
2959EventEmitter.prototype.on = EventEmitter.prototype.addListener;
2960
2961EventEmitter.prototype.once = function(type, listener) {
2962 if (!isFunction(listener))
2963 throw TypeError('listener must be a function');
2964
2965 var fired = false;
2966
2967 function g() {
2968 this.removeListener(type, g);
2969
2970 if (!fired) {
2971 fired = true;
2972 listener.apply(this, arguments);
2973 }
2974 }
2975
2976 g.listener = listener;
2977 this.on(type, g);
2978
2979 return this;
2980};
2981
2982// emits a 'removeListener' event iff the listener was removed
2983EventEmitter.prototype.removeListener = function(type, listener) {
2984 var list, position, length, i;
2985
2986 if (!isFunction(listener))
2987 throw TypeError('listener must be a function');
2988
2989 if (!this._events || !this._events[type])
2990 return this;
2991
2992 list = this._events[type];
2993 length = list.length;
2994 position = -1;
2995
2996 if (list === listener ||
2997 (isFunction(list.listener) && list.listener === listener)) {
2998 delete this._events[type];
2999 if (this._events.removeListener)
3000 this.emit('removeListener', type, listener);
3001
3002 } else if (isObject(list)) {
3003 for (i = length; i-- > 0;) {
3004 if (list[i] === listener ||
3005 (list[i].listener && list[i].listener === listener)) {
3006 position = i;
3007 break;
3008 }
3009 }
3010
3011 if (position < 0)
3012 return this;
3013
3014 if (list.length === 1) {
3015 list.length = 0;
3016 delete this._events[type];
3017 } else {
3018 list.splice(position, 1);
3019 }
3020
3021 if (this._events.removeListener)
3022 this.emit('removeListener', type, listener);
3023 }
3024
3025 return this;
3026};
3027
3028EventEmitter.prototype.removeAllListeners = function(type) {
3029 var key, listeners;
3030
3031 if (!this._events)
3032 return this;
3033
3034 // not listening for removeListener, no need to emit
3035 if (!this._events.removeListener) {
3036 if (arguments.length === 0)
3037 this._events = {};
3038 else if (this._events[type])
3039 delete this._events[type];
3040 return this;
3041 }
3042
3043 // emit removeListener for all listeners on all events
3044 if (arguments.length === 0) {
3045 for (key in this._events) {
3046 if (key === 'removeListener') continue;
3047 this.removeAllListeners(key);
3048 }
3049 this.removeAllListeners('removeListener');
3050 this._events = {};
3051 return this;
3052 }
3053
3054 listeners = this._events[type];
3055
3056 if (isFunction(listeners)) {
3057 this.removeListener(type, listeners);
3058 } else {
3059 // LIFO order
3060 while (listeners.length)
3061 this.removeListener(type, listeners[listeners.length - 1]);
3062 }
3063 delete this._events[type];
3064
3065 return this;
3066};
3067
3068EventEmitter.prototype.listeners = function(type) {
3069 var ret;
3070 if (!this._events || !this._events[type])
3071 ret = [];
3072 else if (isFunction(this._events[type]))
3073 ret = [this._events[type]];
3074 else
3075 ret = this._events[type].slice();
3076 return ret;
3077};
3078
3079EventEmitter.listenerCount = function(emitter, type) {
3080 var ret;
3081 if (!emitter._events || !emitter._events[type])
3082 ret = 0;
3083 else if (isFunction(emitter._events[type]))
3084 ret = 1;
3085 else
3086 ret = emitter._events[type].length;
3087 return ret;
3088};
3089
3090function isFunction(arg) {
3091 return typeof arg === 'function';
3092}
3093
3094function isNumber(arg) {
3095 return typeof arg === 'number';
3096}
3097
3098function isObject(arg) {
3099 return typeof arg === 'object' && arg !== null;
3100}
3101
3102function isUndefined(arg) {
3103 return arg === void 0;
3104}
3105
3106},{}],21:[function(require,module,exports){
3107module.exports=require(10)
3108},{"/Users/Aaron/Sites/rifraf/node_modules/tape/node_modules/inherits/inherits_browser.js":10}],22:[function(require,module,exports){
3109module.exports = Array.isArray || function (arr) {
3110 return Object.prototype.toString.call(arr) == '[object Array]';
3111};
3112
3113},{}],23:[function(require,module,exports){
3114(function (process){
3115// Copyright Joyent, Inc. and other Node contributors.
3116//
3117// Permission is hereby granted, free of charge, to any person obtaining a
3118// copy of this software and associated documentation files (the
3119// "Software"), to deal in the Software without restriction, including
3120// without limitation the rights to use, copy, modify, merge, publish,
3121// distribute, sublicense, and/or sell copies of the Software, and to permit
3122// persons to whom the Software is furnished to do so, subject to the
3123// following conditions:
3124//
3125// The above copyright notice and this permission notice shall be included
3126// in all copies or substantial portions of the Software.
3127//
3128// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3129// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3130// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3131// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3132// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3133// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3134// USE OR OTHER DEALINGS IN THE SOFTWARE.
3135
3136// resolves . and .. elements in a path array with directory names there
3137// must be no slashes, empty elements, or device names (c:\) in the array
3138// (so also no leading and trailing slashes - it does not distinguish
3139// relative and absolute paths)
3140function normalizeArray(parts, allowAboveRoot) {
3141 // if the path tries to go above the root, `up` ends up > 0
3142 var up = 0;
3143 for (var i = parts.length - 1; i >= 0; i--) {
3144 var last = parts[i];
3145 if (last === '.') {
3146 parts.splice(i, 1);
3147 } else if (last === '..') {
3148 parts.splice(i, 1);
3149 up++;
3150 } else if (up) {
3151 parts.splice(i, 1);
3152 up--;
3153 }
3154 }
3155
3156 // if the path is allowed to go above the root, restore leading ..s
3157 if (allowAboveRoot) {
3158 for (; up--; up) {
3159 parts.unshift('..');
3160 }
3161 }
3162
3163 return parts;
3164}
3165
3166// Split a filename into [root, dir, basename, ext], unix version
3167// 'root' is just a slash, or nothing.
3168var splitPathRe =
3169 /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
3170var splitPath = function(filename) {
3171 return splitPathRe.exec(filename).slice(1);
3172};
3173
3174// path.resolve([from ...], to)
3175// posix version
3176exports.resolve = function() {
3177 var resolvedPath = '',
3178 resolvedAbsolute = false;
3179
3180 for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
3181 var path = (i >= 0) ? arguments[i] : process.cwd();
3182
3183 // Skip empty and invalid entries
3184 if (typeof path !== 'string') {
3185 throw new TypeError('Arguments to path.resolve must be strings');
3186 } else if (!path) {
3187 continue;
3188 }
3189
3190 resolvedPath = path + '/' + resolvedPath;
3191 resolvedAbsolute = path.charAt(0) === '/';
3192 }
3193
3194 // At this point the path should be resolved to a full absolute path, but
3195 // handle relative paths to be safe (might happen when process.cwd() fails)
3196
3197 // Normalize the path
3198 resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
3199 return !!p;
3200 }), !resolvedAbsolute).join('/');
3201
3202 return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
3203};
3204
3205// path.normalize(path)
3206// posix version
3207exports.normalize = function(path) {
3208 var isAbsolute = exports.isAbsolute(path),
3209 trailingSlash = substr(path, -1) === '/';
3210
3211 // Normalize the path
3212 path = normalizeArray(filter(path.split('/'), function(p) {
3213 return !!p;
3214 }), !isAbsolute).join('/');
3215
3216 if (!path && !isAbsolute) {
3217 path = '.';
3218 }
3219 if (path && trailingSlash) {
3220 path += '/';
3221 }
3222
3223 return (isAbsolute ? '/' : '') + path;
3224};
3225
3226// posix version
3227exports.isAbsolute = function(path) {
3228 return path.charAt(0) === '/';
3229};
3230
3231// posix version
3232exports.join = function() {
3233 var paths = Array.prototype.slice.call(arguments, 0);
3234 return exports.normalize(filter(paths, function(p, index) {
3235 if (typeof p !== 'string') {
3236 throw new TypeError('Arguments to path.join must be strings');
3237 }
3238 return p;
3239 }).join('/'));
3240};
3241
3242
3243// path.relative(from, to)
3244// posix version
3245exports.relative = function(from, to) {
3246 from = exports.resolve(from).substr(1);
3247 to = exports.resolve(to).substr(1);
3248
3249 function trim(arr) {
3250 var start = 0;
3251 for (; start < arr.length; start++) {
3252 if (arr[start] !== '') break;
3253 }
3254
3255 var end = arr.length - 1;
3256 for (; end >= 0; end--) {
3257 if (arr[end] !== '') break;
3258 }
3259
3260 if (start > end) return [];
3261 return arr.slice(start, end - start + 1);
3262 }
3263
3264 var fromParts = trim(from.split('/'));
3265 var toParts = trim(to.split('/'));
3266
3267 var length = Math.min(fromParts.length, toParts.length);
3268 var samePartsLength = length;
3269 for (var i = 0; i < length; i++) {
3270 if (fromParts[i] !== toParts[i]) {
3271 samePartsLength = i;
3272 break;
3273 }
3274 }
3275
3276 var outputParts = [];
3277 for (var i = samePartsLength; i < fromParts.length; i++) {
3278 outputParts.push('..');
3279 }
3280
3281 outputParts = outputParts.concat(toParts.slice(samePartsLength));
3282
3283 return outputParts.join('/');
3284};
3285
3286exports.sep = '/';
3287exports.delimiter = ':';
3288
3289exports.dirname = function(path) {
3290 var result = splitPath(path),
3291 root = result[0],
3292 dir = result[1];
3293
3294 if (!root && !dir) {
3295 // No dirname whatsoever
3296 return '.';
3297 }
3298
3299 if (dir) {
3300 // It has a dirname, strip trailing slash
3301 dir = dir.substr(0, dir.length - 1);
3302 }
3303
3304 return root + dir;
3305};
3306
3307
3308exports.basename = function(path, ext) {
3309 var f = splitPath(path)[2];
3310 // TODO: make this comparison case-insensitive on windows?
3311 if (ext && f.substr(-1 * ext.length) === ext) {
3312 f = f.substr(0, f.length - ext.length);
3313 }
3314 return f;
3315};
3316
3317
3318exports.extname = function(path) {
3319 return splitPath(path)[3];
3320};
3321
3322function filter (xs, f) {
3323 if (xs.filter) return xs.filter(f);
3324 var res = [];
3325 for (var i = 0; i < xs.length; i++) {
3326 if (f(xs[i], i, xs)) res.push(xs[i]);
3327 }
3328 return res;
3329}
3330
3331// String.prototype.substr - negative index don't work in IE8
3332var substr = 'ab'.substr(-1) === 'b'
3333 ? function (str, start, len) { return str.substr(start, len) }
3334 : function (str, start, len) {
3335 if (start < 0) start = str.length + start;
3336 return str.substr(start, len);
3337 }
3338;
3339
3340}).call(this,require('_process'))
3341},{"_process":24}],24:[function(require,module,exports){
3342// shim for using process in browser
3343
3344var process = module.exports = {};
3345
3346process.nextTick = (function () {
3347 var canSetImmediate = typeof window !== 'undefined'
3348 && window.setImmediate;
3349 var canMutationObserver = typeof window !== 'undefined'
3350 && window.MutationObserver;
3351 var canPost = typeof window !== 'undefined'
3352 && window.postMessage && window.addEventListener
3353 ;
3354
3355 if (canSetImmediate) {
3356 return function (f) { return window.setImmediate(f) };
3357 }
3358
3359 var queue = [];
3360
3361 if (canMutationObserver) {
3362 var hiddenDiv = document.createElement("div");
3363 var observer = new MutationObserver(function () {
3364 var queueList = queue.slice();
3365 queue.length = 0;
3366 queueList.forEach(function (fn) {
3367 fn();
3368 });
3369 });
3370
3371 observer.observe(hiddenDiv, { attributes: true });
3372
3373 return function nextTick(fn) {
3374 if (!queue.length) {
3375 hiddenDiv.setAttribute('yes', 'no');
3376 }
3377 queue.push(fn);
3378 };
3379 }
3380
3381 if (canPost) {
3382 window.addEventListener('message', function (ev) {
3383 var source = ev.source;
3384 if ((source === window || source === null) && ev.data === 'process-tick') {
3385 ev.stopPropagation();
3386 if (queue.length > 0) {
3387 var fn = queue.shift();
3388 fn();
3389 }
3390 }
3391 }, true);
3392
3393 return function nextTick(fn) {
3394 queue.push(fn);
3395 window.postMessage('process-tick', '*');
3396 };
3397 }
3398
3399 return function nextTick(fn) {
3400 setTimeout(fn, 0);
3401 };
3402})();
3403
3404process.title = 'browser';
3405process.browser = true;
3406process.env = {};
3407process.argv = [];
3408
3409function noop() {}
3410
3411process.on = noop;
3412process.addListener = noop;
3413process.once = noop;
3414process.off = noop;
3415process.removeListener = noop;
3416process.removeAllListeners = noop;
3417process.emit = noop;
3418
3419process.binding = function (name) {
3420 throw new Error('process.binding is not supported');
3421};
3422
3423// TODO(shtylman)
3424process.cwd = function () { return '/' };
3425process.chdir = function (dir) {
3426 throw new Error('process.chdir is not supported');
3427};
3428
3429},{}],25:[function(require,module,exports){
3430module.exports = require("./lib/_stream_duplex.js")
3431
3432},{"./lib/_stream_duplex.js":26}],26:[function(require,module,exports){
3433(function (process){
3434// Copyright Joyent, Inc. and other Node contributors.
3435//
3436// Permission is hereby granted, free of charge, to any person obtaining a
3437// copy of this software and associated documentation files (the
3438// "Software"), to deal in the Software without restriction, including
3439// without limitation the rights to use, copy, modify, merge, publish,
3440// distribute, sublicense, and/or sell copies of the Software, and to permit
3441// persons to whom the Software is furnished to do so, subject to the
3442// following conditions:
3443//
3444// The above copyright notice and this permission notice shall be included
3445// in all copies or substantial portions of the Software.
3446//
3447// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3448// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3449// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3450// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3451// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3452// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3453// USE OR OTHER DEALINGS IN THE SOFTWARE.
3454
3455// a duplex stream is just a stream that is both readable and writable.
3456// Since JS doesn't have multiple prototypal inheritance, this class
3457// prototypally inherits from Readable, and then parasitically from
3458// Writable.
3459
3460module.exports = Duplex;
3461
3462/*<replacement>*/
3463var objectKeys = Object.keys || function (obj) {
3464 var keys = [];
3465 for (var key in obj) keys.push(key);
3466 return keys;
3467}
3468/*</replacement>*/
3469
3470
3471/*<replacement>*/
3472var util = require('core-util-is');
3473util.inherits = require('inherits');
3474/*</replacement>*/
3475
3476var Readable = require('./_stream_readable');
3477var Writable = require('./_stream_writable');
3478
3479util.inherits(Duplex, Readable);
3480
3481forEach(objectKeys(Writable.prototype), function(method) {
3482 if (!Duplex.prototype[method])
3483 Duplex.prototype[method] = Writable.prototype[method];
3484});
3485
3486function Duplex(options) {
3487 if (!(this instanceof Duplex))
3488 return new Duplex(options);
3489
3490 Readable.call(this, options);
3491 Writable.call(this, options);
3492
3493 if (options && options.readable === false)
3494 this.readable = false;
3495
3496 if (options && options.writable === false)
3497 this.writable = false;
3498
3499 this.allowHalfOpen = true;
3500 if (options && options.allowHalfOpen === false)
3501 this.allowHalfOpen = false;
3502
3503 this.once('end', onend);
3504}
3505
3506// the no-half-open enforcer
3507function onend() {
3508 // if we allow half-open state, or if the writable side ended,
3509 // then we're ok.
3510 if (this.allowHalfOpen || this._writableState.ended)
3511 return;
3512
3513 // no more data can be written.
3514 // But allow more writes to happen in this tick.
3515 process.nextTick(this.end.bind(this));
3516}
3517
3518function forEach (xs, f) {
3519 for (var i = 0, l = xs.length; i < l; i++) {
3520 f(xs[i], i);
3521 }
3522}
3523
3524}).call(this,require('_process'))
3525},{"./_stream_readable":28,"./_stream_writable":30,"_process":24,"core-util-is":31,"inherits":21}],27:[function(require,module,exports){
3526// Copyright Joyent, Inc. and other Node contributors.
3527//
3528// Permission is hereby granted, free of charge, to any person obtaining a
3529// copy of this software and associated documentation files (the
3530// "Software"), to deal in the Software without restriction, including
3531// without limitation the rights to use, copy, modify, merge, publish,
3532// distribute, sublicense, and/or sell copies of the Software, and to permit
3533// persons to whom the Software is furnished to do so, subject to the
3534// following conditions:
3535//
3536// The above copyright notice and this permission notice shall be included
3537// in all copies or substantial portions of the Software.
3538//
3539// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3540// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3541// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3542// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3543// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3544// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3545// USE OR OTHER DEALINGS IN THE SOFTWARE.
3546
3547// a passthrough stream.
3548// basically just the most minimal sort of Transform stream.
3549// Every written chunk gets output as-is.
3550
3551module.exports = PassThrough;
3552
3553var Transform = require('./_stream_transform');
3554
3555/*<replacement>*/
3556var util = require('core-util-is');
3557util.inherits = require('inherits');
3558/*</replacement>*/
3559
3560util.inherits(PassThrough, Transform);
3561
3562function PassThrough(options) {
3563 if (!(this instanceof PassThrough))
3564 return new PassThrough(options);
3565
3566 Transform.call(this, options);
3567}
3568
3569PassThrough.prototype._transform = function(chunk, encoding, cb) {
3570 cb(null, chunk);
3571};
3572
3573},{"./_stream_transform":29,"core-util-is":31,"inherits":21}],28:[function(require,module,exports){
3574(function (process){
3575// Copyright Joyent, Inc. and other Node contributors.
3576//
3577// Permission is hereby granted, free of charge, to any person obtaining a
3578// copy of this software and associated documentation files (the
3579// "Software"), to deal in the Software without restriction, including
3580// without limitation the rights to use, copy, modify, merge, publish,
3581// distribute, sublicense, and/or sell copies of the Software, and to permit
3582// persons to whom the Software is furnished to do so, subject to the
3583// following conditions:
3584//
3585// The above copyright notice and this permission notice shall be included
3586// in all copies or substantial portions of the Software.
3587//
3588// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3589// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3590// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3591// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3592// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3593// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3594// USE OR OTHER DEALINGS IN THE SOFTWARE.
3595
3596module.exports = Readable;
3597
3598/*<replacement>*/
3599var isArray = require('isarray');
3600/*</replacement>*/
3601
3602
3603/*<replacement>*/
3604var Buffer = require('buffer').Buffer;
3605/*</replacement>*/
3606
3607Readable.ReadableState = ReadableState;
3608
3609var EE = require('events').EventEmitter;
3610
3611/*<replacement>*/
3612if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
3613 return emitter.listeners(type).length;
3614};
3615/*</replacement>*/
3616
3617var Stream = require('stream');
3618
3619/*<replacement>*/
3620var util = require('core-util-is');
3621util.inherits = require('inherits');
3622/*</replacement>*/
3623
3624var StringDecoder;
3625
3626util.inherits(Readable, Stream);
3627
3628function ReadableState(options, stream) {
3629 options = options || {};
3630
3631 // the point at which it stops calling _read() to fill the buffer
3632 // Note: 0 is a valid value, means "don't call _read preemptively ever"
3633 var hwm = options.highWaterMark;
3634 this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
3635
3636 // cast to ints.
3637 this.highWaterMark = ~~this.highWaterMark;
3638
3639 this.buffer = [];
3640 this.length = 0;
3641 this.pipes = null;
3642 this.pipesCount = 0;
3643 this.flowing = false;
3644 this.ended = false;
3645 this.endEmitted = false;
3646 this.reading = false;
3647
3648 // In streams that never have any data, and do push(null) right away,
3649 // the consumer can miss the 'end' event if they do some I/O before
3650 // consuming the stream. So, we don't emit('end') until some reading
3651 // happens.
3652 this.calledRead = false;
3653
3654 // a flag to be able to tell if the onwrite cb is called immediately,
3655 // or on a later tick. We set this to true at first, becuase any
3656 // actions that shouldn't happen until "later" should generally also
3657 // not happen before the first write call.
3658 this.sync = true;
3659
3660 // whenever we return null, then we set a flag to say
3661 // that we're awaiting a 'readable' event emission.
3662 this.needReadable = false;
3663 this.emittedReadable = false;
3664 this.readableListening = false;
3665
3666
3667 // object stream flag. Used to make read(n) ignore n and to
3668 // make all the buffer merging and length checks go away
3669 this.objectMode = !!options.objectMode;
3670
3671 // Crypto is kind of old and crusty. Historically, its default string
3672 // encoding is 'binary' so we have to make this configurable.
3673 // Everything else in the universe uses 'utf8', though.
3674 this.defaultEncoding = options.defaultEncoding || 'utf8';
3675
3676 // when piping, we only care about 'readable' events that happen
3677 // after read()ing all the bytes and not getting any pushback.
3678 this.ranOut = false;
3679
3680 // the number of writers that are awaiting a drain event in .pipe()s
3681 this.awaitDrain = 0;
3682
3683 // if true, a maybeReadMore has been scheduled
3684 this.readingMore = false;
3685
3686 this.decoder = null;
3687 this.encoding = null;
3688 if (options.encoding) {
3689 if (!StringDecoder)
3690 StringDecoder = require('string_decoder/').StringDecoder;
3691 this.decoder = new StringDecoder(options.encoding);
3692 this.encoding = options.encoding;
3693 }
3694}
3695
3696function Readable(options) {
3697 if (!(this instanceof Readable))
3698 return new Readable(options);
3699
3700 this._readableState = new ReadableState(options, this);
3701
3702 // legacy
3703 this.readable = true;
3704
3705 Stream.call(this);
3706}
3707
3708// Manually shove something into the read() buffer.
3709// This returns true if the highWaterMark has not been hit yet,
3710// similar to how Writable.write() returns true if you should
3711// write() some more.
3712Readable.prototype.push = function(chunk, encoding) {
3713 var state = this._readableState;
3714
3715 if (typeof chunk === 'string' && !state.objectMode) {
3716 encoding = encoding || state.defaultEncoding;
3717 if (encoding !== state.encoding) {
3718 chunk = new Buffer(chunk, encoding);
3719 encoding = '';
3720 }
3721 }
3722
3723 return readableAddChunk(this, state, chunk, encoding, false);
3724};
3725
3726// Unshift should *always* be something directly out of read()
3727Readable.prototype.unshift = function(chunk) {
3728 var state = this._readableState;
3729 return readableAddChunk(this, state, chunk, '', true);
3730};
3731
3732function readableAddChunk(stream, state, chunk, encoding, addToFront) {
3733 var er = chunkInvalid(state, chunk);
3734 if (er) {
3735 stream.emit('error', er);
3736 } else if (chunk === null || chunk === undefined) {
3737 state.reading = false;
3738 if (!state.ended)
3739 onEofChunk(stream, state);
3740 } else if (state.objectMode || chunk && chunk.length > 0) {
3741 if (state.ended && !addToFront) {
3742 var e = new Error('stream.push() after EOF');
3743 stream.emit('error', e);
3744 } else if (state.endEmitted && addToFront) {
3745 var e = new Error('stream.unshift() after end event');
3746 stream.emit('error', e);
3747 } else {
3748 if (state.decoder && !addToFront && !encoding)
3749 chunk = state.decoder.write(chunk);
3750
3751 // update the buffer info.
3752 state.length += state.objectMode ? 1 : chunk.length;
3753 if (addToFront) {
3754 state.buffer.unshift(chunk);
3755 } else {
3756 state.reading = false;
3757 state.buffer.push(chunk);
3758 }
3759
3760 if (state.needReadable)
3761 emitReadable(stream);
3762
3763 maybeReadMore(stream, state);
3764 }
3765 } else if (!addToFront) {
3766 state.reading = false;
3767 }
3768
3769 return needMoreData(state);
3770}
3771
3772
3773
3774// if it's past the high water mark, we can push in some more.
3775// Also, if we have no data yet, we can stand some
3776// more bytes. This is to work around cases where hwm=0,
3777// such as the repl. Also, if the push() triggered a
3778// readable event, and the user called read(largeNumber) such that
3779// needReadable was set, then we ought to push more, so that another
3780// 'readable' event will be triggered.
3781function needMoreData(state) {
3782 return !state.ended &&
3783 (state.needReadable ||
3784 state.length < state.highWaterMark ||
3785 state.length === 0);
3786}
3787
3788// backwards compatibility.
3789Readable.prototype.setEncoding = function(enc) {
3790 if (!StringDecoder)
3791 StringDecoder = require('string_decoder/').StringDecoder;
3792 this._readableState.decoder = new StringDecoder(enc);
3793 this._readableState.encoding = enc;
3794};
3795
3796// Don't raise the hwm > 128MB
3797var MAX_HWM = 0x800000;
3798function roundUpToNextPowerOf2(n) {
3799 if (n >= MAX_HWM) {
3800 n = MAX_HWM;
3801 } else {
3802 // Get the next highest power of 2
3803 n--;
3804 for (var p = 1; p < 32; p <<= 1) n |= n >> p;
3805 n++;
3806 }
3807 return n;
3808}
3809
3810function howMuchToRead(n, state) {
3811 if (state.length === 0 && state.ended)
3812 return 0;
3813
3814 if (state.objectMode)
3815 return n === 0 ? 0 : 1;
3816
3817 if (n === null || isNaN(n)) {
3818 // only flow one buffer at a time
3819 if (state.flowing && state.buffer.length)
3820 return state.buffer[0].length;
3821 else
3822 return state.length;
3823 }
3824
3825 if (n <= 0)
3826 return 0;
3827
3828 // If we're asking for more than the target buffer level,
3829 // then raise the water mark. Bump up to the next highest
3830 // power of 2, to prevent increasing it excessively in tiny
3831 // amounts.
3832 if (n > state.highWaterMark)
3833 state.highWaterMark = roundUpToNextPowerOf2(n);
3834
3835 // don't have that much. return null, unless we've ended.
3836 if (n > state.length) {
3837 if (!state.ended) {
3838 state.needReadable = true;
3839 return 0;
3840 } else
3841 return state.length;
3842 }
3843
3844 return n;
3845}
3846
3847// you can override either this method, or the async _read(n) below.
3848Readable.prototype.read = function(n) {
3849 var state = this._readableState;
3850 state.calledRead = true;
3851 var nOrig = n;
3852 var ret;
3853
3854 if (typeof n !== 'number' || n > 0)
3855 state.emittedReadable = false;
3856
3857 // if we're doing read(0) to trigger a readable event, but we
3858 // already have a bunch of data in the buffer, then just trigger
3859 // the 'readable' event and move on.
3860 if (n === 0 &&
3861 state.needReadable &&
3862 (state.length >= state.highWaterMark || state.ended)) {
3863 emitReadable(this);
3864 return null;
3865 }
3866
3867 n = howMuchToRead(n, state);
3868
3869 // if we've ended, and we're now clear, then finish it up.
3870 if (n === 0 && state.ended) {
3871 ret = null;
3872
3873 // In cases where the decoder did not receive enough data
3874 // to produce a full chunk, then immediately received an
3875 // EOF, state.buffer will contain [<Buffer >, <Buffer 00 ...>].
3876 // howMuchToRead will see this and coerce the amount to
3877 // read to zero (because it's looking at the length of the
3878 // first <Buffer > in state.buffer), and we'll end up here.
3879 //
3880 // This can only happen via state.decoder -- no other venue
3881 // exists for pushing a zero-length chunk into state.buffer
3882 // and triggering this behavior. In this case, we return our
3883 // remaining data and end the stream, if appropriate.
3884 if (state.length > 0 && state.decoder) {
3885 ret = fromList(n, state);
3886 state.length -= ret.length;
3887 }
3888
3889 if (state.length === 0)
3890 endReadable(this);
3891
3892 return ret;
3893 }
3894
3895 // All the actual chunk generation logic needs to be
3896 // *below* the call to _read. The reason is that in certain
3897 // synthetic stream cases, such as passthrough streams, _read
3898 // may be a completely synchronous operation which may change
3899 // the state of the read buffer, providing enough data when
3900 // before there was *not* enough.
3901 //
3902 // So, the steps are:
3903 // 1. Figure out what the state of things will be after we do
3904 // a read from the buffer.
3905 //
3906 // 2. If that resulting state will trigger a _read, then call _read.
3907 // Note that this may be asynchronous, or synchronous. Yes, it is
3908 // deeply ugly to write APIs this way, but that still doesn't mean
3909 // that the Readable class should behave improperly, as streams are
3910 // designed to be sync/async agnostic.
3911 // Take note if the _read call is sync or async (ie, if the read call
3912 // has returned yet), so that we know whether or not it's safe to emit
3913 // 'readable' etc.
3914 //
3915 // 3. Actually pull the requested chunks out of the buffer and return.
3916
3917 // if we need a readable event, then we need to do some reading.
3918 var doRead = state.needReadable;
3919
3920 // if we currently have less than the highWaterMark, then also read some
3921 if (state.length - n <= state.highWaterMark)
3922 doRead = true;
3923
3924 // however, if we've ended, then there's no point, and if we're already
3925 // reading, then it's unnecessary.
3926 if (state.ended || state.reading)
3927 doRead = false;
3928
3929 if (doRead) {
3930 state.reading = true;
3931 state.sync = true;
3932 // if the length is currently zero, then we *need* a readable event.
3933 if (state.length === 0)
3934 state.needReadable = true;
3935 // call internal read method
3936 this._read(state.highWaterMark);
3937 state.sync = false;
3938 }
3939
3940 // If _read called its callback synchronously, then `reading`
3941 // will be false, and we need to re-evaluate how much data we
3942 // can return to the user.
3943 if (doRead && !state.reading)
3944 n = howMuchToRead(nOrig, state);
3945
3946 if (n > 0)
3947 ret = fromList(n, state);
3948 else
3949 ret = null;
3950
3951 if (ret === null) {
3952 state.needReadable = true;
3953 n = 0;
3954 }
3955
3956 state.length -= n;
3957
3958 // If we have nothing in the buffer, then we want to know
3959 // as soon as we *do* get something into the buffer.
3960 if (state.length === 0 && !state.ended)
3961 state.needReadable = true;
3962
3963 // If we happened to read() exactly the remaining amount in the
3964 // buffer, and the EOF has been seen at this point, then make sure
3965 // that we emit 'end' on the very next tick.
3966 if (state.ended && !state.endEmitted && state.length === 0)
3967 endReadable(this);
3968
3969 return ret;
3970};
3971
3972function chunkInvalid(state, chunk) {
3973 var er = null;
3974 if (!Buffer.isBuffer(chunk) &&
3975 'string' !== typeof chunk &&
3976 chunk !== null &&
3977 chunk !== undefined &&
3978 !state.objectMode) {
3979 er = new TypeError('Invalid non-string/buffer chunk');
3980 }
3981 return er;
3982}
3983
3984
3985function onEofChunk(stream, state) {
3986 if (state.decoder && !state.ended) {
3987 var chunk = state.decoder.end();
3988 if (chunk && chunk.length) {
3989 state.buffer.push(chunk);
3990 state.length += state.objectMode ? 1 : chunk.length;
3991 }
3992 }
3993 state.ended = true;
3994
3995 // if we've ended and we have some data left, then emit
3996 // 'readable' now to make sure it gets picked up.
3997 if (state.length > 0)
3998 emitReadable(stream);
3999 else
4000 endReadable(stream);
4001}
4002
4003// Don't emit readable right away in sync mode, because this can trigger
4004// another read() call => stack overflow. This way, it might trigger
4005// a nextTick recursion warning, but that's not so bad.
4006function emitReadable(stream) {
4007 var state = stream._readableState;
4008 state.needReadable = false;
4009 if (state.emittedReadable)
4010 return;
4011
4012 state.emittedReadable = true;
4013 if (state.sync)
4014 process.nextTick(function() {
4015 emitReadable_(stream);
4016 });
4017 else
4018 emitReadable_(stream);
4019}
4020
4021function emitReadable_(stream) {
4022 stream.emit('readable');
4023}
4024
4025
4026// at this point, the user has presumably seen the 'readable' event,
4027// and called read() to consume some data. that may have triggered
4028// in turn another _read(n) call, in which case reading = true if
4029// it's in progress.
4030// However, if we're not ended, or reading, and the length < hwm,
4031// then go ahead and try to read some more preemptively.
4032function maybeReadMore(stream, state) {
4033 if (!state.readingMore) {
4034 state.readingMore = true;
4035 process.nextTick(function() {
4036 maybeReadMore_(stream, state);
4037 });
4038 }
4039}
4040
4041function maybeReadMore_(stream, state) {
4042 var len = state.length;
4043 while (!state.reading && !state.flowing && !state.ended &&
4044 state.length < state.highWaterMark) {
4045 stream.read(0);
4046 if (len === state.length)
4047 // didn't get any data, stop spinning.
4048 break;
4049 else
4050 len = state.length;
4051 }
4052 state.readingMore = false;
4053}
4054
4055// abstract method. to be overridden in specific implementation classes.
4056// call cb(er, data) where data is <= n in length.
4057// for virtual (non-string, non-buffer) streams, "length" is somewhat
4058// arbitrary, and perhaps not very meaningful.
4059Readable.prototype._read = function(n) {
4060 this.emit('error', new Error('not implemented'));
4061};
4062
4063Readable.prototype.pipe = function(dest, pipeOpts) {
4064 var src = this;
4065 var state = this._readableState;
4066
4067 switch (state.pipesCount) {
4068 case 0:
4069 state.pipes = dest;
4070 break;
4071 case 1:
4072 state.pipes = [state.pipes, dest];
4073 break;
4074 default:
4075 state.pipes.push(dest);
4076 break;
4077 }
4078 state.pipesCount += 1;
4079
4080 var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
4081 dest !== process.stdout &&
4082 dest !== process.stderr;
4083
4084 var endFn = doEnd ? onend : cleanup;
4085 if (state.endEmitted)
4086 process.nextTick(endFn);
4087 else
4088 src.once('end', endFn);
4089
4090 dest.on('unpipe', onunpipe);
4091 function onunpipe(readable) {
4092 if (readable !== src) return;
4093 cleanup();
4094 }
4095
4096 function onend() {
4097 dest.end();
4098 }
4099
4100 // when the dest drains, it reduces the awaitDrain counter
4101 // on the source. This would be more elegant with a .once()
4102 // handler in flow(), but adding and removing repeatedly is
4103 // too slow.
4104 var ondrain = pipeOnDrain(src);
4105 dest.on('drain', ondrain);
4106
4107 function cleanup() {
4108 // cleanup event handlers once the pipe is broken
4109 dest.removeListener('close', onclose);
4110 dest.removeListener('finish', onfinish);
4111 dest.removeListener('drain', ondrain);
4112 dest.removeListener('error', onerror);
4113 dest.removeListener('unpipe', onunpipe);
4114 src.removeListener('end', onend);
4115 src.removeListener('end', cleanup);
4116
4117 // if the reader is waiting for a drain event from this
4118 // specific writer, then it would cause it to never start
4119 // flowing again.
4120 // So, if this is awaiting a drain, then we just call it now.
4121 // If we don't know, then assume that we are waiting for one.
4122 if (!dest._writableState || dest._writableState.needDrain)
4123 ondrain();
4124 }
4125
4126 // if the dest has an error, then stop piping into it.
4127 // however, don't suppress the throwing behavior for this.
4128 function onerror(er) {
4129 unpipe();
4130 dest.removeListener('error', onerror);
4131 if (EE.listenerCount(dest, 'error') === 0)
4132 dest.emit('error', er);
4133 }
4134 // This is a brutally ugly hack to make sure that our error handler
4135 // is attached before any userland ones. NEVER DO THIS.
4136 if (!dest._events || !dest._events.error)
4137 dest.on('error', onerror);
4138 else if (isArray(dest._events.error))
4139 dest._events.error.unshift(onerror);
4140 else
4141 dest._events.error = [onerror, dest._events.error];
4142
4143
4144
4145 // Both close and finish should trigger unpipe, but only once.
4146 function onclose() {
4147 dest.removeListener('finish', onfinish);
4148 unpipe();
4149 }
4150 dest.once('close', onclose);
4151 function onfinish() {
4152 dest.removeListener('close', onclose);
4153 unpipe();
4154 }
4155 dest.once('finish', onfinish);
4156
4157 function unpipe() {
4158 src.unpipe(dest);
4159 }
4160
4161 // tell the dest that it's being piped to
4162 dest.emit('pipe', src);
4163
4164 // start the flow if it hasn't been started already.
4165 if (!state.flowing) {
4166 // the handler that waits for readable events after all
4167 // the data gets sucked out in flow.
4168 // This would be easier to follow with a .once() handler
4169 // in flow(), but that is too slow.
4170 this.on('readable', pipeOnReadable);
4171
4172 state.flowing = true;
4173 process.nextTick(function() {
4174 flow(src);
4175 });
4176 }
4177
4178 return dest;
4179};
4180
4181function pipeOnDrain(src) {
4182 return function() {
4183 var dest = this;
4184 var state = src._readableState;
4185 state.awaitDrain--;
4186 if (state.awaitDrain === 0)
4187 flow(src);
4188 };
4189}
4190
4191function flow(src) {
4192 var state = src._readableState;
4193 var chunk;
4194 state.awaitDrain = 0;
4195
4196 function write(dest, i, list) {
4197 var written = dest.write(chunk);
4198 if (false === written) {
4199 state.awaitDrain++;
4200 }
4201 }
4202
4203 while (state.pipesCount && null !== (chunk = src.read())) {
4204
4205 if (state.pipesCount === 1)
4206 write(state.pipes, 0, null);
4207 else
4208 forEach(state.pipes, write);
4209
4210 src.emit('data', chunk);
4211
4212 // if anyone needs a drain, then we have to wait for that.
4213 if (state.awaitDrain > 0)
4214 return;
4215 }
4216
4217 // if every destination was unpiped, either before entering this
4218 // function, or in the while loop, then stop flowing.
4219 //
4220 // NB: This is a pretty rare edge case.
4221 if (state.pipesCount === 0) {
4222 state.flowing = false;
4223
4224 // if there were data event listeners added, then switch to old mode.
4225 if (EE.listenerCount(src, 'data') > 0)
4226 emitDataEvents(src);
4227 return;
4228 }
4229
4230 // at this point, no one needed a drain, so we just ran out of data
4231 // on the next readable event, start it over again.
4232 state.ranOut = true;
4233}
4234
4235function pipeOnReadable() {
4236 if (this._readableState.ranOut) {
4237 this._readableState.ranOut = false;
4238 flow(this);
4239 }
4240}
4241
4242
4243Readable.prototype.unpipe = function(dest) {
4244 var state = this._readableState;
4245
4246 // if we're not piping anywhere, then do nothing.
4247 if (state.pipesCount === 0)
4248 return this;
4249
4250 // just one destination. most common case.
4251 if (state.pipesCount === 1) {
4252 // passed in one, but it's not the right one.
4253 if (dest && dest !== state.pipes)
4254 return this;
4255
4256 if (!dest)
4257 dest = state.pipes;
4258
4259 // got a match.
4260 state.pipes = null;
4261 state.pipesCount = 0;
4262 this.removeListener('readable', pipeOnReadable);
4263 state.flowing = false;
4264 if (dest)
4265 dest.emit('unpipe', this);
4266 return this;
4267 }
4268
4269 // slow case. multiple pipe destinations.
4270
4271 if (!dest) {
4272 // remove all.
4273 var dests = state.pipes;
4274 var len = state.pipesCount;
4275 state.pipes = null;
4276 state.pipesCount = 0;
4277 this.removeListener('readable', pipeOnReadable);
4278 state.flowing = false;
4279
4280 for (var i = 0; i < len; i++)
4281 dests[i].emit('unpipe', this);
4282 return this;
4283 }
4284
4285 // try to find the right one.
4286 var i = indexOf(state.pipes, dest);
4287 if (i === -1)
4288 return this;
4289
4290 state.pipes.splice(i, 1);
4291 state.pipesCount -= 1;
4292 if (state.pipesCount === 1)
4293 state.pipes = state.pipes[0];
4294
4295 dest.emit('unpipe', this);
4296
4297 return this;
4298};
4299
4300// set up data events if they are asked for
4301// Ensure readable listeners eventually get something
4302Readable.prototype.on = function(ev, fn) {
4303 var res = Stream.prototype.on.call(this, ev, fn);
4304
4305 if (ev === 'data' && !this._readableState.flowing)
4306 emitDataEvents(this);
4307
4308 if (ev === 'readable' && this.readable) {
4309 var state = this._readableState;
4310 if (!state.readableListening) {
4311 state.readableListening = true;
4312 state.emittedReadable = false;
4313 state.needReadable = true;
4314 if (!state.reading) {
4315 this.read(0);
4316 } else if (state.length) {
4317 emitReadable(this, state);
4318 }
4319 }
4320 }
4321
4322 return res;
4323};
4324Readable.prototype.addListener = Readable.prototype.on;
4325
4326// pause() and resume() are remnants of the legacy readable stream API
4327// If the user uses them, then switch into old mode.
4328Readable.prototype.resume = function() {
4329 emitDataEvents(this);
4330 this.read(0);
4331 this.emit('resume');
4332};
4333
4334Readable.prototype.pause = function() {
4335 emitDataEvents(this, true);
4336 this.emit('pause');
4337};
4338
4339function emitDataEvents(stream, startPaused) {
4340 var state = stream._readableState;
4341
4342 if (state.flowing) {
4343 // https://github.com/isaacs/readable-stream/issues/16
4344 throw new Error('Cannot switch to old mode now.');
4345 }
4346
4347 var paused = startPaused || false;
4348 var readable = false;
4349
4350 // convert to an old-style stream.
4351 stream.readable = true;
4352 stream.pipe = Stream.prototype.pipe;
4353 stream.on = stream.addListener = Stream.prototype.on;
4354
4355 stream.on('readable', function() {
4356 readable = true;
4357
4358 var c;
4359 while (!paused && (null !== (c = stream.read())))
4360 stream.emit('data', c);
4361
4362 if (c === null) {
4363 readable = false;
4364 stream._readableState.needReadable = true;
4365 }
4366 });
4367
4368 stream.pause = function() {
4369 paused = true;
4370 this.emit('pause');
4371 };
4372
4373 stream.resume = function() {
4374 paused = false;
4375 if (readable)
4376 process.nextTick(function() {
4377 stream.emit('readable');
4378 });
4379 else
4380 this.read(0);
4381 this.emit('resume');
4382 };
4383
4384 // now make it start, just in case it hadn't already.
4385 stream.emit('readable');
4386}
4387
4388// wrap an old-style stream as the async data source.
4389// This is *not* part of the readable stream interface.
4390// It is an ugly unfortunate mess of history.
4391Readable.prototype.wrap = function(stream) {
4392 var state = this._readableState;
4393 var paused = false;
4394
4395 var self = this;
4396 stream.on('end', function() {
4397 if (state.decoder && !state.ended) {
4398 var chunk = state.decoder.end();
4399 if (chunk && chunk.length)
4400 self.push(chunk);
4401 }
4402
4403 self.push(null);
4404 });
4405
4406 stream.on('data', function(chunk) {
4407 if (state.decoder)
4408 chunk = state.decoder.write(chunk);
4409
4410 // don't skip over falsy values in objectMode
4411 //if (state.objectMode && util.isNullOrUndefined(chunk))
4412 if (state.objectMode && (chunk === null || chunk === undefined))
4413 return;
4414 else if (!state.objectMode && (!chunk || !chunk.length))
4415 return;
4416
4417 var ret = self.push(chunk);
4418 if (!ret) {
4419 paused = true;
4420 stream.pause();
4421 }
4422 });
4423
4424 // proxy all the other methods.
4425 // important when wrapping filters and duplexes.
4426 for (var i in stream) {
4427 if (typeof stream[i] === 'function' &&
4428 typeof this[i] === 'undefined') {
4429 this[i] = function(method) { return function() {
4430 return stream[method].apply(stream, arguments);
4431 }}(i);
4432 }
4433 }
4434
4435 // proxy certain important events.
4436 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
4437 forEach(events, function(ev) {
4438 stream.on(ev, self.emit.bind(self, ev));
4439 });
4440
4441 // when we try to consume some more bytes, simply unpause the
4442 // underlying stream.
4443 self._read = function(n) {
4444 if (paused) {
4445 paused = false;
4446 stream.resume();
4447 }
4448 };
4449
4450 return self;
4451};
4452
4453
4454
4455// exposed for testing purposes only.
4456Readable._fromList = fromList;
4457
4458// Pluck off n bytes from an array of buffers.
4459// Length is the combined lengths of all the buffers in the list.
4460function fromList(n, state) {
4461 var list = state.buffer;
4462 var length = state.length;
4463 var stringMode = !!state.decoder;
4464 var objectMode = !!state.objectMode;
4465 var ret;
4466
4467 // nothing in the list, definitely empty.
4468 if (list.length === 0)
4469 return null;
4470
4471 if (length === 0)
4472 ret = null;
4473 else if (objectMode)
4474 ret = list.shift();
4475 else if (!n || n >= length) {
4476 // read it all, truncate the array.
4477 if (stringMode)
4478 ret = list.join('');
4479 else
4480 ret = Buffer.concat(list, length);
4481 list.length = 0;
4482 } else {
4483 // read just some of it.
4484 if (n < list[0].length) {
4485 // just take a part of the first list item.
4486 // slice is the same for buffers and strings.
4487 var buf = list[0];
4488 ret = buf.slice(0, n);
4489 list[0] = buf.slice(n);
4490 } else if (n === list[0].length) {
4491 // first list is a perfect match
4492 ret = list.shift();
4493 } else {
4494 // complex case.
4495 // we have enough to cover it, but it spans past the first buffer.
4496 if (stringMode)
4497 ret = '';
4498 else
4499 ret = new Buffer(n);
4500
4501 var c = 0;
4502 for (var i = 0, l = list.length; i < l && c < n; i++) {
4503 var buf = list[0];
4504 var cpy = Math.min(n - c, buf.length);
4505
4506 if (stringMode)
4507 ret += buf.slice(0, cpy);
4508 else
4509 buf.copy(ret, c, 0, cpy);
4510
4511 if (cpy < buf.length)
4512 list[0] = buf.slice(cpy);
4513 else
4514 list.shift();
4515
4516 c += cpy;
4517 }
4518 }
4519 }
4520
4521 return ret;
4522}
4523
4524function endReadable(stream) {
4525 var state = stream._readableState;
4526
4527 // If we get here before consuming all the bytes, then that is a
4528 // bug in node. Should never happen.
4529 if (state.length > 0)
4530 throw new Error('endReadable called on non-empty stream');
4531
4532 if (!state.endEmitted && state.calledRead) {
4533 state.ended = true;
4534 process.nextTick(function() {
4535 // Check that we didn't get one last unshift.
4536 if (!state.endEmitted && state.length === 0) {
4537 state.endEmitted = true;
4538 stream.readable = false;
4539 stream.emit('end');
4540 }
4541 });
4542 }
4543}
4544
4545function forEach (xs, f) {
4546 for (var i = 0, l = xs.length; i < l; i++) {
4547 f(xs[i], i);
4548 }
4549}
4550
4551function indexOf (xs, x) {
4552 for (var i = 0, l = xs.length; i < l; i++) {
4553 if (xs[i] === x) return i;
4554 }
4555 return -1;
4556}
4557
4558}).call(this,require('_process'))
4559},{"_process":24,"buffer":16,"core-util-is":31,"events":20,"inherits":21,"isarray":22,"stream":36,"string_decoder/":37}],29:[function(require,module,exports){
4560// Copyright Joyent, Inc. and other Node contributors.
4561//
4562// Permission is hereby granted, free of charge, to any person obtaining a
4563// copy of this software and associated documentation files (the
4564// "Software"), to deal in the Software without restriction, including
4565// without limitation the rights to use, copy, modify, merge, publish,
4566// distribute, sublicense, and/or sell copies of the Software, and to permit
4567// persons to whom the Software is furnished to do so, subject to the
4568// following conditions:
4569//
4570// The above copyright notice and this permission notice shall be included
4571// in all copies or substantial portions of the Software.
4572//
4573// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4574// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4575// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4576// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4577// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4578// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4579// USE OR OTHER DEALINGS IN THE SOFTWARE.
4580
4581
4582// a transform stream is a readable/writable stream where you do
4583// something with the data. Sometimes it's called a "filter",
4584// but that's not a great name for it, since that implies a thing where
4585// some bits pass through, and others are simply ignored. (That would
4586// be a valid example of a transform, of course.)
4587//
4588// While the output is causally related to the input, it's not a
4589// necessarily symmetric or synchronous transformation. For example,
4590// a zlib stream might take multiple plain-text writes(), and then
4591// emit a single compressed chunk some time in the future.
4592//
4593// Here's how this works:
4594//
4595// The Transform stream has all the aspects of the readable and writable
4596// stream classes. When you write(chunk), that calls _write(chunk,cb)
4597// internally, and returns false if there's a lot of pending writes
4598// buffered up. When you call read(), that calls _read(n) until
4599// there's enough pending readable data buffered up.
4600//
4601// In a transform stream, the written data is placed in a buffer. When
4602// _read(n) is called, it transforms the queued up data, calling the
4603// buffered _write cb's as it consumes chunks. If consuming a single
4604// written chunk would result in multiple output chunks, then the first
4605// outputted bit calls the readcb, and subsequent chunks just go into
4606// the read buffer, and will cause it to emit 'readable' if necessary.
4607//
4608// This way, back-pressure is actually determined by the reading side,
4609// since _read has to be called to start processing a new chunk. However,
4610// a pathological inflate type of transform can cause excessive buffering
4611// here. For example, imagine a stream where every byte of input is
4612// interpreted as an integer from 0-255, and then results in that many
4613// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
4614// 1kb of data being output. In this case, you could write a very small
4615// amount of input, and end up with a very large amount of output. In
4616// such a pathological inflating mechanism, there'd be no way to tell
4617// the system to stop doing the transform. A single 4MB write could
4618// cause the system to run out of memory.
4619//
4620// However, even in such a pathological case, only a single written chunk
4621// would be consumed, and then the rest would wait (un-transformed) until
4622// the results of the previous transformed chunk were consumed.
4623
4624module.exports = Transform;
4625
4626var Duplex = require('./_stream_duplex');
4627
4628/*<replacement>*/
4629var util = require('core-util-is');
4630util.inherits = require('inherits');
4631/*</replacement>*/
4632
4633util.inherits(Transform, Duplex);
4634
4635
4636function TransformState(options, stream) {
4637 this.afterTransform = function(er, data) {
4638 return afterTransform(stream, er, data);
4639 };
4640
4641 this.needTransform = false;
4642 this.transforming = false;
4643 this.writecb = null;
4644 this.writechunk = null;
4645}
4646
4647function afterTransform(stream, er, data) {
4648 var ts = stream._transformState;
4649 ts.transforming = false;
4650
4651 var cb = ts.writecb;
4652
4653 if (!cb)
4654 return stream.emit('error', new Error('no writecb in Transform class'));
4655
4656 ts.writechunk = null;
4657 ts.writecb = null;
4658
4659 if (data !== null && data !== undefined)
4660 stream.push(data);
4661
4662 if (cb)
4663 cb(er);
4664
4665 var rs = stream._readableState;
4666 rs.reading = false;
4667 if (rs.needReadable || rs.length < rs.highWaterMark) {
4668 stream._read(rs.highWaterMark);
4669 }
4670}
4671
4672
4673function Transform(options) {
4674 if (!(this instanceof Transform))
4675 return new Transform(options);
4676
4677 Duplex.call(this, options);
4678
4679 var ts = this._transformState = new TransformState(options, this);
4680
4681 // when the writable side finishes, then flush out anything remaining.
4682 var stream = this;
4683
4684 // start out asking for a readable event once data is transformed.
4685 this._readableState.needReadable = true;
4686
4687 // we have implemented the _read method, and done the other things
4688 // that Readable wants before the first _read call, so unset the
4689 // sync guard flag.
4690 this._readableState.sync = false;
4691
4692 this.once('finish', function() {
4693 if ('function' === typeof this._flush)
4694 this._flush(function(er) {
4695 done(stream, er);
4696 });
4697 else
4698 done(stream);
4699 });
4700}
4701
4702Transform.prototype.push = function(chunk, encoding) {
4703 this._transformState.needTransform = false;
4704 return Duplex.prototype.push.call(this, chunk, encoding);
4705};
4706
4707// This is the part where you do stuff!
4708// override this function in implementation classes.
4709// 'chunk' is an input chunk.
4710//
4711// Call `push(newChunk)` to pass along transformed output
4712// to the readable side. You may call 'push' zero or more times.
4713//
4714// Call `cb(err)` when you are done with this chunk. If you pass
4715// an error, then that'll put the hurt on the whole operation. If you
4716// never call cb(), then you'll never get another chunk.
4717Transform.prototype._transform = function(chunk, encoding, cb) {
4718 throw new Error('not implemented');
4719};
4720
4721Transform.prototype._write = function(chunk, encoding, cb) {
4722 var ts = this._transformState;
4723 ts.writecb = cb;
4724 ts.writechunk = chunk;
4725 ts.writeencoding = encoding;
4726 if (!ts.transforming) {
4727 var rs = this._readableState;
4728 if (ts.needTransform ||
4729 rs.needReadable ||
4730 rs.length < rs.highWaterMark)
4731 this._read(rs.highWaterMark);
4732 }
4733};
4734
4735// Doesn't matter what the args are here.
4736// _transform does all the work.
4737// That we got here means that the readable side wants more data.
4738Transform.prototype._read = function(n) {
4739 var ts = this._transformState;
4740
4741 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
4742 ts.transforming = true;
4743 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
4744 } else {
4745 // mark that we need a transform, so that any data that comes in
4746 // will get processed, now that we've asked for it.
4747 ts.needTransform = true;
4748 }
4749};
4750
4751
4752function done(stream, er) {
4753 if (er)
4754 return stream.emit('error', er);
4755
4756 // if there's nothing in the write buffer, then that means
4757 // that nothing more will ever be provided
4758 var ws = stream._writableState;
4759 var rs = stream._readableState;
4760 var ts = stream._transformState;
4761
4762 if (ws.length)
4763 throw new Error('calling transform done when ws.length != 0');
4764
4765 if (ts.transforming)
4766 throw new Error('calling transform done when still transforming');
4767
4768 return stream.push(null);
4769}
4770
4771},{"./_stream_duplex":26,"core-util-is":31,"inherits":21}],30:[function(require,module,exports){
4772(function (process){
4773// Copyright Joyent, Inc. and other Node contributors.
4774//
4775// Permission is hereby granted, free of charge, to any person obtaining a
4776// copy of this software and associated documentation files (the
4777// "Software"), to deal in the Software without restriction, including
4778// without limitation the rights to use, copy, modify, merge, publish,
4779// distribute, sublicense, and/or sell copies of the Software, and to permit
4780// persons to whom the Software is furnished to do so, subject to the
4781// following conditions:
4782//
4783// The above copyright notice and this permission notice shall be included
4784// in all copies or substantial portions of the Software.
4785//
4786// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4787// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4788// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4789// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4790// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4791// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4792// USE OR OTHER DEALINGS IN THE SOFTWARE.
4793
4794// A bit simpler than readable streams.
4795// Implement an async ._write(chunk, cb), and it'll handle all
4796// the drain event emission and buffering.
4797
4798module.exports = Writable;
4799
4800/*<replacement>*/
4801var Buffer = require('buffer').Buffer;
4802/*</replacement>*/
4803
4804Writable.WritableState = WritableState;
4805
4806
4807/*<replacement>*/
4808var util = require('core-util-is');
4809util.inherits = require('inherits');
4810/*</replacement>*/
4811
4812var Stream = require('stream');
4813
4814util.inherits(Writable, Stream);
4815
4816function WriteReq(chunk, encoding, cb) {
4817 this.chunk = chunk;
4818 this.encoding = encoding;
4819 this.callback = cb;
4820}
4821
4822function WritableState(options, stream) {
4823 options = options || {};
4824
4825 // the point at which write() starts returning false
4826 // Note: 0 is a valid value, means that we always return false if
4827 // the entire buffer is not flushed immediately on write()
4828 var hwm = options.highWaterMark;
4829 this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
4830
4831 // object stream flag to indicate whether or not this stream
4832 // contains buffers or objects.
4833 this.objectMode = !!options.objectMode;
4834
4835 // cast to ints.
4836 this.highWaterMark = ~~this.highWaterMark;
4837
4838 this.needDrain = false;
4839 // at the start of calling end()
4840 this.ending = false;
4841 // when end() has been called, and returned
4842 this.ended = false;
4843 // when 'finish' is emitted
4844 this.finished = false;
4845
4846 // should we decode strings into buffers before passing to _write?
4847 // this is here so that some node-core streams can optimize string
4848 // handling at a lower level.
4849 var noDecode = options.decodeStrings === false;
4850 this.decodeStrings = !noDecode;
4851
4852 // Crypto is kind of old and crusty. Historically, its default string
4853 // encoding is 'binary' so we have to make this configurable.
4854 // Everything else in the universe uses 'utf8', though.
4855 this.defaultEncoding = options.defaultEncoding || 'utf8';
4856
4857 // not an actual buffer we keep track of, but a measurement
4858 // of how much we're waiting to get pushed to some underlying
4859 // socket or file.
4860 this.length = 0;
4861
4862 // a flag to see when we're in the middle of a write.
4863 this.writing = false;
4864
4865 // a flag to be able to tell if the onwrite cb is called immediately,
4866 // or on a later tick. We set this to true at first, becuase any
4867 // actions that shouldn't happen until "later" should generally also
4868 // not happen before the first write call.
4869 this.sync = true;
4870
4871 // a flag to know if we're processing previously buffered items, which
4872 // may call the _write() callback in the same tick, so that we don't
4873 // end up in an overlapped onwrite situation.
4874 this.bufferProcessing = false;
4875
4876 // the callback that's passed to _write(chunk,cb)
4877 this.onwrite = function(er) {
4878 onwrite(stream, er);
4879 };
4880
4881 // the callback that the user supplies to write(chunk,encoding,cb)
4882 this.writecb = null;
4883
4884 // the amount that is being written when _write is called.
4885 this.writelen = 0;
4886
4887 this.buffer = [];
4888
4889 // True if the error was already emitted and should not be thrown again
4890 this.errorEmitted = false;
4891}
4892
4893function Writable(options) {
4894 var Duplex = require('./_stream_duplex');
4895
4896 // Writable ctor is applied to Duplexes, though they're not
4897 // instanceof Writable, they're instanceof Readable.
4898 if (!(this instanceof Writable) && !(this instanceof Duplex))
4899 return new Writable(options);
4900
4901 this._writableState = new WritableState(options, this);
4902
4903 // legacy.
4904 this.writable = true;
4905
4906 Stream.call(this);
4907}
4908
4909// Otherwise people can pipe Writable streams, which is just wrong.
4910Writable.prototype.pipe = function() {
4911 this.emit('error', new Error('Cannot pipe. Not readable.'));
4912};
4913
4914
4915function writeAfterEnd(stream, state, cb) {
4916 var er = new Error('write after end');
4917 // TODO: defer error events consistently everywhere, not just the cb
4918 stream.emit('error', er);
4919 process.nextTick(function() {
4920 cb(er);
4921 });
4922}
4923
4924// If we get something that is not a buffer, string, null, or undefined,
4925// and we're not in objectMode, then that's an error.
4926// Otherwise stream chunks are all considered to be of length=1, and the
4927// watermarks determine how many objects to keep in the buffer, rather than
4928// how many bytes or characters.
4929function validChunk(stream, state, chunk, cb) {
4930 var valid = true;
4931 if (!Buffer.isBuffer(chunk) &&
4932 'string' !== typeof chunk &&
4933 chunk !== null &&
4934 chunk !== undefined &&
4935 !state.objectMode) {
4936 var er = new TypeError('Invalid non-string/buffer chunk');
4937 stream.emit('error', er);
4938 process.nextTick(function() {
4939 cb(er);
4940 });
4941 valid = false;
4942 }
4943 return valid;
4944}
4945
4946Writable.prototype.write = function(chunk, encoding, cb) {
4947 var state = this._writableState;
4948 var ret = false;
4949
4950 if (typeof encoding === 'function') {
4951 cb = encoding;
4952 encoding = null;
4953 }
4954
4955 if (Buffer.isBuffer(chunk))
4956 encoding = 'buffer';
4957 else if (!encoding)
4958 encoding = state.defaultEncoding;
4959
4960 if (typeof cb !== 'function')
4961 cb = function() {};
4962
4963 if (state.ended)
4964 writeAfterEnd(this, state, cb);
4965 else if (validChunk(this, state, chunk, cb))
4966 ret = writeOrBuffer(this, state, chunk, encoding, cb);
4967
4968 return ret;
4969};
4970
4971function decodeChunk(state, chunk, encoding) {
4972 if (!state.objectMode &&
4973 state.decodeStrings !== false &&
4974 typeof chunk === 'string') {
4975 chunk = new Buffer(chunk, encoding);
4976 }
4977 return chunk;
4978}
4979
4980// if we're already writing something, then just put this
4981// in the queue, and wait our turn. Otherwise, call _write
4982// If we return false, then we need a drain event, so set that flag.
4983function writeOrBuffer(stream, state, chunk, encoding, cb) {
4984 chunk = decodeChunk(state, chunk, encoding);
4985 if (Buffer.isBuffer(chunk))
4986 encoding = 'buffer';
4987 var len = state.objectMode ? 1 : chunk.length;
4988
4989 state.length += len;
4990
4991 var ret = state.length < state.highWaterMark;
4992 // we must ensure that previous needDrain will not be reset to false.
4993 if (!ret)
4994 state.needDrain = true;
4995
4996 if (state.writing)
4997 state.buffer.push(new WriteReq(chunk, encoding, cb));
4998 else
4999 doWrite(stream, state, len, chunk, encoding, cb);
5000
5001 return ret;
5002}
5003
5004function doWrite(stream, state, len, chunk, encoding, cb) {
5005 state.writelen = len;
5006 state.writecb = cb;
5007 state.writing = true;
5008 state.sync = true;
5009 stream._write(chunk, encoding, state.onwrite);
5010 state.sync = false;
5011}
5012
5013function onwriteError(stream, state, sync, er, cb) {
5014 if (sync)
5015 process.nextTick(function() {
5016 cb(er);
5017 });
5018 else
5019 cb(er);
5020
5021 stream._writableState.errorEmitted = true;
5022 stream.emit('error', er);
5023}
5024
5025function onwriteStateUpdate(state) {
5026 state.writing = false;
5027 state.writecb = null;
5028 state.length -= state.writelen;
5029 state.writelen = 0;
5030}
5031
5032function onwrite(stream, er) {
5033 var state = stream._writableState;
5034 var sync = state.sync;
5035 var cb = state.writecb;
5036
5037 onwriteStateUpdate(state);
5038
5039 if (er)
5040 onwriteError(stream, state, sync, er, cb);
5041 else {
5042 // Check if we're actually ready to finish, but don't emit yet
5043 var finished = needFinish(stream, state);
5044
5045 if (!finished && !state.bufferProcessing && state.buffer.length)
5046 clearBuffer(stream, state);
5047
5048 if (sync) {
5049 process.nextTick(function() {
5050 afterWrite(stream, state, finished, cb);
5051 });
5052 } else {
5053 afterWrite(stream, state, finished, cb);
5054 }
5055 }
5056}
5057
5058function afterWrite(stream, state, finished, cb) {
5059 if (!finished)
5060 onwriteDrain(stream, state);
5061 cb();
5062 if (finished)
5063 finishMaybe(stream, state);
5064}
5065
5066// Must force callback to be called on nextTick, so that we don't
5067// emit 'drain' before the write() consumer gets the 'false' return
5068// value, and has a chance to attach a 'drain' listener.
5069function onwriteDrain(stream, state) {
5070 if (state.length === 0 && state.needDrain) {
5071 state.needDrain = false;
5072 stream.emit('drain');
5073 }
5074}
5075
5076
5077// if there's something in the buffer waiting, then process it
5078function clearBuffer(stream, state) {
5079 state.bufferProcessing = true;
5080
5081 for (var c = 0; c < state.buffer.length; c++) {
5082 var entry = state.buffer[c];
5083 var chunk = entry.chunk;
5084 var encoding = entry.encoding;
5085 var cb = entry.callback;
5086 var len = state.objectMode ? 1 : chunk.length;
5087
5088 doWrite(stream, state, len, chunk, encoding, cb);
5089
5090 // if we didn't call the onwrite immediately, then
5091 // it means that we need to wait until it does.
5092 // also, that means that the chunk and cb are currently
5093 // being processed, so move the buffer counter past them.
5094 if (state.writing) {
5095 c++;
5096 break;
5097 }
5098 }
5099
5100 state.bufferProcessing = false;
5101 if (c < state.buffer.length)
5102 state.buffer = state.buffer.slice(c);
5103 else
5104 state.buffer.length = 0;
5105}
5106
5107Writable.prototype._write = function(chunk, encoding, cb) {
5108 cb(new Error('not implemented'));
5109};
5110
5111Writable.prototype.end = function(chunk, encoding, cb) {
5112 var state = this._writableState;
5113
5114 if (typeof chunk === 'function') {
5115 cb = chunk;
5116 chunk = null;
5117 encoding = null;
5118 } else if (typeof encoding === 'function') {
5119 cb = encoding;
5120 encoding = null;
5121 }
5122
5123 if (typeof chunk !== 'undefined' && chunk !== null)
5124 this.write(chunk, encoding);
5125
5126 // ignore unnecessary end() calls.
5127 if (!state.ending && !state.finished)
5128 endWritable(this, state, cb);
5129};
5130
5131
5132function needFinish(stream, state) {
5133 return (state.ending &&
5134 state.length === 0 &&
5135 !state.finished &&
5136 !state.writing);
5137}
5138
5139function finishMaybe(stream, state) {
5140 var need = needFinish(stream, state);
5141 if (need) {
5142 state.finished = true;
5143 stream.emit('finish');
5144 }
5145 return need;
5146}
5147
5148function endWritable(stream, state, cb) {
5149 state.ending = true;
5150 finishMaybe(stream, state);
5151 if (cb) {
5152 if (state.finished)
5153 process.nextTick(cb);
5154 else
5155 stream.once('finish', cb);
5156 }
5157 state.ended = true;
5158}
5159
5160}).call(this,require('_process'))
5161},{"./_stream_duplex":26,"_process":24,"buffer":16,"core-util-is":31,"inherits":21,"stream":36}],31:[function(require,module,exports){
5162(function (Buffer){
5163// Copyright Joyent, Inc. and other Node contributors.
5164//
5165// Permission is hereby granted, free of charge, to any person obtaining a
5166// copy of this software and associated documentation files (the
5167// "Software"), to deal in the Software without restriction, including
5168// without limitation the rights to use, copy, modify, merge, publish,
5169// distribute, sublicense, and/or sell copies of the Software, and to permit
5170// persons to whom the Software is furnished to do so, subject to the
5171// following conditions:
5172//
5173// The above copyright notice and this permission notice shall be included
5174// in all copies or substantial portions of the Software.
5175//
5176// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5177// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5178// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5179// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5180// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5181// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5182// USE OR OTHER DEALINGS IN THE SOFTWARE.
5183
5184// NOTE: These type checking functions intentionally don't use `instanceof`
5185// because it is fragile and can be easily faked with `Object.create()`.
5186function isArray(ar) {
5187 return Array.isArray(ar);
5188}
5189exports.isArray = isArray;
5190
5191function isBoolean(arg) {
5192 return typeof arg === 'boolean';
5193}
5194exports.isBoolean = isBoolean;
5195
5196function isNull(arg) {
5197 return arg === null;
5198}
5199exports.isNull = isNull;
5200
5201function isNullOrUndefined(arg) {
5202 return arg == null;
5203}
5204exports.isNullOrUndefined = isNullOrUndefined;
5205
5206function isNumber(arg) {
5207 return typeof arg === 'number';
5208}
5209exports.isNumber = isNumber;
5210
5211function isString(arg) {
5212 return typeof arg === 'string';
5213}
5214exports.isString = isString;
5215
5216function isSymbol(arg) {
5217 return typeof arg === 'symbol';
5218}
5219exports.isSymbol = isSymbol;
5220
5221function isUndefined(arg) {
5222 return arg === void 0;
5223}
5224exports.isUndefined = isUndefined;
5225
5226function isRegExp(re) {
5227 return isObject(re) && objectToString(re) === '[object RegExp]';
5228}
5229exports.isRegExp = isRegExp;
5230
5231function isObject(arg) {
5232 return typeof arg === 'object' && arg !== null;
5233}
5234exports.isObject = isObject;
5235
5236function isDate(d) {
5237 return isObject(d) && objectToString(d) === '[object Date]';
5238}
5239exports.isDate = isDate;
5240
5241function isError(e) {
5242 return isObject(e) &&
5243 (objectToString(e) === '[object Error]' || e instanceof Error);
5244}
5245exports.isError = isError;
5246
5247function isFunction(arg) {
5248 return typeof arg === 'function';
5249}
5250exports.isFunction = isFunction;
5251
5252function isPrimitive(arg) {
5253 return arg === null ||
5254 typeof arg === 'boolean' ||
5255 typeof arg === 'number' ||
5256 typeof arg === 'string' ||
5257 typeof arg === 'symbol' || // ES6 symbol
5258 typeof arg === 'undefined';
5259}
5260exports.isPrimitive = isPrimitive;
5261
5262function isBuffer(arg) {
5263 return Buffer.isBuffer(arg);
5264}
5265exports.isBuffer = isBuffer;
5266
5267function objectToString(o) {
5268 return Object.prototype.toString.call(o);
5269}
5270}).call(this,require("buffer").Buffer)
5271},{"buffer":16}],32:[function(require,module,exports){
5272module.exports = require("./lib/_stream_passthrough.js")
5273
5274},{"./lib/_stream_passthrough.js":27}],33:[function(require,module,exports){
5275var Stream = require('stream'); // hack to fix a circular dependency issue when used with browserify
5276exports = module.exports = require('./lib/_stream_readable.js');
5277exports.Stream = Stream;
5278exports.Readable = exports;
5279exports.Writable = require('./lib/_stream_writable.js');
5280exports.Duplex = require('./lib/_stream_duplex.js');
5281exports.Transform = require('./lib/_stream_transform.js');
5282exports.PassThrough = require('./lib/_stream_passthrough.js');
5283
5284},{"./lib/_stream_duplex.js":26,"./lib/_stream_passthrough.js":27,"./lib/_stream_readable.js":28,"./lib/_stream_transform.js":29,"./lib/_stream_writable.js":30,"stream":36}],34:[function(require,module,exports){
5285module.exports = require("./lib/_stream_transform.js")
5286
5287},{"./lib/_stream_transform.js":29}],35:[function(require,module,exports){
5288module.exports = require("./lib/_stream_writable.js")
5289
5290},{"./lib/_stream_writable.js":30}],36:[function(require,module,exports){
5291// Copyright Joyent, Inc. and other Node contributors.
5292//
5293// Permission is hereby granted, free of charge, to any person obtaining a
5294// copy of this software and associated documentation files (the
5295// "Software"), to deal in the Software without restriction, including
5296// without limitation the rights to use, copy, modify, merge, publish,
5297// distribute, sublicense, and/or sell copies of the Software, and to permit
5298// persons to whom the Software is furnished to do so, subject to the
5299// following conditions:
5300//
5301// The above copyright notice and this permission notice shall be included
5302// in all copies or substantial portions of the Software.
5303//
5304// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5305// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5306// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5307// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5308// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5309// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5310// USE OR OTHER DEALINGS IN THE SOFTWARE.
5311
5312module.exports = Stream;
5313
5314var EE = require('events').EventEmitter;
5315var inherits = require('inherits');
5316
5317inherits(Stream, EE);
5318Stream.Readable = require('readable-stream/readable.js');
5319Stream.Writable = require('readable-stream/writable.js');
5320Stream.Duplex = require('readable-stream/duplex.js');
5321Stream.Transform = require('readable-stream/transform.js');
5322Stream.PassThrough = require('readable-stream/passthrough.js');
5323
5324// Backwards-compat with node 0.4.x
5325Stream.Stream = Stream;
5326
5327
5328
5329// old-style streams. Note that the pipe method (the only relevant
5330// part of this class) is overridden in the Readable class.
5331
5332function Stream() {
5333 EE.call(this);
5334}
5335
5336Stream.prototype.pipe = function(dest, options) {
5337 var source = this;
5338
5339 function ondata(chunk) {
5340 if (dest.writable) {
5341 if (false === dest.write(chunk) && source.pause) {
5342 source.pause();
5343 }
5344 }
5345 }
5346
5347 source.on('data', ondata);
5348
5349 function ondrain() {
5350 if (source.readable && source.resume) {
5351 source.resume();
5352 }
5353 }
5354
5355 dest.on('drain', ondrain);
5356
5357 // If the 'end' option is not supplied, dest.end() will be called when
5358 // source gets the 'end' or 'close' events. Only dest.end() once.
5359 if (!dest._isStdio && (!options || options.end !== false)) {
5360 source.on('end', onend);
5361 source.on('close', onclose);
5362 }
5363
5364 var didOnEnd = false;
5365 function onend() {
5366 if (didOnEnd) return;
5367 didOnEnd = true;
5368
5369 dest.end();
5370 }
5371
5372
5373 function onclose() {
5374 if (didOnEnd) return;
5375 didOnEnd = true;
5376
5377 if (typeof dest.destroy === 'function') dest.destroy();
5378 }
5379
5380 // don't leave dangling pipes when there are errors.
5381 function onerror(er) {
5382 cleanup();
5383 if (EE.listenerCount(this, 'error') === 0) {
5384 throw er; // Unhandled stream error in pipe.
5385 }
5386 }
5387
5388 source.on('error', onerror);
5389 dest.on('error', onerror);
5390
5391 // remove all the event listeners that were added.
5392 function cleanup() {
5393 source.removeListener('data', ondata);
5394 dest.removeListener('drain', ondrain);
5395
5396 source.removeListener('end', onend);
5397 source.removeListener('close', onclose);
5398
5399 source.removeListener('error', onerror);
5400 dest.removeListener('error', onerror);
5401
5402 source.removeListener('end', cleanup);
5403 source.removeListener('close', cleanup);
5404
5405 dest.removeListener('close', cleanup);
5406 }
5407
5408 source.on('end', cleanup);
5409 source.on('close', cleanup);
5410
5411 dest.on('close', cleanup);
5412
5413 dest.emit('pipe', source);
5414
5415 // Allow for unix-like usage: A.pipe(B).pipe(C)
5416 return dest;
5417};
5418
5419},{"events":20,"inherits":21,"readable-stream/duplex.js":25,"readable-stream/passthrough.js":32,"readable-stream/readable.js":33,"readable-stream/transform.js":34,"readable-stream/writable.js":35}],37:[function(require,module,exports){
5420// Copyright Joyent, Inc. and other Node contributors.
5421//
5422// Permission is hereby granted, free of charge, to any person obtaining a
5423// copy of this software and associated documentation files (the
5424// "Software"), to deal in the Software without restriction, including
5425// without limitation the rights to use, copy, modify, merge, publish,
5426// distribute, sublicense, and/or sell copies of the Software, and to permit
5427// persons to whom the Software is furnished to do so, subject to the
5428// following conditions:
5429//
5430// The above copyright notice and this permission notice shall be included
5431// in all copies or substantial portions of the Software.
5432//
5433// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5434// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5435// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5436// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5437// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5438// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5439// USE OR OTHER DEALINGS IN THE SOFTWARE.
5440
5441var Buffer = require('buffer').Buffer;
5442
5443var isBufferEncoding = Buffer.isEncoding
5444 || function(encoding) {
5445 switch (encoding && encoding.toLowerCase()) {
5446 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;
5447 default: return false;
5448 }
5449 }
5450
5451
5452function assertEncoding(encoding) {
5453 if (encoding && !isBufferEncoding(encoding)) {
5454 throw new Error('Unknown encoding: ' + encoding);
5455 }
5456}
5457
5458// StringDecoder provides an interface for efficiently splitting a series of
5459// buffers into a series of JS strings without breaking apart multi-byte
5460// characters. CESU-8 is handled as part of the UTF-8 encoding.
5461//
5462// @TODO Handling all encodings inside a single object makes it very difficult
5463// to reason about this code, so it should be split up in the future.
5464// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
5465// points as used by CESU-8.
5466var StringDecoder = exports.StringDecoder = function(encoding) {
5467 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
5468 assertEncoding(encoding);
5469 switch (this.encoding) {
5470 case 'utf8':
5471 // CESU-8 represents each of Surrogate Pair by 3-bytes
5472 this.surrogateSize = 3;
5473 break;
5474 case 'ucs2':
5475 case 'utf16le':
5476 // UTF-16 represents each of Surrogate Pair by 2-bytes
5477 this.surrogateSize = 2;
5478 this.detectIncompleteChar = utf16DetectIncompleteChar;
5479 break;
5480 case 'base64':
5481 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
5482 this.surrogateSize = 3;
5483 this.detectIncompleteChar = base64DetectIncompleteChar;
5484 break;
5485 default:
5486 this.write = passThroughWrite;
5487 return;
5488 }
5489
5490 // Enough space to store all bytes of a single character. UTF-8 needs 4
5491 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
5492 this.charBuffer = new Buffer(6);
5493 // Number of bytes received for the current incomplete multi-byte character.
5494 this.charReceived = 0;
5495 // Number of bytes expected for the current incomplete multi-byte character.
5496 this.charLength = 0;
5497};
5498
5499
5500// write decodes the given buffer and returns it as JS string that is
5501// guaranteed to not contain any partial multi-byte characters. Any partial
5502// character found at the end of the buffer is buffered up, and will be
5503// returned when calling write again with the remaining bytes.
5504//
5505// Note: Converting a Buffer containing an orphan surrogate to a String
5506// currently works, but converting a String to a Buffer (via `new Buffer`, or
5507// Buffer#write) will replace incomplete surrogates with the unicode
5508// replacement character. See https://codereview.chromium.org/121173009/ .
5509StringDecoder.prototype.write = function(buffer) {
5510 var charStr = '';
5511 // if our last write ended with an incomplete multibyte character
5512 while (this.charLength) {
5513 // determine how many remaining bytes this buffer has to offer for this char
5514 var available = (buffer.length >= this.charLength - this.charReceived) ?
5515 this.charLength - this.charReceived :
5516 buffer.length;
5517
5518 // add the new bytes to the char buffer
5519 buffer.copy(this.charBuffer, this.charReceived, 0, available);
5520 this.charReceived += available;
5521
5522 if (this.charReceived < this.charLength) {
5523 // still not enough chars in this buffer? wait for more ...
5524 return '';
5525 }
5526
5527 // remove bytes belonging to the current character from the buffer
5528 buffer = buffer.slice(available, buffer.length);
5529
5530 // get the character that was split
5531 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
5532
5533 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
5534 var charCode = charStr.charCodeAt(charStr.length - 1);
5535 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
5536 this.charLength += this.surrogateSize;
5537 charStr = '';
5538 continue;
5539 }
5540 this.charReceived = this.charLength = 0;
5541
5542 // if there are no more bytes in this buffer, just emit our char
5543 if (buffer.length === 0) {
5544 return charStr;
5545 }
5546 break;
5547 }
5548
5549 // determine and set charLength / charReceived
5550 this.detectIncompleteChar(buffer);
5551
5552 var end = buffer.length;
5553 if (this.charLength) {
5554 // buffer the incomplete character bytes we got
5555 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
5556 end -= this.charReceived;
5557 }
5558
5559 charStr += buffer.toString(this.encoding, 0, end);
5560
5561 var end = charStr.length - 1;
5562 var charCode = charStr.charCodeAt(end);
5563 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
5564 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
5565 var size = this.surrogateSize;
5566 this.charLength += size;
5567 this.charReceived += size;
5568 this.charBuffer.copy(this.charBuffer, size, 0, size);
5569 buffer.copy(this.charBuffer, 0, 0, size);
5570 return charStr.substring(0, end);
5571 }
5572
5573 // or just emit the charStr
5574 return charStr;
5575};
5576
5577// detectIncompleteChar determines if there is an incomplete UTF-8 character at
5578// the end of the given buffer. If so, it sets this.charLength to the byte
5579// length that character, and sets this.charReceived to the number of bytes
5580// that are available for this character.
5581StringDecoder.prototype.detectIncompleteChar = function(buffer) {
5582 // determine how many bytes we have to check at the end of this buffer
5583 var i = (buffer.length >= 3) ? 3 : buffer.length;
5584
5585 // Figure out if one of the last i bytes of our buffer announces an
5586 // incomplete char.
5587 for (; i > 0; i--) {
5588 var c = buffer[buffer.length - i];
5589
5590 // See http://en.wikipedia.org/wiki/UTF-8#Description
5591
5592 // 110XXXXX
5593 if (i == 1 && c >> 5 == 0x06) {
5594 this.charLength = 2;
5595 break;
5596 }
5597
5598 // 1110XXXX
5599 if (i <= 2 && c >> 4 == 0x0E) {
5600 this.charLength = 3;
5601 break;
5602 }
5603
5604 // 11110XXX
5605 if (i <= 3 && c >> 3 == 0x1E) {
5606 this.charLength = 4;
5607 break;
5608 }
5609 }
5610 this.charReceived = i;
5611};
5612
5613StringDecoder.prototype.end = function(buffer) {
5614 var res = '';
5615 if (buffer && buffer.length)
5616 res = this.write(buffer);
5617
5618 if (this.charReceived) {
5619 var cr = this.charReceived;
5620 var buf = this.charBuffer;
5621 var enc = this.encoding;
5622 res += buf.slice(0, cr).toString(enc);
5623 }
5624
5625 return res;
5626};
5627
5628function passThroughWrite(buffer) {
5629 return buffer.toString(this.encoding);
5630}
5631
5632function utf16DetectIncompleteChar(buffer) {
5633 this.charReceived = buffer.length % 2;
5634 this.charLength = this.charReceived ? 2 : 0;
5635}
5636
5637function base64DetectIncompleteChar(buffer) {
5638 this.charReceived = buffer.length % 3;
5639 this.charLength = this.charReceived ? 3 : 0;
5640}
5641
5642},{"buffer":16}]},{},[14]);