UNPKG

423 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(function (process,global){
3'use strict';
4
5/* eslint no-unused-vars: off */
6/* eslint-env commonjs */
7
8/**
9 * Shim process.stdout.
10 */
11
12process.stdout = require('browser-stdout')();
13
14var Mocha = require('./lib/mocha');
15
16/**
17 * Create a Mocha instance.
18 *
19 * @return {undefined}
20 */
21
22var mocha = new Mocha({ reporter: 'html' });
23
24/**
25 * Save timer references to avoid Sinon interfering (see GH-237).
26 */
27
28var Date = global.Date;
29var setTimeout = global.setTimeout;
30var setInterval = global.setInterval;
31var clearTimeout = global.clearTimeout;
32var clearInterval = global.clearInterval;
33
34var uncaughtExceptionHandlers = [];
35
36var originalOnerrorHandler = global.onerror;
37
38/**
39 * Remove uncaughtException listener.
40 * Revert to original onerror handler if previously defined.
41 */
42
43process.removeListener = function (e, fn) {
44 if (e === 'uncaughtException') {
45 if (originalOnerrorHandler) {
46 global.onerror = originalOnerrorHandler;
47 } else {
48 global.onerror = function () {};
49 }
50 var i = Mocha.utils.indexOf(uncaughtExceptionHandlers, fn);
51 if (i !== -1) {
52 uncaughtExceptionHandlers.splice(i, 1);
53 }
54 }
55};
56
57/**
58 * Implements uncaughtException listener.
59 */
60
61process.on = function (e, fn) {
62 if (e === 'uncaughtException') {
63 global.onerror = function (err, url, line) {
64 fn(new Error(err + ' (' + url + ':' + line + ')'));
65 return !mocha.allowUncaught;
66 };
67 uncaughtExceptionHandlers.push(fn);
68 }
69};
70
71// The BDD UI is registered by default, but no UI will be functional in the
72// browser without an explicit call to the overridden `mocha.ui` (see below).
73// Ensure that this default UI does not expose its methods to the global scope.
74mocha.suite.removeAllListeners('pre-require');
75
76var immediateQueue = [];
77var immediateTimeout;
78
79function timeslice () {
80 var immediateStart = new Date().getTime();
81 while (immediateQueue.length && (new Date().getTime() - immediateStart) < 100) {
82 immediateQueue.shift()();
83 }
84 if (immediateQueue.length) {
85 immediateTimeout = setTimeout(timeslice, 0);
86 } else {
87 immediateTimeout = null;
88 }
89}
90
91/**
92 * High-performance override of Runner.immediately.
93 */
94
95Mocha.Runner.immediately = function (callback) {
96 immediateQueue.push(callback);
97 if (!immediateTimeout) {
98 immediateTimeout = setTimeout(timeslice, 0);
99 }
100};
101
102/**
103 * Function to allow assertion libraries to throw errors directly into mocha.
104 * This is useful when running tests in a browser because window.onerror will
105 * only receive the 'message' attribute of the Error.
106 */
107mocha.throwError = function (err) {
108 Mocha.utils.forEach(uncaughtExceptionHandlers, function (fn) {
109 fn(err);
110 });
111 throw err;
112};
113
114/**
115 * Override ui to ensure that the ui functions are initialized.
116 * Normally this would happen in Mocha.prototype.loadFiles.
117 */
118
119mocha.ui = function (ui) {
120 Mocha.prototype.ui.call(this, ui);
121 this.suite.emit('pre-require', global, null, this);
122 return this;
123};
124
125/**
126 * Setup mocha with the given setting options.
127 */
128
129mocha.setup = function (opts) {
130 if (typeof opts === 'string') {
131 opts = { ui: opts };
132 }
133 for (var opt in opts) {
134 if (opts.hasOwnProperty(opt)) {
135 this[opt](opts[opt]);
136 }
137 }
138 return this;
139};
140
141/**
142 * Run mocha, returning the Runner.
143 */
144
145mocha.run = function (fn) {
146 var options = mocha.options;
147 mocha.globals('location');
148
149 var query = Mocha.utils.parseQuery(global.location.search || '');
150 if (query.grep) {
151 mocha.grep(query.grep);
152 }
153 if (query.fgrep) {
154 mocha.fgrep(query.fgrep);
155 }
156 if (query.invert) {
157 mocha.invert();
158 }
159
160 return Mocha.prototype.run.call(mocha, function (err) {
161 // The DOM Document is not available in Web Workers.
162 var document = global.document;
163 if (document && document.getElementById('mocha') && options.noHighlighting !== true) {
164 Mocha.utils.highlightTags('code');
165 }
166 if (fn) {
167 fn(err);
168 }
169 });
170};
171
172/**
173 * Expose the process shim.
174 * https://github.com/mochajs/mocha/pull/916
175 */
176
177Mocha.process = process;
178
179/**
180 * Expose mocha.
181 */
182
183global.Mocha = Mocha;
184global.mocha = mocha;
185
186// this allows test/acceptance/required-tokens.js to pass; thus,
187// you can now do `const describe = require('mocha').describe` in a
188// browser context (assuming browserification). should fix #880
189module.exports = global;
190
191}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
192},{"./lib/mocha":14,"_process":67,"browser-stdout":41}],2:[function(require,module,exports){
193'use strict';
194
195function noop () {}
196
197module.exports = function () {
198 return noop;
199};
200
201},{}],3:[function(require,module,exports){
202'use strict';
203
204/**
205 * Module exports.
206 */
207
208exports.EventEmitter = EventEmitter;
209
210/**
211 * Object#toString reference.
212 */
213var objToString = Object.prototype.toString;
214
215/**
216 * Check if a value is an array.
217 *
218 * @api private
219 * @param {*} val The value to test.
220 * @return {boolean} true if the value is an array, otherwise false.
221 */
222function isArray (val) {
223 return objToString.call(val) === '[object Array]';
224}
225
226/**
227 * Event emitter constructor.
228 *
229 * @api public
230 */
231function EventEmitter () {}
232
233/**
234 * Add a listener.
235 *
236 * @api public
237 * @param {string} name Event name.
238 * @param {Function} fn Event handler.
239 * @return {EventEmitter} Emitter instance.
240 */
241EventEmitter.prototype.on = function (name, fn) {
242 if (!this.$events) {
243 this.$events = {};
244 }
245
246 if (!this.$events[name]) {
247 this.$events[name] = fn;
248 } else if (isArray(this.$events[name])) {
249 this.$events[name].push(fn);
250 } else {
251 this.$events[name] = [this.$events[name], fn];
252 }
253
254 return this;
255};
256
257EventEmitter.prototype.addListener = EventEmitter.prototype.on;
258
259/**
260 * Adds a volatile listener.
261 *
262 * @api public
263 * @param {string} name Event name.
264 * @param {Function} fn Event handler.
265 * @return {EventEmitter} Emitter instance.
266 */
267EventEmitter.prototype.once = function (name, fn) {
268 var self = this;
269
270 function on () {
271 self.removeListener(name, on);
272 fn.apply(this, arguments);
273 }
274
275 on.listener = fn;
276 this.on(name, on);
277
278 return this;
279};
280
281/**
282 * Remove a listener.
283 *
284 * @api public
285 * @param {string} name Event name.
286 * @param {Function} fn Event handler.
287 * @return {EventEmitter} Emitter instance.
288 */
289EventEmitter.prototype.removeListener = function (name, fn) {
290 if (this.$events && this.$events[name]) {
291 var list = this.$events[name];
292
293 if (isArray(list)) {
294 var pos = -1;
295
296 for (var i = 0, l = list.length; i < l; i++) {
297 if (list[i] === fn || (list[i].listener && list[i].listener === fn)) {
298 pos = i;
299 break;
300 }
301 }
302
303 if (pos < 0) {
304 return this;
305 }
306
307 list.splice(pos, 1);
308
309 if (!list.length) {
310 delete this.$events[name];
311 }
312 } else if (list === fn || (list.listener && list.listener === fn)) {
313 delete this.$events[name];
314 }
315 }
316
317 return this;
318};
319
320/**
321 * Remove all listeners for an event.
322 *
323 * @api public
324 * @param {string} name Event name.
325 * @return {EventEmitter} Emitter instance.
326 */
327EventEmitter.prototype.removeAllListeners = function (name) {
328 if (name === undefined) {
329 this.$events = {};
330 return this;
331 }
332
333 if (this.$events && this.$events[name]) {
334 this.$events[name] = null;
335 }
336
337 return this;
338};
339
340/**
341 * Get all listeners for a given event.
342 *
343 * @api public
344 * @param {string} name Event name.
345 * @return {EventEmitter} Emitter instance.
346 */
347EventEmitter.prototype.listeners = function (name) {
348 if (!this.$events) {
349 this.$events = {};
350 }
351
352 if (!this.$events[name]) {
353 this.$events[name] = [];
354 }
355
356 if (!isArray(this.$events[name])) {
357 this.$events[name] = [this.$events[name]];
358 }
359
360 return this.$events[name];
361};
362
363/**
364 * Emit an event.
365 *
366 * @api public
367 * @param {string} name Event name.
368 * @return {boolean} true if at least one handler was invoked, else false.
369 */
370EventEmitter.prototype.emit = function (name) {
371 if (!this.$events) {
372 return false;
373 }
374
375 var handler = this.$events[name];
376
377 if (!handler) {
378 return false;
379 }
380
381 var args = Array.prototype.slice.call(arguments, 1);
382
383 if (typeof handler === 'function') {
384 handler.apply(this, args);
385 } else if (isArray(handler)) {
386 var listeners = handler.slice();
387
388 for (var i = 0, l = listeners.length; i < l; i++) {
389 listeners[i].apply(this, args);
390 }
391 } else {
392 return false;
393 }
394
395 return true;
396};
397
398},{}],4:[function(require,module,exports){
399'use strict';
400
401/**
402 * Expose `Progress`.
403 */
404
405module.exports = Progress;
406
407/**
408 * Initialize a new `Progress` indicator.
409 */
410function Progress () {
411 this.percent = 0;
412 this.size(0);
413 this.fontSize(11);
414 this.font('helvetica, arial, sans-serif');
415}
416
417/**
418 * Set progress size to `size`.
419 *
420 * @api public
421 * @param {number} size
422 * @return {Progress} Progress instance.
423 */
424Progress.prototype.size = function (size) {
425 this._size = size;
426 return this;
427};
428
429/**
430 * Set text to `text`.
431 *
432 * @api public
433 * @param {string} text
434 * @return {Progress} Progress instance.
435 */
436Progress.prototype.text = function (text) {
437 this._text = text;
438 return this;
439};
440
441/**
442 * Set font size to `size`.
443 *
444 * @api public
445 * @param {number} size
446 * @return {Progress} Progress instance.
447 */
448Progress.prototype.fontSize = function (size) {
449 this._fontSize = size;
450 return this;
451};
452
453/**
454 * Set font to `family`.
455 *
456 * @param {string} family
457 * @return {Progress} Progress instance.
458 */
459Progress.prototype.font = function (family) {
460 this._font = family;
461 return this;
462};
463
464/**
465 * Update percentage to `n`.
466 *
467 * @param {number} n
468 * @return {Progress} Progress instance.
469 */
470Progress.prototype.update = function (n) {
471 this.percent = n;
472 return this;
473};
474
475/**
476 * Draw on `ctx`.
477 *
478 * @param {CanvasRenderingContext2d} ctx
479 * @return {Progress} Progress instance.
480 */
481Progress.prototype.draw = function (ctx) {
482 try {
483 var percent = Math.min(this.percent, 100);
484 var size = this._size;
485 var half = size / 2;
486 var x = half;
487 var y = half;
488 var rad = half - 1;
489 var fontSize = this._fontSize;
490
491 ctx.font = fontSize + 'px ' + this._font;
492
493 var angle = Math.PI * 2 * (percent / 100);
494 ctx.clearRect(0, 0, size, size);
495
496 // outer circle
497 ctx.strokeStyle = '#9f9f9f';
498 ctx.beginPath();
499 ctx.arc(x, y, rad, 0, angle, false);
500 ctx.stroke();
501
502 // inner circle
503 ctx.strokeStyle = '#eee';
504 ctx.beginPath();
505 ctx.arc(x, y, rad - 1, 0, angle, true);
506 ctx.stroke();
507
508 // text
509 var text = this._text || (percent | 0) + '%';
510 var w = ctx.measureText(text).width;
511
512 ctx.fillText(text, x - w / 2 + 1, y + fontSize / 2 - 1);
513 } catch (err) {
514 // don't fail if we can't render progress
515 }
516 return this;
517};
518
519},{}],5:[function(require,module,exports){
520(function (global){
521'use strict';
522
523exports.isatty = function isatty () {
524 return true;
525};
526
527exports.getWindowSize = function getWindowSize () {
528 if ('innerHeight' in global) {
529 return [global.innerHeight, global.innerWidth];
530 }
531 // In a Web Worker, the DOM Window is not available.
532 return [640, 480];
533};
534
535}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
536},{}],6:[function(require,module,exports){
537'use strict';
538
539/**
540 * Module dependencies.
541 */
542
543var JSON = require('json3');
544
545/**
546 * Expose `Context`.
547 */
548
549module.exports = Context;
550
551/**
552 * Initialize a new `Context`.
553 *
554 * @api private
555 */
556function Context () {}
557
558/**
559 * Set or get the context `Runnable` to `runnable`.
560 *
561 * @api private
562 * @param {Runnable} runnable
563 * @return {Context}
564 */
565Context.prototype.runnable = function (runnable) {
566 if (!arguments.length) {
567 return this._runnable;
568 }
569 this.test = this._runnable = runnable;
570 return this;
571};
572
573/**
574 * Set test timeout `ms`.
575 *
576 * @api private
577 * @param {number} ms
578 * @return {Context} self
579 */
580Context.prototype.timeout = function (ms) {
581 if (!arguments.length) {
582 return this.runnable().timeout();
583 }
584 this.runnable().timeout(ms);
585 return this;
586};
587
588/**
589 * Set test timeout `enabled`.
590 *
591 * @api private
592 * @param {boolean} enabled
593 * @return {Context} self
594 */
595Context.prototype.enableTimeouts = function (enabled) {
596 this.runnable().enableTimeouts(enabled);
597 return this;
598};
599
600/**
601 * Set test slowness threshold `ms`.
602 *
603 * @api private
604 * @param {number} ms
605 * @return {Context} self
606 */
607Context.prototype.slow = function (ms) {
608 this.runnable().slow(ms);
609 return this;
610};
611
612/**
613 * Mark a test as skipped.
614 *
615 * @api private
616 * @return {Context} self
617 */
618Context.prototype.skip = function () {
619 this.runnable().skip();
620 return this;
621};
622
623/**
624 * Allow a number of retries on failed tests
625 *
626 * @api private
627 * @param {number} n
628 * @return {Context} self
629 */
630Context.prototype.retries = function (n) {
631 if (!arguments.length) {
632 return this.runnable().retries();
633 }
634 this.runnable().retries(n);
635 return this;
636};
637
638/**
639 * Inspect the context void of `._runnable`.
640 *
641 * @api private
642 * @return {string}
643 */
644Context.prototype.inspect = function () {
645 return JSON.stringify(this, function (key, val) {
646 return key === 'runnable' || key === 'test' ? undefined : val;
647 }, 2);
648};
649
650},{"json3":54}],7:[function(require,module,exports){
651'use strict';
652
653/**
654 * Module dependencies.
655 */
656
657var Runnable = require('./runnable');
658var inherits = require('./utils').inherits;
659
660/**
661 * Expose `Hook`.
662 */
663
664module.exports = Hook;
665
666/**
667 * Initialize a new `Hook` with the given `title` and callback `fn`.
668 *
669 * @param {String} title
670 * @param {Function} fn
671 * @api private
672 */
673function Hook (title, fn) {
674 Runnable.call(this, title, fn);
675 this.type = 'hook';
676}
677
678/**
679 * Inherit from `Runnable.prototype`.
680 */
681inherits(Hook, Runnable);
682
683/**
684 * Get or set the test `err`.
685 *
686 * @param {Error} err
687 * @return {Error}
688 * @api public
689 */
690Hook.prototype.error = function (err) {
691 if (!arguments.length) {
692 err = this._error;
693 this._error = null;
694 return err;
695 }
696
697 this._error = err;
698};
699
700},{"./runnable":33,"./utils":38}],8:[function(require,module,exports){
701'use strict';
702
703/**
704 * Module dependencies.
705 */
706
707var Test = require('../test');
708
709/**
710 * BDD-style interface:
711 *
712 * describe('Array', function() {
713 * describe('#indexOf()', function() {
714 * it('should return -1 when not present', function() {
715 * // ...
716 * });
717 *
718 * it('should return the index when present', function() {
719 * // ...
720 * });
721 * });
722 * });
723 *
724 * @param {Suite} suite Root suite.
725 */
726module.exports = function (suite) {
727 var suites = [suite];
728
729 suite.on('pre-require', function (context, file, mocha) {
730 var common = require('./common')(suites, context, mocha);
731
732 context.before = common.before;
733 context.after = common.after;
734 context.beforeEach = common.beforeEach;
735 context.afterEach = common.afterEach;
736 context.run = mocha.options.delay && common.runWithSuite(suite);
737 /**
738 * Describe a "suite" with the given `title`
739 * and callback `fn` containing nested suites
740 * and/or tests.
741 */
742
743 context.describe = context.context = function (title, fn) {
744 return common.suite.create({
745 title: title,
746 file: file,
747 fn: fn
748 });
749 };
750
751 /**
752 * Pending describe.
753 */
754
755 context.xdescribe = context.xcontext = context.describe.skip = function (title, fn) {
756 return common.suite.skip({
757 title: title,
758 file: file,
759 fn: fn
760 });
761 };
762
763 /**
764 * Exclusive suite.
765 */
766
767 context.describe.only = function (title, fn) {
768 return common.suite.only({
769 title: title,
770 file: file,
771 fn: fn
772 });
773 };
774
775 /**
776 * Describe a specification or test-case
777 * with the given `title` and callback `fn`
778 * acting as a thunk.
779 */
780
781 context.it = context.specify = function (title, fn) {
782 var suite = suites[0];
783 if (suite.isPending()) {
784 fn = null;
785 }
786 var test = new Test(title, fn);
787 test.file = file;
788 suite.addTest(test);
789 return test;
790 };
791
792 /**
793 * Exclusive test-case.
794 */
795
796 context.it.only = function (title, fn) {
797 return common.test.only(mocha, context.it(title, fn));
798 };
799
800 /**
801 * Pending test case.
802 */
803
804 context.xit = context.xspecify = context.it.skip = function (title) {
805 context.it(title);
806 };
807
808 /**
809 * Number of attempts to retry.
810 */
811 context.it.retries = function (n) {
812 context.retries(n);
813 };
814 });
815};
816
817},{"../test":36,"./common":9}],9:[function(require,module,exports){
818'use strict';
819
820var Suite = require('../suite');
821
822/**
823 * Functions common to more than one interface.
824 *
825 * @param {Suite[]} suites
826 * @param {Context} context
827 * @param {Mocha} mocha
828 * @return {Object} An object containing common functions.
829 */
830module.exports = function (suites, context, mocha) {
831 return {
832 /**
833 * This is only present if flag --delay is passed into Mocha. It triggers
834 * root suite execution.
835 *
836 * @param {Suite} suite The root suite.
837 * @return {Function} A function which runs the root suite
838 */
839 runWithSuite: function runWithSuite (suite) {
840 return function run () {
841 suite.run();
842 };
843 },
844
845 /**
846 * Execute before running tests.
847 *
848 * @param {string} name
849 * @param {Function} fn
850 */
851 before: function (name, fn) {
852 suites[0].beforeAll(name, fn);
853 },
854
855 /**
856 * Execute after running tests.
857 *
858 * @param {string} name
859 * @param {Function} fn
860 */
861 after: function (name, fn) {
862 suites[0].afterAll(name, fn);
863 },
864
865 /**
866 * Execute before each test case.
867 *
868 * @param {string} name
869 * @param {Function} fn
870 */
871 beforeEach: function (name, fn) {
872 suites[0].beforeEach(name, fn);
873 },
874
875 /**
876 * Execute after each test case.
877 *
878 * @param {string} name
879 * @param {Function} fn
880 */
881 afterEach: function (name, fn) {
882 suites[0].afterEach(name, fn);
883 },
884
885 suite: {
886 /**
887 * Create an exclusive Suite; convenience function
888 * See docstring for create() below.
889 *
890 * @param {Object} opts
891 * @returns {Suite}
892 */
893 only: function only (opts) {
894 mocha.options.hasOnly = true;
895 opts.isOnly = true;
896 return this.create(opts);
897 },
898
899 /**
900 * Create a Suite, but skip it; convenience function
901 * See docstring for create() below.
902 *
903 * @param {Object} opts
904 * @returns {Suite}
905 */
906 skip: function skip (opts) {
907 opts.pending = true;
908 return this.create(opts);
909 },
910
911 /**
912 * Creates a suite.
913 * @param {Object} opts Options
914 * @param {string} opts.title Title of Suite
915 * @param {Function} [opts.fn] Suite Function (not always applicable)
916 * @param {boolean} [opts.pending] Is Suite pending?
917 * @param {string} [opts.file] Filepath where this Suite resides
918 * @param {boolean} [opts.isOnly] Is Suite exclusive?
919 * @returns {Suite}
920 */
921 create: function create (opts) {
922 var suite = Suite.create(suites[0], opts.title);
923 suite.pending = Boolean(opts.pending);
924 suite.file = opts.file;
925 suites.unshift(suite);
926 if (opts.isOnly) {
927 suite.parent._onlySuites = suite.parent._onlySuites.concat(suite);
928 mocha.options.hasOnly = true;
929 }
930 if (typeof opts.fn === 'function') {
931 opts.fn.call(suite);
932 suites.shift();
933 } else if (typeof opts.fn === 'undefined' && !suite.pending) {
934 throw new Error('Suite "' + suite.fullTitle() + '" was defined but no callback was supplied. Supply a callback or explicitly skip the suite.');
935 }
936
937 return suite;
938 }
939 },
940
941 test: {
942
943 /**
944 * Exclusive test-case.
945 *
946 * @param {Object} mocha
947 * @param {Function} test
948 * @returns {*}
949 */
950 only: function (mocha, test) {
951 test.parent._onlyTests = test.parent._onlyTests.concat(test);
952 mocha.options.hasOnly = true;
953 return test;
954 },
955
956 /**
957 * Pending test case.
958 *
959 * @param {string} title
960 */
961 skip: function (title) {
962 context.test(title);
963 },
964
965 /**
966 * Number of retry attempts
967 *
968 * @param {number} n
969 */
970 retries: function (n) {
971 context.retries(n);
972 }
973 }
974 };
975};
976
977},{"../suite":35}],10:[function(require,module,exports){
978'use strict';
979
980/**
981 * Module dependencies.
982 */
983
984var Suite = require('../suite');
985var Test = require('../test');
986
987/**
988 * Exports-style (as Node.js module) interface:
989 *
990 * exports.Array = {
991 * '#indexOf()': {
992 * 'should return -1 when the value is not present': function() {
993 *
994 * },
995 *
996 * 'should return the correct index when the value is present': function() {
997 *
998 * }
999 * }
1000 * };
1001 *
1002 * @param {Suite} suite Root suite.
1003 */
1004module.exports = function (suite) {
1005 var suites = [suite];
1006
1007 suite.on('require', visit);
1008
1009 function visit (obj, file) {
1010 var suite;
1011 for (var key in obj) {
1012 if (typeof obj[key] === 'function') {
1013 var fn = obj[key];
1014 switch (key) {
1015 case 'before':
1016 suites[0].beforeAll(fn);
1017 break;
1018 case 'after':
1019 suites[0].afterAll(fn);
1020 break;
1021 case 'beforeEach':
1022 suites[0].beforeEach(fn);
1023 break;
1024 case 'afterEach':
1025 suites[0].afterEach(fn);
1026 break;
1027 default:
1028 var test = new Test(key, fn);
1029 test.file = file;
1030 suites[0].addTest(test);
1031 }
1032 } else {
1033 suite = Suite.create(suites[0], key);
1034 suites.unshift(suite);
1035 visit(obj[key], file);
1036 suites.shift();
1037 }
1038 }
1039 }
1040};
1041
1042},{"../suite":35,"../test":36}],11:[function(require,module,exports){
1043'use strict';
1044
1045exports.bdd = require('./bdd');
1046exports.tdd = require('./tdd');
1047exports.qunit = require('./qunit');
1048exports.exports = require('./exports');
1049
1050},{"./bdd":8,"./exports":10,"./qunit":12,"./tdd":13}],12:[function(require,module,exports){
1051'use strict';
1052
1053/**
1054 * Module dependencies.
1055 */
1056
1057var Test = require('../test');
1058
1059/**
1060 * QUnit-style interface:
1061 *
1062 * suite('Array');
1063 *
1064 * test('#length', function() {
1065 * var arr = [1,2,3];
1066 * ok(arr.length == 3);
1067 * });
1068 *
1069 * test('#indexOf()', function() {
1070 * var arr = [1,2,3];
1071 * ok(arr.indexOf(1) == 0);
1072 * ok(arr.indexOf(2) == 1);
1073 * ok(arr.indexOf(3) == 2);
1074 * });
1075 *
1076 * suite('String');
1077 *
1078 * test('#length', function() {
1079 * ok('foo'.length == 3);
1080 * });
1081 *
1082 * @param {Suite} suite Root suite.
1083 */
1084module.exports = function (suite) {
1085 var suites = [suite];
1086
1087 suite.on('pre-require', function (context, file, mocha) {
1088 var common = require('./common')(suites, context, mocha);
1089
1090 context.before = common.before;
1091 context.after = common.after;
1092 context.beforeEach = common.beforeEach;
1093 context.afterEach = common.afterEach;
1094 context.run = mocha.options.delay && common.runWithSuite(suite);
1095 /**
1096 * Describe a "suite" with the given `title`.
1097 */
1098
1099 context.suite = function (title) {
1100 if (suites.length > 1) {
1101 suites.shift();
1102 }
1103 return common.suite.create({
1104 title: title,
1105 file: file,
1106 fn: false
1107 });
1108 };
1109
1110 /**
1111 * Exclusive Suite.
1112 */
1113
1114 context.suite.only = function (title) {
1115 if (suites.length > 1) {
1116 suites.shift();
1117 }
1118 return common.suite.only({
1119 title: title,
1120 file: file,
1121 fn: false
1122 });
1123 };
1124
1125 /**
1126 * Describe a specification or test-case
1127 * with the given `title` and callback `fn`
1128 * acting as a thunk.
1129 */
1130
1131 context.test = function (title, fn) {
1132 var test = new Test(title, fn);
1133 test.file = file;
1134 suites[0].addTest(test);
1135 return test;
1136 };
1137
1138 /**
1139 * Exclusive test-case.
1140 */
1141
1142 context.test.only = function (title, fn) {
1143 return common.test.only(mocha, context.test(title, fn));
1144 };
1145
1146 context.test.skip = common.test.skip;
1147 context.test.retries = common.test.retries;
1148 });
1149};
1150
1151},{"../test":36,"./common":9}],13:[function(require,module,exports){
1152'use strict';
1153
1154/**
1155 * Module dependencies.
1156 */
1157
1158var Test = require('../test');
1159
1160/**
1161 * TDD-style interface:
1162 *
1163 * suite('Array', function() {
1164 * suite('#indexOf()', function() {
1165 * suiteSetup(function() {
1166 *
1167 * });
1168 *
1169 * test('should return -1 when not present', function() {
1170 *
1171 * });
1172 *
1173 * test('should return the index when present', function() {
1174 *
1175 * });
1176 *
1177 * suiteTeardown(function() {
1178 *
1179 * });
1180 * });
1181 * });
1182 *
1183 * @param {Suite} suite Root suite.
1184 */
1185module.exports = function (suite) {
1186 var suites = [suite];
1187
1188 suite.on('pre-require', function (context, file, mocha) {
1189 var common = require('./common')(suites, context, mocha);
1190
1191 context.setup = common.beforeEach;
1192 context.teardown = common.afterEach;
1193 context.suiteSetup = common.before;
1194 context.suiteTeardown = common.after;
1195 context.run = mocha.options.delay && common.runWithSuite(suite);
1196
1197 /**
1198 * Describe a "suite" with the given `title` and callback `fn` containing
1199 * nested suites and/or tests.
1200 */
1201 context.suite = function (title, fn) {
1202 return common.suite.create({
1203 title: title,
1204 file: file,
1205 fn: fn
1206 });
1207 };
1208
1209 /**
1210 * Pending suite.
1211 */
1212 context.suite.skip = function (title, fn) {
1213 return common.suite.skip({
1214 title: title,
1215 file: file,
1216 fn: fn
1217 });
1218 };
1219
1220 /**
1221 * Exclusive test-case.
1222 */
1223 context.suite.only = function (title, fn) {
1224 return common.suite.only({
1225 title: title,
1226 file: file,
1227 fn: fn
1228 });
1229 };
1230
1231 /**
1232 * Describe a specification or test-case with the given `title` and
1233 * callback `fn` acting as a thunk.
1234 */
1235 context.test = function (title, fn) {
1236 var suite = suites[0];
1237 if (suite.isPending()) {
1238 fn = null;
1239 }
1240 var test = new Test(title, fn);
1241 test.file = file;
1242 suite.addTest(test);
1243 return test;
1244 };
1245
1246 /**
1247 * Exclusive test-case.
1248 */
1249
1250 context.test.only = function (title, fn) {
1251 return common.test.only(mocha, context.test(title, fn));
1252 };
1253
1254 context.test.skip = common.test.skip;
1255 context.test.retries = common.test.retries;
1256 });
1257};
1258
1259},{"../test":36,"./common":9}],14:[function(require,module,exports){
1260(function (process,global,__dirname){
1261'use strict';
1262
1263/*!
1264 * mocha
1265 * Copyright(c) 2011 TJ Holowaychuk <tj@vision-media.ca>
1266 * MIT Licensed
1267 */
1268
1269/**
1270 * Module dependencies.
1271 */
1272
1273var escapeRe = require('escape-string-regexp');
1274var path = require('path');
1275var reporters = require('./reporters');
1276var utils = require('./utils');
1277
1278/**
1279 * Expose `Mocha`.
1280 */
1281
1282exports = module.exports = Mocha;
1283
1284/**
1285 * To require local UIs and reporters when running in node.
1286 */
1287
1288if (!process.browser) {
1289 var cwd = process.cwd();
1290 module.paths.push(cwd, path.join(cwd, 'node_modules'));
1291}
1292
1293/**
1294 * Expose internals.
1295 */
1296
1297exports.utils = utils;
1298exports.interfaces = require('./interfaces');
1299exports.reporters = reporters;
1300exports.Runnable = require('./runnable');
1301exports.Context = require('./context');
1302exports.Runner = require('./runner');
1303exports.Suite = require('./suite');
1304exports.Hook = require('./hook');
1305exports.Test = require('./test');
1306
1307/**
1308 * Return image `name` path.
1309 *
1310 * @api private
1311 * @param {string} name
1312 * @return {string}
1313 */
1314function image (name) {
1315 return path.join(__dirname, '../images', name + '.png');
1316}
1317
1318/**
1319 * Set up mocha with `options`.
1320 *
1321 * Options:
1322 *
1323 * - `ui` name "bdd", "tdd", "exports" etc
1324 * - `reporter` reporter instance, defaults to `mocha.reporters.spec`
1325 * - `globals` array of accepted globals
1326 * - `timeout` timeout in milliseconds
1327 * - `retries` number of times to retry failed tests
1328 * - `bail` bail on the first test failure
1329 * - `slow` milliseconds to wait before considering a test slow
1330 * - `ignoreLeaks` ignore global leaks
1331 * - `fullTrace` display the full stack-trace on failing
1332 * - `grep` string or regexp to filter tests with
1333 *
1334 * @param {Object} options
1335 * @api public
1336 */
1337function Mocha (options) {
1338 options = options || {};
1339 this.files = [];
1340 this.options = options;
1341 if (options.grep) {
1342 this.grep(new RegExp(options.grep));
1343 }
1344 if (options.fgrep) {
1345 this.fgrep(options.fgrep);
1346 }
1347 this.suite = new exports.Suite('', new exports.Context());
1348 this.ui(options.ui);
1349 this.bail(options.bail);
1350 this.reporter(options.reporter, options.reporterOptions);
1351 if (typeof options.timeout !== 'undefined' && options.timeout !== null) {
1352 this.timeout(options.timeout);
1353 }
1354 if (typeof options.retries !== 'undefined' && options.retries !== null) {
1355 this.retries(options.retries);
1356 }
1357 this.useColors(options.useColors);
1358 if (options.enableTimeouts !== null) {
1359 this.enableTimeouts(options.enableTimeouts);
1360 }
1361 if (options.slow) {
1362 this.slow(options.slow);
1363 }
1364}
1365
1366/**
1367 * Enable or disable bailing on the first failure.
1368 *
1369 * @api public
1370 * @param {boolean} [bail]
1371 */
1372Mocha.prototype.bail = function (bail) {
1373 if (!arguments.length) {
1374 bail = true;
1375 }
1376 this.suite.bail(bail);
1377 return this;
1378};
1379
1380/**
1381 * Add test `file`.
1382 *
1383 * @api public
1384 * @param {string} file
1385 */
1386Mocha.prototype.addFile = function (file) {
1387 this.files.push(file);
1388 return this;
1389};
1390
1391/**
1392 * Set reporter to `reporter`, defaults to "spec".
1393 *
1394 * @param {String|Function} reporter name or constructor
1395 * @param {Object} reporterOptions optional options
1396 * @api public
1397 * @param {string|Function} reporter name or constructor
1398 * @param {Object} reporterOptions optional options
1399 */
1400Mocha.prototype.reporter = function (reporter, reporterOptions) {
1401 if (typeof reporter === 'function') {
1402 this._reporter = reporter;
1403 } else {
1404 reporter = reporter || 'spec';
1405 var _reporter;
1406 // Try to load a built-in reporter.
1407 if (reporters[reporter]) {
1408 _reporter = reporters[reporter];
1409 }
1410 // Try to load reporters from process.cwd() and node_modules
1411 if (!_reporter) {
1412 try {
1413 _reporter = require(reporter);
1414 } catch (err) {
1415 err.message.indexOf('Cannot find module') !== -1
1416 ? console.warn('"' + reporter + '" reporter not found')
1417 : console.warn('"' + reporter + '" reporter blew up with error:\n' + err.stack);
1418 }
1419 }
1420 if (!_reporter && reporter === 'teamcity') {
1421 console.warn('The Teamcity reporter was moved to a package named ' +
1422 'mocha-teamcity-reporter ' +
1423 '(https://npmjs.org/package/mocha-teamcity-reporter).');
1424 }
1425 if (!_reporter) {
1426 throw new Error('invalid reporter "' + reporter + '"');
1427 }
1428 this._reporter = _reporter;
1429 }
1430 this.options.reporterOptions = reporterOptions;
1431 return this;
1432};
1433
1434/**
1435 * Set test UI `name`, defaults to "bdd".
1436 *
1437 * @api public
1438 * @param {string} bdd
1439 */
1440Mocha.prototype.ui = function (name) {
1441 name = name || 'bdd';
1442 this._ui = exports.interfaces[name];
1443 if (!this._ui) {
1444 try {
1445 this._ui = require(name);
1446 } catch (err) {
1447 throw new Error('invalid interface "' + name + '"');
1448 }
1449 }
1450 this._ui = this._ui(this.suite);
1451
1452 this.suite.on('pre-require', function (context) {
1453 exports.afterEach = context.afterEach || context.teardown;
1454 exports.after = context.after || context.suiteTeardown;
1455 exports.beforeEach = context.beforeEach || context.setup;
1456 exports.before = context.before || context.suiteSetup;
1457 exports.describe = context.describe || context.suite;
1458 exports.it = context.it || context.test;
1459 exports.setup = context.setup || context.beforeEach;
1460 exports.suiteSetup = context.suiteSetup || context.before;
1461 exports.suiteTeardown = context.suiteTeardown || context.after;
1462 exports.suite = context.suite || context.describe;
1463 exports.teardown = context.teardown || context.afterEach;
1464 exports.test = context.test || context.it;
1465 exports.run = context.run;
1466 });
1467
1468 return this;
1469};
1470
1471/**
1472 * Load registered files.
1473 *
1474 * @api private
1475 */
1476Mocha.prototype.loadFiles = function (fn) {
1477 var self = this;
1478 var suite = this.suite;
1479 this.files.forEach(function (file) {
1480 file = path.resolve(file);
1481 suite.emit('pre-require', global, file, self);
1482 suite.emit('require', require(file), file, self);
1483 suite.emit('post-require', global, file, self);
1484 });
1485 fn && fn();
1486};
1487
1488/**
1489 * Enable growl support.
1490 *
1491 * @api private
1492 */
1493Mocha.prototype._growl = function (runner, reporter) {
1494 var notify = require('growl');
1495
1496 runner.on('end', function () {
1497 var stats = reporter.stats;
1498 if (stats.failures) {
1499 var msg = stats.failures + ' of ' + runner.total + ' tests failed';
1500 notify(msg, { name: 'mocha', title: 'Failed', image: image('error') });
1501 } else {
1502 notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', {
1503 name: 'mocha',
1504 title: 'Passed',
1505 image: image('ok')
1506 });
1507 }
1508 });
1509};
1510
1511/**
1512 * Escape string and add it to grep as a regexp.
1513 *
1514 * @api public
1515 * @param str
1516 * @returns {Mocha}
1517 */
1518Mocha.prototype.fgrep = function (str) {
1519 return this.grep(new RegExp(escapeRe(str)));
1520};
1521
1522/**
1523 * Add regexp to grep, if `re` is a string it is escaped.
1524 *
1525 * @param {RegExp|String} re
1526 * @return {Mocha}
1527 * @api public
1528 * @param {RegExp|string} re
1529 * @return {Mocha}
1530 */
1531Mocha.prototype.grep = function (re) {
1532 if (utils.isString(re)) {
1533 // extract args if it's regex-like, i.e: [string, pattern, flag]
1534 var arg = re.match(/^\/(.*)\/(g|i|)$|.*/);
1535 this.options.grep = new RegExp(arg[1] || arg[0], arg[2]);
1536 } else {
1537 this.options.grep = re;
1538 }
1539 return this;
1540};
1541/**
1542 * Invert `.grep()` matches.
1543 *
1544 * @return {Mocha}
1545 * @api public
1546 */
1547Mocha.prototype.invert = function () {
1548 this.options.invert = true;
1549 return this;
1550};
1551
1552/**
1553 * Ignore global leaks.
1554 *
1555 * @param {Boolean} ignore
1556 * @return {Mocha}
1557 * @api public
1558 * @param {boolean} ignore
1559 * @return {Mocha}
1560 */
1561Mocha.prototype.ignoreLeaks = function (ignore) {
1562 this.options.ignoreLeaks = Boolean(ignore);
1563 return this;
1564};
1565
1566/**
1567 * Enable global leak checking.
1568 *
1569 * @return {Mocha}
1570 * @api public
1571 */
1572Mocha.prototype.checkLeaks = function () {
1573 this.options.ignoreLeaks = false;
1574 return this;
1575};
1576
1577/**
1578 * Display long stack-trace on failing
1579 *
1580 * @return {Mocha}
1581 * @api public
1582 */
1583Mocha.prototype.fullTrace = function () {
1584 this.options.fullStackTrace = true;
1585 return this;
1586};
1587
1588/**
1589 * Enable growl support.
1590 *
1591 * @return {Mocha}
1592 * @api public
1593 */
1594Mocha.prototype.growl = function () {
1595 this.options.growl = true;
1596 return this;
1597};
1598
1599/**
1600 * Ignore `globals` array or string.
1601 *
1602 * @param {Array|String} globals
1603 * @return {Mocha}
1604 * @api public
1605 * @param {Array|string} globals
1606 * @return {Mocha}
1607 */
1608Mocha.prototype.globals = function (globals) {
1609 this.options.globals = (this.options.globals || []).concat(globals);
1610 return this;
1611};
1612
1613/**
1614 * Emit color output.
1615 *
1616 * @param {Boolean} colors
1617 * @return {Mocha}
1618 * @api public
1619 * @param {boolean} colors
1620 * @return {Mocha}
1621 */
1622Mocha.prototype.useColors = function (colors) {
1623 if (colors !== undefined) {
1624 this.options.useColors = colors;
1625 }
1626 return this;
1627};
1628
1629/**
1630 * Use inline diffs rather than +/-.
1631 *
1632 * @param {Boolean} inlineDiffs
1633 * @return {Mocha}
1634 * @api public
1635 * @param {boolean} inlineDiffs
1636 * @return {Mocha}
1637 */
1638Mocha.prototype.useInlineDiffs = function (inlineDiffs) {
1639 this.options.useInlineDiffs = inlineDiffs !== undefined && inlineDiffs;
1640 return this;
1641};
1642
1643/**
1644 * Set the timeout in milliseconds.
1645 *
1646 * @param {Number} timeout
1647 * @return {Mocha}
1648 * @api public
1649 * @param {number} timeout
1650 * @return {Mocha}
1651 */
1652Mocha.prototype.timeout = function (timeout) {
1653 this.suite.timeout(timeout);
1654 return this;
1655};
1656
1657/**
1658 * Set the number of times to retry failed tests.
1659 *
1660 * @param {Number} retry times
1661 * @return {Mocha}
1662 * @api public
1663 */
1664Mocha.prototype.retries = function (n) {
1665 this.suite.retries(n);
1666 return this;
1667};
1668
1669/**
1670 * Set slowness threshold in milliseconds.
1671 *
1672 * @param {Number} slow
1673 * @return {Mocha}
1674 * @api public
1675 * @param {number} slow
1676 * @return {Mocha}
1677 */
1678Mocha.prototype.slow = function (slow) {
1679 this.suite.slow(slow);
1680 return this;
1681};
1682
1683/**
1684 * Enable timeouts.
1685 *
1686 * @param {Boolean} enabled
1687 * @return {Mocha}
1688 * @api public
1689 * @param {boolean} enabled
1690 * @return {Mocha}
1691 */
1692Mocha.prototype.enableTimeouts = function (enabled) {
1693 this.suite.enableTimeouts(arguments.length && enabled !== undefined ? enabled : true);
1694 return this;
1695};
1696
1697/**
1698 * Makes all tests async (accepting a callback)
1699 *
1700 * @return {Mocha}
1701 * @api public
1702 */
1703Mocha.prototype.asyncOnly = function () {
1704 this.options.asyncOnly = true;
1705 return this;
1706};
1707
1708/**
1709 * Disable syntax highlighting (in browser).
1710 *
1711 * @api public
1712 */
1713Mocha.prototype.noHighlighting = function () {
1714 this.options.noHighlighting = true;
1715 return this;
1716};
1717
1718/**
1719 * Enable uncaught errors to propagate (in browser).
1720 *
1721 * @return {Mocha}
1722 * @api public
1723 */
1724Mocha.prototype.allowUncaught = function () {
1725 this.options.allowUncaught = true;
1726 return this;
1727};
1728
1729/**
1730 * Delay root suite execution.
1731 * @returns {Mocha}
1732 */
1733Mocha.prototype.delay = function delay () {
1734 this.options.delay = true;
1735 return this;
1736};
1737
1738/**
1739 * Run tests and invoke `fn()` when complete.
1740 *
1741 * @api public
1742 * @param {Function} fn
1743 * @return {Runner}
1744 */
1745Mocha.prototype.run = function (fn) {
1746 if (this.files.length) {
1747 this.loadFiles();
1748 }
1749 var suite = this.suite;
1750 var options = this.options;
1751 options.files = this.files;
1752 var runner = new exports.Runner(suite, options.delay);
1753 var reporter = new this._reporter(runner, options);
1754 runner.ignoreLeaks = options.ignoreLeaks !== false;
1755 runner.fullStackTrace = options.fullStackTrace;
1756 runner.hasOnly = options.hasOnly;
1757 runner.asyncOnly = options.asyncOnly;
1758 runner.allowUncaught = options.allowUncaught;
1759 if (options.grep) {
1760 runner.grep(options.grep, options.invert);
1761 }
1762 if (options.globals) {
1763 runner.globals(options.globals);
1764 }
1765 if (options.growl) {
1766 this._growl(runner, reporter);
1767 }
1768 if (options.useColors !== undefined) {
1769 exports.reporters.Base.useColors = options.useColors;
1770 }
1771 exports.reporters.Base.inlineDiffs = options.useInlineDiffs;
1772
1773 function done (failures) {
1774 if (reporter.done) {
1775 reporter.done(failures, fn);
1776 } else {
1777 fn && fn(failures);
1778 }
1779 }
1780
1781 return runner.run(done);
1782};
1783
1784}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},"/lib")
1785},{"./context":6,"./hook":7,"./interfaces":11,"./reporters":21,"./runnable":33,"./runner":34,"./suite":35,"./test":36,"./utils":38,"_process":67,"escape-string-regexp":47,"growl":49,"path":42}],15:[function(require,module,exports){
1786'use strict';
1787
1788/**
1789 * Helpers.
1790 */
1791
1792var s = 1000;
1793var m = s * 60;
1794var h = m * 60;
1795var d = h * 24;
1796var y = d * 365.25;
1797
1798/**
1799 * Parse or format the given `val`.
1800 *
1801 * Options:
1802 *
1803 * - `long` verbose formatting [false]
1804 *
1805 * @api public
1806 * @param {string|number} val
1807 * @param {Object} options
1808 * @return {string|number}
1809 */
1810module.exports = function (val, options) {
1811 options = options || {};
1812 if (typeof val === 'string') {
1813 return parse(val);
1814 }
1815 // https://github.com/mochajs/mocha/pull/1035
1816 return options['long'] ? longFormat(val) : shortFormat(val);
1817};
1818
1819/**
1820 * Parse the given `str` and return milliseconds.
1821 *
1822 * @api private
1823 * @param {string} str
1824 * @return {number}
1825 */
1826function parse (str) {
1827 var match = (/^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i).exec(str);
1828 if (!match) {
1829 return;
1830 }
1831 var n = parseFloat(match[1]);
1832 var type = (match[2] || 'ms').toLowerCase();
1833 switch (type) {
1834 case 'years':
1835 case 'year':
1836 case 'y':
1837 return n * y;
1838 case 'days':
1839 case 'day':
1840 case 'd':
1841 return n * d;
1842 case 'hours':
1843 case 'hour':
1844 case 'h':
1845 return n * h;
1846 case 'minutes':
1847 case 'minute':
1848 case 'm':
1849 return n * m;
1850 case 'seconds':
1851 case 'second':
1852 case 's':
1853 return n * s;
1854 case 'ms':
1855 return n;
1856 default:
1857 // No default case
1858 }
1859}
1860
1861/**
1862 * Short format for `ms`.
1863 *
1864 * @api private
1865 * @param {number} ms
1866 * @return {string}
1867 */
1868function shortFormat (ms) {
1869 if (ms >= d) {
1870 return Math.round(ms / d) + 'd';
1871 }
1872 if (ms >= h) {
1873 return Math.round(ms / h) + 'h';
1874 }
1875 if (ms >= m) {
1876 return Math.round(ms / m) + 'm';
1877 }
1878 if (ms >= s) {
1879 return Math.round(ms / s) + 's';
1880 }
1881 return ms + 'ms';
1882}
1883
1884/**
1885 * Long format for `ms`.
1886 *
1887 * @api private
1888 * @param {number} ms
1889 * @return {string}
1890 */
1891function longFormat (ms) {
1892 return plural(ms, d, 'day') ||
1893 plural(ms, h, 'hour') ||
1894 plural(ms, m, 'minute') ||
1895 plural(ms, s, 'second') ||
1896 ms + ' ms';
1897}
1898
1899/**
1900 * Pluralization helper.
1901 *
1902 * @api private
1903 * @param {number} ms
1904 * @param {number} n
1905 * @param {string} name
1906 */
1907function plural (ms, n, name) {
1908 if (ms < n) {
1909 return;
1910 }
1911 if (ms < n * 1.5) {
1912 return Math.floor(ms / n) + ' ' + name;
1913 }
1914 return Math.ceil(ms / n) + ' ' + name + 's';
1915}
1916
1917},{}],16:[function(require,module,exports){
1918'use strict';
1919
1920/**
1921 * Expose `Pending`.
1922 */
1923
1924module.exports = Pending;
1925
1926/**
1927 * Initialize a new `Pending` error with the given message.
1928 *
1929 * @param {string} message
1930 */
1931function Pending (message) {
1932 this.message = message;
1933}
1934
1935},{}],17:[function(require,module,exports){
1936(function (process,global){
1937'use strict';
1938
1939/**
1940 * Module dependencies.
1941 */
1942
1943var tty = require('tty');
1944var diff = require('diff');
1945var ms = require('../ms');
1946var utils = require('../utils');
1947var supportsColor = process.browser ? null : require('supports-color');
1948
1949/**
1950 * Expose `Base`.
1951 */
1952
1953exports = module.exports = Base;
1954
1955/**
1956 * Save timer references to avoid Sinon interfering.
1957 * See: https://github.com/mochajs/mocha/issues/237
1958 */
1959
1960/* eslint-disable no-unused-vars, no-native-reassign */
1961var Date = global.Date;
1962var setTimeout = global.setTimeout;
1963var setInterval = global.setInterval;
1964var clearTimeout = global.clearTimeout;
1965var clearInterval = global.clearInterval;
1966/* eslint-enable no-unused-vars, no-native-reassign */
1967
1968/**
1969 * Check if both stdio streams are associated with a tty.
1970 */
1971
1972var isatty = tty.isatty(1) && tty.isatty(2);
1973
1974/**
1975 * Enable coloring by default, except in the browser interface.
1976 */
1977
1978exports.useColors = !process.browser && (supportsColor || (process.env.MOCHA_COLORS !== undefined));
1979
1980/**
1981 * Inline diffs instead of +/-
1982 */
1983
1984exports.inlineDiffs = false;
1985
1986/**
1987 * Default color map.
1988 */
1989
1990exports.colors = {
1991 pass: 90,
1992 fail: 31,
1993 'bright pass': 92,
1994 'bright fail': 91,
1995 'bright yellow': 93,
1996 pending: 36,
1997 suite: 0,
1998 'error title': 0,
1999 'error message': 31,
2000 'error stack': 90,
2001 checkmark: 32,
2002 fast: 90,
2003 medium: 33,
2004 slow: 31,
2005 green: 32,
2006 light: 90,
2007 'diff gutter': 90,
2008 'diff added': 32,
2009 'diff removed': 31
2010};
2011
2012/**
2013 * Default symbol map.
2014 */
2015
2016exports.symbols = {
2017 ok: '✓',
2018 err: '✖',
2019 dot: '․',
2020 comma: ',',
2021 bang: '!'
2022};
2023
2024// With node.js on Windows: use symbols available in terminal default fonts
2025if (process.platform === 'win32') {
2026 exports.symbols.ok = '\u221A';
2027 exports.symbols.err = '\u00D7';
2028 exports.symbols.dot = '.';
2029}
2030
2031/**
2032 * Color `str` with the given `type`,
2033 * allowing colors to be disabled,
2034 * as well as user-defined color
2035 * schemes.
2036 *
2037 * @param {string} type
2038 * @param {string} str
2039 * @return {string}
2040 * @api private
2041 */
2042var color = exports.color = function (type, str) {
2043 if (!exports.useColors) {
2044 return String(str);
2045 }
2046 return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m';
2047};
2048
2049/**
2050 * Expose term window size, with some defaults for when stderr is not a tty.
2051 */
2052
2053exports.window = {
2054 width: 75
2055};
2056
2057if (isatty) {
2058 exports.window.width = process.stdout.getWindowSize
2059 ? process.stdout.getWindowSize(1)[0]
2060 : tty.getWindowSize()[1];
2061}
2062
2063/**
2064 * Expose some basic cursor interactions that are common among reporters.
2065 */
2066
2067exports.cursor = {
2068 hide: function () {
2069 isatty && process.stdout.write('\u001b[?25l');
2070 },
2071
2072 show: function () {
2073 isatty && process.stdout.write('\u001b[?25h');
2074 },
2075
2076 deleteLine: function () {
2077 isatty && process.stdout.write('\u001b[2K');
2078 },
2079
2080 beginningOfLine: function () {
2081 isatty && process.stdout.write('\u001b[0G');
2082 },
2083
2084 CR: function () {
2085 if (isatty) {
2086 exports.cursor.deleteLine();
2087 exports.cursor.beginningOfLine();
2088 } else {
2089 process.stdout.write('\r');
2090 }
2091 }
2092};
2093
2094/**
2095 * Outut the given `failures` as a list.
2096 *
2097 * @param {Array} failures
2098 * @api public
2099 */
2100
2101exports.list = function (failures) {
2102 console.log();
2103 failures.forEach(function (test, i) {
2104 // format
2105 var fmt = color('error title', ' %s) %s:\n') +
2106 color('error message', ' %s') +
2107 color('error stack', '\n%s\n');
2108
2109 // msg
2110 var msg;
2111 var err = test.err;
2112 var message;
2113 if (err.message && typeof err.message.toString === 'function') {
2114 message = err.message + '';
2115 } else if (typeof err.inspect === 'function') {
2116 message = err.inspect() + '';
2117 } else {
2118 message = '';
2119 }
2120 var stack = err.stack || message;
2121 var index = message ? stack.indexOf(message) : -1;
2122 var actual = err.actual;
2123 var expected = err.expected;
2124 var escape = true;
2125
2126 if (index === -1) {
2127 msg = message;
2128 } else {
2129 index += message.length;
2130 msg = stack.slice(0, index);
2131 // remove msg from stack
2132 stack = stack.slice(index + 1);
2133 }
2134
2135 // uncaught
2136 if (err.uncaught) {
2137 msg = 'Uncaught ' + msg;
2138 }
2139 // explicitly show diff
2140 if (err.showDiff !== false && sameType(actual, expected) && expected !== undefined) {
2141 escape = false;
2142 if (!(utils.isString(actual) && utils.isString(expected))) {
2143 err.actual = actual = utils.stringify(actual);
2144 err.expected = expected = utils.stringify(expected);
2145 }
2146
2147 fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n');
2148 var match = message.match(/^([^:]+): expected/);
2149 msg = '\n ' + color('error message', match ? match[1] : msg);
2150
2151 if (exports.inlineDiffs) {
2152 msg += inlineDiff(err, escape);
2153 } else {
2154 msg += unifiedDiff(err, escape);
2155 }
2156 }
2157
2158 // indent stack trace
2159 stack = stack.replace(/^/gm, ' ');
2160
2161 console.log(fmt, (i + 1), test.fullTitle(), msg, stack);
2162 });
2163};
2164
2165/**
2166 * Initialize a new `Base` reporter.
2167 *
2168 * All other reporters generally
2169 * inherit from this reporter, providing
2170 * stats such as test duration, number
2171 * of tests passed / failed etc.
2172 *
2173 * @param {Runner} runner
2174 * @api public
2175 */
2176
2177function Base (runner) {
2178 var stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 };
2179 var failures = this.failures = [];
2180
2181 if (!runner) {
2182 return;
2183 }
2184 this.runner = runner;
2185
2186 runner.stats = stats;
2187
2188 runner.on('start', function () {
2189 stats.start = new Date();
2190 });
2191
2192 runner.on('suite', function (suite) {
2193 stats.suites = stats.suites || 0;
2194 suite.root || stats.suites++;
2195 });
2196
2197 runner.on('test end', function () {
2198 stats.tests = stats.tests || 0;
2199 stats.tests++;
2200 });
2201
2202 runner.on('pass', function (test) {
2203 stats.passes = stats.passes || 0;
2204
2205 if (test.duration > test.slow()) {
2206 test.speed = 'slow';
2207 } else if (test.duration > test.slow() / 2) {
2208 test.speed = 'medium';
2209 } else {
2210 test.speed = 'fast';
2211 }
2212
2213 stats.passes++;
2214 });
2215
2216 runner.on('fail', function (test, err) {
2217 stats.failures = stats.failures || 0;
2218 stats.failures++;
2219 test.err = err;
2220 failures.push(test);
2221 });
2222
2223 runner.on('end', function () {
2224 stats.end = new Date();
2225 stats.duration = new Date() - stats.start;
2226 });
2227
2228 runner.on('pending', function () {
2229 stats.pending++;
2230 });
2231}
2232
2233/**
2234 * Output common epilogue used by many of
2235 * the bundled reporters.
2236 *
2237 * @api public
2238 */
2239Base.prototype.epilogue = function () {
2240 var stats = this.stats;
2241 var fmt;
2242
2243 console.log();
2244
2245 // passes
2246 fmt = color('bright pass', ' ') +
2247 color('green', ' %d passing') +
2248 color('light', ' (%s)');
2249
2250 console.log(fmt,
2251 stats.passes || 0,
2252 ms(stats.duration));
2253
2254 // pending
2255 if (stats.pending) {
2256 fmt = color('pending', ' ') +
2257 color('pending', ' %d pending');
2258
2259 console.log(fmt, stats.pending);
2260 }
2261
2262 // failures
2263 if (stats.failures) {
2264 fmt = color('fail', ' %d failing');
2265
2266 console.log(fmt, stats.failures);
2267
2268 Base.list(this.failures);
2269 console.log();
2270 }
2271
2272 console.log();
2273};
2274
2275/**
2276 * Pad the given `str` to `len`.
2277 *
2278 * @api private
2279 * @param {string} str
2280 * @param {string} len
2281 * @return {string}
2282 */
2283function pad (str, len) {
2284 str = String(str);
2285 return Array(len - str.length + 1).join(' ') + str;
2286}
2287
2288/**
2289 * Returns an inline diff between 2 strings with coloured ANSI output
2290 *
2291 * @api private
2292 * @param {Error} err with actual/expected
2293 * @param {boolean} escape
2294 * @return {string} Diff
2295 */
2296function inlineDiff (err, escape) {
2297 var msg = errorDiff(err, 'WordsWithSpace', escape);
2298
2299 // linenos
2300 var lines = msg.split('\n');
2301 if (lines.length > 4) {
2302 var width = String(lines.length).length;
2303 msg = lines.map(function (str, i) {
2304 return pad(++i, width) + ' |' + ' ' + str;
2305 }).join('\n');
2306 }
2307
2308 // legend
2309 msg = '\n' +
2310 color('diff removed', 'actual') +
2311 ' ' +
2312 color('diff added', 'expected') +
2313 '\n\n' +
2314 msg +
2315 '\n';
2316
2317 // indent
2318 msg = msg.replace(/^/gm, ' ');
2319 return msg;
2320}
2321
2322/**
2323 * Returns a unified diff between two strings.
2324 *
2325 * @api private
2326 * @param {Error} err with actual/expected
2327 * @param {boolean} escape
2328 * @return {string} The diff.
2329 */
2330function unifiedDiff (err, escape) {
2331 var indent = ' ';
2332 function cleanUp (line) {
2333 if (escape) {
2334 line = escapeInvisibles(line);
2335 }
2336 if (line[0] === '+') {
2337 return indent + colorLines('diff added', line);
2338 }
2339 if (line[0] === '-') {
2340 return indent + colorLines('diff removed', line);
2341 }
2342 if (line.match(/@@/)) {
2343 return null;
2344 }
2345 if (line.match(/\\ No newline/)) {
2346 return null;
2347 }
2348 return indent + line;
2349 }
2350 function notBlank (line) {
2351 return typeof line !== 'undefined' && line !== null;
2352 }
2353 var msg = diff.createPatch('string', err.actual, err.expected);
2354 var lines = msg.split('\n').splice(4);
2355 return '\n ' +
2356 colorLines('diff added', '+ expected') + ' ' +
2357 colorLines('diff removed', '- actual') +
2358 '\n\n' +
2359 lines.map(cleanUp).filter(notBlank).join('\n');
2360}
2361
2362/**
2363 * Return a character diff for `err`.
2364 *
2365 * @api private
2366 * @param {Error} err
2367 * @param {string} type
2368 * @param {boolean} escape
2369 * @return {string}
2370 */
2371function errorDiff (err, type, escape) {
2372 var actual = escape ? escapeInvisibles(err.actual) : err.actual;
2373 var expected = escape ? escapeInvisibles(err.expected) : err.expected;
2374 return diff['diff' + type](actual, expected).map(function (str) {
2375 if (str.added) {
2376 return colorLines('diff added', str.value);
2377 }
2378 if (str.removed) {
2379 return colorLines('diff removed', str.value);
2380 }
2381 return str.value;
2382 }).join('');
2383}
2384
2385/**
2386 * Returns a string with all invisible characters in plain text
2387 *
2388 * @api private
2389 * @param {string} line
2390 * @return {string}
2391 */
2392function escapeInvisibles (line) {
2393 return line.replace(/\t/g, '<tab>')
2394 .replace(/\r/g, '<CR>')
2395 .replace(/\n/g, '<LF>\n');
2396}
2397
2398/**
2399 * Color lines for `str`, using the color `name`.
2400 *
2401 * @api private
2402 * @param {string} name
2403 * @param {string} str
2404 * @return {string}
2405 */
2406function colorLines (name, str) {
2407 return str.split('\n').map(function (str) {
2408 return color(name, str);
2409 }).join('\n');
2410}
2411
2412/**
2413 * Object#toString reference.
2414 */
2415var objToString = Object.prototype.toString;
2416
2417/**
2418 * Check that a / b have the same type.
2419 *
2420 * @api private
2421 * @param {Object} a
2422 * @param {Object} b
2423 * @return {boolean}
2424 */
2425function sameType (a, b) {
2426 return objToString.call(a) === objToString.call(b);
2427}
2428
2429}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
2430},{"../ms":15,"../utils":38,"_process":67,"diff":46,"supports-color":42,"tty":5}],18:[function(require,module,exports){
2431'use strict';
2432
2433/**
2434 * Module dependencies.
2435 */
2436
2437var Base = require('./base');
2438var utils = require('../utils');
2439
2440/**
2441 * Expose `Doc`.
2442 */
2443
2444exports = module.exports = Doc;
2445
2446/**
2447 * Initialize a new `Doc` reporter.
2448 *
2449 * @param {Runner} runner
2450 * @api public
2451 */
2452function Doc (runner) {
2453 Base.call(this, runner);
2454
2455 var indents = 2;
2456
2457 function indent () {
2458 return Array(indents).join(' ');
2459 }
2460
2461 runner.on('suite', function (suite) {
2462 if (suite.root) {
2463 return;
2464 }
2465 ++indents;
2466 console.log('%s<section class="suite">', indent());
2467 ++indents;
2468 console.log('%s<h1>%s</h1>', indent(), utils.escape(suite.title));
2469 console.log('%s<dl>', indent());
2470 });
2471
2472 runner.on('suite end', function (suite) {
2473 if (suite.root) {
2474 return;
2475 }
2476 console.log('%s</dl>', indent());
2477 --indents;
2478 console.log('%s</section>', indent());
2479 --indents;
2480 });
2481
2482 runner.on('pass', function (test) {
2483 console.log('%s <dt>%s</dt>', indent(), utils.escape(test.title));
2484 var code = utils.escape(utils.clean(test.body));
2485 console.log('%s <dd><pre><code>%s</code></pre></dd>', indent(), code);
2486 });
2487
2488 runner.on('fail', function (test, err) {
2489 console.log('%s <dt class="error">%s</dt>', indent(), utils.escape(test.title));
2490 var code = utils.escape(utils.clean(test.body));
2491 console.log('%s <dd class="error"><pre><code>%s</code></pre></dd>', indent(), code);
2492 console.log('%s <dd class="error">%s</dd>', indent(), utils.escape(err));
2493 });
2494}
2495
2496},{"../utils":38,"./base":17}],19:[function(require,module,exports){
2497(function (process){
2498'use strict';
2499
2500/**
2501 * Module dependencies.
2502 */
2503
2504var Base = require('./base');
2505var inherits = require('../utils').inherits;
2506var color = Base.color;
2507
2508/**
2509 * Expose `Dot`.
2510 */
2511
2512exports = module.exports = Dot;
2513
2514/**
2515 * Initialize a new `Dot` matrix test reporter.
2516 *
2517 * @api public
2518 * @param {Runner} runner
2519 */
2520function Dot (runner) {
2521 Base.call(this, runner);
2522
2523 var self = this;
2524 var width = Base.window.width * 0.75 | 0;
2525 var n = -1;
2526
2527 runner.on('start', function () {
2528 process.stdout.write('\n');
2529 });
2530
2531 runner.on('pending', function () {
2532 if (++n % width === 0) {
2533 process.stdout.write('\n ');
2534 }
2535 process.stdout.write(color('pending', Base.symbols.comma));
2536 });
2537
2538 runner.on('pass', function (test) {
2539 if (++n % width === 0) {
2540 process.stdout.write('\n ');
2541 }
2542 if (test.speed === 'slow') {
2543 process.stdout.write(color('bright yellow', Base.symbols.dot));
2544 } else {
2545 process.stdout.write(color(test.speed, Base.symbols.dot));
2546 }
2547 });
2548
2549 runner.on('fail', function () {
2550 if (++n % width === 0) {
2551 process.stdout.write('\n ');
2552 }
2553 process.stdout.write(color('fail', Base.symbols.bang));
2554 });
2555
2556 runner.on('end', function () {
2557 console.log();
2558 self.epilogue();
2559 });
2560}
2561
2562/**
2563 * Inherit from `Base.prototype`.
2564 */
2565inherits(Dot, Base);
2566
2567}).call(this,require('_process'))
2568},{"../utils":38,"./base":17,"_process":67}],20:[function(require,module,exports){
2569(function (global){
2570'use strict';
2571
2572/* eslint-env browser */
2573
2574/**
2575 * Module dependencies.
2576 */
2577
2578var Base = require('./base');
2579var utils = require('../utils');
2580var Progress = require('../browser/progress');
2581var escapeRe = require('escape-string-regexp');
2582var escape = utils.escape;
2583
2584/**
2585 * Save timer references to avoid Sinon interfering (see GH-237).
2586 */
2587
2588/* eslint-disable no-unused-vars, no-native-reassign */
2589var Date = global.Date;
2590var setTimeout = global.setTimeout;
2591var setInterval = global.setInterval;
2592var clearTimeout = global.clearTimeout;
2593var clearInterval = global.clearInterval;
2594/* eslint-enable no-unused-vars, no-native-reassign */
2595
2596/**
2597 * Expose `HTML`.
2598 */
2599
2600exports = module.exports = HTML;
2601
2602/**
2603 * Stats template.
2604 */
2605
2606var statsTemplate = '<ul id="mocha-stats">' +
2607 '<li class="progress"><canvas width="40" height="40"></canvas></li>' +
2608 '<li class="passes"><a href="javascript:void(0);">passes:</a> <em>0</em></li>' +
2609 '<li class="failures"><a href="javascript:void(0);">failures:</a> <em>0</em></li>' +
2610 '<li class="duration">duration: <em>0</em>s</li>' +
2611 '</ul>';
2612
2613/**
2614 * Initialize a new `HTML` reporter.
2615 *
2616 * @api public
2617 * @param {Runner} runner
2618 */
2619function HTML (runner) {
2620 Base.call(this, runner);
2621
2622 var self = this;
2623 var stats = this.stats;
2624 var stat = fragment(statsTemplate);
2625 var items = stat.getElementsByTagName('li');
2626 var passes = items[1].getElementsByTagName('em')[0];
2627 var passesLink = items[1].getElementsByTagName('a')[0];
2628 var failures = items[2].getElementsByTagName('em')[0];
2629 var failuresLink = items[2].getElementsByTagName('a')[0];
2630 var duration = items[3].getElementsByTagName('em')[0];
2631 var canvas = stat.getElementsByTagName('canvas')[0];
2632 var report = fragment('<ul id="mocha-report"></ul>');
2633 var stack = [report];
2634 var progress;
2635 var ctx;
2636 var root = document.getElementById('mocha');
2637
2638 if (canvas.getContext) {
2639 var ratio = window.devicePixelRatio || 1;
2640 canvas.style.width = canvas.width;
2641 canvas.style.height = canvas.height;
2642 canvas.width *= ratio;
2643 canvas.height *= ratio;
2644 ctx = canvas.getContext('2d');
2645 ctx.scale(ratio, ratio);
2646 progress = new Progress();
2647 }
2648
2649 if (!root) {
2650 return error('#mocha div missing, add it to your document');
2651 }
2652
2653 // pass toggle
2654 on(passesLink, 'click', function (evt) {
2655 evt.preventDefault();
2656 unhide();
2657 var name = (/pass/).test(report.className) ? '' : ' pass';
2658 report.className = report.className.replace(/fail|pass/g, '') + name;
2659 if (report.className.trim()) {
2660 hideSuitesWithout('test pass');
2661 }
2662 });
2663
2664 // failure toggle
2665 on(failuresLink, 'click', function (evt) {
2666 evt.preventDefault();
2667 unhide();
2668 var name = (/fail/).test(report.className) ? '' : ' fail';
2669 report.className = report.className.replace(/fail|pass/g, '') + name;
2670 if (report.className.trim()) {
2671 hideSuitesWithout('test fail');
2672 }
2673 });
2674
2675 root.appendChild(stat);
2676 root.appendChild(report);
2677
2678 if (progress) {
2679 progress.size(40);
2680 }
2681
2682 runner.on('suite', function (suite) {
2683 if (suite.root) {
2684 return;
2685 }
2686
2687 // suite
2688 var url = self.suiteURL(suite);
2689 var el = fragment('<li class="suite"><h1><a href="%s">%s</a></h1></li>', url, escape(suite.title));
2690
2691 // container
2692 stack[0].appendChild(el);
2693 stack.unshift(document.createElement('ul'));
2694 el.appendChild(stack[0]);
2695 });
2696
2697 runner.on('suite end', function (suite) {
2698 if (suite.root) {
2699 updateStats();
2700 return;
2701 }
2702 stack.shift();
2703 });
2704
2705 runner.on('pass', function (test) {
2706 var url = self.testURL(test);
2707 var markup = '<li class="test pass %e"><h2>%e<span class="duration">%ems</span> ' +
2708 '<a href="%s" class="replay">‣</a></h2></li>';
2709 var el = fragment(markup, test.speed, test.title, test.duration, url);
2710 self.addCodeToggle(el, test.body);
2711 appendToStack(el);
2712 updateStats();
2713 });
2714
2715 runner.on('fail', function (test) {
2716 var el = fragment('<li class="test fail"><h2>%e <a href="%e" class="replay">‣</a></h2></li>',
2717 test.title, self.testURL(test));
2718 var stackString; // Note: Includes leading newline
2719 var message = test.err.toString();
2720
2721 // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we
2722 // check for the result of the stringifying.
2723 if (message === '[object Error]') {
2724 message = test.err.message;
2725 }
2726
2727 if (test.err.stack) {
2728 var indexOfMessage = test.err.stack.indexOf(test.err.message);
2729 if (indexOfMessage === -1) {
2730 stackString = test.err.stack;
2731 } else {
2732 stackString = test.err.stack.substr(test.err.message.length + indexOfMessage);
2733 }
2734 } else if (test.err.sourceURL && test.err.line !== undefined) {
2735 // Safari doesn't give you a stack. Let's at least provide a source line.
2736 stackString = '\n(' + test.err.sourceURL + ':' + test.err.line + ')';
2737 }
2738
2739 stackString = stackString || '';
2740
2741 if (test.err.htmlMessage && stackString) {
2742 el.appendChild(fragment('<div class="html-error">%s\n<pre class="error">%e</pre></div>',
2743 test.err.htmlMessage, stackString));
2744 } else if (test.err.htmlMessage) {
2745 el.appendChild(fragment('<div class="html-error">%s</div>', test.err.htmlMessage));
2746 } else {
2747 el.appendChild(fragment('<pre class="error">%e%e</pre>', message, stackString));
2748 }
2749
2750 self.addCodeToggle(el, test.body);
2751 appendToStack(el);
2752 updateStats();
2753 });
2754
2755 runner.on('pending', function (test) {
2756 var el = fragment('<li class="test pass pending"><h2>%e</h2></li>', test.title);
2757 appendToStack(el);
2758 updateStats();
2759 });
2760
2761 function appendToStack (el) {
2762 // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack.
2763 if (stack[0]) {
2764 stack[0].appendChild(el);
2765 }
2766 }
2767
2768 function updateStats () {
2769 // TODO: add to stats
2770 var percent = stats.tests / runner.total * 100 | 0;
2771 if (progress) {
2772 progress.update(percent).draw(ctx);
2773 }
2774
2775 // update stats
2776 var ms = new Date() - stats.start;
2777 text(passes, stats.passes);
2778 text(failures, stats.failures);
2779 text(duration, (ms / 1000).toFixed(2));
2780 }
2781}
2782
2783/**
2784 * Makes a URL, preserving querystring ("search") parameters.
2785 *
2786 * @param {string} s
2787 * @return {string} A new URL.
2788 */
2789function makeUrl (s) {
2790 var search = window.location.search;
2791
2792 // Remove previous grep query parameter if present
2793 if (search) {
2794 search = search.replace(/[?&]grep=[^&\s]*/g, '').replace(/^&/, '?');
2795 }
2796
2797 return window.location.pathname + (search ? search + '&' : '?') + 'grep=' + encodeURIComponent(escapeRe(s));
2798}
2799
2800/**
2801 * Provide suite URL.
2802 *
2803 * @param {Object} [suite]
2804 */
2805HTML.prototype.suiteURL = function (suite) {
2806 return makeUrl(suite.fullTitle());
2807};
2808
2809/**
2810 * Provide test URL.
2811 *
2812 * @param {Object} [test]
2813 */
2814HTML.prototype.testURL = function (test) {
2815 return makeUrl(test.fullTitle());
2816};
2817
2818/**
2819 * Adds code toggle functionality for the provided test's list element.
2820 *
2821 * @param {HTMLLIElement} el
2822 * @param {string} contents
2823 */
2824HTML.prototype.addCodeToggle = function (el, contents) {
2825 var h2 = el.getElementsByTagName('h2')[0];
2826
2827 on(h2, 'click', function () {
2828 pre.style.display = pre.style.display === 'none' ? 'block' : 'none';
2829 });
2830
2831 var pre = fragment('<pre><code>%e</code></pre>', utils.clean(contents));
2832 el.appendChild(pre);
2833 pre.style.display = 'none';
2834};
2835
2836/**
2837 * Display error `msg`.
2838 *
2839 * @param {string} msg
2840 */
2841function error (msg) {
2842 document.body.appendChild(fragment('<div id="mocha-error">%s</div>', msg));
2843}
2844
2845/**
2846 * Return a DOM fragment from `html`.
2847 *
2848 * @param {string} html
2849 */
2850function fragment (html) {
2851 var args = arguments;
2852 var div = document.createElement('div');
2853 var i = 1;
2854
2855 div.innerHTML = html.replace(/%([se])/g, function (_, type) {
2856 switch (type) {
2857 case 's': return String(args[i++]);
2858 case 'e': return escape(args[i++]);
2859 // no default
2860 }
2861 });
2862
2863 return div.firstChild;
2864}
2865
2866/**
2867 * Check for suites that do not have elements
2868 * with `classname`, and hide them.
2869 *
2870 * @param {text} classname
2871 */
2872function hideSuitesWithout (classname) {
2873 var suites = document.getElementsByClassName('suite');
2874 for (var i = 0; i < suites.length; i++) {
2875 var els = suites[i].getElementsByClassName(classname);
2876 if (!els.length) {
2877 suites[i].className += ' hidden';
2878 }
2879 }
2880}
2881
2882/**
2883 * Unhide .hidden suites.
2884 */
2885function unhide () {
2886 var els = document.getElementsByClassName('suite hidden');
2887 for (var i = 0; i < els.length; ++i) {
2888 els[i].className = els[i].className.replace('suite hidden', 'suite');
2889 }
2890}
2891
2892/**
2893 * Set an element's text contents.
2894 *
2895 * @param {HTMLElement} el
2896 * @param {string} contents
2897 */
2898function text (el, contents) {
2899 if (el.textContent) {
2900 el.textContent = contents;
2901 } else {
2902 el.innerText = contents;
2903 }
2904}
2905
2906/**
2907 * Listen on `event` with callback `fn`.
2908 */
2909function on (el, event, fn) {
2910 if (el.addEventListener) {
2911 el.addEventListener(event, fn, false);
2912 } else {
2913 el.attachEvent('on' + event, fn);
2914 }
2915}
2916
2917}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
2918},{"../browser/progress":4,"../utils":38,"./base":17,"escape-string-regexp":47}],21:[function(require,module,exports){
2919'use strict';
2920
2921// Alias exports to a their normalized format Mocha#reporter to prevent a need
2922// for dynamic (try/catch) requires, which Browserify doesn't handle.
2923exports.Base = exports.base = require('./base');
2924exports.Dot = exports.dot = require('./dot');
2925exports.Doc = exports.doc = require('./doc');
2926exports.TAP = exports.tap = require('./tap');
2927exports.JSON = exports.json = require('./json');
2928exports.HTML = exports.html = require('./html');
2929exports.List = exports.list = require('./list');
2930exports.Min = exports.min = require('./min');
2931exports.Spec = exports.spec = require('./spec');
2932exports.Nyan = exports.nyan = require('./nyan');
2933exports.XUnit = exports.xunit = require('./xunit');
2934exports.Markdown = exports.markdown = require('./markdown');
2935exports.Progress = exports.progress = require('./progress');
2936exports.Landing = exports.landing = require('./landing');
2937exports.JSONStream = exports['json-stream'] = require('./json-stream');
2938
2939},{"./base":17,"./doc":18,"./dot":19,"./html":20,"./json":23,"./json-stream":22,"./landing":24,"./list":25,"./markdown":26,"./min":27,"./nyan":28,"./progress":29,"./spec":30,"./tap":31,"./xunit":32}],22:[function(require,module,exports){
2940(function (process){
2941'use strict';
2942
2943/**
2944 * Module dependencies.
2945 */
2946
2947var Base = require('./base');
2948var JSON = require('json3');
2949
2950/**
2951 * Expose `List`.
2952 */
2953
2954exports = module.exports = List;
2955
2956/**
2957 * Initialize a new `List` test reporter.
2958 *
2959 * @api public
2960 * @param {Runner} runner
2961 */
2962function List (runner) {
2963 Base.call(this, runner);
2964
2965 var self = this;
2966 var total = runner.total;
2967
2968 runner.on('start', function () {
2969 console.log(JSON.stringify(['start', { total: total }]));
2970 });
2971
2972 runner.on('pass', function (test) {
2973 console.log(JSON.stringify(['pass', clean(test)]));
2974 });
2975
2976 runner.on('fail', function (test, err) {
2977 test = clean(test);
2978 test.err = err.message;
2979 test.stack = err.stack || null;
2980 console.log(JSON.stringify(['fail', test]));
2981 });
2982
2983 runner.on('end', function () {
2984 process.stdout.write(JSON.stringify(['end', self.stats]));
2985 });
2986}
2987
2988/**
2989 * Return a plain-object representation of `test`
2990 * free of cyclic properties etc.
2991 *
2992 * @api private
2993 * @param {Object} test
2994 * @return {Object}
2995 */
2996function clean (test) {
2997 return {
2998 title: test.title,
2999 fullTitle: test.fullTitle(),
3000 duration: test.duration,
3001 currentRetry: test.currentRetry()
3002 };
3003}
3004
3005}).call(this,require('_process'))
3006},{"./base":17,"_process":67,"json3":54}],23:[function(require,module,exports){
3007(function (process){
3008'use strict';
3009
3010/**
3011 * Module dependencies.
3012 */
3013
3014var Base = require('./base');
3015
3016/**
3017 * Expose `JSON`.
3018 */
3019
3020exports = module.exports = JSONReporter;
3021
3022/**
3023 * Initialize a new `JSON` reporter.
3024 *
3025 * @api public
3026 * @param {Runner} runner
3027 */
3028function JSONReporter (runner) {
3029 Base.call(this, runner);
3030
3031 var self = this;
3032 var tests = [];
3033 var pending = [];
3034 var failures = [];
3035 var passes = [];
3036
3037 runner.on('test end', function (test) {
3038 tests.push(test);
3039 });
3040
3041 runner.on('pass', function (test) {
3042 passes.push(test);
3043 });
3044
3045 runner.on('fail', function (test) {
3046 failures.push(test);
3047 });
3048
3049 runner.on('pending', function (test) {
3050 pending.push(test);
3051 });
3052
3053 runner.on('end', function () {
3054 var obj = {
3055 stats: self.stats,
3056 tests: tests.map(clean),
3057 pending: pending.map(clean),
3058 failures: failures.map(clean),
3059 passes: passes.map(clean)
3060 };
3061
3062 runner.testResults = obj;
3063
3064 process.stdout.write(JSON.stringify(obj, null, 2));
3065 });
3066}
3067
3068/**
3069 * Return a plain-object representation of `test`
3070 * free of cyclic properties etc.
3071 *
3072 * @api private
3073 * @param {Object} test
3074 * @return {Object}
3075 */
3076function clean (test) {
3077 return {
3078 title: test.title,
3079 fullTitle: test.fullTitle(),
3080 duration: test.duration,
3081 currentRetry: test.currentRetry(),
3082 err: errorJSON(test.err || {})
3083 };
3084}
3085
3086/**
3087 * Transform `error` into a JSON object.
3088 *
3089 * @api private
3090 * @param {Error} err
3091 * @return {Object}
3092 */
3093function errorJSON (err) {
3094 var res = {};
3095 Object.getOwnPropertyNames(err).forEach(function (key) {
3096 res[key] = err[key];
3097 }, err);
3098 return res;
3099}
3100
3101}).call(this,require('_process'))
3102},{"./base":17,"_process":67}],24:[function(require,module,exports){
3103(function (process){
3104'use strict';
3105
3106/**
3107 * Module dependencies.
3108 */
3109
3110var Base = require('./base');
3111var inherits = require('../utils').inherits;
3112var cursor = Base.cursor;
3113var color = Base.color;
3114
3115/**
3116 * Expose `Landing`.
3117 */
3118
3119exports = module.exports = Landing;
3120
3121/**
3122 * Airplane color.
3123 */
3124
3125Base.colors.plane = 0;
3126
3127/**
3128 * Airplane crash color.
3129 */
3130
3131Base.colors['plane crash'] = 31;
3132
3133/**
3134 * Runway color.
3135 */
3136
3137Base.colors.runway = 90;
3138
3139/**
3140 * Initialize a new `Landing` reporter.
3141 *
3142 * @api public
3143 * @param {Runner} runner
3144 */
3145function Landing (runner) {
3146 Base.call(this, runner);
3147
3148 var self = this;
3149 var width = Base.window.width * 0.75 | 0;
3150 var total = runner.total;
3151 var stream = process.stdout;
3152 var plane = color('plane', '✈');
3153 var crashed = -1;
3154 var n = 0;
3155
3156 function runway () {
3157 var buf = Array(width).join('-');
3158 return ' ' + color('runway', buf);
3159 }
3160
3161 runner.on('start', function () {
3162 stream.write('\n\n\n ');
3163 cursor.hide();
3164 });
3165
3166 runner.on('test end', function (test) {
3167 // check if the plane crashed
3168 var col = crashed === -1 ? width * ++n / total | 0 : crashed;
3169
3170 // show the crash
3171 if (test.state === 'failed') {
3172 plane = color('plane crash', '✈');
3173 crashed = col;
3174 }
3175
3176 // render landing strip
3177 stream.write('\u001b[' + (width + 1) + 'D\u001b[2A');
3178 stream.write(runway());
3179 stream.write('\n ');
3180 stream.write(color('runway', Array(col).join('⋅')));
3181 stream.write(plane);
3182 stream.write(color('runway', Array(width - col).join('⋅') + '\n'));
3183 stream.write(runway());
3184 stream.write('\u001b[0m');
3185 });
3186
3187 runner.on('end', function () {
3188 cursor.show();
3189 console.log();
3190 self.epilogue();
3191 });
3192}
3193
3194/**
3195 * Inherit from `Base.prototype`.
3196 */
3197inherits(Landing, Base);
3198
3199}).call(this,require('_process'))
3200},{"../utils":38,"./base":17,"_process":67}],25:[function(require,module,exports){
3201(function (process){
3202'use strict';
3203
3204/**
3205 * Module dependencies.
3206 */
3207
3208var Base = require('./base');
3209var inherits = require('../utils').inherits;
3210var color = Base.color;
3211var cursor = Base.cursor;
3212
3213/**
3214 * Expose `List`.
3215 */
3216
3217exports = module.exports = List;
3218
3219/**
3220 * Initialize a new `List` test reporter.
3221 *
3222 * @api public
3223 * @param {Runner} runner
3224 */
3225function List (runner) {
3226 Base.call(this, runner);
3227
3228 var self = this;
3229 var n = 0;
3230
3231 runner.on('start', function () {
3232 console.log();
3233 });
3234
3235 runner.on('test', function (test) {
3236 process.stdout.write(color('pass', ' ' + test.fullTitle() + ': '));
3237 });
3238
3239 runner.on('pending', function (test) {
3240 var fmt = color('checkmark', ' -') +
3241 color('pending', ' %s');
3242 console.log(fmt, test.fullTitle());
3243 });
3244
3245 runner.on('pass', function (test) {
3246 var fmt = color('checkmark', ' ' + Base.symbols.ok) +
3247 color('pass', ' %s: ') +
3248 color(test.speed, '%dms');
3249 cursor.CR();
3250 console.log(fmt, test.fullTitle(), test.duration);
3251 });
3252
3253 runner.on('fail', function (test) {
3254 cursor.CR();
3255 console.log(color('fail', ' %d) %s'), ++n, test.fullTitle());
3256 });
3257
3258 runner.on('end', self.epilogue.bind(self));
3259}
3260
3261/**
3262 * Inherit from `Base.prototype`.
3263 */
3264inherits(List, Base);
3265
3266}).call(this,require('_process'))
3267},{"../utils":38,"./base":17,"_process":67}],26:[function(require,module,exports){
3268(function (process){
3269'use strict';
3270
3271/**
3272 * Module dependencies.
3273 */
3274
3275var Base = require('./base');
3276var utils = require('../utils');
3277
3278/**
3279 * Constants
3280 */
3281
3282var SUITE_PREFIX = '$';
3283
3284/**
3285 * Expose `Markdown`.
3286 */
3287
3288exports = module.exports = Markdown;
3289
3290/**
3291 * Initialize a new `Markdown` reporter.
3292 *
3293 * @api public
3294 * @param {Runner} runner
3295 */
3296function Markdown (runner) {
3297 Base.call(this, runner);
3298
3299 var level = 0;
3300 var buf = '';
3301
3302 function title (str) {
3303 return Array(level).join('#') + ' ' + str;
3304 }
3305
3306 function mapTOC (suite, obj) {
3307 var ret = obj;
3308 var key = SUITE_PREFIX + suite.title;
3309
3310 obj = obj[key] = obj[key] || { suite: suite };
3311 suite.suites.forEach(function (suite) {
3312 mapTOC(suite, obj);
3313 });
3314
3315 return ret;
3316 }
3317
3318 function stringifyTOC (obj, level) {
3319 ++level;
3320 var buf = '';
3321 var link;
3322 for (var key in obj) {
3323 if (key === 'suite') {
3324 continue;
3325 }
3326 if (key !== SUITE_PREFIX) {
3327 link = ' - [' + key.substring(1) + ']';
3328 link += '(#' + utils.slug(obj[key].suite.fullTitle()) + ')\n';
3329 buf += Array(level).join(' ') + link;
3330 }
3331 buf += stringifyTOC(obj[key], level);
3332 }
3333 return buf;
3334 }
3335
3336 function generateTOC (suite) {
3337 var obj = mapTOC(suite, {});
3338 return stringifyTOC(obj, 0);
3339 }
3340
3341 generateTOC(runner.suite);
3342
3343 runner.on('suite', function (suite) {
3344 ++level;
3345 var slug = utils.slug(suite.fullTitle());
3346 buf += '<a name="' + slug + '"></a>' + '\n';
3347 buf += title(suite.title) + '\n';
3348 });
3349
3350 runner.on('suite end', function () {
3351 --level;
3352 });
3353
3354 runner.on('pass', function (test) {
3355 var code = utils.clean(test.body);
3356 buf += test.title + '.\n';
3357 buf += '\n```js\n';
3358 buf += code + '\n';
3359 buf += '```\n\n';
3360 });
3361
3362 runner.on('end', function () {
3363 process.stdout.write('# TOC\n');
3364 process.stdout.write(generateTOC(runner.suite));
3365 process.stdout.write(buf);
3366 });
3367}
3368
3369}).call(this,require('_process'))
3370},{"../utils":38,"./base":17,"_process":67}],27:[function(require,module,exports){
3371(function (process){
3372'use strict';
3373
3374/**
3375 * Module dependencies.
3376 */
3377
3378var Base = require('./base');
3379var inherits = require('../utils').inherits;
3380
3381/**
3382 * Expose `Min`.
3383 */
3384
3385exports = module.exports = Min;
3386
3387/**
3388 * Initialize a new `Min` minimal test reporter (best used with --watch).
3389 *
3390 * @api public
3391 * @param {Runner} runner
3392 */
3393function Min (runner) {
3394 Base.call(this, runner);
3395
3396 runner.on('start', function () {
3397 // clear screen
3398 process.stdout.write('\u001b[2J');
3399 // set cursor position
3400 process.stdout.write('\u001b[1;3H');
3401 });
3402
3403 runner.on('end', this.epilogue.bind(this));
3404}
3405
3406/**
3407 * Inherit from `Base.prototype`.
3408 */
3409inherits(Min, Base);
3410
3411}).call(this,require('_process'))
3412},{"../utils":38,"./base":17,"_process":67}],28:[function(require,module,exports){
3413(function (process){
3414'use strict';
3415
3416/**
3417 * Module dependencies.
3418 */
3419
3420var Base = require('./base');
3421var inherits = require('../utils').inherits;
3422
3423/**
3424 * Expose `Dot`.
3425 */
3426
3427exports = module.exports = NyanCat;
3428
3429/**
3430 * Initialize a new `Dot` matrix test reporter.
3431 *
3432 * @param {Runner} runner
3433 * @api public
3434 */
3435
3436function NyanCat (runner) {
3437 Base.call(this, runner);
3438
3439 var self = this;
3440 var width = Base.window.width * 0.75 | 0;
3441 var nyanCatWidth = this.nyanCatWidth = 11;
3442
3443 this.colorIndex = 0;
3444 this.numberOfLines = 4;
3445 this.rainbowColors = self.generateColors();
3446 this.scoreboardWidth = 5;
3447 this.tick = 0;
3448 this.trajectories = [[], [], [], []];
3449 this.trajectoryWidthMax = (width - nyanCatWidth);
3450
3451 runner.on('start', function () {
3452 Base.cursor.hide();
3453 self.draw();
3454 });
3455
3456 runner.on('pending', function () {
3457 self.draw();
3458 });
3459
3460 runner.on('pass', function () {
3461 self.draw();
3462 });
3463
3464 runner.on('fail', function () {
3465 self.draw();
3466 });
3467
3468 runner.on('end', function () {
3469 Base.cursor.show();
3470 for (var i = 0; i < self.numberOfLines; i++) {
3471 write('\n');
3472 }
3473 self.epilogue();
3474 });
3475}
3476
3477/**
3478 * Inherit from `Base.prototype`.
3479 */
3480inherits(NyanCat, Base);
3481
3482/**
3483 * Draw the nyan cat
3484 *
3485 * @api private
3486 */
3487
3488NyanCat.prototype.draw = function () {
3489 this.appendRainbow();
3490 this.drawScoreboard();
3491 this.drawRainbow();
3492 this.drawNyanCat();
3493 this.tick = !this.tick;
3494};
3495
3496/**
3497 * Draw the "scoreboard" showing the number
3498 * of passes, failures and pending tests.
3499 *
3500 * @api private
3501 */
3502
3503NyanCat.prototype.drawScoreboard = function () {
3504 var stats = this.stats;
3505
3506 function draw (type, n) {
3507 write(' ');
3508 write(Base.color(type, n));
3509 write('\n');
3510 }
3511
3512 draw('green', stats.passes);
3513 draw('fail', stats.failures);
3514 draw('pending', stats.pending);
3515 write('\n');
3516
3517 this.cursorUp(this.numberOfLines);
3518};
3519
3520/**
3521 * Append the rainbow.
3522 *
3523 * @api private
3524 */
3525
3526NyanCat.prototype.appendRainbow = function () {
3527 var segment = this.tick ? '_' : '-';
3528 var rainbowified = this.rainbowify(segment);
3529
3530 for (var index = 0; index < this.numberOfLines; index++) {
3531 var trajectory = this.trajectories[index];
3532 if (trajectory.length >= this.trajectoryWidthMax) {
3533 trajectory.shift();
3534 }
3535 trajectory.push(rainbowified);
3536 }
3537};
3538
3539/**
3540 * Draw the rainbow.
3541 *
3542 * @api private
3543 */
3544
3545NyanCat.prototype.drawRainbow = function () {
3546 var self = this;
3547
3548 this.trajectories.forEach(function (line) {
3549 write('\u001b[' + self.scoreboardWidth + 'C');
3550 write(line.join(''));
3551 write('\n');
3552 });
3553
3554 this.cursorUp(this.numberOfLines);
3555};
3556
3557/**
3558 * Draw the nyan cat
3559 *
3560 * @api private
3561 */
3562NyanCat.prototype.drawNyanCat = function () {
3563 var self = this;
3564 var startWidth = this.scoreboardWidth + this.trajectories[0].length;
3565 var dist = '\u001b[' + startWidth + 'C';
3566 var padding = '';
3567
3568 write(dist);
3569 write('_,------,');
3570 write('\n');
3571
3572 write(dist);
3573 padding = self.tick ? ' ' : ' ';
3574 write('_|' + padding + '/\\_/\\ ');
3575 write('\n');
3576
3577 write(dist);
3578 padding = self.tick ? '_' : '__';
3579 var tail = self.tick ? '~' : '^';
3580 write(tail + '|' + padding + this.face() + ' ');
3581 write('\n');
3582
3583 write(dist);
3584 padding = self.tick ? ' ' : ' ';
3585 write(padding + '"" "" ');
3586 write('\n');
3587
3588 this.cursorUp(this.numberOfLines);
3589};
3590
3591/**
3592 * Draw nyan cat face.
3593 *
3594 * @api private
3595 * @return {string}
3596 */
3597
3598NyanCat.prototype.face = function () {
3599 var stats = this.stats;
3600 if (stats.failures) {
3601 return '( x .x)';
3602 } else if (stats.pending) {
3603 return '( o .o)';
3604 } else if (stats.passes) {
3605 return '( ^ .^)';
3606 }
3607 return '( - .-)';
3608};
3609
3610/**
3611 * Move cursor up `n`.
3612 *
3613 * @api private
3614 * @param {number} n
3615 */
3616
3617NyanCat.prototype.cursorUp = function (n) {
3618 write('\u001b[' + n + 'A');
3619};
3620
3621/**
3622 * Move cursor down `n`.
3623 *
3624 * @api private
3625 * @param {number} n
3626 */
3627
3628NyanCat.prototype.cursorDown = function (n) {
3629 write('\u001b[' + n + 'B');
3630};
3631
3632/**
3633 * Generate rainbow colors.
3634 *
3635 * @api private
3636 * @return {Array}
3637 */
3638NyanCat.prototype.generateColors = function () {
3639 var colors = [];
3640
3641 for (var i = 0; i < (6 * 7); i++) {
3642 var pi3 = Math.floor(Math.PI / 3);
3643 var n = (i * (1.0 / 6));
3644 var r = Math.floor(3 * Math.sin(n) + 3);
3645 var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3);
3646 var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3);
3647 colors.push(36 * r + 6 * g + b + 16);
3648 }
3649
3650 return colors;
3651};
3652
3653/**
3654 * Apply rainbow to the given `str`.
3655 *
3656 * @api private
3657 * @param {string} str
3658 * @return {string}
3659 */
3660NyanCat.prototype.rainbowify = function (str) {
3661 if (!Base.useColors) {
3662 return str;
3663 }
3664 var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length];
3665 this.colorIndex += 1;
3666 return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m';
3667};
3668
3669/**
3670 * Stdout helper.
3671 *
3672 * @param {string} string A message to write to stdout.
3673 */
3674function write (string) {
3675 process.stdout.write(string);
3676}
3677
3678}).call(this,require('_process'))
3679},{"../utils":38,"./base":17,"_process":67}],29:[function(require,module,exports){
3680(function (process){
3681'use strict';
3682
3683/**
3684 * Module dependencies.
3685 */
3686
3687var Base = require('./base');
3688var inherits = require('../utils').inherits;
3689var color = Base.color;
3690var cursor = Base.cursor;
3691
3692/**
3693 * Expose `Progress`.
3694 */
3695
3696exports = module.exports = Progress;
3697
3698/**
3699 * General progress bar color.
3700 */
3701
3702Base.colors.progress = 90;
3703
3704/**
3705 * Initialize a new `Progress` bar test reporter.
3706 *
3707 * @api public
3708 * @param {Runner} runner
3709 * @param {Object} options
3710 */
3711function Progress (runner, options) {
3712 Base.call(this, runner);
3713
3714 var self = this;
3715 var width = Base.window.width * 0.50 | 0;
3716 var total = runner.total;
3717 var complete = 0;
3718 var lastN = -1;
3719
3720 // default chars
3721 options = options || {};
3722 options.open = options.open || '[';
3723 options.complete = options.complete || '▬';
3724 options.incomplete = options.incomplete || Base.symbols.dot;
3725 options.close = options.close || ']';
3726 options.verbose = false;
3727
3728 // tests started
3729 runner.on('start', function () {
3730 console.log();
3731 cursor.hide();
3732 });
3733
3734 // tests complete
3735 runner.on('test end', function () {
3736 complete++;
3737
3738 var percent = complete / total;
3739 var n = width * percent | 0;
3740 var i = width - n;
3741
3742 if (n === lastN && !options.verbose) {
3743 // Don't re-render the line if it hasn't changed
3744 return;
3745 }
3746 lastN = n;
3747
3748 cursor.CR();
3749 process.stdout.write('\u001b[J');
3750 process.stdout.write(color('progress', ' ' + options.open));
3751 process.stdout.write(Array(n).join(options.complete));
3752 process.stdout.write(Array(i).join(options.incomplete));
3753 process.stdout.write(color('progress', options.close));
3754 if (options.verbose) {
3755 process.stdout.write(color('progress', ' ' + complete + ' of ' + total));
3756 }
3757 });
3758
3759 // tests are complete, output some stats
3760 // and the failures if any
3761 runner.on('end', function () {
3762 cursor.show();
3763 console.log();
3764 self.epilogue();
3765 });
3766}
3767
3768/**
3769 * Inherit from `Base.prototype`.
3770 */
3771inherits(Progress, Base);
3772
3773}).call(this,require('_process'))
3774},{"../utils":38,"./base":17,"_process":67}],30:[function(require,module,exports){
3775'use strict';
3776
3777/**
3778 * Module dependencies.
3779 */
3780
3781var Base = require('./base');
3782var inherits = require('../utils').inherits;
3783var color = Base.color;
3784
3785/**
3786 * Expose `Spec`.
3787 */
3788
3789exports = module.exports = Spec;
3790
3791/**
3792 * Initialize a new `Spec` test reporter.
3793 *
3794 * @api public
3795 * @param {Runner} runner
3796 */
3797function Spec (runner) {
3798 Base.call(this, runner);
3799
3800 var self = this;
3801 var indents = 0;
3802 var n = 0;
3803
3804 function indent () {
3805 return Array(indents).join(' ');
3806 }
3807
3808 runner.on('start', function () {
3809 console.log();
3810 });
3811
3812 runner.on('suite', function (suite) {
3813 ++indents;
3814 console.log(color('suite', '%s%s'), indent(), suite.title);
3815 });
3816
3817 runner.on('suite end', function () {
3818 --indents;
3819 if (indents === 1) {
3820 console.log();
3821 }
3822 });
3823
3824 runner.on('pending', function (test) {
3825 var fmt = indent() + color('pending', ' - %s');
3826 console.log(fmt, test.title);
3827 });
3828
3829 runner.on('pass', function (test) {
3830 var fmt;
3831 if (test.speed === 'fast') {
3832 fmt = indent() +
3833 color('checkmark', ' ' + Base.symbols.ok) +
3834 color('pass', ' %s');
3835 console.log(fmt, test.title);
3836 } else {
3837 fmt = indent() +
3838 color('checkmark', ' ' + Base.symbols.ok) +
3839 color('pass', ' %s') +
3840 color(test.speed, ' (%dms)');
3841 console.log(fmt, test.title, test.duration);
3842 }
3843 });
3844
3845 runner.on('fail', function (test) {
3846 console.log(indent() + color('fail', ' %d) %s'), ++n, test.title);
3847 });
3848
3849 runner.on('end', self.epilogue.bind(self));
3850}
3851
3852/**
3853 * Inherit from `Base.prototype`.
3854 */
3855inherits(Spec, Base);
3856
3857},{"../utils":38,"./base":17}],31:[function(require,module,exports){
3858'use strict';
3859
3860/**
3861 * Module dependencies.
3862 */
3863
3864var Base = require('./base');
3865
3866/**
3867 * Expose `TAP`.
3868 */
3869
3870exports = module.exports = TAP;
3871
3872/**
3873 * Initialize a new `TAP` reporter.
3874 *
3875 * @api public
3876 * @param {Runner} runner
3877 */
3878function TAP (runner) {
3879 Base.call(this, runner);
3880
3881 var n = 1;
3882 var passes = 0;
3883 var failures = 0;
3884
3885 runner.on('start', function () {
3886 var total = runner.grepTotal(runner.suite);
3887 console.log('%d..%d', 1, total);
3888 });
3889
3890 runner.on('test end', function () {
3891 ++n;
3892 });
3893
3894 runner.on('pending', function (test) {
3895 console.log('ok %d %s # SKIP -', n, title(test));
3896 });
3897
3898 runner.on('pass', function (test) {
3899 passes++;
3900 console.log('ok %d %s', n, title(test));
3901 });
3902
3903 runner.on('fail', function (test, err) {
3904 failures++;
3905 console.log('not ok %d %s', n, title(test));
3906 if (err.stack) {
3907 console.log(err.stack.replace(/^/gm, ' '));
3908 }
3909 });
3910
3911 runner.on('end', function () {
3912 console.log('# tests ' + (passes + failures));
3913 console.log('# pass ' + passes);
3914 console.log('# fail ' + failures);
3915 });
3916}
3917
3918/**
3919 * Return a TAP-safe title of `test`
3920 *
3921 * @api private
3922 * @param {Object} test
3923 * @return {String}
3924 */
3925function title (test) {
3926 return test.fullTitle().replace(/#/g, '');
3927}
3928
3929},{"./base":17}],32:[function(require,module,exports){
3930(function (process,global){
3931'use strict';
3932
3933/**
3934 * Module dependencies.
3935 */
3936
3937var Base = require('./base');
3938var utils = require('../utils');
3939var inherits = utils.inherits;
3940var fs = require('fs');
3941var escape = utils.escape;
3942var mkdirp = require('mkdirp');
3943var path = require('path');
3944
3945/**
3946 * Save timer references to avoid Sinon interfering (see GH-237).
3947 */
3948
3949/* eslint-disable no-unused-vars, no-native-reassign */
3950var Date = global.Date;
3951var setTimeout = global.setTimeout;
3952var setInterval = global.setInterval;
3953var clearTimeout = global.clearTimeout;
3954var clearInterval = global.clearInterval;
3955/* eslint-enable no-unused-vars, no-native-reassign */
3956
3957/**
3958 * Expose `XUnit`.
3959 */
3960
3961exports = module.exports = XUnit;
3962
3963/**
3964 * Initialize a new `XUnit` reporter.
3965 *
3966 * @api public
3967 * @param {Runner} runner
3968 */
3969function XUnit (runner, options) {
3970 Base.call(this, runner);
3971
3972 var stats = this.stats;
3973 var tests = [];
3974 var self = this;
3975
3976 if (options && options.reporterOptions && options.reporterOptions.output) {
3977 if (!fs.createWriteStream) {
3978 throw new Error('file output not supported in browser');
3979 }
3980 mkdirp.sync(path.dirname(options.reporterOptions.output));
3981 self.fileStream = fs.createWriteStream(options.reporterOptions.output);
3982 }
3983
3984 runner.on('pending', function (test) {
3985 tests.push(test);
3986 });
3987
3988 runner.on('pass', function (test) {
3989 tests.push(test);
3990 });
3991
3992 runner.on('fail', function (test) {
3993 tests.push(test);
3994 });
3995
3996 runner.on('end', function () {
3997 self.write(tag('testsuite', {
3998 name: 'Mocha Tests',
3999 tests: stats.tests,
4000 failures: stats.failures,
4001 errors: stats.failures,
4002 skipped: stats.tests - stats.failures - stats.passes,
4003 timestamp: (new Date()).toUTCString(),
4004 time: (stats.duration / 1000) || 0
4005 }, false));
4006
4007 tests.forEach(function (t) {
4008 self.test(t);
4009 });
4010
4011 self.write('</testsuite>');
4012 });
4013}
4014
4015/**
4016 * Inherit from `Base.prototype`.
4017 */
4018inherits(XUnit, Base);
4019
4020/**
4021 * Override done to close the stream (if it's a file).
4022 *
4023 * @param failures
4024 * @param {Function} fn
4025 */
4026XUnit.prototype.done = function (failures, fn) {
4027 if (this.fileStream) {
4028 this.fileStream.end(function () {
4029 fn(failures);
4030 });
4031 } else {
4032 fn(failures);
4033 }
4034};
4035
4036/**
4037 * Write out the given line.
4038 *
4039 * @param {string} line
4040 */
4041XUnit.prototype.write = function (line) {
4042 if (this.fileStream) {
4043 this.fileStream.write(line + '\n');
4044 } else if (typeof process === 'object' && process.stdout) {
4045 process.stdout.write(line + '\n');
4046 } else {
4047 console.log(line);
4048 }
4049};
4050
4051/**
4052 * Output tag for the given `test.`
4053 *
4054 * @param {Test} test
4055 */
4056XUnit.prototype.test = function (test) {
4057 var attrs = {
4058 classname: test.parent.fullTitle(),
4059 name: test.title,
4060 time: (test.duration / 1000) || 0
4061 };
4062
4063 if (test.state === 'failed') {
4064 var err = test.err;
4065 this.write(tag('testcase', attrs, false, tag('failure', {}, false, escape(err.message) + '\n' + escape(err.stack))));
4066 } else if (test.isPending()) {
4067 this.write(tag('testcase', attrs, false, tag('skipped', {}, true)));
4068 } else {
4069 this.write(tag('testcase', attrs, true));
4070 }
4071};
4072
4073/**
4074 * HTML tag helper.
4075 *
4076 * @param name
4077 * @param attrs
4078 * @param close
4079 * @param content
4080 * @return {string}
4081 */
4082function tag (name, attrs, close, content) {
4083 var end = close ? '/>' : '>';
4084 var pairs = [];
4085 var tag;
4086
4087 for (var key in attrs) {
4088 if (Object.prototype.hasOwnProperty.call(attrs, key)) {
4089 pairs.push(key + '="' + escape(attrs[key]) + '"');
4090 }
4091 }
4092
4093 tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end;
4094 if (content) {
4095 tag += content + '</' + name + end;
4096 }
4097 return tag;
4098}
4099
4100}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
4101},{"../utils":38,"./base":17,"_process":67,"fs":42,"mkdirp":64,"path":42}],33:[function(require,module,exports){
4102(function (global){
4103'use strict';
4104
4105/**
4106 * Module dependencies.
4107 */
4108
4109var EventEmitter = require('events').EventEmitter;
4110var JSON = require('json3');
4111var Pending = require('./pending');
4112var debug = require('debug')('mocha:runnable');
4113var milliseconds = require('./ms');
4114var utils = require('./utils');
4115var create = require('lodash.create');
4116
4117/**
4118 * Save timer references to avoid Sinon interfering (see GH-237).
4119 */
4120
4121/* eslint-disable no-unused-vars, no-native-reassign */
4122var Date = global.Date;
4123var setTimeout = global.setTimeout;
4124var setInterval = global.setInterval;
4125var clearTimeout = global.clearTimeout;
4126var clearInterval = global.clearInterval;
4127/* eslint-enable no-unused-vars, no-native-reassign */
4128
4129/**
4130 * Object#toString().
4131 */
4132
4133var toString = Object.prototype.toString;
4134
4135/**
4136 * Expose `Runnable`.
4137 */
4138
4139module.exports = Runnable;
4140
4141/**
4142 * Initialize a new `Runnable` with the given `title` and callback `fn`.
4143 *
4144 * @param {String} title
4145 * @param {Function} fn
4146 * @api private
4147 * @param {string} title
4148 * @param {Function} fn
4149 */
4150function Runnable (title, fn) {
4151 this.title = title;
4152 this.fn = fn;
4153 this.body = (fn || '').toString();
4154 this.async = fn && fn.length;
4155 this.sync = !this.async;
4156 this._timeout = 2000;
4157 this._slow = 75;
4158 this._enableTimeouts = true;
4159 this.timedOut = false;
4160 this._trace = new Error('done() called multiple times');
4161 this._retries = -1;
4162 this._currentRetry = 0;
4163 this.pending = false;
4164}
4165
4166/**
4167 * Inherit from `EventEmitter.prototype`.
4168 */
4169Runnable.prototype = create(EventEmitter.prototype, {
4170 constructor: Runnable
4171});
4172
4173/**
4174 * Set & get timeout `ms`.
4175 *
4176 * @api private
4177 * @param {number|string} ms
4178 * @return {Runnable|number} ms or Runnable instance.
4179 */
4180Runnable.prototype.timeout = function (ms) {
4181 if (!arguments.length) {
4182 return this._timeout;
4183 }
4184 // see #1652 for reasoning
4185 if (ms === 0 || ms > Math.pow(2, 31)) {
4186 this._enableTimeouts = false;
4187 }
4188 if (typeof ms === 'string') {
4189 ms = milliseconds(ms);
4190 }
4191 debug('timeout %d', ms);
4192 this._timeout = ms;
4193 if (this.timer) {
4194 this.resetTimeout();
4195 }
4196 return this;
4197};
4198
4199/**
4200 * Set & get slow `ms`.
4201 *
4202 * @api private
4203 * @param {number|string} ms
4204 * @return {Runnable|number} ms or Runnable instance.
4205 */
4206Runnable.prototype.slow = function (ms) {
4207 if (typeof ms === 'undefined') {
4208 return this._slow;
4209 }
4210 if (typeof ms === 'string') {
4211 ms = milliseconds(ms);
4212 }
4213 debug('timeout %d', ms);
4214 this._slow = ms;
4215 return this;
4216};
4217
4218/**
4219 * Set and get whether timeout is `enabled`.
4220 *
4221 * @api private
4222 * @param {boolean} enabled
4223 * @return {Runnable|boolean} enabled or Runnable instance.
4224 */
4225Runnable.prototype.enableTimeouts = function (enabled) {
4226 if (!arguments.length) {
4227 return this._enableTimeouts;
4228 }
4229 debug('enableTimeouts %s', enabled);
4230 this._enableTimeouts = enabled;
4231 return this;
4232};
4233
4234/**
4235 * Halt and mark as pending.
4236 *
4237 * @api public
4238 */
4239Runnable.prototype.skip = function () {
4240 throw new Pending('sync skip');
4241};
4242
4243/**
4244 * Check if this runnable or its parent suite is marked as pending.
4245 *
4246 * @api private
4247 */
4248Runnable.prototype.isPending = function () {
4249 return this.pending || (this.parent && this.parent.isPending());
4250};
4251
4252/**
4253 * Set number of retries.
4254 *
4255 * @api private
4256 */
4257Runnable.prototype.retries = function (n) {
4258 if (!arguments.length) {
4259 return this._retries;
4260 }
4261 this._retries = n;
4262};
4263
4264/**
4265 * Get current retry
4266 *
4267 * @api private
4268 */
4269Runnable.prototype.currentRetry = function (n) {
4270 if (!arguments.length) {
4271 return this._currentRetry;
4272 }
4273 this._currentRetry = n;
4274};
4275
4276/**
4277 * Return the full title generated by recursively concatenating the parent's
4278 * full title.
4279 *
4280 * @api public
4281 * @return {string}
4282 */
4283Runnable.prototype.fullTitle = function () {
4284 return this.parent.fullTitle() + ' ' + this.title;
4285};
4286
4287/**
4288 * Clear the timeout.
4289 *
4290 * @api private
4291 */
4292Runnable.prototype.clearTimeout = function () {
4293 clearTimeout(this.timer);
4294};
4295
4296/**
4297 * Inspect the runnable void of private properties.
4298 *
4299 * @api private
4300 * @return {string}
4301 */
4302Runnable.prototype.inspect = function () {
4303 return JSON.stringify(this, function (key, val) {
4304 if (key[0] === '_') {
4305 return;
4306 }
4307 if (key === 'parent') {
4308 return '#<Suite>';
4309 }
4310 if (key === 'ctx') {
4311 return '#<Context>';
4312 }
4313 return val;
4314 }, 2);
4315};
4316
4317/**
4318 * Reset the timeout.
4319 *
4320 * @api private
4321 */
4322Runnable.prototype.resetTimeout = function () {
4323 var self = this;
4324 var ms = this.timeout() || 1e9;
4325
4326 if (!this._enableTimeouts) {
4327 return;
4328 }
4329 this.clearTimeout();
4330 this.timer = setTimeout(function () {
4331 if (!self._enableTimeouts) {
4332 return;
4333 }
4334 self.callback(new Error('Timeout of ' + ms +
4335 'ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.'));
4336 self.timedOut = true;
4337 }, ms);
4338};
4339
4340/**
4341 * Whitelist a list of globals for this test run.
4342 *
4343 * @api private
4344 * @param {string[]} globals
4345 */
4346Runnable.prototype.globals = function (globals) {
4347 if (!arguments.length) {
4348 return this._allowedGlobals;
4349 }
4350 this._allowedGlobals = globals;
4351};
4352
4353/**
4354 * Run the test and invoke `fn(err)`.
4355 *
4356 * @param {Function} fn
4357 * @api private
4358 */
4359Runnable.prototype.run = function (fn) {
4360 var self = this;
4361 var start = new Date();
4362 var ctx = this.ctx;
4363 var finished;
4364 var emitted;
4365
4366 // Sometimes the ctx exists, but it is not runnable
4367 if (ctx && ctx.runnable) {
4368 ctx.runnable(this);
4369 }
4370
4371 // called multiple times
4372 function multiple (err) {
4373 if (emitted) {
4374 return;
4375 }
4376 emitted = true;
4377 self.emit('error', err || new Error('done() called multiple times; stacktrace may be inaccurate'));
4378 }
4379
4380 // finished
4381 function done (err) {
4382 var ms = self.timeout();
4383 if (self.timedOut) {
4384 return;
4385 }
4386 if (finished) {
4387 return multiple(err || self._trace);
4388 }
4389
4390 self.clearTimeout();
4391 self.duration = new Date() - start;
4392 finished = true;
4393 if (!err && self.duration > ms && self._enableTimeouts) {
4394 err = new Error('Timeout of ' + ms +
4395 'ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.');
4396 }
4397 fn(err);
4398 }
4399
4400 // for .resetTimeout()
4401 this.callback = done;
4402
4403 // explicit async with `done` argument
4404 if (this.async) {
4405 this.resetTimeout();
4406
4407 // allows skip() to be used in an explicit async context
4408 this.skip = function asyncSkip () {
4409 done(new Pending('async skip call'));
4410 // halt execution. the Runnable will be marked pending
4411 // by the previous call, and the uncaught handler will ignore
4412 // the failure.
4413 throw new Pending('async skip; aborting execution');
4414 };
4415
4416 if (this.allowUncaught) {
4417 return callFnAsync(this.fn);
4418 }
4419 try {
4420 callFnAsync(this.fn);
4421 } catch (err) {
4422 emitted = true;
4423 done(utils.getError(err));
4424 }
4425 return;
4426 }
4427
4428 if (this.allowUncaught) {
4429 callFn(this.fn);
4430 done();
4431 return;
4432 }
4433
4434 // sync or promise-returning
4435 try {
4436 if (this.isPending()) {
4437 done();
4438 } else {
4439 callFn(this.fn);
4440 }
4441 } catch (err) {
4442 emitted = true;
4443 done(utils.getError(err));
4444 }
4445
4446 function callFn (fn) {
4447 var result = fn.call(ctx);
4448 if (result && typeof result.then === 'function') {
4449 self.resetTimeout();
4450 result
4451 .then(function () {
4452 done();
4453 // Return null so libraries like bluebird do not warn about
4454 // subsequently constructed Promises.
4455 return null;
4456 },
4457 function (reason) {
4458 done(reason || new Error('Promise rejected with no or falsy reason'));
4459 });
4460 } else {
4461 if (self.asyncOnly) {
4462 return done(new Error('--async-only option in use without declaring `done()` or returning a promise'));
4463 }
4464
4465 done();
4466 }
4467 }
4468
4469 function callFnAsync (fn) {
4470 var result = fn.call(ctx, function (err) {
4471 if (err instanceof Error || toString.call(err) === '[object Error]') {
4472 return done(err);
4473 }
4474 if (err) {
4475 if (Object.prototype.toString.call(err) === '[object Object]') {
4476 return done(new Error('done() invoked with non-Error: ' +
4477 JSON.stringify(err)));
4478 }
4479 return done(new Error('done() invoked with non-Error: ' + err));
4480 }
4481 if (result && utils.isPromise(result)) {
4482 return done(new Error('Resolution method is overspecified. Specify a callback *or* return a Promise; not both.'));
4483 }
4484
4485 done();
4486 });
4487 }
4488};
4489
4490}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
4491},{"./ms":15,"./pending":16,"./utils":38,"debug":2,"events":3,"json3":54,"lodash.create":60}],34:[function(require,module,exports){
4492(function (process,global){
4493'use strict';
4494
4495/**
4496 * Module dependencies.
4497 */
4498
4499var EventEmitter = require('events').EventEmitter;
4500var Pending = require('./pending');
4501var utils = require('./utils');
4502var inherits = utils.inherits;
4503var debug = require('debug')('mocha:runner');
4504var Runnable = require('./runnable');
4505var filter = utils.filter;
4506var indexOf = utils.indexOf;
4507var some = utils.some;
4508var keys = utils.keys;
4509var stackFilter = utils.stackTraceFilter();
4510var stringify = utils.stringify;
4511var type = utils.type;
4512var undefinedError = utils.undefinedError;
4513var isArray = utils.isArray;
4514
4515/**
4516 * Non-enumerable globals.
4517 */
4518
4519var globals = [
4520 'setTimeout',
4521 'clearTimeout',
4522 'setInterval',
4523 'clearInterval',
4524 'XMLHttpRequest',
4525 'Date',
4526 'setImmediate',
4527 'clearImmediate'
4528];
4529
4530/**
4531 * Expose `Runner`.
4532 */
4533
4534module.exports = Runner;
4535
4536/**
4537 * Initialize a `Runner` for the given `suite`.
4538 *
4539 * Events:
4540 *
4541 * - `start` execution started
4542 * - `end` execution complete
4543 * - `suite` (suite) test suite execution started
4544 * - `suite end` (suite) all tests (and sub-suites) have finished
4545 * - `test` (test) test execution started
4546 * - `test end` (test) test completed
4547 * - `hook` (hook) hook execution started
4548 * - `hook end` (hook) hook complete
4549 * - `pass` (test) test passed
4550 * - `fail` (test, err) test failed
4551 * - `pending` (test) test pending
4552 *
4553 * @api public
4554 * @param {Suite} suite Root suite
4555 * @param {boolean} [delay] Whether or not to delay execution of root suite
4556 * until ready.
4557 */
4558function Runner (suite, delay) {
4559 var self = this;
4560 this._globals = [];
4561 this._abort = false;
4562 this._delay = delay;
4563 this.suite = suite;
4564 this.started = false;
4565 this.total = suite.total();
4566 this.failures = 0;
4567 this.on('test end', function (test) {
4568 self.checkGlobals(test);
4569 });
4570 this.on('hook end', function (hook) {
4571 self.checkGlobals(hook);
4572 });
4573 this._defaultGrep = /.*/;
4574 this.grep(this._defaultGrep);
4575 this.globals(this.globalProps().concat(extraGlobals()));
4576}
4577
4578/**
4579 * Wrapper for setImmediate, process.nextTick, or browser polyfill.
4580 *
4581 * @param {Function} fn
4582 * @api private
4583 */
4584Runner.immediately = global.setImmediate || process.nextTick;
4585
4586/**
4587 * Inherit from `EventEmitter.prototype`.
4588 */
4589inherits(Runner, EventEmitter);
4590
4591/**
4592 * Run tests with full titles matching `re`. Updates runner.total
4593 * with number of tests matched.
4594 *
4595 * @param {RegExp} re
4596 * @param {Boolean} invert
4597 * @return {Runner} for chaining
4598 * @api public
4599 * @param {RegExp} re
4600 * @param {boolean} invert
4601 * @return {Runner} Runner instance.
4602 */
4603Runner.prototype.grep = function (re, invert) {
4604 debug('grep %s', re);
4605 this._grep = re;
4606 this._invert = invert;
4607 this.total = this.grepTotal(this.suite);
4608 return this;
4609};
4610
4611/**
4612 * Returns the number of tests matching the grep search for the
4613 * given suite.
4614 *
4615 * @param {Suite} suite
4616 * @return {Number}
4617 * @api public
4618 * @param {Suite} suite
4619 * @return {number}
4620 */
4621Runner.prototype.grepTotal = function (suite) {
4622 var self = this;
4623 var total = 0;
4624
4625 suite.eachTest(function (test) {
4626 var match = self._grep.test(test.fullTitle());
4627 if (self._invert) {
4628 match = !match;
4629 }
4630 if (match) {
4631 total++;
4632 }
4633 });
4634
4635 return total;
4636};
4637
4638/**
4639 * Return a list of global properties.
4640 *
4641 * @return {Array}
4642 * @api private
4643 */
4644Runner.prototype.globalProps = function () {
4645 var props = keys(global);
4646
4647 // non-enumerables
4648 for (var i = 0; i < globals.length; ++i) {
4649 if (~indexOf(props, globals[i])) {
4650 continue;
4651 }
4652 props.push(globals[i]);
4653 }
4654
4655 return props;
4656};
4657
4658/**
4659 * Allow the given `arr` of globals.
4660 *
4661 * @param {Array} arr
4662 * @return {Runner} for chaining
4663 * @api public
4664 * @param {Array} arr
4665 * @return {Runner} Runner instance.
4666 */
4667Runner.prototype.globals = function (arr) {
4668 if (!arguments.length) {
4669 return this._globals;
4670 }
4671 debug('globals %j', arr);
4672 this._globals = this._globals.concat(arr);
4673 return this;
4674};
4675
4676/**
4677 * Check for global variable leaks.
4678 *
4679 * @api private
4680 */
4681Runner.prototype.checkGlobals = function (test) {
4682 if (this.ignoreLeaks) {
4683 return;
4684 }
4685 var ok = this._globals;
4686
4687 var globals = this.globalProps();
4688 var leaks;
4689
4690 if (test) {
4691 ok = ok.concat(test._allowedGlobals || []);
4692 }
4693
4694 if (this.prevGlobalsLength === globals.length) {
4695 return;
4696 }
4697 this.prevGlobalsLength = globals.length;
4698
4699 leaks = filterLeaks(ok, globals);
4700 this._globals = this._globals.concat(leaks);
4701
4702 if (leaks.length > 1) {
4703 this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + ''));
4704 } else if (leaks.length) {
4705 this.fail(test, new Error('global leak detected: ' + leaks[0]));
4706 }
4707};
4708
4709/**
4710 * Fail the given `test`.
4711 *
4712 * @api private
4713 * @param {Test} test
4714 * @param {Error} err
4715 */
4716Runner.prototype.fail = function (test, err) {
4717 if (test.isPending()) {
4718 return;
4719 }
4720
4721 ++this.failures;
4722 test.state = 'failed';
4723
4724 if (!(err instanceof Error || err && typeof err.message === 'string')) {
4725 err = new Error('the ' + type(err) + ' ' + stringify(err) + ' was thrown, throw an Error :)');
4726 }
4727
4728 try {
4729 err.stack = (this.fullStackTrace || !err.stack)
4730 ? err.stack
4731 : stackFilter(err.stack);
4732 } catch (ignored) {
4733 // some environments do not take kindly to monkeying with the stack
4734 }
4735
4736 this.emit('fail', test, err);
4737};
4738
4739/**
4740 * Fail the given `hook` with `err`.
4741 *
4742 * Hook failures work in the following pattern:
4743 * - If bail, then exit
4744 * - Failed `before` hook skips all tests in a suite and subsuites,
4745 * but jumps to corresponding `after` hook
4746 * - Failed `before each` hook skips remaining tests in a
4747 * suite and jumps to corresponding `after each` hook,
4748 * which is run only once
4749 * - Failed `after` hook does not alter
4750 * execution order
4751 * - Failed `after each` hook skips remaining tests in a
4752 * suite and subsuites, but executes other `after each`
4753 * hooks
4754 *
4755 * @api private
4756 * @param {Hook} hook
4757 * @param {Error} err
4758 */
4759Runner.prototype.failHook = function (hook, err) {
4760 if (hook.ctx && hook.ctx.currentTest) {
4761 hook.originalTitle = hook.originalTitle || hook.title;
4762 hook.title = hook.originalTitle + ' for "' + hook.ctx.currentTest.title + '"';
4763 }
4764
4765 this.fail(hook, err);
4766 if (this.suite.bail()) {
4767 this.emit('end');
4768 }
4769};
4770
4771/**
4772 * Run hook `name` callbacks and then invoke `fn()`.
4773 *
4774 * @api private
4775 * @param {string} name
4776 * @param {Function} fn
4777 */
4778
4779Runner.prototype.hook = function (name, fn) {
4780 var suite = this.suite;
4781 var hooks = suite['_' + name];
4782 var self = this;
4783
4784 function next (i) {
4785 var hook = hooks[i];
4786 if (!hook) {
4787 return fn();
4788 }
4789 self.currentRunnable = hook;
4790
4791 hook.ctx.currentTest = self.test;
4792
4793 self.emit('hook', hook);
4794
4795 if (!hook.listeners('error').length) {
4796 hook.on('error', function (err) {
4797 self.failHook(hook, err);
4798 });
4799 }
4800
4801 hook.run(function (err) {
4802 var testError = hook.error();
4803 if (testError) {
4804 self.fail(self.test, testError);
4805 }
4806 if (err) {
4807 if (err instanceof Pending) {
4808 if (name === 'beforeEach' || name === 'afterEach') {
4809 self.test.pending = true;
4810 } else {
4811 utils.forEach(suite.tests, function (test) {
4812 test.pending = true;
4813 });
4814 // a pending hook won't be executed twice.
4815 hook.pending = true;
4816 }
4817 } else {
4818 self.failHook(hook, err);
4819
4820 // stop executing hooks, notify callee of hook err
4821 return fn(err);
4822 }
4823 }
4824 self.emit('hook end', hook);
4825 delete hook.ctx.currentTest;
4826 next(++i);
4827 });
4828 }
4829
4830 Runner.immediately(function () {
4831 next(0);
4832 });
4833};
4834
4835/**
4836 * Run hook `name` for the given array of `suites`
4837 * in order, and callback `fn(err, errSuite)`.
4838 *
4839 * @api private
4840 * @param {string} name
4841 * @param {Array} suites
4842 * @param {Function} fn
4843 */
4844Runner.prototype.hooks = function (name, suites, fn) {
4845 var self = this;
4846 var orig = this.suite;
4847
4848 function next (suite) {
4849 self.suite = suite;
4850
4851 if (!suite) {
4852 self.suite = orig;
4853 return fn();
4854 }
4855
4856 self.hook(name, function (err) {
4857 if (err) {
4858 var errSuite = self.suite;
4859 self.suite = orig;
4860 return fn(err, errSuite);
4861 }
4862
4863 next(suites.pop());
4864 });
4865 }
4866
4867 next(suites.pop());
4868};
4869
4870/**
4871 * Run hooks from the top level down.
4872 *
4873 * @param {String} name
4874 * @param {Function} fn
4875 * @api private
4876 */
4877Runner.prototype.hookUp = function (name, fn) {
4878 var suites = [this.suite].concat(this.parents()).reverse();
4879 this.hooks(name, suites, fn);
4880};
4881
4882/**
4883 * Run hooks from the bottom up.
4884 *
4885 * @param {String} name
4886 * @param {Function} fn
4887 * @api private
4888 */
4889Runner.prototype.hookDown = function (name, fn) {
4890 var suites = [this.suite].concat(this.parents());
4891 this.hooks(name, suites, fn);
4892};
4893
4894/**
4895 * Return an array of parent Suites from
4896 * closest to furthest.
4897 *
4898 * @return {Array}
4899 * @api private
4900 */
4901Runner.prototype.parents = function () {
4902 var suite = this.suite;
4903 var suites = [];
4904 while (suite.parent) {
4905 suite = suite.parent;
4906 suites.push(suite);
4907 }
4908 return suites;
4909};
4910
4911/**
4912 * Run the current test and callback `fn(err)`.
4913 *
4914 * @param {Function} fn
4915 * @api private
4916 */
4917Runner.prototype.runTest = function (fn) {
4918 var self = this;
4919 var test = this.test;
4920
4921 if (!test) {
4922 return;
4923 }
4924 if (this.asyncOnly) {
4925 test.asyncOnly = true;
4926 }
4927
4928 if (this.allowUncaught) {
4929 test.allowUncaught = true;
4930 return test.run(fn);
4931 }
4932 try {
4933 test.on('error', function (err) {
4934 self.fail(test, err);
4935 });
4936 test.run(fn);
4937 } catch (err) {
4938 fn(err);
4939 }
4940};
4941
4942/**
4943 * Run tests in the given `suite` and invoke the callback `fn()` when complete.
4944 *
4945 * @api private
4946 * @param {Suite} suite
4947 * @param {Function} fn
4948 */
4949Runner.prototype.runTests = function (suite, fn) {
4950 var self = this;
4951 var tests = suite.tests.slice();
4952 var test;
4953
4954 function hookErr (_, errSuite, after) {
4955 // before/after Each hook for errSuite failed:
4956 var orig = self.suite;
4957
4958 // for failed 'after each' hook start from errSuite parent,
4959 // otherwise start from errSuite itself
4960 self.suite = after ? errSuite.parent : errSuite;
4961
4962 if (self.suite) {
4963 // call hookUp afterEach
4964 self.hookUp('afterEach', function (err2, errSuite2) {
4965 self.suite = orig;
4966 // some hooks may fail even now
4967 if (err2) {
4968 return hookErr(err2, errSuite2, true);
4969 }
4970 // report error suite
4971 fn(errSuite);
4972 });
4973 } else {
4974 // there is no need calling other 'after each' hooks
4975 self.suite = orig;
4976 fn(errSuite);
4977 }
4978 }
4979
4980 function next (err, errSuite) {
4981 // if we bail after first err
4982 if (self.failures && suite._bail) {
4983 return fn();
4984 }
4985
4986 if (self._abort) {
4987 return fn();
4988 }
4989
4990 if (err) {
4991 return hookErr(err, errSuite, true);
4992 }
4993
4994 // next test
4995 test = tests.shift();
4996
4997 // all done
4998 if (!test) {
4999 return fn();
5000 }
5001
5002 // grep
5003 var match = self._grep.test(test.fullTitle());
5004 if (self._invert) {
5005 match = !match;
5006 }
5007 if (!match) {
5008 // Run immediately only if we have defined a grep. When we
5009 // define a grep — It can cause maximum callstack error if
5010 // the grep is doing a large recursive loop by neglecting
5011 // all tests. The run immediately function also comes with
5012 // a performance cost. So we don't want to run immediately
5013 // if we run the whole test suite, because running the whole
5014 // test suite don't do any immediate recursive loops. Thus,
5015 // allowing a JS runtime to breathe.
5016 if (self._grep !== self._defaultGrep) {
5017 Runner.immediately(next);
5018 } else {
5019 next();
5020 }
5021 return;
5022 }
5023
5024 if (test.isPending()) {
5025 self.emit('pending', test);
5026 self.emit('test end', test);
5027 return next();
5028 }
5029
5030 // execute test and hook(s)
5031 self.emit('test', self.test = test);
5032 self.hookDown('beforeEach', function (err, errSuite) {
5033 if (test.isPending()) {
5034 self.emit('pending', test);
5035 self.emit('test end', test);
5036 return next();
5037 }
5038 if (err) {
5039 return hookErr(err, errSuite, false);
5040 }
5041 self.currentRunnable = self.test;
5042 self.runTest(function (err) {
5043 test = self.test;
5044 if (err) {
5045 var retry = test.currentRetry();
5046 if (err instanceof Pending) {
5047 test.pending = true;
5048 self.emit('pending', test);
5049 } else if (retry < test.retries()) {
5050 var clonedTest = test.clone();
5051 clonedTest.currentRetry(retry + 1);
5052 tests.unshift(clonedTest);
5053
5054 // Early return + hook trigger so that it doesn't
5055 // increment the count wrong
5056 return self.hookUp('afterEach', next);
5057 } else {
5058 self.fail(test, err);
5059 }
5060 self.emit('test end', test);
5061
5062 if (err instanceof Pending) {
5063 return next();
5064 }
5065
5066 return self.hookUp('afterEach', next);
5067 }
5068
5069 test.state = 'passed';
5070 self.emit('pass', test);
5071 self.emit('test end', test);
5072 self.hookUp('afterEach', next);
5073 });
5074 });
5075 }
5076
5077 this.next = next;
5078 this.hookErr = hookErr;
5079 next();
5080};
5081
5082/**
5083 * Run the given `suite` and invoke the callback `fn()` when complete.
5084 *
5085 * @api private
5086 * @param {Suite} suite
5087 * @param {Function} fn
5088 */
5089Runner.prototype.runSuite = function (suite, fn) {
5090 var i = 0;
5091 var self = this;
5092 var total = this.grepTotal(suite);
5093 var afterAllHookCalled = false;
5094
5095 debug('run suite %s', suite.fullTitle());
5096
5097 if (!total || (self.failures && suite._bail)) {
5098 return fn();
5099 }
5100
5101 this.emit('suite', this.suite = suite);
5102
5103 function next (errSuite) {
5104 if (errSuite) {
5105 // current suite failed on a hook from errSuite
5106 if (errSuite === suite) {
5107 // if errSuite is current suite
5108 // continue to the next sibling suite
5109 return done();
5110 }
5111 // errSuite is among the parents of current suite
5112 // stop execution of errSuite and all sub-suites
5113 return done(errSuite);
5114 }
5115
5116 if (self._abort) {
5117 return done();
5118 }
5119
5120 var curr = suite.suites[i++];
5121 if (!curr) {
5122 return done();
5123 }
5124
5125 // Avoid grep neglecting large number of tests causing a
5126 // huge recursive loop and thus a maximum call stack error.
5127 // See comment in `this.runTests()` for more information.
5128 if (self._grep !== self._defaultGrep) {
5129 Runner.immediately(function () {
5130 self.runSuite(curr, next);
5131 });
5132 } else {
5133 self.runSuite(curr, next);
5134 }
5135 }
5136
5137 function done (errSuite) {
5138 self.suite = suite;
5139 self.nextSuite = next;
5140
5141 if (afterAllHookCalled) {
5142 fn(errSuite);
5143 } else {
5144 // mark that the afterAll block has been called once
5145 // and so can be skipped if there is an error in it.
5146 afterAllHookCalled = true;
5147
5148 // remove reference to test
5149 delete self.test;
5150
5151 self.hook('afterAll', function () {
5152 self.emit('suite end', suite);
5153 fn(errSuite);
5154 });
5155 }
5156 }
5157
5158 this.nextSuite = next;
5159
5160 this.hook('beforeAll', function (err) {
5161 if (err) {
5162 return done();
5163 }
5164 self.runTests(suite, next);
5165 });
5166};
5167
5168/**
5169 * Handle uncaught exceptions.
5170 *
5171 * @param {Error} err
5172 * @api private
5173 */
5174Runner.prototype.uncaught = function (err) {
5175 if (err) {
5176 debug('uncaught exception %s', err !== function () {
5177 return this;
5178 }.call(err) ? err : (err.message || err));
5179 } else {
5180 debug('uncaught undefined exception');
5181 err = undefinedError();
5182 }
5183 err.uncaught = true;
5184
5185 var runnable = this.currentRunnable;
5186
5187 if (!runnable) {
5188 runnable = new Runnable('Uncaught error outside test suite');
5189 runnable.parent = this.suite;
5190
5191 if (this.started) {
5192 this.fail(runnable, err);
5193 } else {
5194 // Can't recover from this failure
5195 this.emit('start');
5196 this.fail(runnable, err);
5197 this.emit('end');
5198 }
5199
5200 return;
5201 }
5202
5203 runnable.clearTimeout();
5204
5205 // Ignore errors if complete or pending
5206 if (runnable.state || runnable.isPending()) {
5207 return;
5208 }
5209 this.fail(runnable, err);
5210
5211 // recover from test
5212 if (runnable.type === 'test') {
5213 this.emit('test end', runnable);
5214 this.hookUp('afterEach', this.next);
5215 return;
5216 }
5217
5218 // recover from hooks
5219 if (runnable.type === 'hook') {
5220 var errSuite = this.suite;
5221 // if hook failure is in afterEach block
5222 if (runnable.fullTitle().indexOf('after each') > -1) {
5223 return this.hookErr(err, errSuite, true);
5224 }
5225 // if hook failure is in beforeEach block
5226 if (runnable.fullTitle().indexOf('before each') > -1) {
5227 return this.hookErr(err, errSuite, false);
5228 }
5229 // if hook failure is in after or before blocks
5230 return this.nextSuite(errSuite);
5231 }
5232
5233 // bail
5234 this.emit('end');
5235};
5236
5237/**
5238 * Cleans up the references to all the deferred functions
5239 * (before/after/beforeEach/afterEach) and tests of a Suite.
5240 * These must be deleted otherwise a memory leak can happen,
5241 * as those functions may reference variables from closures,
5242 * thus those variables can never be garbage collected as long
5243 * as the deferred functions exist.
5244 *
5245 * @param {Suite} suite
5246 */
5247function cleanSuiteReferences (suite) {
5248 function cleanArrReferences (arr) {
5249 for (var i = 0; i < arr.length; i++) {
5250 delete arr[i].fn;
5251 }
5252 }
5253
5254 if (isArray(suite._beforeAll)) {
5255 cleanArrReferences(suite._beforeAll);
5256 }
5257
5258 if (isArray(suite._beforeEach)) {
5259 cleanArrReferences(suite._beforeEach);
5260 }
5261
5262 if (isArray(suite._afterAll)) {
5263 cleanArrReferences(suite._afterAll);
5264 }
5265
5266 if (isArray(suite._afterEach)) {
5267 cleanArrReferences(suite._afterEach);
5268 }
5269
5270 for (var i = 0; i < suite.tests.length; i++) {
5271 delete suite.tests[i].fn;
5272 }
5273}
5274
5275/**
5276 * Run the root suite and invoke `fn(failures)`
5277 * on completion.
5278 *
5279 * @param {Function} fn
5280 * @return {Runner} for chaining
5281 * @api public
5282 * @param {Function} fn
5283 * @return {Runner} Runner instance.
5284 */
5285Runner.prototype.run = function (fn) {
5286 var self = this;
5287 var rootSuite = this.suite;
5288
5289 // If there is an `only` filter
5290 if (this.hasOnly) {
5291 filterOnly(rootSuite);
5292 }
5293
5294 fn = fn || function () {};
5295
5296 function uncaught (err) {
5297 self.uncaught(err);
5298 }
5299
5300 function start () {
5301 self.started = true;
5302 self.emit('start');
5303 self.runSuite(rootSuite, function () {
5304 debug('finished running');
5305 self.emit('end');
5306 });
5307 }
5308
5309 debug('start');
5310
5311 // references cleanup to avoid memory leaks
5312 this.on('suite end', cleanSuiteReferences);
5313
5314 // callback
5315 this.on('end', function () {
5316 debug('end');
5317 process.removeListener('uncaughtException', uncaught);
5318 fn(self.failures);
5319 });
5320
5321 // uncaught exception
5322 process.on('uncaughtException', uncaught);
5323
5324 if (this._delay) {
5325 // for reporters, I guess.
5326 // might be nice to debounce some dots while we wait.
5327 this.emit('waiting', rootSuite);
5328 rootSuite.once('run', start);
5329 } else {
5330 start();
5331 }
5332
5333 return this;
5334};
5335
5336/**
5337 * Cleanly abort execution.
5338 *
5339 * @api public
5340 * @return {Runner} Runner instance.
5341 */
5342Runner.prototype.abort = function () {
5343 debug('aborting');
5344 this._abort = true;
5345
5346 return this;
5347};
5348
5349/**
5350 * Filter suites based on `isOnly` logic.
5351 *
5352 * @param {Array} suite
5353 * @returns {Boolean}
5354 * @api private
5355 */
5356function filterOnly (suite) {
5357 if (suite._onlyTests.length) {
5358 // If the suite contains `only` tests, run those and ignore any nested suites.
5359 suite.tests = suite._onlyTests;
5360 suite.suites = [];
5361 } else {
5362 // Otherwise, do not run any of the tests in this suite.
5363 suite.tests = [];
5364 utils.forEach(suite._onlySuites, function (onlySuite) {
5365 // If there are other `only` tests/suites nested in the current `only` suite, then filter that `only` suite.
5366 // Otherwise, all of the tests on this `only` suite should be run, so don't filter it.
5367 if (hasOnly(onlySuite)) {
5368 filterOnly(onlySuite);
5369 }
5370 });
5371 // Run the `only` suites, as well as any other suites that have `only` tests/suites as descendants.
5372 suite.suites = filter(suite.suites, function (childSuite) {
5373 return indexOf(suite._onlySuites, childSuite) !== -1 || filterOnly(childSuite);
5374 });
5375 }
5376 // Keep the suite only if there is something to run
5377 return suite.tests.length || suite.suites.length;
5378}
5379
5380/**
5381 * Determines whether a suite has an `only` test or suite as a descendant.
5382 *
5383 * @param {Array} suite
5384 * @returns {Boolean}
5385 * @api private
5386 */
5387function hasOnly (suite) {
5388 return suite._onlyTests.length || suite._onlySuites.length || some(suite.suites, hasOnly);
5389}
5390
5391/**
5392 * Filter leaks with the given globals flagged as `ok`.
5393 *
5394 * @api private
5395 * @param {Array} ok
5396 * @param {Array} globals
5397 * @return {Array}
5398 */
5399function filterLeaks (ok, globals) {
5400 return filter(globals, function (key) {
5401 // Firefox and Chrome exposes iframes as index inside the window object
5402 if (/^\d+/.test(key)) {
5403 return false;
5404 }
5405
5406 // in firefox
5407 // if runner runs in an iframe, this iframe's window.getInterface method
5408 // not init at first it is assigned in some seconds
5409 if (global.navigator && (/^getInterface/).test(key)) {
5410 return false;
5411 }
5412
5413 // an iframe could be approached by window[iframeIndex]
5414 // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak
5415 if (global.navigator && (/^\d+/).test(key)) {
5416 return false;
5417 }
5418
5419 // Opera and IE expose global variables for HTML element IDs (issue #243)
5420 if (/^mocha-/.test(key)) {
5421 return false;
5422 }
5423
5424 var matched = filter(ok, function (ok) {
5425 if (~ok.indexOf('*')) {
5426 return key.indexOf(ok.split('*')[0]) === 0;
5427 }
5428 return key === ok;
5429 });
5430 return !matched.length && (!global.navigator || key !== 'onerror');
5431 });
5432}
5433
5434/**
5435 * Array of globals dependent on the environment.
5436 *
5437 * @return {Array}
5438 * @api private
5439 */
5440function extraGlobals () {
5441 if (typeof process === 'object' && typeof process.version === 'string') {
5442 var parts = process.version.split('.');
5443 var nodeVersion = utils.reduce(parts, function (a, v) {
5444 return a << 8 | v;
5445 });
5446
5447 // 'errno' was renamed to process._errno in v0.9.11.
5448
5449 if (nodeVersion < 0x00090B) {
5450 return ['errno'];
5451 }
5452 }
5453
5454 return [];
5455}
5456
5457}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5458},{"./pending":16,"./runnable":33,"./utils":38,"_process":67,"debug":2,"events":3}],35:[function(require,module,exports){
5459'use strict';
5460
5461/**
5462 * Module dependencies.
5463 */
5464
5465var EventEmitter = require('events').EventEmitter;
5466var Hook = require('./hook');
5467var utils = require('./utils');
5468var inherits = utils.inherits;
5469var debug = require('debug')('mocha:suite');
5470var milliseconds = require('./ms');
5471
5472/**
5473 * Expose `Suite`.
5474 */
5475
5476exports = module.exports = Suite;
5477
5478/**
5479 * Create a new `Suite` with the given `title` and parent `Suite`. When a suite
5480 * with the same title is already present, that suite is returned to provide
5481 * nicer reporter and more flexible meta-testing.
5482 *
5483 * @api public
5484 * @param {Suite} parent
5485 * @param {string} title
5486 * @return {Suite}
5487 */
5488exports.create = function (parent, title) {
5489 var suite = new Suite(title, parent.ctx);
5490 suite.parent = parent;
5491 title = suite.fullTitle();
5492 parent.addSuite(suite);
5493 return suite;
5494};
5495
5496/**
5497 * Initialize a new `Suite` with the given `title` and `ctx`.
5498 *
5499 * @api private
5500 * @param {string} title
5501 * @param {Context} parentContext
5502 */
5503function Suite (title, parentContext) {
5504 if (!utils.isString(title)) {
5505 throw new Error('Suite `title` should be a "string" but "' + typeof title + '" was given instead.');
5506 }
5507 this.title = title;
5508 function Context () {}
5509 Context.prototype = parentContext;
5510 this.ctx = new Context();
5511 this.suites = [];
5512 this.tests = [];
5513 this.pending = false;
5514 this._beforeEach = [];
5515 this._beforeAll = [];
5516 this._afterEach = [];
5517 this._afterAll = [];
5518 this.root = !title;
5519 this._timeout = 2000;
5520 this._enableTimeouts = true;
5521 this._slow = 75;
5522 this._bail = false;
5523 this._retries = -1;
5524 this._onlyTests = [];
5525 this._onlySuites = [];
5526 this.delayed = false;
5527}
5528
5529/**
5530 * Inherit from `EventEmitter.prototype`.
5531 */
5532inherits(Suite, EventEmitter);
5533
5534/**
5535 * Return a clone of this `Suite`.
5536 *
5537 * @api private
5538 * @return {Suite}
5539 */
5540Suite.prototype.clone = function () {
5541 var suite = new Suite(this.title);
5542 debug('clone');
5543 suite.ctx = this.ctx;
5544 suite.timeout(this.timeout());
5545 suite.retries(this.retries());
5546 suite.enableTimeouts(this.enableTimeouts());
5547 suite.slow(this.slow());
5548 suite.bail(this.bail());
5549 return suite;
5550};
5551
5552/**
5553 * Set timeout `ms` or short-hand such as "2s".
5554 *
5555 * @api private
5556 * @param {number|string} ms
5557 * @return {Suite|number} for chaining
5558 */
5559Suite.prototype.timeout = function (ms) {
5560 if (!arguments.length) {
5561 return this._timeout;
5562 }
5563 if (ms.toString() === '0') {
5564 this._enableTimeouts = false;
5565 }
5566 if (typeof ms === 'string') {
5567 ms = milliseconds(ms);
5568 }
5569 debug('timeout %d', ms);
5570 this._timeout = parseInt(ms, 10);
5571 return this;
5572};
5573
5574/**
5575 * Set number of times to retry a failed test.
5576 *
5577 * @api private
5578 * @param {number|string} n
5579 * @return {Suite|number} for chaining
5580 */
5581Suite.prototype.retries = function (n) {
5582 if (!arguments.length) {
5583 return this._retries;
5584 }
5585 debug('retries %d', n);
5586 this._retries = parseInt(n, 10) || 0;
5587 return this;
5588};
5589
5590/**
5591 * Set timeout to `enabled`.
5592 *
5593 * @api private
5594 * @param {boolean} enabled
5595 * @return {Suite|boolean} self or enabled
5596 */
5597Suite.prototype.enableTimeouts = function (enabled) {
5598 if (!arguments.length) {
5599 return this._enableTimeouts;
5600 }
5601 debug('enableTimeouts %s', enabled);
5602 this._enableTimeouts = enabled;
5603 return this;
5604};
5605
5606/**
5607 * Set slow `ms` or short-hand such as "2s".
5608 *
5609 * @api private
5610 * @param {number|string} ms
5611 * @return {Suite|number} for chaining
5612 */
5613Suite.prototype.slow = function (ms) {
5614 if (!arguments.length) {
5615 return this._slow;
5616 }
5617 if (typeof ms === 'string') {
5618 ms = milliseconds(ms);
5619 }
5620 debug('slow %d', ms);
5621 this._slow = ms;
5622 return this;
5623};
5624
5625/**
5626 * Sets whether to bail after first error.
5627 *
5628 * @api private
5629 * @param {boolean} bail
5630 * @return {Suite|number} for chaining
5631 */
5632Suite.prototype.bail = function (bail) {
5633 if (!arguments.length) {
5634 return this._bail;
5635 }
5636 debug('bail %s', bail);
5637 this._bail = bail;
5638 return this;
5639};
5640
5641/**
5642 * Check if this suite or its parent suite is marked as pending.
5643 *
5644 * @api private
5645 */
5646Suite.prototype.isPending = function () {
5647 return this.pending || (this.parent && this.parent.isPending());
5648};
5649
5650/**
5651 * Run `fn(test[, done])` before running tests.
5652 *
5653 * @api private
5654 * @param {string} title
5655 * @param {Function} fn
5656 * @return {Suite} for chaining
5657 */
5658Suite.prototype.beforeAll = function (title, fn) {
5659 if (this.isPending()) {
5660 return this;
5661 }
5662 if (typeof title === 'function') {
5663 fn = title;
5664 title = fn.name;
5665 }
5666 title = '"before all" hook' + (title ? ': ' + title : '');
5667
5668 var hook = new Hook(title, fn);
5669 hook.parent = this;
5670 hook.timeout(this.timeout());
5671 hook.retries(this.retries());
5672 hook.enableTimeouts(this.enableTimeouts());
5673 hook.slow(this.slow());
5674 hook.ctx = this.ctx;
5675 this._beforeAll.push(hook);
5676 this.emit('beforeAll', hook);
5677 return this;
5678};
5679
5680/**
5681 * Run `fn(test[, done])` after running tests.
5682 *
5683 * @api private
5684 * @param {string} title
5685 * @param {Function} fn
5686 * @return {Suite} for chaining
5687 */
5688Suite.prototype.afterAll = function (title, fn) {
5689 if (this.isPending()) {
5690 return this;
5691 }
5692 if (typeof title === 'function') {
5693 fn = title;
5694 title = fn.name;
5695 }
5696 title = '"after all" hook' + (title ? ': ' + title : '');
5697
5698 var hook = new Hook(title, fn);
5699 hook.parent = this;
5700 hook.timeout(this.timeout());
5701 hook.retries(this.retries());
5702 hook.enableTimeouts(this.enableTimeouts());
5703 hook.slow(this.slow());
5704 hook.ctx = this.ctx;
5705 this._afterAll.push(hook);
5706 this.emit('afterAll', hook);
5707 return this;
5708};
5709
5710/**
5711 * Run `fn(test[, done])` before each test case.
5712 *
5713 * @api private
5714 * @param {string} title
5715 * @param {Function} fn
5716 * @return {Suite} for chaining
5717 */
5718Suite.prototype.beforeEach = function (title, fn) {
5719 if (this.isPending()) {
5720 return this;
5721 }
5722 if (typeof title === 'function') {
5723 fn = title;
5724 title = fn.name;
5725 }
5726 title = '"before each" hook' + (title ? ': ' + title : '');
5727
5728 var hook = new Hook(title, fn);
5729 hook.parent = this;
5730 hook.timeout(this.timeout());
5731 hook.retries(this.retries());
5732 hook.enableTimeouts(this.enableTimeouts());
5733 hook.slow(this.slow());
5734 hook.ctx = this.ctx;
5735 this._beforeEach.push(hook);
5736 this.emit('beforeEach', hook);
5737 return this;
5738};
5739
5740/**
5741 * Run `fn(test[, done])` after each test case.
5742 *
5743 * @api private
5744 * @param {string} title
5745 * @param {Function} fn
5746 * @return {Suite} for chaining
5747 */
5748Suite.prototype.afterEach = function (title, fn) {
5749 if (this.isPending()) {
5750 return this;
5751 }
5752 if (typeof title === 'function') {
5753 fn = title;
5754 title = fn.name;
5755 }
5756 title = '"after each" hook' + (title ? ': ' + title : '');
5757
5758 var hook = new Hook(title, fn);
5759 hook.parent = this;
5760 hook.timeout(this.timeout());
5761 hook.retries(this.retries());
5762 hook.enableTimeouts(this.enableTimeouts());
5763 hook.slow(this.slow());
5764 hook.ctx = this.ctx;
5765 this._afterEach.push(hook);
5766 this.emit('afterEach', hook);
5767 return this;
5768};
5769
5770/**
5771 * Add a test `suite`.
5772 *
5773 * @api private
5774 * @param {Suite} suite
5775 * @return {Suite} for chaining
5776 */
5777Suite.prototype.addSuite = function (suite) {
5778 suite.parent = this;
5779 suite.timeout(this.timeout());
5780 suite.retries(this.retries());
5781 suite.enableTimeouts(this.enableTimeouts());
5782 suite.slow(this.slow());
5783 suite.bail(this.bail());
5784 this.suites.push(suite);
5785 this.emit('suite', suite);
5786 return this;
5787};
5788
5789/**
5790 * Add a `test` to this suite.
5791 *
5792 * @api private
5793 * @param {Test} test
5794 * @return {Suite} for chaining
5795 */
5796Suite.prototype.addTest = function (test) {
5797 test.parent = this;
5798 test.timeout(this.timeout());
5799 test.retries(this.retries());
5800 test.enableTimeouts(this.enableTimeouts());
5801 test.slow(this.slow());
5802 test.ctx = this.ctx;
5803 this.tests.push(test);
5804 this.emit('test', test);
5805 return this;
5806};
5807
5808/**
5809 * Return the full title generated by recursively concatenating the parent's
5810 * full title.
5811 *
5812 * @api public
5813 * @return {string}
5814 */
5815Suite.prototype.fullTitle = function () {
5816 if (this.parent) {
5817 var full = this.parent.fullTitle();
5818 if (full) {
5819 return full + ' ' + this.title;
5820 }
5821 }
5822 return this.title;
5823};
5824
5825/**
5826 * Return the total number of tests.
5827 *
5828 * @api public
5829 * @return {number}
5830 */
5831Suite.prototype.total = function () {
5832 return utils.reduce(this.suites, function (sum, suite) {
5833 return sum + suite.total();
5834 }, 0) + this.tests.length;
5835};
5836
5837/**
5838 * Iterates through each suite recursively to find all tests. Applies a
5839 * function in the format `fn(test)`.
5840 *
5841 * @api private
5842 * @param {Function} fn
5843 * @return {Suite}
5844 */
5845Suite.prototype.eachTest = function (fn) {
5846 utils.forEach(this.tests, fn);
5847 utils.forEach(this.suites, function (suite) {
5848 suite.eachTest(fn);
5849 });
5850 return this;
5851};
5852
5853/**
5854 * This will run the root suite if we happen to be running in delayed mode.
5855 */
5856Suite.prototype.run = function run () {
5857 if (this.root) {
5858 this.emit('run');
5859 }
5860};
5861
5862},{"./hook":7,"./ms":15,"./utils":38,"debug":2,"events":3}],36:[function(require,module,exports){
5863'use strict';
5864
5865/**
5866 * Module dependencies.
5867 */
5868
5869var Runnable = require('./runnable');
5870var create = require('lodash.create');
5871var isString = require('./utils').isString;
5872
5873/**
5874 * Expose `Test`.
5875 */
5876
5877module.exports = Test;
5878
5879/**
5880 * Initialize a new `Test` with the given `title` and callback `fn`.
5881 *
5882 * @api private
5883 * @param {String} title
5884 * @param {Function} fn
5885 */
5886function Test (title, fn) {
5887 if (!isString(title)) {
5888 throw new Error('Test `title` should be a "string" but "' + typeof title + '" was given instead.');
5889 }
5890 Runnable.call(this, title, fn);
5891 this.pending = !fn;
5892 this.type = 'test';
5893}
5894
5895/**
5896 * Inherit from `Runnable.prototype`.
5897 */
5898Test.prototype = create(Runnable.prototype, {
5899 constructor: Test
5900});
5901
5902Test.prototype.clone = function () {
5903 var test = new Test(this.title, this.fn);
5904 test.timeout(this.timeout());
5905 test.slow(this.slow());
5906 test.enableTimeouts(this.enableTimeouts());
5907 test.retries(this.retries());
5908 test.currentRetry(this.currentRetry());
5909 test.globals(this.globals());
5910 test.parent = this.parent;
5911 test.file = this.file;
5912 test.ctx = this.ctx;
5913 return test;
5914};
5915
5916},{"./runnable":33,"./utils":38,"lodash.create":60}],37:[function(require,module,exports){
5917'use strict';
5918
5919/**
5920 * Pad a `number` with a ten's place zero.
5921 *
5922 * @param {number} number
5923 * @return {string}
5924 */
5925function pad(number) {
5926 var n = number.toString();
5927 return n.length === 1 ? '0' + n : n;
5928}
5929
5930/**
5931 * Turn a `date` into an ISO string.
5932 *
5933 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
5934 *
5935 * @param {Date} date
5936 * @return {string}
5937 */
5938function toISOString(date) {
5939 return date.getUTCFullYear()
5940 + '-' + pad(date.getUTCMonth() + 1)
5941 + '-' + pad(date.getUTCDate())
5942 + 'T' + pad(date.getUTCHours())
5943 + ':' + pad(date.getUTCMinutes())
5944 + ':' + pad(date.getUTCSeconds())
5945 + '.' + String((date.getUTCMilliseconds()/1000).toFixed(3)).slice(2, 5)
5946 + 'Z';
5947}
5948
5949/*
5950 * Exports.
5951 */
5952
5953module.exports = toISOString;
5954
5955},{}],38:[function(require,module,exports){
5956(function (process,Buffer){
5957'use strict';
5958
5959/* eslint-env browser */
5960
5961/**
5962 * Module dependencies.
5963 */
5964
5965var JSON = require('json3');
5966var basename = require('path').basename;
5967var debug = require('debug')('mocha:watch');
5968var exists = require('fs').existsSync || require('path').existsSync;
5969var glob = require('glob');
5970var path = require('path');
5971var join = path.join;
5972var readdirSync = require('fs').readdirSync;
5973var statSync = require('fs').statSync;
5974var watchFile = require('fs').watchFile;
5975var lstatSync = require('fs').lstatSync;
5976var toISOString = require('./to-iso-string');
5977
5978/**
5979 * Ignored directories.
5980 */
5981
5982var ignore = ['node_modules', '.git'];
5983
5984exports.inherits = require('util').inherits;
5985
5986/**
5987 * Escape special characters in the given string of html.
5988 *
5989 * @api private
5990 * @param {string} html
5991 * @return {string}
5992 */
5993exports.escape = function (html) {
5994 return String(html)
5995 .replace(/&/g, '&amp;')
5996 .replace(/"/g, '&quot;')
5997 .replace(/</g, '&lt;')
5998 .replace(/>/g, '&gt;');
5999};
6000
6001/**
6002 * Array#forEach (<=IE8)
6003 *
6004 * @api private
6005 * @param {Array} arr
6006 * @param {Function} fn
6007 * @param {Object} scope
6008 */
6009exports.forEach = function (arr, fn, scope) {
6010 for (var i = 0, l = arr.length; i < l; i++) {
6011 fn.call(scope, arr[i], i);
6012 }
6013};
6014
6015/**
6016 * Test if the given obj is type of string.
6017 *
6018 * @api private
6019 * @param {Object} obj
6020 * @return {boolean}
6021 */
6022exports.isString = function (obj) {
6023 return typeof obj === 'string';
6024};
6025
6026/**
6027 * Array#map (<=IE8)
6028 *
6029 * @api private
6030 * @param {Array} arr
6031 * @param {Function} fn
6032 * @param {Object} scope
6033 * @return {Array}
6034 */
6035exports.map = function (arr, fn, scope) {
6036 var result = [];
6037 for (var i = 0, l = arr.length; i < l; i++) {
6038 result.push(fn.call(scope, arr[i], i, arr));
6039 }
6040 return result;
6041};
6042
6043/**
6044 * Array#indexOf (<=IE8)
6045 *
6046 * @api private
6047 * @param {Array} arr
6048 * @param {Object} obj to find index of
6049 * @param {number} start
6050 * @return {number}
6051 */
6052var indexOf = exports.indexOf = function (arr, obj, start) {
6053 for (var i = start || 0, l = arr.length; i < l; i++) {
6054 if (arr[i] === obj) {
6055 return i;
6056 }
6057 }
6058 return -1;
6059};
6060
6061/**
6062 * Array#reduce (<=IE8)
6063 *
6064 * @api private
6065 * @param {Array} arr
6066 * @param {Function} fn
6067 * @param {Object} val Initial value.
6068 * @return {*}
6069 */
6070var reduce = exports.reduce = function (arr, fn, val) {
6071 var rval = val;
6072
6073 for (var i = 0, l = arr.length; i < l; i++) {
6074 rval = fn(rval, arr[i], i, arr);
6075 }
6076
6077 return rval;
6078};
6079
6080/**
6081 * Array#filter (<=IE8)
6082 *
6083 * @api private
6084 * @param {Array} arr
6085 * @param {Function} fn
6086 * @return {Array}
6087 */
6088exports.filter = function (arr, fn) {
6089 var ret = [];
6090
6091 for (var i = 0, l = arr.length; i < l; i++) {
6092 var val = arr[i];
6093 if (fn(val, i, arr)) {
6094 ret.push(val);
6095 }
6096 }
6097
6098 return ret;
6099};
6100
6101/**
6102 * Array#some (<=IE8)
6103 *
6104 * @api private
6105 * @param {Array} arr
6106 * @param {Function} fn
6107 * @return {Array}
6108 */
6109exports.some = function (arr, fn) {
6110 for (var i = 0, l = arr.length; i < l; i++) {
6111 if (fn(arr[i])) {
6112 return true;
6113 }
6114 }
6115 return false;
6116};
6117
6118/**
6119 * Object.keys (<=IE8)
6120 *
6121 * @api private
6122 * @param {Object} obj
6123 * @return {Array} keys
6124 */
6125exports.keys = typeof Object.keys === 'function' ? Object.keys : function (obj) {
6126 var keys = [];
6127 var has = Object.prototype.hasOwnProperty; // for `window` on <=IE8
6128
6129 for (var key in obj) {
6130 if (has.call(obj, key)) {
6131 keys.push(key);
6132 }
6133 }
6134
6135 return keys;
6136};
6137
6138/**
6139 * Watch the given `files` for changes
6140 * and invoke `fn(file)` on modification.
6141 *
6142 * @api private
6143 * @param {Array} files
6144 * @param {Function} fn
6145 */
6146exports.watch = function (files, fn) {
6147 var options = { interval: 100 };
6148 files.forEach(function (file) {
6149 debug('file %s', file);
6150 watchFile(file, options, function (curr, prev) {
6151 if (prev.mtime < curr.mtime) {
6152 fn(file);
6153 }
6154 });
6155 });
6156};
6157
6158/**
6159 * Array.isArray (<=IE8)
6160 *
6161 * @api private
6162 * @param {Object} obj
6163 * @return {Boolean}
6164 */
6165var isArray = typeof Array.isArray === 'function' ? Array.isArray : function (obj) {
6166 return Object.prototype.toString.call(obj) === '[object Array]';
6167};
6168
6169exports.isArray = isArray;
6170
6171/**
6172 * Buffer.prototype.toJSON polyfill.
6173 *
6174 * @type {Function}
6175 */
6176if (typeof Buffer !== 'undefined' && Buffer.prototype) {
6177 Buffer.prototype.toJSON = Buffer.prototype.toJSON || function () {
6178 return Array.prototype.slice.call(this, 0);
6179 };
6180}
6181
6182/**
6183 * Ignored files.
6184 *
6185 * @api private
6186 * @param {string} path
6187 * @return {boolean}
6188 */
6189function ignored (path) {
6190 return !~ignore.indexOf(path);
6191}
6192
6193/**
6194 * Lookup files in the given `dir`.
6195 *
6196 * @api private
6197 * @param {string} dir
6198 * @param {string[]} [ext=['.js']]
6199 * @param {Array} [ret=[]]
6200 * @return {Array}
6201 */
6202exports.files = function (dir, ext, ret) {
6203 ret = ret || [];
6204 ext = ext || ['js'];
6205
6206 var re = new RegExp('\\.(' + ext.join('|') + ')$');
6207
6208 readdirSync(dir)
6209 .filter(ignored)
6210 .forEach(function (path) {
6211 path = join(dir, path);
6212 if (lstatSync(path).isDirectory()) {
6213 exports.files(path, ext, ret);
6214 } else if (path.match(re)) {
6215 ret.push(path);
6216 }
6217 });
6218
6219 return ret;
6220};
6221
6222/**
6223 * Compute a slug from the given `str`.
6224 *
6225 * @api private
6226 * @param {string} str
6227 * @return {string}
6228 */
6229exports.slug = function (str) {
6230 return str
6231 .toLowerCase()
6232 .replace(/ +/g, '-')
6233 .replace(/[^-\w]/g, '');
6234};
6235
6236/**
6237 * Strip the function definition from `str`, and re-indent for pre whitespace.
6238 *
6239 * @param {string} str
6240 * @return {string}
6241 */
6242exports.clean = function (str) {
6243 str = str
6244 .replace(/\r\n?|[\n\u2028\u2029]/g, '\n').replace(/^\uFEFF/, '')
6245 // (traditional)-> space/name parameters body (lambda)-> parameters body multi-statement/single keep body content
6246 .replace(/^function(?:\s*|\s+[^(]*)\([^)]*\)\s*\{((?:.|\n)*?)\s*\}$|^\([^)]*\)\s*=>\s*(?:\{((?:.|\n)*?)\s*\}|((?:.|\n)*))$/, '$1$2$3');
6247
6248 var spaces = str.match(/^\n?( *)/)[1].length;
6249 var tabs = str.match(/^\n?(\t*)/)[1].length;
6250 var re = new RegExp('^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs || spaces) + '}', 'gm');
6251
6252 str = str.replace(re, '');
6253
6254 return exports.trim(str);
6255};
6256
6257/**
6258 * Trim the given `str`.
6259 *
6260 * @api private
6261 * @param {string} str
6262 * @return {string}
6263 */
6264exports.trim = function (str) {
6265 return str.replace(/^\s+|\s+$/g, '');
6266};
6267
6268/**
6269 * Parse the given `qs`.
6270 *
6271 * @api private
6272 * @param {string} qs
6273 * @return {Object}
6274 */
6275exports.parseQuery = function (qs) {
6276 return reduce(qs.replace('?', '').split('&'), function (obj, pair) {
6277 var i = pair.indexOf('=');
6278 var key = pair.slice(0, i);
6279 var val = pair.slice(++i);
6280
6281 obj[key] = decodeURIComponent(val);
6282 return obj;
6283 }, {});
6284};
6285
6286/**
6287 * Highlight the given string of `js`.
6288 *
6289 * @api private
6290 * @param {string} js
6291 * @return {string}
6292 */
6293function highlight (js) {
6294 return js
6295 .replace(/</g, '&lt;')
6296 .replace(/>/g, '&gt;')
6297 .replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>')
6298 .replace(/('.*?')/gm, '<span class="string">$1</span>')
6299 .replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>')
6300 .replace(/(\d+)/gm, '<span class="number">$1</span>')
6301 .replace(/\bnew[ \t]+(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>')
6302 .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>');
6303}
6304
6305/**
6306 * Highlight the contents of tag `name`.
6307 *
6308 * @api private
6309 * @param {string} name
6310 */
6311exports.highlightTags = function (name) {
6312 var code = document.getElementById('mocha').getElementsByTagName(name);
6313 for (var i = 0, len = code.length; i < len; ++i) {
6314 code[i].innerHTML = highlight(code[i].innerHTML);
6315 }
6316};
6317
6318/**
6319 * If a value could have properties, and has none, this function is called,
6320 * which returns a string representation of the empty value.
6321 *
6322 * Functions w/ no properties return `'[Function]'`
6323 * Arrays w/ length === 0 return `'[]'`
6324 * Objects w/ no properties return `'{}'`
6325 * All else: return result of `value.toString()`
6326 *
6327 * @api private
6328 * @param {*} value The value to inspect.
6329 * @param {string} typeHint The type of the value
6330 * @returns {string}
6331 */
6332function emptyRepresentation (value, typeHint) {
6333 switch (typeHint) {
6334 case 'function':
6335 return '[Function]';
6336 case 'object':
6337 return '{}';
6338 case 'array':
6339 return '[]';
6340 default:
6341 return value.toString();
6342 }
6343}
6344
6345/**
6346 * Takes some variable and asks `Object.prototype.toString()` what it thinks it
6347 * is.
6348 *
6349 * @api private
6350 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
6351 * @param {*} value The value to test.
6352 * @returns {string} Computed type
6353 * @example
6354 * type({}) // 'object'
6355 * type([]) // 'array'
6356 * type(1) // 'number'
6357 * type(false) // 'boolean'
6358 * type(Infinity) // 'number'
6359 * type(null) // 'null'
6360 * type(new Date()) // 'date'
6361 * type(/foo/) // 'regexp'
6362 * type('type') // 'string'
6363 * type(global) // 'global'
6364 * type(new String('foo') // 'object'
6365 */
6366var type = exports.type = function type (value) {
6367 if (value === undefined) {
6368 return 'undefined';
6369 } else if (value === null) {
6370 return 'null';
6371 } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {
6372 return 'buffer';
6373 }
6374 return Object.prototype.toString.call(value)
6375 .replace(/^\[.+\s(.+?)\]$/, '$1')
6376 .toLowerCase();
6377};
6378
6379/**
6380 * Stringify `value`. Different behavior depending on type of value:
6381 *
6382 * - If `value` is undefined or null, return `'[undefined]'` or `'[null]'`, respectively.
6383 * - If `value` is not an object, function or array, return result of `value.toString()` wrapped in double-quotes.
6384 * - If `value` is an *empty* object, function, or array, return result of function
6385 * {@link emptyRepresentation}.
6386 * - If `value` has properties, call {@link exports.canonicalize} on it, then return result of
6387 * JSON.stringify().
6388 *
6389 * @api private
6390 * @see exports.type
6391 * @param {*} value
6392 * @return {string}
6393 */
6394exports.stringify = function (value) {
6395 var typeHint = type(value);
6396
6397 if (!~indexOf(['object', 'array', 'function'], typeHint)) {
6398 if (typeHint === 'buffer') {
6399 var json = value.toJSON();
6400 // Based on the toJSON result
6401 return jsonStringify(json.data && json.type ? json.data : json, 2)
6402 .replace(/,(\n|$)/g, '$1');
6403 }
6404
6405 // IE7/IE8 has a bizarre String constructor; needs to be coerced
6406 // into an array and back to obj.
6407 if (typeHint === 'string' && typeof value === 'object') {
6408 value = reduce(value.split(''), function (acc, char, idx) {
6409 acc[idx] = char;
6410 return acc;
6411 }, {});
6412 typeHint = 'object';
6413 } else {
6414 return jsonStringify(value);
6415 }
6416 }
6417
6418 for (var prop in value) {
6419 if (Object.prototype.hasOwnProperty.call(value, prop)) {
6420 return jsonStringify(exports.canonicalize(value, null, typeHint), 2).replace(/,(\n|$)/g, '$1');
6421 }
6422 }
6423
6424 return emptyRepresentation(value, typeHint);
6425};
6426
6427/**
6428 * like JSON.stringify but more sense.
6429 *
6430 * @api private
6431 * @param {Object} object
6432 * @param {number=} spaces
6433 * @param {number=} depth
6434 * @returns {*}
6435 */
6436function jsonStringify (object, spaces, depth) {
6437 if (typeof spaces === 'undefined') {
6438 // primitive types
6439 return _stringify(object);
6440 }
6441
6442 depth = depth || 1;
6443 var space = spaces * depth;
6444 var str = isArray(object) ? '[' : '{';
6445 var end = isArray(object) ? ']' : '}';
6446 var length = typeof object.length === 'number' ? object.length : exports.keys(object).length;
6447 // `.repeat()` polyfill
6448 function repeat (s, n) {
6449 return new Array(n).join(s);
6450 }
6451
6452 function _stringify (val) {
6453 switch (type(val)) {
6454 case 'null':
6455 case 'undefined':
6456 val = '[' + val + ']';
6457 break;
6458 case 'array':
6459 case 'object':
6460 val = jsonStringify(val, spaces, depth + 1);
6461 break;
6462 case 'boolean':
6463 case 'regexp':
6464 case 'symbol':
6465 case 'number':
6466 val = val === 0 && (1 / val) === -Infinity // `-0`
6467 ? '-0'
6468 : val.toString();
6469 break;
6470 case 'date':
6471 var sDate;
6472 if (isNaN(val.getTime())) { // Invalid date
6473 sDate = val.toString();
6474 } else {
6475 sDate = val.toISOString ? val.toISOString() : toISOString(val);
6476 }
6477 val = '[Date: ' + sDate + ']';
6478 break;
6479 case 'buffer':
6480 var json = val.toJSON();
6481 // Based on the toJSON result
6482 json = json.data && json.type ? json.data : json;
6483 val = '[Buffer: ' + jsonStringify(json, 2, depth + 1) + ']';
6484 break;
6485 default:
6486 val = (val === '[Function]' || val === '[Circular]')
6487 ? val
6488 : JSON.stringify(val); // string
6489 }
6490 return val;
6491 }
6492
6493 for (var i in object) {
6494 if (!Object.prototype.hasOwnProperty.call(object, i)) {
6495 continue; // not my business
6496 }
6497 --length;
6498 str += '\n ' + repeat(' ', space) +
6499 (isArray(object) ? '' : '"' + i + '": ') + // key
6500 _stringify(object[i]) + // value
6501 (length ? ',' : ''); // comma
6502 }
6503
6504 return str +
6505 // [], {}
6506 (str.length !== 1 ? '\n' + repeat(' ', --space) + end : end);
6507}
6508
6509/**
6510 * Test if a value is a buffer.
6511 *
6512 * @api private
6513 * @param {*} value The value to test.
6514 * @return {boolean} True if `value` is a buffer, otherwise false
6515 */
6516exports.isBuffer = function (value) {
6517 return typeof Buffer !== 'undefined' && Buffer.isBuffer(value);
6518};
6519
6520/**
6521 * Return a new Thing that has the keys in sorted order. Recursive.
6522 *
6523 * If the Thing...
6524 * - has already been seen, return string `'[Circular]'`
6525 * - is `undefined`, return string `'[undefined]'`
6526 * - is `null`, return value `null`
6527 * - is some other primitive, return the value
6528 * - is not a primitive or an `Array`, `Object`, or `Function`, return the value of the Thing's `toString()` method
6529 * - is a non-empty `Array`, `Object`, or `Function`, return the result of calling this function again.
6530 * - is an empty `Array`, `Object`, or `Function`, return the result of calling `emptyRepresentation()`
6531 *
6532 * @api private
6533 * @see {@link exports.stringify}
6534 * @param {*} value Thing to inspect. May or may not have properties.
6535 * @param {Array} [stack=[]] Stack of seen values
6536 * @param {string} [typeHint] Type hint
6537 * @return {(Object|Array|Function|string|undefined)}
6538 */
6539exports.canonicalize = function canonicalize (value, stack, typeHint) {
6540 var canonicalizedObj;
6541 /* eslint-disable no-unused-vars */
6542 var prop;
6543 /* eslint-enable no-unused-vars */
6544 typeHint = typeHint || type(value);
6545 function withStack (value, fn) {
6546 stack.push(value);
6547 fn();
6548 stack.pop();
6549 }
6550
6551 stack = stack || [];
6552
6553 if (indexOf(stack, value) !== -1) {
6554 return '[Circular]';
6555 }
6556
6557 switch (typeHint) {
6558 case 'undefined':
6559 case 'buffer':
6560 case 'null':
6561 canonicalizedObj = value;
6562 break;
6563 case 'array':
6564 withStack(value, function () {
6565 canonicalizedObj = exports.map(value, function (item) {
6566 return exports.canonicalize(item, stack);
6567 });
6568 });
6569 break;
6570 case 'function':
6571 /* eslint-disable guard-for-in */
6572 for (prop in value) {
6573 canonicalizedObj = {};
6574 break;
6575 }
6576 /* eslint-enable guard-for-in */
6577 if (!canonicalizedObj) {
6578 canonicalizedObj = emptyRepresentation(value, typeHint);
6579 break;
6580 }
6581 /* falls through */
6582 case 'object':
6583 canonicalizedObj = canonicalizedObj || {};
6584 withStack(value, function () {
6585 exports.forEach(exports.keys(value).sort(), function (key) {
6586 canonicalizedObj[key] = exports.canonicalize(value[key], stack);
6587 });
6588 });
6589 break;
6590 case 'date':
6591 case 'number':
6592 case 'regexp':
6593 case 'boolean':
6594 case 'symbol':
6595 canonicalizedObj = value;
6596 break;
6597 default:
6598 canonicalizedObj = value + '';
6599 }
6600
6601 return canonicalizedObj;
6602};
6603
6604/**
6605 * Lookup file names at the given `path`.
6606 *
6607 * @api public
6608 * @param {string} path Base path to start searching from.
6609 * @param {string[]} extensions File extensions to look for.
6610 * @param {boolean} recursive Whether or not to recurse into subdirectories.
6611 * @return {string[]} An array of paths.
6612 */
6613exports.lookupFiles = function lookupFiles (path, extensions, recursive) {
6614 var files = [];
6615 var re = new RegExp('\\.(' + extensions.join('|') + ')$');
6616
6617 if (!exists(path)) {
6618 if (exists(path + '.js')) {
6619 path += '.js';
6620 } else {
6621 files = glob.sync(path);
6622 if (!files.length) {
6623 throw new Error("cannot resolve path (or pattern) '" + path + "'");
6624 }
6625 return files;
6626 }
6627 }
6628
6629 try {
6630 var stat = statSync(path);
6631 if (stat.isFile()) {
6632 return path;
6633 }
6634 } catch (err) {
6635 // ignore error
6636 return;
6637 }
6638
6639 readdirSync(path).forEach(function (file) {
6640 file = join(path, file);
6641 try {
6642 var stat = statSync(file);
6643 if (stat.isDirectory()) {
6644 if (recursive) {
6645 files = files.concat(lookupFiles(file, extensions, recursive));
6646 }
6647 return;
6648 }
6649 } catch (err) {
6650 // ignore error
6651 return;
6652 }
6653 if (!stat.isFile() || !re.test(file) || basename(file)[0] === '.') {
6654 return;
6655 }
6656 files.push(file);
6657 });
6658
6659 return files;
6660};
6661
6662/**
6663 * Generate an undefined error with a message warning the user.
6664 *
6665 * @return {Error}
6666 */
6667
6668exports.undefinedError = function () {
6669 return new Error('Caught undefined error, did you throw without specifying what?');
6670};
6671
6672/**
6673 * Generate an undefined error if `err` is not defined.
6674 *
6675 * @param {Error} err
6676 * @return {Error}
6677 */
6678
6679exports.getError = function (err) {
6680 return err || exports.undefinedError();
6681};
6682
6683/**
6684 * @summary
6685 * This Filter based on `mocha-clean` module.(see: `github.com/rstacruz/mocha-clean`)
6686 * @description
6687 * When invoking this function you get a filter function that get the Error.stack as an input,
6688 * and return a prettify output.
6689 * (i.e: strip Mocha and internal node functions from stack trace).
6690 * @returns {Function}
6691 */
6692exports.stackTraceFilter = function () {
6693 // TODO: Replace with `process.browser`
6694 var is = typeof document === 'undefined' ? { node: true } : { browser: true };
6695 var slash = path.sep;
6696 var cwd;
6697 if (is.node) {
6698 cwd = process.cwd() + slash;
6699 } else {
6700 cwd = (typeof location === 'undefined' ? window.location : location).href.replace(/\/[^\/]*$/, '/');
6701 slash = '/';
6702 }
6703
6704 function isMochaInternal (line) {
6705 return (~line.indexOf('node_modules' + slash + 'mocha' + slash)) ||
6706 (~line.indexOf('node_modules' + slash + 'mocha.js')) ||
6707 (~line.indexOf('bower_components' + slash + 'mocha.js')) ||
6708 (~line.indexOf(slash + 'mocha.js'));
6709 }
6710
6711 function isNodeInternal (line) {
6712 return (~line.indexOf('(timers.js:')) ||
6713 (~line.indexOf('(events.js:')) ||
6714 (~line.indexOf('(node.js:')) ||
6715 (~line.indexOf('(module.js:')) ||
6716 (~line.indexOf('GeneratorFunctionPrototype.next (native)')) ||
6717 false;
6718 }
6719
6720 return function (stack) {
6721 stack = stack.split('\n');
6722
6723 stack = reduce(stack, function (list, line) {
6724 if (isMochaInternal(line)) {
6725 return list;
6726 }
6727
6728 if (is.node && isNodeInternal(line)) {
6729 return list;
6730 }
6731
6732 // Clean up cwd(absolute)
6733 if (/\(?.+:\d+:\d+\)?$/.test(line)) {
6734 line = line.replace(cwd, '');
6735 }
6736
6737 list.push(line);
6738 return list;
6739 }, []);
6740
6741 return stack.join('\n');
6742 };
6743};
6744
6745/**
6746 * Crude, but effective.
6747 * @api
6748 * @param {*} value
6749 * @returns {boolean} Whether or not `value` is a Promise
6750 */
6751exports.isPromise = function isPromise (value) {
6752 return typeof value === 'object' && typeof value.then === 'function';
6753};
6754
6755/**
6756 * It's a noop.
6757 * @api
6758 */
6759exports.noop = function () {};
6760
6761}).call(this,require('_process'),require("buffer").Buffer)
6762},{"./to-iso-string":37,"_process":67,"buffer":44,"debug":2,"fs":42,"glob":42,"json3":54,"path":42,"util":84}],39:[function(require,module,exports){
6763'use strict'
6764
6765exports.byteLength = byteLength
6766exports.toByteArray = toByteArray
6767exports.fromByteArray = fromByteArray
6768
6769var lookup = []
6770var revLookup = []
6771var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
6772
6773var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
6774for (var i = 0, len = code.length; i < len; ++i) {
6775 lookup[i] = code[i]
6776 revLookup[code.charCodeAt(i)] = i
6777}
6778
6779revLookup['-'.charCodeAt(0)] = 62
6780revLookup['_'.charCodeAt(0)] = 63
6781
6782function placeHoldersCount (b64) {
6783 var len = b64.length
6784 if (len % 4 > 0) {
6785 throw new Error('Invalid string. Length must be a multiple of 4')
6786 }
6787
6788 // the number of equal signs (place holders)
6789 // if there are two placeholders, than the two characters before it
6790 // represent one byte
6791 // if there is only one, then the three characters before it represent 2 bytes
6792 // this is just a cheap hack to not do indexOf twice
6793 return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
6794}
6795
6796function byteLength (b64) {
6797 // base64 is 4/3 + up to two characters of the original data
6798 return b64.length * 3 / 4 - placeHoldersCount(b64)
6799}
6800
6801function toByteArray (b64) {
6802 var i, j, l, tmp, placeHolders, arr
6803 var len = b64.length
6804 placeHolders = placeHoldersCount(b64)
6805
6806 arr = new Arr(len * 3 / 4 - placeHolders)
6807
6808 // if there are placeholders, only get up to the last complete 4 chars
6809 l = placeHolders > 0 ? len - 4 : len
6810
6811 var L = 0
6812
6813 for (i = 0, j = 0; i < l; i += 4, j += 3) {
6814 tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
6815 arr[L++] = (tmp >> 16) & 0xFF
6816 arr[L++] = (tmp >> 8) & 0xFF
6817 arr[L++] = tmp & 0xFF
6818 }
6819
6820 if (placeHolders === 2) {
6821 tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
6822 arr[L++] = tmp & 0xFF
6823 } else if (placeHolders === 1) {
6824 tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
6825 arr[L++] = (tmp >> 8) & 0xFF
6826 arr[L++] = tmp & 0xFF
6827 }
6828
6829 return arr
6830}
6831
6832function tripletToBase64 (num) {
6833 return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
6834}
6835
6836function encodeChunk (uint8, start, end) {
6837 var tmp
6838 var output = []
6839 for (var i = start; i < end; i += 3) {
6840 tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
6841 output.push(tripletToBase64(tmp))
6842 }
6843 return output.join('')
6844}
6845
6846function fromByteArray (uint8) {
6847 var tmp
6848 var len = uint8.length
6849 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
6850 var output = ''
6851 var parts = []
6852 var maxChunkLength = 16383 // must be multiple of 3
6853
6854 // go through the array every three bytes, we'll deal with trailing stuff later
6855 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
6856 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
6857 }
6858
6859 // pad the end with zeros, but make sure to not forget the extra bytes
6860 if (extraBytes === 1) {
6861 tmp = uint8[len - 1]
6862 output += lookup[tmp >> 2]
6863 output += lookup[(tmp << 4) & 0x3F]
6864 output += '=='
6865 } else if (extraBytes === 2) {
6866 tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
6867 output += lookup[tmp >> 10]
6868 output += lookup[(tmp >> 4) & 0x3F]
6869 output += lookup[(tmp << 2) & 0x3F]
6870 output += '='
6871 }
6872
6873 parts.push(output)
6874
6875 return parts.join('')
6876}
6877
6878},{}],40:[function(require,module,exports){
6879
6880},{}],41:[function(require,module,exports){
6881(function (process){
6882var WritableStream = require('stream').Writable
6883var inherits = require('util').inherits
6884
6885module.exports = BrowserStdout
6886
6887
6888inherits(BrowserStdout, WritableStream)
6889
6890function BrowserStdout(opts) {
6891 if (!(this instanceof BrowserStdout)) return new BrowserStdout(opts)
6892
6893 opts = opts || {}
6894 WritableStream.call(this, opts)
6895 this.label = (opts.label !== undefined) ? opts.label : 'stdout'
6896}
6897
6898BrowserStdout.prototype._write = function(chunks, encoding, cb) {
6899 var output = chunks.toString ? chunks.toString() : chunks
6900 if (this.label === false) {
6901 console.log(output)
6902 } else {
6903 console.log(this.label+':', output)
6904 }
6905 process.nextTick(cb)
6906}
6907
6908}).call(this,require('_process'))
6909},{"_process":67,"stream":79,"util":84}],42:[function(require,module,exports){
6910arguments[4][40][0].apply(exports,arguments)
6911},{"dup":40}],43:[function(require,module,exports){
6912(function (global){
6913'use strict';
6914
6915var buffer = require('buffer');
6916var Buffer = buffer.Buffer;
6917var SlowBuffer = buffer.SlowBuffer;
6918var MAX_LEN = buffer.kMaxLength || 2147483647;
6919exports.alloc = function alloc(size, fill, encoding) {
6920 if (typeof Buffer.alloc === 'function') {
6921 return Buffer.alloc(size, fill, encoding);
6922 }
6923 if (typeof encoding === 'number') {
6924 throw new TypeError('encoding must not be number');
6925 }
6926 if (typeof size !== 'number') {
6927 throw new TypeError('size must be a number');
6928 }
6929 if (size > MAX_LEN) {
6930 throw new RangeError('size is too large');
6931 }
6932 var enc = encoding;
6933 var _fill = fill;
6934 if (_fill === undefined) {
6935 enc = undefined;
6936 _fill = 0;
6937 }
6938 var buf = new Buffer(size);
6939 if (typeof _fill === 'string') {
6940 var fillBuf = new Buffer(_fill, enc);
6941 var flen = fillBuf.length;
6942 var i = -1;
6943 while (++i < size) {
6944 buf[i] = fillBuf[i % flen];
6945 }
6946 } else {
6947 buf.fill(_fill);
6948 }
6949 return buf;
6950}
6951exports.allocUnsafe = function allocUnsafe(size) {
6952 if (typeof Buffer.allocUnsafe === 'function') {
6953 return Buffer.allocUnsafe(size);
6954 }
6955 if (typeof size !== 'number') {
6956 throw new TypeError('size must be a number');
6957 }
6958 if (size > MAX_LEN) {
6959 throw new RangeError('size is too large');
6960 }
6961 return new Buffer(size);
6962}
6963exports.from = function from(value, encodingOrOffset, length) {
6964 if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) {
6965 return Buffer.from(value, encodingOrOffset, length);
6966 }
6967 if (typeof value === 'number') {
6968 throw new TypeError('"value" argument must not be a number');
6969 }
6970 if (typeof value === 'string') {
6971 return new Buffer(value, encodingOrOffset);
6972 }
6973 if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
6974 var offset = encodingOrOffset;
6975 if (arguments.length === 1) {
6976 return new Buffer(value);
6977 }
6978 if (typeof offset === 'undefined') {
6979 offset = 0;
6980 }
6981 var len = length;
6982 if (typeof len === 'undefined') {
6983 len = value.byteLength - offset;
6984 }
6985 if (offset >= value.byteLength) {
6986 throw new RangeError('\'offset\' is out of bounds');
6987 }
6988 if (len > value.byteLength - offset) {
6989 throw new RangeError('\'length\' is out of bounds');
6990 }
6991 return new Buffer(value.slice(offset, offset + len));
6992 }
6993 if (Buffer.isBuffer(value)) {
6994 var out = new Buffer(value.length);
6995 value.copy(out, 0, 0, value.length);
6996 return out;
6997 }
6998 if (value) {
6999 if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) {
7000 return new Buffer(value);
7001 }
7002 if (value.type === 'Buffer' && Array.isArray(value.data)) {
7003 return new Buffer(value.data);
7004 }
7005 }
7006
7007 throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.');
7008}
7009exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
7010 if (typeof Buffer.allocUnsafeSlow === 'function') {
7011 return Buffer.allocUnsafeSlow(size);
7012 }
7013 if (typeof size !== 'number') {
7014 throw new TypeError('size must be a number');
7015 }
7016 if (size >= MAX_LEN) {
7017 throw new RangeError('size is too large');
7018 }
7019 return new SlowBuffer(size);
7020}
7021
7022}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
7023},{"buffer":44}],44:[function(require,module,exports){
7024(function (global){
7025/*!
7026 * The buffer module from node.js, for the browser.
7027 *
7028 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
7029 * @license MIT
7030 */
7031/* eslint-disable no-proto */
7032
7033'use strict'
7034
7035var base64 = require('base64-js')
7036var ieee754 = require('ieee754')
7037var isArray = require('isarray')
7038
7039exports.Buffer = Buffer
7040exports.SlowBuffer = SlowBuffer
7041exports.INSPECT_MAX_BYTES = 50
7042
7043/**
7044 * If `Buffer.TYPED_ARRAY_SUPPORT`:
7045 * === true Use Uint8Array implementation (fastest)
7046 * === false Use Object implementation (most compatible, even IE6)
7047 *
7048 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
7049 * Opera 11.6+, iOS 4.2+.
7050 *
7051 * Due to various browser bugs, sometimes the Object implementation will be used even
7052 * when the browser supports typed arrays.
7053 *
7054 * Note:
7055 *
7056 * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
7057 * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
7058 *
7059 * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
7060 *
7061 * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
7062 * incorrect length in some situations.
7063
7064 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
7065 * get the Object implementation, which is slower but behaves correctly.
7066 */
7067Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
7068 ? global.TYPED_ARRAY_SUPPORT
7069 : typedArraySupport()
7070
7071/*
7072 * Export kMaxLength after typed array support is determined.
7073 */
7074exports.kMaxLength = kMaxLength()
7075
7076function typedArraySupport () {
7077 try {
7078 var arr = new Uint8Array(1)
7079 arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
7080 return arr.foo() === 42 && // typed array instances can be augmented
7081 typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
7082 arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
7083 } catch (e) {
7084 return false
7085 }
7086}
7087
7088function kMaxLength () {
7089 return Buffer.TYPED_ARRAY_SUPPORT
7090 ? 0x7fffffff
7091 : 0x3fffffff
7092}
7093
7094function createBuffer (that, length) {
7095 if (kMaxLength() < length) {
7096 throw new RangeError('Invalid typed array length')
7097 }
7098 if (Buffer.TYPED_ARRAY_SUPPORT) {
7099 // Return an augmented `Uint8Array` instance, for best performance
7100 that = new Uint8Array(length)
7101 that.__proto__ = Buffer.prototype
7102 } else {
7103 // Fallback: Return an object instance of the Buffer class
7104 if (that === null) {
7105 that = new Buffer(length)
7106 }
7107 that.length = length
7108 }
7109
7110 return that
7111}
7112
7113/**
7114 * The Buffer constructor returns instances of `Uint8Array` that have their
7115 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
7116 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
7117 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
7118 * returns a single octet.
7119 *
7120 * The `Uint8Array` prototype remains unmodified.
7121 */
7122
7123function Buffer (arg, encodingOrOffset, length) {
7124 if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
7125 return new Buffer(arg, encodingOrOffset, length)
7126 }
7127
7128 // Common case.
7129 if (typeof arg === 'number') {
7130 if (typeof encodingOrOffset === 'string') {
7131 throw new Error(
7132 'If encoding is specified then the first argument must be a string'
7133 )
7134 }
7135 return allocUnsafe(this, arg)
7136 }
7137 return from(this, arg, encodingOrOffset, length)
7138}
7139
7140Buffer.poolSize = 8192 // not used by this implementation
7141
7142// TODO: Legacy, not needed anymore. Remove in next major version.
7143Buffer._augment = function (arr) {
7144 arr.__proto__ = Buffer.prototype
7145 return arr
7146}
7147
7148function from (that, value, encodingOrOffset, length) {
7149 if (typeof value === 'number') {
7150 throw new TypeError('"value" argument must not be a number')
7151 }
7152
7153 if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
7154 return fromArrayBuffer(that, value, encodingOrOffset, length)
7155 }
7156
7157 if (typeof value === 'string') {
7158 return fromString(that, value, encodingOrOffset)
7159 }
7160
7161 return fromObject(that, value)
7162}
7163
7164/**
7165 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
7166 * if value is a number.
7167 * Buffer.from(str[, encoding])
7168 * Buffer.from(array)
7169 * Buffer.from(buffer)
7170 * Buffer.from(arrayBuffer[, byteOffset[, length]])
7171 **/
7172Buffer.from = function (value, encodingOrOffset, length) {
7173 return from(null, value, encodingOrOffset, length)
7174}
7175
7176if (Buffer.TYPED_ARRAY_SUPPORT) {
7177 Buffer.prototype.__proto__ = Uint8Array.prototype
7178 Buffer.__proto__ = Uint8Array
7179 if (typeof Symbol !== 'undefined' && Symbol.species &&
7180 Buffer[Symbol.species] === Buffer) {
7181 // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
7182 Object.defineProperty(Buffer, Symbol.species, {
7183 value: null,
7184 configurable: true
7185 })
7186 }
7187}
7188
7189function assertSize (size) {
7190 if (typeof size !== 'number') {
7191 throw new TypeError('"size" argument must be a number')
7192 } else if (size < 0) {
7193 throw new RangeError('"size" argument must not be negative')
7194 }
7195}
7196
7197function alloc (that, size, fill, encoding) {
7198 assertSize(size)
7199 if (size <= 0) {
7200 return createBuffer(that, size)
7201 }
7202 if (fill !== undefined) {
7203 // Only pay attention to encoding if it's a string. This
7204 // prevents accidentally sending in a number that would
7205 // be interpretted as a start offset.
7206 return typeof encoding === 'string'
7207 ? createBuffer(that, size).fill(fill, encoding)
7208 : createBuffer(that, size).fill(fill)
7209 }
7210 return createBuffer(that, size)
7211}
7212
7213/**
7214 * Creates a new filled Buffer instance.
7215 * alloc(size[, fill[, encoding]])
7216 **/
7217Buffer.alloc = function (size, fill, encoding) {
7218 return alloc(null, size, fill, encoding)
7219}
7220
7221function allocUnsafe (that, size) {
7222 assertSize(size)
7223 that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
7224 if (!Buffer.TYPED_ARRAY_SUPPORT) {
7225 for (var i = 0; i < size; ++i) {
7226 that[i] = 0
7227 }
7228 }
7229 return that
7230}
7231
7232/**
7233 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
7234 * */
7235Buffer.allocUnsafe = function (size) {
7236 return allocUnsafe(null, size)
7237}
7238/**
7239 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
7240 */
7241Buffer.allocUnsafeSlow = function (size) {
7242 return allocUnsafe(null, size)
7243}
7244
7245function fromString (that, string, encoding) {
7246 if (typeof encoding !== 'string' || encoding === '') {
7247 encoding = 'utf8'
7248 }
7249
7250 if (!Buffer.isEncoding(encoding)) {
7251 throw new TypeError('"encoding" must be a valid string encoding')
7252 }
7253
7254 var length = byteLength(string, encoding) | 0
7255 that = createBuffer(that, length)
7256
7257 var actual = that.write(string, encoding)
7258
7259 if (actual !== length) {
7260 // Writing a hex string, for example, that contains invalid characters will
7261 // cause everything after the first invalid character to be ignored. (e.g.
7262 // 'abxxcd' will be treated as 'ab')
7263 that = that.slice(0, actual)
7264 }
7265
7266 return that
7267}
7268
7269function fromArrayLike (that, array) {
7270 var length = array.length < 0 ? 0 : checked(array.length) | 0
7271 that = createBuffer(that, length)
7272 for (var i = 0; i < length; i += 1) {
7273 that[i] = array[i] & 255
7274 }
7275 return that
7276}
7277
7278function fromArrayBuffer (that, array, byteOffset, length) {
7279 array.byteLength // this throws if `array` is not a valid ArrayBuffer
7280
7281 if (byteOffset < 0 || array.byteLength < byteOffset) {
7282 throw new RangeError('\'offset\' is out of bounds')
7283 }
7284
7285 if (array.byteLength < byteOffset + (length || 0)) {
7286 throw new RangeError('\'length\' is out of bounds')
7287 }
7288
7289 if (byteOffset === undefined && length === undefined) {
7290 array = new Uint8Array(array)
7291 } else if (length === undefined) {
7292 array = new Uint8Array(array, byteOffset)
7293 } else {
7294 array = new Uint8Array(array, byteOffset, length)
7295 }
7296
7297 if (Buffer.TYPED_ARRAY_SUPPORT) {
7298 // Return an augmented `Uint8Array` instance, for best performance
7299 that = array
7300 that.__proto__ = Buffer.prototype
7301 } else {
7302 // Fallback: Return an object instance of the Buffer class
7303 that = fromArrayLike(that, array)
7304 }
7305 return that
7306}
7307
7308function fromObject (that, obj) {
7309 if (Buffer.isBuffer(obj)) {
7310 var len = checked(obj.length) | 0
7311 that = createBuffer(that, len)
7312
7313 if (that.length === 0) {
7314 return that
7315 }
7316
7317 obj.copy(that, 0, 0, len)
7318 return that
7319 }
7320
7321 if (obj) {
7322 if ((typeof ArrayBuffer !== 'undefined' &&
7323 obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
7324 if (typeof obj.length !== 'number' || isnan(obj.length)) {
7325 return createBuffer(that, 0)
7326 }
7327 return fromArrayLike(that, obj)
7328 }
7329
7330 if (obj.type === 'Buffer' && isArray(obj.data)) {
7331 return fromArrayLike(that, obj.data)
7332 }
7333 }
7334
7335 throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
7336}
7337
7338function checked (length) {
7339 // Note: cannot use `length < kMaxLength()` here because that fails when
7340 // length is NaN (which is otherwise coerced to zero.)
7341 if (length >= kMaxLength()) {
7342 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
7343 'size: 0x' + kMaxLength().toString(16) + ' bytes')
7344 }
7345 return length | 0
7346}
7347
7348function SlowBuffer (length) {
7349 if (+length != length) { // eslint-disable-line eqeqeq
7350 length = 0
7351 }
7352 return Buffer.alloc(+length)
7353}
7354
7355Buffer.isBuffer = function isBuffer (b) {
7356 return !!(b != null && b._isBuffer)
7357}
7358
7359Buffer.compare = function compare (a, b) {
7360 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
7361 throw new TypeError('Arguments must be Buffers')
7362 }
7363
7364 if (a === b) return 0
7365
7366 var x = a.length
7367 var y = b.length
7368
7369 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
7370 if (a[i] !== b[i]) {
7371 x = a[i]
7372 y = b[i]
7373 break
7374 }
7375 }
7376
7377 if (x < y) return -1
7378 if (y < x) return 1
7379 return 0
7380}
7381
7382Buffer.isEncoding = function isEncoding (encoding) {
7383 switch (String(encoding).toLowerCase()) {
7384 case 'hex':
7385 case 'utf8':
7386 case 'utf-8':
7387 case 'ascii':
7388 case 'latin1':
7389 case 'binary':
7390 case 'base64':
7391 case 'ucs2':
7392 case 'ucs-2':
7393 case 'utf16le':
7394 case 'utf-16le':
7395 return true
7396 default:
7397 return false
7398 }
7399}
7400
7401Buffer.concat = function concat (list, length) {
7402 if (!isArray(list)) {
7403 throw new TypeError('"list" argument must be an Array of Buffers')
7404 }
7405
7406 if (list.length === 0) {
7407 return Buffer.alloc(0)
7408 }
7409
7410 var i
7411 if (length === undefined) {
7412 length = 0
7413 for (i = 0; i < list.length; ++i) {
7414 length += list[i].length
7415 }
7416 }
7417
7418 var buffer = Buffer.allocUnsafe(length)
7419 var pos = 0
7420 for (i = 0; i < list.length; ++i) {
7421 var buf = list[i]
7422 if (!Buffer.isBuffer(buf)) {
7423 throw new TypeError('"list" argument must be an Array of Buffers')
7424 }
7425 buf.copy(buffer, pos)
7426 pos += buf.length
7427 }
7428 return buffer
7429}
7430
7431function byteLength (string, encoding) {
7432 if (Buffer.isBuffer(string)) {
7433 return string.length
7434 }
7435 if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
7436 (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
7437 return string.byteLength
7438 }
7439 if (typeof string !== 'string') {
7440 string = '' + string
7441 }
7442
7443 var len = string.length
7444 if (len === 0) return 0
7445
7446 // Use a for loop to avoid recursion
7447 var loweredCase = false
7448 for (;;) {
7449 switch (encoding) {
7450 case 'ascii':
7451 case 'latin1':
7452 case 'binary':
7453 return len
7454 case 'utf8':
7455 case 'utf-8':
7456 case undefined:
7457 return utf8ToBytes(string).length
7458 case 'ucs2':
7459 case 'ucs-2':
7460 case 'utf16le':
7461 case 'utf-16le':
7462 return len * 2
7463 case 'hex':
7464 return len >>> 1
7465 case 'base64':
7466 return base64ToBytes(string).length
7467 default:
7468 if (loweredCase) return utf8ToBytes(string).length // assume utf8
7469 encoding = ('' + encoding).toLowerCase()
7470 loweredCase = true
7471 }
7472 }
7473}
7474Buffer.byteLength = byteLength
7475
7476function slowToString (encoding, start, end) {
7477 var loweredCase = false
7478
7479 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
7480 // property of a typed array.
7481
7482 // This behaves neither like String nor Uint8Array in that we set start/end
7483 // to their upper/lower bounds if the value passed is out of range.
7484 // undefined is handled specially as per ECMA-262 6th Edition,
7485 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
7486 if (start === undefined || start < 0) {
7487 start = 0
7488 }
7489 // Return early if start > this.length. Done here to prevent potential uint32
7490 // coercion fail below.
7491 if (start > this.length) {
7492 return ''
7493 }
7494
7495 if (end === undefined || end > this.length) {
7496 end = this.length
7497 }
7498
7499 if (end <= 0) {
7500 return ''
7501 }
7502
7503 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
7504 end >>>= 0
7505 start >>>= 0
7506
7507 if (end <= start) {
7508 return ''
7509 }
7510
7511 if (!encoding) encoding = 'utf8'
7512
7513 while (true) {
7514 switch (encoding) {
7515 case 'hex':
7516 return hexSlice(this, start, end)
7517
7518 case 'utf8':
7519 case 'utf-8':
7520 return utf8Slice(this, start, end)
7521
7522 case 'ascii':
7523 return asciiSlice(this, start, end)
7524
7525 case 'latin1':
7526 case 'binary':
7527 return latin1Slice(this, start, end)
7528
7529 case 'base64':
7530 return base64Slice(this, start, end)
7531
7532 case 'ucs2':
7533 case 'ucs-2':
7534 case 'utf16le':
7535 case 'utf-16le':
7536 return utf16leSlice(this, start, end)
7537
7538 default:
7539 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
7540 encoding = (encoding + '').toLowerCase()
7541 loweredCase = true
7542 }
7543 }
7544}
7545
7546// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
7547// Buffer instances.
7548Buffer.prototype._isBuffer = true
7549
7550function swap (b, n, m) {
7551 var i = b[n]
7552 b[n] = b[m]
7553 b[m] = i
7554}
7555
7556Buffer.prototype.swap16 = function swap16 () {
7557 var len = this.length
7558 if (len % 2 !== 0) {
7559 throw new RangeError('Buffer size must be a multiple of 16-bits')
7560 }
7561 for (var i = 0; i < len; i += 2) {
7562 swap(this, i, i + 1)
7563 }
7564 return this
7565}
7566
7567Buffer.prototype.swap32 = function swap32 () {
7568 var len = this.length
7569 if (len % 4 !== 0) {
7570 throw new RangeError('Buffer size must be a multiple of 32-bits')
7571 }
7572 for (var i = 0; i < len; i += 4) {
7573 swap(this, i, i + 3)
7574 swap(this, i + 1, i + 2)
7575 }
7576 return this
7577}
7578
7579Buffer.prototype.swap64 = function swap64 () {
7580 var len = this.length
7581 if (len % 8 !== 0) {
7582 throw new RangeError('Buffer size must be a multiple of 64-bits')
7583 }
7584 for (var i = 0; i < len; i += 8) {
7585 swap(this, i, i + 7)
7586 swap(this, i + 1, i + 6)
7587 swap(this, i + 2, i + 5)
7588 swap(this, i + 3, i + 4)
7589 }
7590 return this
7591}
7592
7593Buffer.prototype.toString = function toString () {
7594 var length = this.length | 0
7595 if (length === 0) return ''
7596 if (arguments.length === 0) return utf8Slice(this, 0, length)
7597 return slowToString.apply(this, arguments)
7598}
7599
7600Buffer.prototype.equals = function equals (b) {
7601 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
7602 if (this === b) return true
7603 return Buffer.compare(this, b) === 0
7604}
7605
7606Buffer.prototype.inspect = function inspect () {
7607 var str = ''
7608 var max = exports.INSPECT_MAX_BYTES
7609 if (this.length > 0) {
7610 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
7611 if (this.length > max) str += ' ... '
7612 }
7613 return '<Buffer ' + str + '>'
7614}
7615
7616Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
7617 if (!Buffer.isBuffer(target)) {
7618 throw new TypeError('Argument must be a Buffer')
7619 }
7620
7621 if (start === undefined) {
7622 start = 0
7623 }
7624 if (end === undefined) {
7625 end = target ? target.length : 0
7626 }
7627 if (thisStart === undefined) {
7628 thisStart = 0
7629 }
7630 if (thisEnd === undefined) {
7631 thisEnd = this.length
7632 }
7633
7634 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
7635 throw new RangeError('out of range index')
7636 }
7637
7638 if (thisStart >= thisEnd && start >= end) {
7639 return 0
7640 }
7641 if (thisStart >= thisEnd) {
7642 return -1
7643 }
7644 if (start >= end) {
7645 return 1
7646 }
7647
7648 start >>>= 0
7649 end >>>= 0
7650 thisStart >>>= 0
7651 thisEnd >>>= 0
7652
7653 if (this === target) return 0
7654
7655 var x = thisEnd - thisStart
7656 var y = end - start
7657 var len = Math.min(x, y)
7658
7659 var thisCopy = this.slice(thisStart, thisEnd)
7660 var targetCopy = target.slice(start, end)
7661
7662 for (var i = 0; i < len; ++i) {
7663 if (thisCopy[i] !== targetCopy[i]) {
7664 x = thisCopy[i]
7665 y = targetCopy[i]
7666 break
7667 }
7668 }
7669
7670 if (x < y) return -1
7671 if (y < x) return 1
7672 return 0
7673}
7674
7675// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
7676// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
7677//
7678// Arguments:
7679// - buffer - a Buffer to search
7680// - val - a string, Buffer, or number
7681// - byteOffset - an index into `buffer`; will be clamped to an int32
7682// - encoding - an optional encoding, relevant is val is a string
7683// - dir - true for indexOf, false for lastIndexOf
7684function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
7685 // Empty buffer means no match
7686 if (buffer.length === 0) return -1
7687
7688 // Normalize byteOffset
7689 if (typeof byteOffset === 'string') {
7690 encoding = byteOffset
7691 byteOffset = 0
7692 } else if (byteOffset > 0x7fffffff) {
7693 byteOffset = 0x7fffffff
7694 } else if (byteOffset < -0x80000000) {
7695 byteOffset = -0x80000000
7696 }
7697 byteOffset = +byteOffset // Coerce to Number.
7698 if (isNaN(byteOffset)) {
7699 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
7700 byteOffset = dir ? 0 : (buffer.length - 1)
7701 }
7702
7703 // Normalize byteOffset: negative offsets start from the end of the buffer
7704 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
7705 if (byteOffset >= buffer.length) {
7706 if (dir) return -1
7707 else byteOffset = buffer.length - 1
7708 } else if (byteOffset < 0) {
7709 if (dir) byteOffset = 0
7710 else return -1
7711 }
7712
7713 // Normalize val
7714 if (typeof val === 'string') {
7715 val = Buffer.from(val, encoding)
7716 }
7717
7718 // Finally, search either indexOf (if dir is true) or lastIndexOf
7719 if (Buffer.isBuffer(val)) {
7720 // Special case: looking for empty string/buffer always fails
7721 if (val.length === 0) {
7722 return -1
7723 }
7724 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
7725 } else if (typeof val === 'number') {
7726 val = val & 0xFF // Search for a byte value [0-255]
7727 if (Buffer.TYPED_ARRAY_SUPPORT &&
7728 typeof Uint8Array.prototype.indexOf === 'function') {
7729 if (dir) {
7730 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
7731 } else {
7732 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
7733 }
7734 }
7735 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
7736 }
7737
7738 throw new TypeError('val must be string, number or Buffer')
7739}
7740
7741function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
7742 var indexSize = 1
7743 var arrLength = arr.length
7744 var valLength = val.length
7745
7746 if (encoding !== undefined) {
7747 encoding = String(encoding).toLowerCase()
7748 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
7749 encoding === 'utf16le' || encoding === 'utf-16le') {
7750 if (arr.length < 2 || val.length < 2) {
7751 return -1
7752 }
7753 indexSize = 2
7754 arrLength /= 2
7755 valLength /= 2
7756 byteOffset /= 2
7757 }
7758 }
7759
7760 function read (buf, i) {
7761 if (indexSize === 1) {
7762 return buf[i]
7763 } else {
7764 return buf.readUInt16BE(i * indexSize)
7765 }
7766 }
7767
7768 var i
7769 if (dir) {
7770 var foundIndex = -1
7771 for (i = byteOffset; i < arrLength; i++) {
7772 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
7773 if (foundIndex === -1) foundIndex = i
7774 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
7775 } else {
7776 if (foundIndex !== -1) i -= i - foundIndex
7777 foundIndex = -1
7778 }
7779 }
7780 } else {
7781 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
7782 for (i = byteOffset; i >= 0; i--) {
7783 var found = true
7784 for (var j = 0; j < valLength; j++) {
7785 if (read(arr, i + j) !== read(val, j)) {
7786 found = false
7787 break
7788 }
7789 }
7790 if (found) return i
7791 }
7792 }
7793
7794 return -1
7795}
7796
7797Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
7798 return this.indexOf(val, byteOffset, encoding) !== -1
7799}
7800
7801Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
7802 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
7803}
7804
7805Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
7806 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
7807}
7808
7809function hexWrite (buf, string, offset, length) {
7810 offset = Number(offset) || 0
7811 var remaining = buf.length - offset
7812 if (!length) {
7813 length = remaining
7814 } else {
7815 length = Number(length)
7816 if (length > remaining) {
7817 length = remaining
7818 }
7819 }
7820
7821 // must be an even number of digits
7822 var strLen = string.length
7823 if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
7824
7825 if (length > strLen / 2) {
7826 length = strLen / 2
7827 }
7828 for (var i = 0; i < length; ++i) {
7829 var parsed = parseInt(string.substr(i * 2, 2), 16)
7830 if (isNaN(parsed)) return i
7831 buf[offset + i] = parsed
7832 }
7833 return i
7834}
7835
7836function utf8Write (buf, string, offset, length) {
7837 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
7838}
7839
7840function asciiWrite (buf, string, offset, length) {
7841 return blitBuffer(asciiToBytes(string), buf, offset, length)
7842}
7843
7844function latin1Write (buf, string, offset, length) {
7845 return asciiWrite(buf, string, offset, length)
7846}
7847
7848function base64Write (buf, string, offset, length) {
7849 return blitBuffer(base64ToBytes(string), buf, offset, length)
7850}
7851
7852function ucs2Write (buf, string, offset, length) {
7853 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
7854}
7855
7856Buffer.prototype.write = function write (string, offset, length, encoding) {
7857 // Buffer#write(string)
7858 if (offset === undefined) {
7859 encoding = 'utf8'
7860 length = this.length
7861 offset = 0
7862 // Buffer#write(string, encoding)
7863 } else if (length === undefined && typeof offset === 'string') {
7864 encoding = offset
7865 length = this.length
7866 offset = 0
7867 // Buffer#write(string, offset[, length][, encoding])
7868 } else if (isFinite(offset)) {
7869 offset = offset | 0
7870 if (isFinite(length)) {
7871 length = length | 0
7872 if (encoding === undefined) encoding = 'utf8'
7873 } else {
7874 encoding = length
7875 length = undefined
7876 }
7877 // legacy write(string, encoding, offset, length) - remove in v0.13
7878 } else {
7879 throw new Error(
7880 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
7881 )
7882 }
7883
7884 var remaining = this.length - offset
7885 if (length === undefined || length > remaining) length = remaining
7886
7887 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
7888 throw new RangeError('Attempt to write outside buffer bounds')
7889 }
7890
7891 if (!encoding) encoding = 'utf8'
7892
7893 var loweredCase = false
7894 for (;;) {
7895 switch (encoding) {
7896 case 'hex':
7897 return hexWrite(this, string, offset, length)
7898
7899 case 'utf8':
7900 case 'utf-8':
7901 return utf8Write(this, string, offset, length)
7902
7903 case 'ascii':
7904 return asciiWrite(this, string, offset, length)
7905
7906 case 'latin1':
7907 case 'binary':
7908 return latin1Write(this, string, offset, length)
7909
7910 case 'base64':
7911 // Warning: maxLength not taken into account in base64Write
7912 return base64Write(this, string, offset, length)
7913
7914 case 'ucs2':
7915 case 'ucs-2':
7916 case 'utf16le':
7917 case 'utf-16le':
7918 return ucs2Write(this, string, offset, length)
7919
7920 default:
7921 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
7922 encoding = ('' + encoding).toLowerCase()
7923 loweredCase = true
7924 }
7925 }
7926}
7927
7928Buffer.prototype.toJSON = function toJSON () {
7929 return {
7930 type: 'Buffer',
7931 data: Array.prototype.slice.call(this._arr || this, 0)
7932 }
7933}
7934
7935function base64Slice (buf, start, end) {
7936 if (start === 0 && end === buf.length) {
7937 return base64.fromByteArray(buf)
7938 } else {
7939 return base64.fromByteArray(buf.slice(start, end))
7940 }
7941}
7942
7943function utf8Slice (buf, start, end) {
7944 end = Math.min(buf.length, end)
7945 var res = []
7946
7947 var i = start
7948 while (i < end) {
7949 var firstByte = buf[i]
7950 var codePoint = null
7951 var bytesPerSequence = (firstByte > 0xEF) ? 4
7952 : (firstByte > 0xDF) ? 3
7953 : (firstByte > 0xBF) ? 2
7954 : 1
7955
7956 if (i + bytesPerSequence <= end) {
7957 var secondByte, thirdByte, fourthByte, tempCodePoint
7958
7959 switch (bytesPerSequence) {
7960 case 1:
7961 if (firstByte < 0x80) {
7962 codePoint = firstByte
7963 }
7964 break
7965 case 2:
7966 secondByte = buf[i + 1]
7967 if ((secondByte & 0xC0) === 0x80) {
7968 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
7969 if (tempCodePoint > 0x7F) {
7970 codePoint = tempCodePoint
7971 }
7972 }
7973 break
7974 case 3:
7975 secondByte = buf[i + 1]
7976 thirdByte = buf[i + 2]
7977 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
7978 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
7979 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
7980 codePoint = tempCodePoint
7981 }
7982 }
7983 break
7984 case 4:
7985 secondByte = buf[i + 1]
7986 thirdByte = buf[i + 2]
7987 fourthByte = buf[i + 3]
7988 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
7989 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
7990 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
7991 codePoint = tempCodePoint
7992 }
7993 }
7994 }
7995 }
7996
7997 if (codePoint === null) {
7998 // we did not generate a valid codePoint so insert a
7999 // replacement char (U+FFFD) and advance only 1 byte
8000 codePoint = 0xFFFD
8001 bytesPerSequence = 1
8002 } else if (codePoint > 0xFFFF) {
8003 // encode to utf16 (surrogate pair dance)
8004 codePoint -= 0x10000
8005 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
8006 codePoint = 0xDC00 | codePoint & 0x3FF
8007 }
8008
8009 res.push(codePoint)
8010 i += bytesPerSequence
8011 }
8012
8013 return decodeCodePointsArray(res)
8014}
8015
8016// Based on http://stackoverflow.com/a/22747272/680742, the browser with
8017// the lowest limit is Chrome, with 0x10000 args.
8018// We go 1 magnitude less, for safety
8019var MAX_ARGUMENTS_LENGTH = 0x1000
8020
8021function decodeCodePointsArray (codePoints) {
8022 var len = codePoints.length
8023 if (len <= MAX_ARGUMENTS_LENGTH) {
8024 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
8025 }
8026
8027 // Decode in chunks to avoid "call stack size exceeded".
8028 var res = ''
8029 var i = 0
8030 while (i < len) {
8031 res += String.fromCharCode.apply(
8032 String,
8033 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
8034 )
8035 }
8036 return res
8037}
8038
8039function asciiSlice (buf, start, end) {
8040 var ret = ''
8041 end = Math.min(buf.length, end)
8042
8043 for (var i = start; i < end; ++i) {
8044 ret += String.fromCharCode(buf[i] & 0x7F)
8045 }
8046 return ret
8047}
8048
8049function latin1Slice (buf, start, end) {
8050 var ret = ''
8051 end = Math.min(buf.length, end)
8052
8053 for (var i = start; i < end; ++i) {
8054 ret += String.fromCharCode(buf[i])
8055 }
8056 return ret
8057}
8058
8059function hexSlice (buf, start, end) {
8060 var len = buf.length
8061
8062 if (!start || start < 0) start = 0
8063 if (!end || end < 0 || end > len) end = len
8064
8065 var out = ''
8066 for (var i = start; i < end; ++i) {
8067 out += toHex(buf[i])
8068 }
8069 return out
8070}
8071
8072function utf16leSlice (buf, start, end) {
8073 var bytes = buf.slice(start, end)
8074 var res = ''
8075 for (var i = 0; i < bytes.length; i += 2) {
8076 res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
8077 }
8078 return res
8079}
8080
8081Buffer.prototype.slice = function slice (start, end) {
8082 var len = this.length
8083 start = ~~start
8084 end = end === undefined ? len : ~~end
8085
8086 if (start < 0) {
8087 start += len
8088 if (start < 0) start = 0
8089 } else if (start > len) {
8090 start = len
8091 }
8092
8093 if (end < 0) {
8094 end += len
8095 if (end < 0) end = 0
8096 } else if (end > len) {
8097 end = len
8098 }
8099
8100 if (end < start) end = start
8101
8102 var newBuf
8103 if (Buffer.TYPED_ARRAY_SUPPORT) {
8104 newBuf = this.subarray(start, end)
8105 newBuf.__proto__ = Buffer.prototype
8106 } else {
8107 var sliceLen = end - start
8108 newBuf = new Buffer(sliceLen, undefined)
8109 for (var i = 0; i < sliceLen; ++i) {
8110 newBuf[i] = this[i + start]
8111 }
8112 }
8113
8114 return newBuf
8115}
8116
8117/*
8118 * Need to make sure that buffer isn't trying to write out of bounds.
8119 */
8120function checkOffset (offset, ext, length) {
8121 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
8122 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
8123}
8124
8125Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
8126 offset = offset | 0
8127 byteLength = byteLength | 0
8128 if (!noAssert) checkOffset(offset, byteLength, this.length)
8129
8130 var val = this[offset]
8131 var mul = 1
8132 var i = 0
8133 while (++i < byteLength && (mul *= 0x100)) {
8134 val += this[offset + i] * mul
8135 }
8136
8137 return val
8138}
8139
8140Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
8141 offset = offset | 0
8142 byteLength = byteLength | 0
8143 if (!noAssert) {
8144 checkOffset(offset, byteLength, this.length)
8145 }
8146
8147 var val = this[offset + --byteLength]
8148 var mul = 1
8149 while (byteLength > 0 && (mul *= 0x100)) {
8150 val += this[offset + --byteLength] * mul
8151 }
8152
8153 return val
8154}
8155
8156Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
8157 if (!noAssert) checkOffset(offset, 1, this.length)
8158 return this[offset]
8159}
8160
8161Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
8162 if (!noAssert) checkOffset(offset, 2, this.length)
8163 return this[offset] | (this[offset + 1] << 8)
8164}
8165
8166Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
8167 if (!noAssert) checkOffset(offset, 2, this.length)
8168 return (this[offset] << 8) | this[offset + 1]
8169}
8170
8171Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
8172 if (!noAssert) checkOffset(offset, 4, this.length)
8173
8174 return ((this[offset]) |
8175 (this[offset + 1] << 8) |
8176 (this[offset + 2] << 16)) +
8177 (this[offset + 3] * 0x1000000)
8178}
8179
8180Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
8181 if (!noAssert) checkOffset(offset, 4, this.length)
8182
8183 return (this[offset] * 0x1000000) +
8184 ((this[offset + 1] << 16) |
8185 (this[offset + 2] << 8) |
8186 this[offset + 3])
8187}
8188
8189Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
8190 offset = offset | 0
8191 byteLength = byteLength | 0
8192 if (!noAssert) checkOffset(offset, byteLength, this.length)
8193
8194 var val = this[offset]
8195 var mul = 1
8196 var i = 0
8197 while (++i < byteLength && (mul *= 0x100)) {
8198 val += this[offset + i] * mul
8199 }
8200 mul *= 0x80
8201
8202 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
8203
8204 return val
8205}
8206
8207Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
8208 offset = offset | 0
8209 byteLength = byteLength | 0
8210 if (!noAssert) checkOffset(offset, byteLength, this.length)
8211
8212 var i = byteLength
8213 var mul = 1
8214 var val = this[offset + --i]
8215 while (i > 0 && (mul *= 0x100)) {
8216 val += this[offset + --i] * mul
8217 }
8218 mul *= 0x80
8219
8220 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
8221
8222 return val
8223}
8224
8225Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
8226 if (!noAssert) checkOffset(offset, 1, this.length)
8227 if (!(this[offset] & 0x80)) return (this[offset])
8228 return ((0xff - this[offset] + 1) * -1)
8229}
8230
8231Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
8232 if (!noAssert) checkOffset(offset, 2, this.length)
8233 var val = this[offset] | (this[offset + 1] << 8)
8234 return (val & 0x8000) ? val | 0xFFFF0000 : val
8235}
8236
8237Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
8238 if (!noAssert) checkOffset(offset, 2, this.length)
8239 var val = this[offset + 1] | (this[offset] << 8)
8240 return (val & 0x8000) ? val | 0xFFFF0000 : val
8241}
8242
8243Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
8244 if (!noAssert) checkOffset(offset, 4, this.length)
8245
8246 return (this[offset]) |
8247 (this[offset + 1] << 8) |
8248 (this[offset + 2] << 16) |
8249 (this[offset + 3] << 24)
8250}
8251
8252Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
8253 if (!noAssert) checkOffset(offset, 4, this.length)
8254
8255 return (this[offset] << 24) |
8256 (this[offset + 1] << 16) |
8257 (this[offset + 2] << 8) |
8258 (this[offset + 3])
8259}
8260
8261Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
8262 if (!noAssert) checkOffset(offset, 4, this.length)
8263 return ieee754.read(this, offset, true, 23, 4)
8264}
8265
8266Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
8267 if (!noAssert) checkOffset(offset, 4, this.length)
8268 return ieee754.read(this, offset, false, 23, 4)
8269}
8270
8271Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
8272 if (!noAssert) checkOffset(offset, 8, this.length)
8273 return ieee754.read(this, offset, true, 52, 8)
8274}
8275
8276Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
8277 if (!noAssert) checkOffset(offset, 8, this.length)
8278 return ieee754.read(this, offset, false, 52, 8)
8279}
8280
8281function checkInt (buf, value, offset, ext, max, min) {
8282 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
8283 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
8284 if (offset + ext > buf.length) throw new RangeError('Index out of range')
8285}
8286
8287Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
8288 value = +value
8289 offset = offset | 0
8290 byteLength = byteLength | 0
8291 if (!noAssert) {
8292 var maxBytes = Math.pow(2, 8 * byteLength) - 1
8293 checkInt(this, value, offset, byteLength, maxBytes, 0)
8294 }
8295
8296 var mul = 1
8297 var i = 0
8298 this[offset] = value & 0xFF
8299 while (++i < byteLength && (mul *= 0x100)) {
8300 this[offset + i] = (value / mul) & 0xFF
8301 }
8302
8303 return offset + byteLength
8304}
8305
8306Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
8307 value = +value
8308 offset = offset | 0
8309 byteLength = byteLength | 0
8310 if (!noAssert) {
8311 var maxBytes = Math.pow(2, 8 * byteLength) - 1
8312 checkInt(this, value, offset, byteLength, maxBytes, 0)
8313 }
8314
8315 var i = byteLength - 1
8316 var mul = 1
8317 this[offset + i] = value & 0xFF
8318 while (--i >= 0 && (mul *= 0x100)) {
8319 this[offset + i] = (value / mul) & 0xFF
8320 }
8321
8322 return offset + byteLength
8323}
8324
8325Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
8326 value = +value
8327 offset = offset | 0
8328 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
8329 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
8330 this[offset] = (value & 0xff)
8331 return offset + 1
8332}
8333
8334function objectWriteUInt16 (buf, value, offset, littleEndian) {
8335 if (value < 0) value = 0xffff + value + 1
8336 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
8337 buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
8338 (littleEndian ? i : 1 - i) * 8
8339 }
8340}
8341
8342Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
8343 value = +value
8344 offset = offset | 0
8345 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
8346 if (Buffer.TYPED_ARRAY_SUPPORT) {
8347 this[offset] = (value & 0xff)
8348 this[offset + 1] = (value >>> 8)
8349 } else {
8350 objectWriteUInt16(this, value, offset, true)
8351 }
8352 return offset + 2
8353}
8354
8355Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
8356 value = +value
8357 offset = offset | 0
8358 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
8359 if (Buffer.TYPED_ARRAY_SUPPORT) {
8360 this[offset] = (value >>> 8)
8361 this[offset + 1] = (value & 0xff)
8362 } else {
8363 objectWriteUInt16(this, value, offset, false)
8364 }
8365 return offset + 2
8366}
8367
8368function objectWriteUInt32 (buf, value, offset, littleEndian) {
8369 if (value < 0) value = 0xffffffff + value + 1
8370 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
8371 buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
8372 }
8373}
8374
8375Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
8376 value = +value
8377 offset = offset | 0
8378 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
8379 if (Buffer.TYPED_ARRAY_SUPPORT) {
8380 this[offset + 3] = (value >>> 24)
8381 this[offset + 2] = (value >>> 16)
8382 this[offset + 1] = (value >>> 8)
8383 this[offset] = (value & 0xff)
8384 } else {
8385 objectWriteUInt32(this, value, offset, true)
8386 }
8387 return offset + 4
8388}
8389
8390Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
8391 value = +value
8392 offset = offset | 0
8393 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
8394 if (Buffer.TYPED_ARRAY_SUPPORT) {
8395 this[offset] = (value >>> 24)
8396 this[offset + 1] = (value >>> 16)
8397 this[offset + 2] = (value >>> 8)
8398 this[offset + 3] = (value & 0xff)
8399 } else {
8400 objectWriteUInt32(this, value, offset, false)
8401 }
8402 return offset + 4
8403}
8404
8405Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
8406 value = +value
8407 offset = offset | 0
8408 if (!noAssert) {
8409 var limit = Math.pow(2, 8 * byteLength - 1)
8410
8411 checkInt(this, value, offset, byteLength, limit - 1, -limit)
8412 }
8413
8414 var i = 0
8415 var mul = 1
8416 var sub = 0
8417 this[offset] = value & 0xFF
8418 while (++i < byteLength && (mul *= 0x100)) {
8419 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
8420 sub = 1
8421 }
8422 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
8423 }
8424
8425 return offset + byteLength
8426}
8427
8428Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
8429 value = +value
8430 offset = offset | 0
8431 if (!noAssert) {
8432 var limit = Math.pow(2, 8 * byteLength - 1)
8433
8434 checkInt(this, value, offset, byteLength, limit - 1, -limit)
8435 }
8436
8437 var i = byteLength - 1
8438 var mul = 1
8439 var sub = 0
8440 this[offset + i] = value & 0xFF
8441 while (--i >= 0 && (mul *= 0x100)) {
8442 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
8443 sub = 1
8444 }
8445 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
8446 }
8447
8448 return offset + byteLength
8449}
8450
8451Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
8452 value = +value
8453 offset = offset | 0
8454 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
8455 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
8456 if (value < 0) value = 0xff + value + 1
8457 this[offset] = (value & 0xff)
8458 return offset + 1
8459}
8460
8461Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
8462 value = +value
8463 offset = offset | 0
8464 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
8465 if (Buffer.TYPED_ARRAY_SUPPORT) {
8466 this[offset] = (value & 0xff)
8467 this[offset + 1] = (value >>> 8)
8468 } else {
8469 objectWriteUInt16(this, value, offset, true)
8470 }
8471 return offset + 2
8472}
8473
8474Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
8475 value = +value
8476 offset = offset | 0
8477 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
8478 if (Buffer.TYPED_ARRAY_SUPPORT) {
8479 this[offset] = (value >>> 8)
8480 this[offset + 1] = (value & 0xff)
8481 } else {
8482 objectWriteUInt16(this, value, offset, false)
8483 }
8484 return offset + 2
8485}
8486
8487Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
8488 value = +value
8489 offset = offset | 0
8490 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
8491 if (Buffer.TYPED_ARRAY_SUPPORT) {
8492 this[offset] = (value & 0xff)
8493 this[offset + 1] = (value >>> 8)
8494 this[offset + 2] = (value >>> 16)
8495 this[offset + 3] = (value >>> 24)
8496 } else {
8497 objectWriteUInt32(this, value, offset, true)
8498 }
8499 return offset + 4
8500}
8501
8502Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
8503 value = +value
8504 offset = offset | 0
8505 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
8506 if (value < 0) value = 0xffffffff + value + 1
8507 if (Buffer.TYPED_ARRAY_SUPPORT) {
8508 this[offset] = (value >>> 24)
8509 this[offset + 1] = (value >>> 16)
8510 this[offset + 2] = (value >>> 8)
8511 this[offset + 3] = (value & 0xff)
8512 } else {
8513 objectWriteUInt32(this, value, offset, false)
8514 }
8515 return offset + 4
8516}
8517
8518function checkIEEE754 (buf, value, offset, ext, max, min) {
8519 if (offset + ext > buf.length) throw new RangeError('Index out of range')
8520 if (offset < 0) throw new RangeError('Index out of range')
8521}
8522
8523function writeFloat (buf, value, offset, littleEndian, noAssert) {
8524 if (!noAssert) {
8525 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
8526 }
8527 ieee754.write(buf, value, offset, littleEndian, 23, 4)
8528 return offset + 4
8529}
8530
8531Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
8532 return writeFloat(this, value, offset, true, noAssert)
8533}
8534
8535Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
8536 return writeFloat(this, value, offset, false, noAssert)
8537}
8538
8539function writeDouble (buf, value, offset, littleEndian, noAssert) {
8540 if (!noAssert) {
8541 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
8542 }
8543 ieee754.write(buf, value, offset, littleEndian, 52, 8)
8544 return offset + 8
8545}
8546
8547Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
8548 return writeDouble(this, value, offset, true, noAssert)
8549}
8550
8551Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
8552 return writeDouble(this, value, offset, false, noAssert)
8553}
8554
8555// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
8556Buffer.prototype.copy = function copy (target, targetStart, start, end) {
8557 if (!start) start = 0
8558 if (!end && end !== 0) end = this.length
8559 if (targetStart >= target.length) targetStart = target.length
8560 if (!targetStart) targetStart = 0
8561 if (end > 0 && end < start) end = start
8562
8563 // Copy 0 bytes; we're done
8564 if (end === start) return 0
8565 if (target.length === 0 || this.length === 0) return 0
8566
8567 // Fatal error conditions
8568 if (targetStart < 0) {
8569 throw new RangeError('targetStart out of bounds')
8570 }
8571 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
8572 if (end < 0) throw new RangeError('sourceEnd out of bounds')
8573
8574 // Are we oob?
8575 if (end > this.length) end = this.length
8576 if (target.length - targetStart < end - start) {
8577 end = target.length - targetStart + start
8578 }
8579
8580 var len = end - start
8581 var i
8582
8583 if (this === target && start < targetStart && targetStart < end) {
8584 // descending copy from end
8585 for (i = len - 1; i >= 0; --i) {
8586 target[i + targetStart] = this[i + start]
8587 }
8588 } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
8589 // ascending copy from start
8590 for (i = 0; i < len; ++i) {
8591 target[i + targetStart] = this[i + start]
8592 }
8593 } else {
8594 Uint8Array.prototype.set.call(
8595 target,
8596 this.subarray(start, start + len),
8597 targetStart
8598 )
8599 }
8600
8601 return len
8602}
8603
8604// Usage:
8605// buffer.fill(number[, offset[, end]])
8606// buffer.fill(buffer[, offset[, end]])
8607// buffer.fill(string[, offset[, end]][, encoding])
8608Buffer.prototype.fill = function fill (val, start, end, encoding) {
8609 // Handle string cases:
8610 if (typeof val === 'string') {
8611 if (typeof start === 'string') {
8612 encoding = start
8613 start = 0
8614 end = this.length
8615 } else if (typeof end === 'string') {
8616 encoding = end
8617 end = this.length
8618 }
8619 if (val.length === 1) {
8620 var code = val.charCodeAt(0)
8621 if (code < 256) {
8622 val = code
8623 }
8624 }
8625 if (encoding !== undefined && typeof encoding !== 'string') {
8626 throw new TypeError('encoding must be a string')
8627 }
8628 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
8629 throw new TypeError('Unknown encoding: ' + encoding)
8630 }
8631 } else if (typeof val === 'number') {
8632 val = val & 255
8633 }
8634
8635 // Invalid ranges are not set to a default, so can range check early.
8636 if (start < 0 || this.length < start || this.length < end) {
8637 throw new RangeError('Out of range index')
8638 }
8639
8640 if (end <= start) {
8641 return this
8642 }
8643
8644 start = start >>> 0
8645 end = end === undefined ? this.length : end >>> 0
8646
8647 if (!val) val = 0
8648
8649 var i
8650 if (typeof val === 'number') {
8651 for (i = start; i < end; ++i) {
8652 this[i] = val
8653 }
8654 } else {
8655 var bytes = Buffer.isBuffer(val)
8656 ? val
8657 : utf8ToBytes(new Buffer(val, encoding).toString())
8658 var len = bytes.length
8659 for (i = 0; i < end - start; ++i) {
8660 this[i + start] = bytes[i % len]
8661 }
8662 }
8663
8664 return this
8665}
8666
8667// HELPER FUNCTIONS
8668// ================
8669
8670var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
8671
8672function base64clean (str) {
8673 // Node strips out invalid characters like \n and \t from the string, base64-js does not
8674 str = stringtrim(str).replace(INVALID_BASE64_RE, '')
8675 // Node converts strings with length < 2 to ''
8676 if (str.length < 2) return ''
8677 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
8678 while (str.length % 4 !== 0) {
8679 str = str + '='
8680 }
8681 return str
8682}
8683
8684function stringtrim (str) {
8685 if (str.trim) return str.trim()
8686 return str.replace(/^\s+|\s+$/g, '')
8687}
8688
8689function toHex (n) {
8690 if (n < 16) return '0' + n.toString(16)
8691 return n.toString(16)
8692}
8693
8694function utf8ToBytes (string, units) {
8695 units = units || Infinity
8696 var codePoint
8697 var length = string.length
8698 var leadSurrogate = null
8699 var bytes = []
8700
8701 for (var i = 0; i < length; ++i) {
8702 codePoint = string.charCodeAt(i)
8703
8704 // is surrogate component
8705 if (codePoint > 0xD7FF && codePoint < 0xE000) {
8706 // last char was a lead
8707 if (!leadSurrogate) {
8708 // no lead yet
8709 if (codePoint > 0xDBFF) {
8710 // unexpected trail
8711 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
8712 continue
8713 } else if (i + 1 === length) {
8714 // unpaired lead
8715 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
8716 continue
8717 }
8718
8719 // valid lead
8720 leadSurrogate = codePoint
8721
8722 continue
8723 }
8724
8725 // 2 leads in a row
8726 if (codePoint < 0xDC00) {
8727 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
8728 leadSurrogate = codePoint
8729 continue
8730 }
8731
8732 // valid surrogate pair
8733 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
8734 } else if (leadSurrogate) {
8735 // valid bmp char, but last char was a lead
8736 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
8737 }
8738
8739 leadSurrogate = null
8740
8741 // encode utf8
8742 if (codePoint < 0x80) {
8743 if ((units -= 1) < 0) break
8744 bytes.push(codePoint)
8745 } else if (codePoint < 0x800) {
8746 if ((units -= 2) < 0) break
8747 bytes.push(
8748 codePoint >> 0x6 | 0xC0,
8749 codePoint & 0x3F | 0x80
8750 )
8751 } else if (codePoint < 0x10000) {
8752 if ((units -= 3) < 0) break
8753 bytes.push(
8754 codePoint >> 0xC | 0xE0,
8755 codePoint >> 0x6 & 0x3F | 0x80,
8756 codePoint & 0x3F | 0x80
8757 )
8758 } else if (codePoint < 0x110000) {
8759 if ((units -= 4) < 0) break
8760 bytes.push(
8761 codePoint >> 0x12 | 0xF0,
8762 codePoint >> 0xC & 0x3F | 0x80,
8763 codePoint >> 0x6 & 0x3F | 0x80,
8764 codePoint & 0x3F | 0x80
8765 )
8766 } else {
8767 throw new Error('Invalid code point')
8768 }
8769 }
8770
8771 return bytes
8772}
8773
8774function asciiToBytes (str) {
8775 var byteArray = []
8776 for (var i = 0; i < str.length; ++i) {
8777 // Node's code seems to be doing this and not & 0x7F..
8778 byteArray.push(str.charCodeAt(i) & 0xFF)
8779 }
8780 return byteArray
8781}
8782
8783function utf16leToBytes (str, units) {
8784 var c, hi, lo
8785 var byteArray = []
8786 for (var i = 0; i < str.length; ++i) {
8787 if ((units -= 2) < 0) break
8788
8789 c = str.charCodeAt(i)
8790 hi = c >> 8
8791 lo = c % 256
8792 byteArray.push(lo)
8793 byteArray.push(hi)
8794 }
8795
8796 return byteArray
8797}
8798
8799function base64ToBytes (str) {
8800 return base64.toByteArray(base64clean(str))
8801}
8802
8803function blitBuffer (src, dst, offset, length) {
8804 for (var i = 0; i < length; ++i) {
8805 if ((i + offset >= dst.length) || (i >= src.length)) break
8806 dst[i + offset] = src[i]
8807 }
8808 return i
8809}
8810
8811function isnan (val) {
8812 return val !== val // eslint-disable-line no-self-compare
8813}
8814
8815}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
8816},{"base64-js":39,"ieee754":50,"isarray":53}],45:[function(require,module,exports){
8817(function (Buffer){
8818// Copyright Joyent, Inc. and other Node contributors.
8819//
8820// Permission is hereby granted, free of charge, to any person obtaining a
8821// copy of this software and associated documentation files (the
8822// "Software"), to deal in the Software without restriction, including
8823// without limitation the rights to use, copy, modify, merge, publish,
8824// distribute, sublicense, and/or sell copies of the Software, and to permit
8825// persons to whom the Software is furnished to do so, subject to the
8826// following conditions:
8827//
8828// The above copyright notice and this permission notice shall be included
8829// in all copies or substantial portions of the Software.
8830//
8831// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
8832// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
8833// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
8834// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
8835// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
8836// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
8837// USE OR OTHER DEALINGS IN THE SOFTWARE.
8838
8839// NOTE: These type checking functions intentionally don't use `instanceof`
8840// because it is fragile and can be easily faked with `Object.create()`.
8841
8842function isArray(arg) {
8843 if (Array.isArray) {
8844 return Array.isArray(arg);
8845 }
8846 return objectToString(arg) === '[object Array]';
8847}
8848exports.isArray = isArray;
8849
8850function isBoolean(arg) {
8851 return typeof arg === 'boolean';
8852}
8853exports.isBoolean = isBoolean;
8854
8855function isNull(arg) {
8856 return arg === null;
8857}
8858exports.isNull = isNull;
8859
8860function isNullOrUndefined(arg) {
8861 return arg == null;
8862}
8863exports.isNullOrUndefined = isNullOrUndefined;
8864
8865function isNumber(arg) {
8866 return typeof arg === 'number';
8867}
8868exports.isNumber = isNumber;
8869
8870function isString(arg) {
8871 return typeof arg === 'string';
8872}
8873exports.isString = isString;
8874
8875function isSymbol(arg) {
8876 return typeof arg === 'symbol';
8877}
8878exports.isSymbol = isSymbol;
8879
8880function isUndefined(arg) {
8881 return arg === void 0;
8882}
8883exports.isUndefined = isUndefined;
8884
8885function isRegExp(re) {
8886 return objectToString(re) === '[object RegExp]';
8887}
8888exports.isRegExp = isRegExp;
8889
8890function isObject(arg) {
8891 return typeof arg === 'object' && arg !== null;
8892}
8893exports.isObject = isObject;
8894
8895function isDate(d) {
8896 return objectToString(d) === '[object Date]';
8897}
8898exports.isDate = isDate;
8899
8900function isError(e) {
8901 return (objectToString(e) === '[object Error]' || e instanceof Error);
8902}
8903exports.isError = isError;
8904
8905function isFunction(arg) {
8906 return typeof arg === 'function';
8907}
8908exports.isFunction = isFunction;
8909
8910function isPrimitive(arg) {
8911 return arg === null ||
8912 typeof arg === 'boolean' ||
8913 typeof arg === 'number' ||
8914 typeof arg === 'string' ||
8915 typeof arg === 'symbol' || // ES6 symbol
8916 typeof arg === 'undefined';
8917}
8918exports.isPrimitive = isPrimitive;
8919
8920exports.isBuffer = Buffer.isBuffer;
8921
8922function objectToString(o) {
8923 return Object.prototype.toString.call(o);
8924}
8925
8926}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
8927},{"../../is-buffer/index.js":52}],46:[function(require,module,exports){
8928/* See LICENSE file for terms of use */
8929
8930/*
8931 * Text diff implementation.
8932 *
8933 * This library supports the following APIS:
8934 * JsDiff.diffChars: Character by character diff
8935 * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
8936 * JsDiff.diffLines: Line based diff
8937 *
8938 * JsDiff.diffCss: Diff targeted at CSS content
8939 *
8940 * These methods are based on the implementation proposed in
8941 * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
8942 * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
8943 */
8944(function(global, undefined) {
8945 var objectPrototypeToString = Object.prototype.toString;
8946
8947 /*istanbul ignore next*/
8948 function map(arr, mapper, that) {
8949 if (Array.prototype.map) {
8950 return Array.prototype.map.call(arr, mapper, that);
8951 }
8952
8953 var other = new Array(arr.length);
8954
8955 for (var i = 0, n = arr.length; i < n; i++) {
8956 other[i] = mapper.call(that, arr[i], i, arr);
8957 }
8958 return other;
8959 }
8960 function clonePath(path) {
8961 return { newPos: path.newPos, components: path.components.slice(0) };
8962 }
8963 function removeEmpty(array) {
8964 var ret = [];
8965 for (var i = 0; i < array.length; i++) {
8966 if (array[i]) {
8967 ret.push(array[i]);
8968 }
8969 }
8970 return ret;
8971 }
8972 function escapeHTML(s) {
8973 var n = s;
8974 n = n.replace(/&/g, '&amp;');
8975 n = n.replace(/</g, '&lt;');
8976 n = n.replace(/>/g, '&gt;');
8977 n = n.replace(/"/g, '&quot;');
8978
8979 return n;
8980 }
8981
8982 // This function handles the presence of circular references by bailing out when encountering an
8983 // object that is already on the "stack" of items being processed.
8984 function canonicalize(obj, stack, replacementStack) {
8985 stack = stack || [];
8986 replacementStack = replacementStack || [];
8987
8988 var i;
8989
8990 for (i = 0; i < stack.length; i += 1) {
8991 if (stack[i] === obj) {
8992 return replacementStack[i];
8993 }
8994 }
8995
8996 var canonicalizedObj;
8997
8998 if ('[object Array]' === objectPrototypeToString.call(obj)) {
8999 stack.push(obj);
9000 canonicalizedObj = new Array(obj.length);
9001 replacementStack.push(canonicalizedObj);
9002 for (i = 0; i < obj.length; i += 1) {
9003 canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack);
9004 }
9005 stack.pop();
9006 replacementStack.pop();
9007 } else if (typeof obj === 'object' && obj !== null) {
9008 stack.push(obj);
9009 canonicalizedObj = {};
9010 replacementStack.push(canonicalizedObj);
9011 var sortedKeys = [],
9012 key;
9013 for (key in obj) {
9014 sortedKeys.push(key);
9015 }
9016 sortedKeys.sort();
9017 for (i = 0; i < sortedKeys.length; i += 1) {
9018 key = sortedKeys[i];
9019 canonicalizedObj[key] = canonicalize(obj[key], stack, replacementStack);
9020 }
9021 stack.pop();
9022 replacementStack.pop();
9023 } else {
9024 canonicalizedObj = obj;
9025 }
9026 return canonicalizedObj;
9027 }
9028
9029 function buildValues(components, newString, oldString, useLongestToken) {
9030 var componentPos = 0,
9031 componentLen = components.length,
9032 newPos = 0,
9033 oldPos = 0;
9034
9035 for (; componentPos < componentLen; componentPos++) {
9036 var component = components[componentPos];
9037 if (!component.removed) {
9038 if (!component.added && useLongestToken) {
9039 var value = newString.slice(newPos, newPos + component.count);
9040 value = map(value, function(value, i) {
9041 var oldValue = oldString[oldPos + i];
9042 return oldValue.length > value.length ? oldValue : value;
9043 });
9044
9045 component.value = value.join('');
9046 } else {
9047 component.value = newString.slice(newPos, newPos + component.count).join('');
9048 }
9049 newPos += component.count;
9050
9051 // Common case
9052 if (!component.added) {
9053 oldPos += component.count;
9054 }
9055 } else {
9056 component.value = oldString.slice(oldPos, oldPos + component.count).join('');
9057 oldPos += component.count;
9058
9059 // Reverse add and remove so removes are output first to match common convention
9060 // The diffing algorithm is tied to add then remove output and this is the simplest
9061 // route to get the desired output with minimal overhead.
9062 if (componentPos && components[componentPos - 1].added) {
9063 var tmp = components[componentPos - 1];
9064 components[componentPos - 1] = components[componentPos];
9065 components[componentPos] = tmp;
9066 }
9067 }
9068 }
9069
9070 return components;
9071 }
9072
9073 function Diff(ignoreWhitespace) {
9074 this.ignoreWhitespace = ignoreWhitespace;
9075 }
9076 Diff.prototype = {
9077 diff: function(oldString, newString, callback) {
9078 var self = this;
9079
9080 function done(value) {
9081 if (callback) {
9082 setTimeout(function() { callback(undefined, value); }, 0);
9083 return true;
9084 } else {
9085 return value;
9086 }
9087 }
9088
9089 // Handle the identity case (this is due to unrolling editLength == 0
9090 if (newString === oldString) {
9091 return done([{ value: newString }]);
9092 }
9093 if (!newString) {
9094 return done([{ value: oldString, removed: true }]);
9095 }
9096 if (!oldString) {
9097 return done([{ value: newString, added: true }]);
9098 }
9099
9100 newString = this.tokenize(newString);
9101 oldString = this.tokenize(oldString);
9102
9103 var newLen = newString.length, oldLen = oldString.length;
9104 var editLength = 1;
9105 var maxEditLength = newLen + oldLen;
9106 var bestPath = [{ newPos: -1, components: [] }];
9107
9108 // Seed editLength = 0, i.e. the content starts with the same values
9109 var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
9110 if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
9111 // Identity per the equality and tokenizer
9112 return done([{value: newString.join('')}]);
9113 }
9114
9115 // Main worker method. checks all permutations of a given edit length for acceptance.
9116 function execEditLength() {
9117 for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
9118 var basePath;
9119 var addPath = bestPath[diagonalPath - 1],
9120 removePath = bestPath[diagonalPath + 1],
9121 oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
9122 if (addPath) {
9123 // No one else is going to attempt to use this value, clear it
9124 bestPath[diagonalPath - 1] = undefined;
9125 }
9126
9127 var canAdd = addPath && addPath.newPos + 1 < newLen,
9128 canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
9129 if (!canAdd && !canRemove) {
9130 // If this path is a terminal then prune
9131 bestPath[diagonalPath] = undefined;
9132 continue;
9133 }
9134
9135 // Select the diagonal that we want to branch from. We select the prior
9136 // path whose position in the new string is the farthest from the origin
9137 // and does not pass the bounds of the diff graph
9138 if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
9139 basePath = clonePath(removePath);
9140 self.pushComponent(basePath.components, undefined, true);
9141 } else {
9142 basePath = addPath; // No need to clone, we've pulled it from the list
9143 basePath.newPos++;
9144 self.pushComponent(basePath.components, true, undefined);
9145 }
9146
9147 oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath);
9148
9149 // If we have hit the end of both strings, then we are done
9150 if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
9151 return done(buildValues(basePath.components, newString, oldString, self.useLongestToken));
9152 } else {
9153 // Otherwise track this path as a potential candidate and continue.
9154 bestPath[diagonalPath] = basePath;
9155 }
9156 }
9157
9158 editLength++;
9159 }
9160
9161 // Performs the length of edit iteration. Is a bit fugly as this has to support the
9162 // sync and async mode which is never fun. Loops over execEditLength until a value
9163 // is produced.
9164 if (callback) {
9165 (function exec() {
9166 setTimeout(function() {
9167 // This should not happen, but we want to be safe.
9168 /*istanbul ignore next */
9169 if (editLength > maxEditLength) {
9170 return callback();
9171 }
9172
9173 if (!execEditLength()) {
9174 exec();
9175 }
9176 }, 0);
9177 }());
9178 } else {
9179 while (editLength <= maxEditLength) {
9180 var ret = execEditLength();
9181 if (ret) {
9182 return ret;
9183 }
9184 }
9185 }
9186 },
9187
9188 pushComponent: function(components, added, removed) {
9189 var last = components[components.length - 1];
9190 if (last && last.added === added && last.removed === removed) {
9191 // We need to clone here as the component clone operation is just
9192 // as shallow array clone
9193 components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
9194 } else {
9195 components.push({count: 1, added: added, removed: removed });
9196 }
9197 },
9198 extractCommon: function(basePath, newString, oldString, diagonalPath) {
9199 var newLen = newString.length,
9200 oldLen = oldString.length,
9201 newPos = basePath.newPos,
9202 oldPos = newPos - diagonalPath,
9203
9204 commonCount = 0;
9205 while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
9206 newPos++;
9207 oldPos++;
9208 commonCount++;
9209 }
9210
9211 if (commonCount) {
9212 basePath.components.push({count: commonCount});
9213 }
9214
9215 basePath.newPos = newPos;
9216 return oldPos;
9217 },
9218
9219 equals: function(left, right) {
9220 var reWhitespace = /\S/;
9221 return left === right || (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right));
9222 },
9223 tokenize: function(value) {
9224 return value.split('');
9225 }
9226 };
9227
9228 var CharDiff = new Diff();
9229
9230 var WordDiff = new Diff(true);
9231 var WordWithSpaceDiff = new Diff();
9232 WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) {
9233 return removeEmpty(value.split(/(\s+|\b)/));
9234 };
9235
9236 var CssDiff = new Diff(true);
9237 CssDiff.tokenize = function(value) {
9238 return removeEmpty(value.split(/([{}:;,]|\s+)/));
9239 };
9240
9241 var LineDiff = new Diff();
9242
9243 var TrimmedLineDiff = new Diff();
9244 TrimmedLineDiff.ignoreTrim = true;
9245
9246 LineDiff.tokenize = TrimmedLineDiff.tokenize = function(value) {
9247 var retLines = [],
9248 lines = value.split(/^/m);
9249 for (var i = 0; i < lines.length; i++) {
9250 var line = lines[i],
9251 lastLine = lines[i - 1],
9252 lastLineLastChar = lastLine && lastLine[lastLine.length - 1];
9253
9254 // Merge lines that may contain windows new lines
9255 if (line === '\n' && lastLineLastChar === '\r') {
9256 retLines[retLines.length - 1] = retLines[retLines.length - 1].slice(0, -1) + '\r\n';
9257 } else {
9258 if (this.ignoreTrim) {
9259 line = line.trim();
9260 // add a newline unless this is the last line.
9261 if (i < lines.length - 1) {
9262 line += '\n';
9263 }
9264 }
9265 retLines.push(line);
9266 }
9267 }
9268
9269 return retLines;
9270 };
9271
9272 var PatchDiff = new Diff();
9273 PatchDiff.tokenize = function(value) {
9274 var ret = [],
9275 linesAndNewlines = value.split(/(\n|\r\n)/);
9276
9277 // Ignore the final empty token that occurs if the string ends with a new line
9278 if (!linesAndNewlines[linesAndNewlines.length - 1]) {
9279 linesAndNewlines.pop();
9280 }
9281
9282 // Merge the content and line separators into single tokens
9283 for (var i = 0; i < linesAndNewlines.length; i++) {
9284 var line = linesAndNewlines[i];
9285
9286 if (i % 2) {
9287 ret[ret.length - 1] += line;
9288 } else {
9289 ret.push(line);
9290 }
9291 }
9292 return ret;
9293 };
9294
9295 var SentenceDiff = new Diff();
9296 SentenceDiff.tokenize = function(value) {
9297 return removeEmpty(value.split(/(\S.+?[.!?])(?=\s+|$)/));
9298 };
9299
9300 var JsonDiff = new Diff();
9301 // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
9302 // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
9303 JsonDiff.useLongestToken = true;
9304 JsonDiff.tokenize = LineDiff.tokenize;
9305 JsonDiff.equals = function(left, right) {
9306 return LineDiff.equals(left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
9307 };
9308
9309 var JsDiff = {
9310 Diff: Diff,
9311
9312 diffChars: function(oldStr, newStr, callback) { return CharDiff.diff(oldStr, newStr, callback); },
9313 diffWords: function(oldStr, newStr, callback) { return WordDiff.diff(oldStr, newStr, callback); },
9314 diffWordsWithSpace: function(oldStr, newStr, callback) { return WordWithSpaceDiff.diff(oldStr, newStr, callback); },
9315 diffLines: function(oldStr, newStr, callback) { return LineDiff.diff(oldStr, newStr, callback); },
9316 diffTrimmedLines: function(oldStr, newStr, callback) { return TrimmedLineDiff.diff(oldStr, newStr, callback); },
9317
9318 diffSentences: function(oldStr, newStr, callback) { return SentenceDiff.diff(oldStr, newStr, callback); },
9319
9320 diffCss: function(oldStr, newStr, callback) { return CssDiff.diff(oldStr, newStr, callback); },
9321 diffJson: function(oldObj, newObj, callback) {
9322 return JsonDiff.diff(
9323 typeof oldObj === 'string' ? oldObj : JSON.stringify(canonicalize(oldObj), undefined, ' '),
9324 typeof newObj === 'string' ? newObj : JSON.stringify(canonicalize(newObj), undefined, ' '),
9325 callback
9326 );
9327 },
9328
9329 createTwoFilesPatch: function(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader) {
9330 var ret = [];
9331
9332 if (oldFileName == newFileName) {
9333 ret.push('Index: ' + oldFileName);
9334 }
9335 ret.push('===================================================================');
9336 ret.push('--- ' + oldFileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader));
9337 ret.push('+++ ' + newFileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader));
9338
9339 var diff = PatchDiff.diff(oldStr, newStr);
9340 diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier
9341
9342 // Formats a given set of lines for printing as context lines in a patch
9343 function contextLines(lines) {
9344 return map(lines, function(entry) { return ' ' + entry; });
9345 }
9346
9347 // Outputs the no newline at end of file warning if needed
9348 function eofNL(curRange, i, current) {
9349 var last = diff[diff.length - 2],
9350 isLast = i === diff.length - 2,
9351 isLastOfType = i === diff.length - 3 && current.added !== last.added;
9352
9353 // Figure out if this is the last line for the given file and missing NL
9354 if (!(/\n$/.test(current.value)) && (isLast || isLastOfType)) {
9355 curRange.push('\\ No newline at end of file');
9356 }
9357 }
9358
9359 var oldRangeStart = 0, newRangeStart = 0, curRange = [],
9360 oldLine = 1, newLine = 1;
9361 for (var i = 0; i < diff.length; i++) {
9362 var current = diff[i],
9363 lines = current.lines || current.value.replace(/\n$/, '').split('\n');
9364 current.lines = lines;
9365
9366 if (current.added || current.removed) {
9367 // If we have previous context, start with that
9368 if (!oldRangeStart) {
9369 var prev = diff[i - 1];
9370 oldRangeStart = oldLine;
9371 newRangeStart = newLine;
9372
9373 if (prev) {
9374 curRange = contextLines(prev.lines.slice(-4));
9375 oldRangeStart -= curRange.length;
9376 newRangeStart -= curRange.length;
9377 }
9378 }
9379
9380 // Output our changes
9381 curRange.push.apply(curRange, map(lines, function(entry) {
9382 return (current.added ? '+' : '-') + entry;
9383 }));
9384 eofNL(curRange, i, current);
9385
9386 // Track the updated file position
9387 if (current.added) {
9388 newLine += lines.length;
9389 } else {
9390 oldLine += lines.length;
9391 }
9392 } else {
9393 // Identical context lines. Track line changes
9394 if (oldRangeStart) {
9395 // Close out any changes that have been output (or join overlapping)
9396 if (lines.length <= 8 && i < diff.length - 2) {
9397 // Overlapping
9398 curRange.push.apply(curRange, contextLines(lines));
9399 } else {
9400 // end the range and output
9401 var contextSize = Math.min(lines.length, 4);
9402 ret.push(
9403 '@@ -' + oldRangeStart + ',' + (oldLine - oldRangeStart + contextSize)
9404 + ' +' + newRangeStart + ',' + (newLine - newRangeStart + contextSize)
9405 + ' @@');
9406 ret.push.apply(ret, curRange);
9407 ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
9408 if (lines.length <= 4) {
9409 eofNL(ret, i, current);
9410 }
9411
9412 oldRangeStart = 0;
9413 newRangeStart = 0;
9414 curRange = [];
9415 }
9416 }
9417 oldLine += lines.length;
9418 newLine += lines.length;
9419 }
9420 }
9421
9422 return ret.join('\n') + '\n';
9423 },
9424
9425 createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) {
9426 return JsDiff.createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader);
9427 },
9428
9429 applyPatch: function(oldStr, uniDiff) {
9430 var diffstr = uniDiff.split('\n'),
9431 hunks = [],
9432 i = 0,
9433 remEOFNL = false,
9434 addEOFNL = false;
9435
9436 // Skip to the first change hunk
9437 while (i < diffstr.length && !(/^@@/.test(diffstr[i]))) {
9438 i++;
9439 }
9440
9441 // Parse the unified diff
9442 for (; i < diffstr.length; i++) {
9443 if (diffstr[i][0] === '@') {
9444 var chnukHeader = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
9445 hunks.unshift({
9446 start: chnukHeader[3],
9447 oldlength: +chnukHeader[2],
9448 removed: [],
9449 newlength: chnukHeader[4],
9450 added: []
9451 });
9452 } else if (diffstr[i][0] === '+') {
9453 hunks[0].added.push(diffstr[i].substr(1));
9454 } else if (diffstr[i][0] === '-') {
9455 hunks[0].removed.push(diffstr[i].substr(1));
9456 } else if (diffstr[i][0] === ' ') {
9457 hunks[0].added.push(diffstr[i].substr(1));
9458 hunks[0].removed.push(diffstr[i].substr(1));
9459 } else if (diffstr[i][0] === '\\') {
9460 if (diffstr[i - 1][0] === '+') {
9461 remEOFNL = true;
9462 } else if (diffstr[i - 1][0] === '-') {
9463 addEOFNL = true;
9464 }
9465 }
9466 }
9467
9468 // Apply the diff to the input
9469 var lines = oldStr.split('\n');
9470 for (i = hunks.length - 1; i >= 0; i--) {
9471 var hunk = hunks[i];
9472 // Sanity check the input string. Bail if we don't match.
9473 for (var j = 0; j < hunk.oldlength; j++) {
9474 if (lines[hunk.start - 1 + j] !== hunk.removed[j]) {
9475 return false;
9476 }
9477 }
9478 Array.prototype.splice.apply(lines, [hunk.start - 1, hunk.oldlength].concat(hunk.added));
9479 }
9480
9481 // Handle EOFNL insertion/removal
9482 if (remEOFNL) {
9483 while (!lines[lines.length - 1]) {
9484 lines.pop();
9485 }
9486 } else if (addEOFNL) {
9487 lines.push('');
9488 }
9489 return lines.join('\n');
9490 },
9491
9492 convertChangesToXML: function(changes) {
9493 var ret = [];
9494 for (var i = 0; i < changes.length; i++) {
9495 var change = changes[i];
9496 if (change.added) {
9497 ret.push('<ins>');
9498 } else if (change.removed) {
9499 ret.push('<del>');
9500 }
9501
9502 ret.push(escapeHTML(change.value));
9503
9504 if (change.added) {
9505 ret.push('</ins>');
9506 } else if (change.removed) {
9507 ret.push('</del>');
9508 }
9509 }
9510 return ret.join('');
9511 },
9512
9513 // See: http://code.google.com/p/google-diff-match-patch/wiki/API
9514 convertChangesToDMP: function(changes) {
9515 var ret = [],
9516 change,
9517 operation;
9518 for (var i = 0; i < changes.length; i++) {
9519 change = changes[i];
9520 if (change.added) {
9521 operation = 1;
9522 } else if (change.removed) {
9523 operation = -1;
9524 } else {
9525 operation = 0;
9526 }
9527
9528 ret.push([operation, change.value]);
9529 }
9530 return ret;
9531 },
9532
9533 canonicalize: canonicalize
9534 };
9535
9536 /*istanbul ignore next */
9537 /*global module */
9538 if (typeof module !== 'undefined' && module.exports) {
9539 module.exports = JsDiff;
9540 } else if (false) {
9541 /*global define */
9542 define([], function() { return JsDiff; });
9543 } else if (typeof global.JsDiff === 'undefined') {
9544 global.JsDiff = JsDiff;
9545 }
9546}(this));
9547
9548},{}],47:[function(require,module,exports){
9549'use strict';
9550
9551var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
9552
9553module.exports = function (str) {
9554 if (typeof str !== 'string') {
9555 throw new TypeError('Expected a string');
9556 }
9557
9558 return str.replace(matchOperatorsRe, '\\$&');
9559};
9560
9561},{}],48:[function(require,module,exports){
9562// Copyright Joyent, Inc. and other Node contributors.
9563//
9564// Permission is hereby granted, free of charge, to any person obtaining a
9565// copy of this software and associated documentation files (the
9566// "Software"), to deal in the Software without restriction, including
9567// without limitation the rights to use, copy, modify, merge, publish,
9568// distribute, sublicense, and/or sell copies of the Software, and to permit
9569// persons to whom the Software is furnished to do so, subject to the
9570// following conditions:
9571//
9572// The above copyright notice and this permission notice shall be included
9573// in all copies or substantial portions of the Software.
9574//
9575// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
9576// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
9577// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
9578// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
9579// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
9580// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
9581// USE OR OTHER DEALINGS IN THE SOFTWARE.
9582
9583function EventEmitter() {
9584 this._events = this._events || {};
9585 this._maxListeners = this._maxListeners || undefined;
9586}
9587module.exports = EventEmitter;
9588
9589// Backwards-compat with node 0.10.x
9590EventEmitter.EventEmitter = EventEmitter;
9591
9592EventEmitter.prototype._events = undefined;
9593EventEmitter.prototype._maxListeners = undefined;
9594
9595// By default EventEmitters will print a warning if more than 10 listeners are
9596// added to it. This is a useful default which helps finding memory leaks.
9597EventEmitter.defaultMaxListeners = 10;
9598
9599// Obviously not all Emitters should be limited to 10. This function allows
9600// that to be increased. Set to zero for unlimited.
9601EventEmitter.prototype.setMaxListeners = function(n) {
9602 if (!isNumber(n) || n < 0 || isNaN(n))
9603 throw TypeError('n must be a positive number');
9604 this._maxListeners = n;
9605 return this;
9606};
9607
9608EventEmitter.prototype.emit = function(type) {
9609 var er, handler, len, args, i, listeners;
9610
9611 if (!this._events)
9612 this._events = {};
9613
9614 // If there is no 'error' event listener then throw.
9615 if (type === 'error') {
9616 if (!this._events.error ||
9617 (isObject(this._events.error) && !this._events.error.length)) {
9618 er = arguments[1];
9619 if (er instanceof Error) {
9620 throw er; // Unhandled 'error' event
9621 } else {
9622 // At least give some kind of context to the user
9623 var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
9624 err.context = er;
9625 throw err;
9626 }
9627 }
9628 }
9629
9630 handler = this._events[type];
9631
9632 if (isUndefined(handler))
9633 return false;
9634
9635 if (isFunction(handler)) {
9636 switch (arguments.length) {
9637 // fast cases
9638 case 1:
9639 handler.call(this);
9640 break;
9641 case 2:
9642 handler.call(this, arguments[1]);
9643 break;
9644 case 3:
9645 handler.call(this, arguments[1], arguments[2]);
9646 break;
9647 // slower
9648 default:
9649 args = Array.prototype.slice.call(arguments, 1);
9650 handler.apply(this, args);
9651 }
9652 } else if (isObject(handler)) {
9653 args = Array.prototype.slice.call(arguments, 1);
9654 listeners = handler.slice();
9655 len = listeners.length;
9656 for (i = 0; i < len; i++)
9657 listeners[i].apply(this, args);
9658 }
9659
9660 return true;
9661};
9662
9663EventEmitter.prototype.addListener = function(type, listener) {
9664 var m;
9665
9666 if (!isFunction(listener))
9667 throw TypeError('listener must be a function');
9668
9669 if (!this._events)
9670 this._events = {};
9671
9672 // To avoid recursion in the case that type === "newListener"! Before
9673 // adding it to the listeners, first emit "newListener".
9674 if (this._events.newListener)
9675 this.emit('newListener', type,
9676 isFunction(listener.listener) ?
9677 listener.listener : listener);
9678
9679 if (!this._events[type])
9680 // Optimize the case of one listener. Don't need the extra array object.
9681 this._events[type] = listener;
9682 else if (isObject(this._events[type]))
9683 // If we've already got an array, just append.
9684 this._events[type].push(listener);
9685 else
9686 // Adding the second element, need to change to array.
9687 this._events[type] = [this._events[type], listener];
9688
9689 // Check for listener leak
9690 if (isObject(this._events[type]) && !this._events[type].warned) {
9691 if (!isUndefined(this._maxListeners)) {
9692 m = this._maxListeners;
9693 } else {
9694 m = EventEmitter.defaultMaxListeners;
9695 }
9696
9697 if (m && m > 0 && this._events[type].length > m) {
9698 this._events[type].warned = true;
9699 console.error('(node) warning: possible EventEmitter memory ' +
9700 'leak detected. %d listeners added. ' +
9701 'Use emitter.setMaxListeners() to increase limit.',
9702 this._events[type].length);
9703 if (typeof console.trace === 'function') {
9704 // not supported in IE 10
9705 console.trace();
9706 }
9707 }
9708 }
9709
9710 return this;
9711};
9712
9713EventEmitter.prototype.on = EventEmitter.prototype.addListener;
9714
9715EventEmitter.prototype.once = function(type, listener) {
9716 if (!isFunction(listener))
9717 throw TypeError('listener must be a function');
9718
9719 var fired = false;
9720
9721 function g() {
9722 this.removeListener(type, g);
9723
9724 if (!fired) {
9725 fired = true;
9726 listener.apply(this, arguments);
9727 }
9728 }
9729
9730 g.listener = listener;
9731 this.on(type, g);
9732
9733 return this;
9734};
9735
9736// emits a 'removeListener' event iff the listener was removed
9737EventEmitter.prototype.removeListener = function(type, listener) {
9738 var list, position, length, i;
9739
9740 if (!isFunction(listener))
9741 throw TypeError('listener must be a function');
9742
9743 if (!this._events || !this._events[type])
9744 return this;
9745
9746 list = this._events[type];
9747 length = list.length;
9748 position = -1;
9749
9750 if (list === listener ||
9751 (isFunction(list.listener) && list.listener === listener)) {
9752 delete this._events[type];
9753 if (this._events.removeListener)
9754 this.emit('removeListener', type, listener);
9755
9756 } else if (isObject(list)) {
9757 for (i = length; i-- > 0;) {
9758 if (list[i] === listener ||
9759 (list[i].listener && list[i].listener === listener)) {
9760 position = i;
9761 break;
9762 }
9763 }
9764
9765 if (position < 0)
9766 return this;
9767
9768 if (list.length === 1) {
9769 list.length = 0;
9770 delete this._events[type];
9771 } else {
9772 list.splice(position, 1);
9773 }
9774
9775 if (this._events.removeListener)
9776 this.emit('removeListener', type, listener);
9777 }
9778
9779 return this;
9780};
9781
9782EventEmitter.prototype.removeAllListeners = function(type) {
9783 var key, listeners;
9784
9785 if (!this._events)
9786 return this;
9787
9788 // not listening for removeListener, no need to emit
9789 if (!this._events.removeListener) {
9790 if (arguments.length === 0)
9791 this._events = {};
9792 else if (this._events[type])
9793 delete this._events[type];
9794 return this;
9795 }
9796
9797 // emit removeListener for all listeners on all events
9798 if (arguments.length === 0) {
9799 for (key in this._events) {
9800 if (key === 'removeListener') continue;
9801 this.removeAllListeners(key);
9802 }
9803 this.removeAllListeners('removeListener');
9804 this._events = {};
9805 return this;
9806 }
9807
9808 listeners = this._events[type];
9809
9810 if (isFunction(listeners)) {
9811 this.removeListener(type, listeners);
9812 } else if (listeners) {
9813 // LIFO order
9814 while (listeners.length)
9815 this.removeListener(type, listeners[listeners.length - 1]);
9816 }
9817 delete this._events[type];
9818
9819 return this;
9820};
9821
9822EventEmitter.prototype.listeners = function(type) {
9823 var ret;
9824 if (!this._events || !this._events[type])
9825 ret = [];
9826 else if (isFunction(this._events[type]))
9827 ret = [this._events[type]];
9828 else
9829 ret = this._events[type].slice();
9830 return ret;
9831};
9832
9833EventEmitter.prototype.listenerCount = function(type) {
9834 if (this._events) {
9835 var evlistener = this._events[type];
9836
9837 if (isFunction(evlistener))
9838 return 1;
9839 else if (evlistener)
9840 return evlistener.length;
9841 }
9842 return 0;
9843};
9844
9845EventEmitter.listenerCount = function(emitter, type) {
9846 return emitter.listenerCount(type);
9847};
9848
9849function isFunction(arg) {
9850 return typeof arg === 'function';
9851}
9852
9853function isNumber(arg) {
9854 return typeof arg === 'number';
9855}
9856
9857function isObject(arg) {
9858 return typeof arg === 'object' && arg !== null;
9859}
9860
9861function isUndefined(arg) {
9862 return arg === void 0;
9863}
9864
9865},{}],49:[function(require,module,exports){
9866(function (process){
9867// Growl - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)
9868
9869/**
9870 * Module dependencies.
9871 */
9872
9873var exec = require('child_process').exec
9874 , fs = require('fs')
9875 , path = require('path')
9876 , exists = fs.existsSync || path.existsSync
9877 , os = require('os')
9878 , quote = JSON.stringify
9879 , cmd;
9880
9881function which(name) {
9882 var paths = process.env.PATH.split(':');
9883 var loc;
9884
9885 for (var i = 0, len = paths.length; i < len; ++i) {
9886 loc = path.join(paths[i], name);
9887 if (exists(loc)) return loc;
9888 }
9889}
9890
9891switch(os.type()) {
9892 case 'Darwin':
9893 if (which('terminal-notifier')) {
9894 cmd = {
9895 type: "Darwin-NotificationCenter"
9896 , pkg: "terminal-notifier"
9897 , msg: '-message'
9898 , title: '-title'
9899 , subtitle: '-subtitle'
9900 , icon: '-appIcon'
9901 , sound: '-sound'
9902 , url: '-open'
9903 , priority: {
9904 cmd: '-execute'
9905 , range: []
9906 }
9907 };
9908 } else {
9909 cmd = {
9910 type: "Darwin-Growl"
9911 , pkg: "growlnotify"
9912 , msg: '-m'
9913 , sticky: '--sticky'
9914 , priority: {
9915 cmd: '--priority'
9916 , range: [
9917 -2
9918 , -1
9919 , 0
9920 , 1
9921 , 2
9922 , "Very Low"
9923 , "Moderate"
9924 , "Normal"
9925 , "High"
9926 , "Emergency"
9927 ]
9928 }
9929 };
9930 }
9931 break;
9932 case 'Linux':
9933 if (which('growl')) {
9934 cmd = {
9935 type: "Linux-Growl"
9936 , pkg: "growl"
9937 , msg: '-m'
9938 , title: '-title'
9939 , subtitle: '-subtitle'
9940 , host: {
9941 cmd: '-H'
9942 , hostname: '192.168.33.1'
9943 }
9944 };
9945 } else {
9946 cmd = {
9947 type: "Linux"
9948 , pkg: "notify-send"
9949 , msg: ''
9950 , sticky: '-t 0'
9951 , icon: '-i'
9952 , priority: {
9953 cmd: '-u'
9954 , range: [
9955 "low"
9956 , "normal"
9957 , "critical"
9958 ]
9959 }
9960 };
9961 }
9962 break;
9963 case 'Windows_NT':
9964 cmd = {
9965 type: "Windows"
9966 , pkg: "growlnotify"
9967 , msg: ''
9968 , sticky: '/s:true'
9969 , title: '/t:'
9970 , icon: '/i:'
9971 , url: '/cu:'
9972 , priority: {
9973 cmd: '/p:'
9974 , range: [
9975 -2
9976 , -1
9977 , 0
9978 , 1
9979 , 2
9980 ]
9981 }
9982 };
9983 break;
9984}
9985
9986/**
9987 * Expose `growl`.
9988 */
9989
9990exports = module.exports = growl;
9991
9992/**
9993 * Node-growl version.
9994 */
9995
9996exports.version = '1.4.1'
9997
9998/**
9999 * Send growl notification _msg_ with _options_.
10000 *
10001 * Options:
10002 *
10003 * - title Notification title
10004 * - sticky Make the notification stick (defaults to false)
10005 * - priority Specify an int or named key (default is 0)
10006 * - name Application name (defaults to growlnotify)
10007 * - sound Sound efect ( in OSx defined in preferences -> sound -> effects) * works only in OSX > 10.8x
10008 * - image
10009 * - path to an icon sets --iconpath
10010 * - path to an image sets --image
10011 * - capitalized word sets --appIcon
10012 * - filename uses extname as --icon
10013 * - otherwise treated as --icon
10014 *
10015 * Examples:
10016 *
10017 * growl('New email')
10018 * growl('5 new emails', { title: 'Thunderbird' })
10019 * growl('5 new emails', { title: 'Thunderbird', sound: 'Purr' })
10020 * growl('Email sent', function(){
10021 * // ... notification sent
10022 * })
10023 *
10024 * @param {string} msg
10025 * @param {object} options
10026 * @param {function} fn
10027 * @api public
10028 */
10029
10030function growl(msg, options, fn) {
10031 var image
10032 , args
10033 , options = options || {}
10034 , fn = fn || function(){};
10035
10036 if (options.exec) {
10037 cmd = {
10038 type: "Custom"
10039 , pkg: options.exec
10040 , range: []
10041 };
10042 }
10043
10044 // noop
10045 if (!cmd) return fn(new Error('growl not supported on this platform'));
10046 args = [cmd.pkg];
10047
10048 // image
10049 if (image = options.image) {
10050 switch(cmd.type) {
10051 case 'Darwin-Growl':
10052 var flag, ext = path.extname(image).substr(1)
10053 flag = flag || ext == 'icns' && 'iconpath'
10054 flag = flag || /^[A-Z]/.test(image) && 'appIcon'
10055 flag = flag || /^png|gif|jpe?g$/.test(ext) && 'image'
10056 flag = flag || ext && (image = ext) && 'icon'
10057 flag = flag || 'icon'
10058 args.push('--' + flag, quote(image))
10059 break;
10060 case 'Darwin-NotificationCenter':
10061 args.push(cmd.icon, quote(image));
10062 break;
10063 case 'Linux':
10064 args.push(cmd.icon, quote(image));
10065 // libnotify defaults to sticky, set a hint for transient notifications
10066 if (!options.sticky) args.push('--hint=int:transient:1');
10067 break;
10068 case 'Windows':
10069 args.push(cmd.icon + quote(image));
10070 break;
10071 }
10072 }
10073
10074 // sticky
10075 if (options.sticky) args.push(cmd.sticky);
10076
10077 // priority
10078 if (options.priority) {
10079 var priority = options.priority + '';
10080 var checkindexOf = cmd.priority.range.indexOf(priority);
10081 if (~cmd.priority.range.indexOf(priority)) {
10082 args.push(cmd.priority, options.priority);
10083 }
10084 }
10085
10086 //sound
10087 if(options.sound && cmd.type === 'Darwin-NotificationCenter'){
10088 args.push(cmd.sound, options.sound)
10089 }
10090
10091 // name
10092 if (options.name && cmd.type === "Darwin-Growl") {
10093 args.push('--name', options.name);
10094 }
10095
10096 switch(cmd.type) {
10097 case 'Darwin-Growl':
10098 args.push(cmd.msg);
10099 args.push(quote(msg).replace(/\\n/g, '\n'));
10100 if (options.title) args.push(quote(options.title));
10101 break;
10102 case 'Darwin-NotificationCenter':
10103 args.push(cmd.msg);
10104 var stringifiedMsg = quote(msg);
10105 var escapedMsg = stringifiedMsg.replace(/\\n/g, '\n');
10106 args.push(escapedMsg);
10107 if (options.title) {
10108 args.push(cmd.title);
10109 args.push(quote(options.title));
10110 }
10111 if (options.subtitle) {
10112 args.push(cmd.subtitle);
10113 args.push(quote(options.subtitle));
10114 }
10115 if (options.url) {
10116 args.push(cmd.url);
10117 args.push(quote(options.url));
10118 }
10119 break;
10120 case 'Linux-Growl':
10121 args.push(cmd.msg);
10122 args.push(quote(msg).replace(/\\n/g, '\n'));
10123 if (options.title) args.push(quote(options.title));
10124 if (cmd.host) {
10125 args.push(cmd.host.cmd, cmd.host.hostname)
10126 }
10127 break;
10128 case 'Linux':
10129 if (options.title) {
10130 args.push(quote(options.title));
10131 args.push(cmd.msg);
10132 args.push(quote(msg).replace(/\\n/g, '\n'));
10133 } else {
10134 args.push(quote(msg).replace(/\\n/g, '\n'));
10135 }
10136 break;
10137 case 'Windows':
10138 args.push(quote(msg).replace(/\\n/g, '\n'));
10139 if (options.title) args.push(cmd.title + quote(options.title));
10140 if (options.url) args.push(cmd.url + quote(options.url));
10141 break;
10142 case 'Custom':
10143 args[0] = (function(origCommand) {
10144 var message = options.title
10145 ? options.title + ': ' + msg
10146 : msg;
10147 var command = origCommand.replace(/(^|[^%])%s/g, '$1' + quote(message));
10148 if (command === origCommand) args.push(quote(message));
10149 return command;
10150 })(args[0]);
10151 break;
10152 }
10153
10154 // execute
10155 exec(args.join(' '), fn);
10156};
10157
10158}).call(this,require('_process'))
10159},{"_process":67,"child_process":42,"fs":42,"os":65,"path":42}],50:[function(require,module,exports){
10160exports.read = function (buffer, offset, isLE, mLen, nBytes) {
10161 var e, m
10162 var eLen = nBytes * 8 - mLen - 1
10163 var eMax = (1 << eLen) - 1
10164 var eBias = eMax >> 1
10165 var nBits = -7
10166 var i = isLE ? (nBytes - 1) : 0
10167 var d = isLE ? -1 : 1
10168 var s = buffer[offset + i]
10169
10170 i += d
10171
10172 e = s & ((1 << (-nBits)) - 1)
10173 s >>= (-nBits)
10174 nBits += eLen
10175 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
10176
10177 m = e & ((1 << (-nBits)) - 1)
10178 e >>= (-nBits)
10179 nBits += mLen
10180 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
10181
10182 if (e === 0) {
10183 e = 1 - eBias
10184 } else if (e === eMax) {
10185 return m ? NaN : ((s ? -1 : 1) * Infinity)
10186 } else {
10187 m = m + Math.pow(2, mLen)
10188 e = e - eBias
10189 }
10190 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
10191}
10192
10193exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
10194 var e, m, c
10195 var eLen = nBytes * 8 - mLen - 1
10196 var eMax = (1 << eLen) - 1
10197 var eBias = eMax >> 1
10198 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
10199 var i = isLE ? 0 : (nBytes - 1)
10200 var d = isLE ? 1 : -1
10201 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
10202
10203 value = Math.abs(value)
10204
10205 if (isNaN(value) || value === Infinity) {
10206 m = isNaN(value) ? 1 : 0
10207 e = eMax
10208 } else {
10209 e = Math.floor(Math.log(value) / Math.LN2)
10210 if (value * (c = Math.pow(2, -e)) < 1) {
10211 e--
10212 c *= 2
10213 }
10214 if (e + eBias >= 1) {
10215 value += rt / c
10216 } else {
10217 value += rt * Math.pow(2, 1 - eBias)
10218 }
10219 if (value * c >= 2) {
10220 e++
10221 c /= 2
10222 }
10223
10224 if (e + eBias >= eMax) {
10225 m = 0
10226 e = eMax
10227 } else if (e + eBias >= 1) {
10228 m = (value * c - 1) * Math.pow(2, mLen)
10229 e = e + eBias
10230 } else {
10231 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
10232 e = 0
10233 }
10234 }
10235
10236 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
10237
10238 e = (e << mLen) | m
10239 eLen += mLen
10240 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
10241
10242 buffer[offset + i - d] |= s * 128
10243}
10244
10245},{}],51:[function(require,module,exports){
10246if (typeof Object.create === 'function') {
10247 // implementation from standard node.js 'util' module
10248 module.exports = function inherits(ctor, superCtor) {
10249 ctor.super_ = superCtor
10250 ctor.prototype = Object.create(superCtor.prototype, {
10251 constructor: {
10252 value: ctor,
10253 enumerable: false,
10254 writable: true,
10255 configurable: true
10256 }
10257 });
10258 };
10259} else {
10260 // old school shim for old browsers
10261 module.exports = function inherits(ctor, superCtor) {
10262 ctor.super_ = superCtor
10263 var TempCtor = function () {}
10264 TempCtor.prototype = superCtor.prototype
10265 ctor.prototype = new TempCtor()
10266 ctor.prototype.constructor = ctor
10267 }
10268}
10269
10270},{}],52:[function(require,module,exports){
10271/*!
10272 * Determine if an object is a Buffer
10273 *
10274 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
10275 * @license MIT
10276 */
10277
10278// The _isBuffer check is for Safari 5-7 support, because it's missing
10279// Object.prototype.constructor. Remove this eventually
10280module.exports = function (obj) {
10281 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
10282}
10283
10284function isBuffer (obj) {
10285 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
10286}
10287
10288// For Node v0.10 support. Remove this eventually.
10289function isSlowBuffer (obj) {
10290 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
10291}
10292
10293},{}],53:[function(require,module,exports){
10294var toString = {}.toString;
10295
10296module.exports = Array.isArray || function (arr) {
10297 return toString.call(arr) == '[object Array]';
10298};
10299
10300},{}],54:[function(require,module,exports){
10301(function (global){
10302/*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */
10303;(function () {
10304 // Detect the `define` function exposed by asynchronous module loaders. The
10305 // strict `define` check is necessary for compatibility with `r.js`.
10306 var isLoader = false;
10307
10308 // A set of types used to distinguish objects from primitives.
10309 var objectTypes = {
10310 "function": true,
10311 "object": true
10312 };
10313
10314 // Detect the `exports` object exposed by CommonJS implementations.
10315 var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
10316
10317 // Use the `global` object exposed by Node (including Browserify via
10318 // `insert-module-globals`), Narwhal, and Ringo as the default context,
10319 // and the `window` object in browsers. Rhino exports a `global` function
10320 // instead.
10321 var root = objectTypes[typeof window] && window || this,
10322 freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global;
10323
10324 if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) {
10325 root = freeGlobal;
10326 }
10327
10328 // Public: Initializes JSON 3 using the given `context` object, attaching the
10329 // `stringify` and `parse` functions to the specified `exports` object.
10330 function runInContext(context, exports) {
10331 context || (context = root["Object"]());
10332 exports || (exports = root["Object"]());
10333
10334 // Native constructor aliases.
10335 var Number = context["Number"] || root["Number"],
10336 String = context["String"] || root["String"],
10337 Object = context["Object"] || root["Object"],
10338 Date = context["Date"] || root["Date"],
10339 SyntaxError = context["SyntaxError"] || root["SyntaxError"],
10340 TypeError = context["TypeError"] || root["TypeError"],
10341 Math = context["Math"] || root["Math"],
10342 nativeJSON = context["JSON"] || root["JSON"];
10343
10344 // Delegate to the native `stringify` and `parse` implementations.
10345 if (typeof nativeJSON == "object" && nativeJSON) {
10346 exports.stringify = nativeJSON.stringify;
10347 exports.parse = nativeJSON.parse;
10348 }
10349
10350 // Convenience aliases.
10351 var objectProto = Object.prototype,
10352 getClass = objectProto.toString,
10353 isProperty, forEach, undef;
10354
10355 // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
10356 var isExtended = new Date(-3509827334573292);
10357 try {
10358 // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
10359 // results for certain dates in Opera >= 10.53.
10360 isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
10361 // Safari < 2.0.2 stores the internal millisecond time value correctly,
10362 // but clips the values returned by the date methods to the range of
10363 // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
10364 isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
10365 } catch (exception) {}
10366
10367 // Internal: Determines whether the native `JSON.stringify` and `parse`
10368 // implementations are spec-compliant. Based on work by Ken Snyder.
10369 function has(name) {
10370 if (has[name] !== undef) {
10371 // Return cached feature test result.
10372 return has[name];
10373 }
10374 var isSupported;
10375 if (name == "bug-string-char-index") {
10376 // IE <= 7 doesn't support accessing string characters using square
10377 // bracket notation. IE 8 only supports this for primitives.
10378 isSupported = "a"[0] != "a";
10379 } else if (name == "json") {
10380 // Indicates whether both `JSON.stringify` and `JSON.parse` are
10381 // supported.
10382 isSupported = has("json-stringify") && has("json-parse");
10383 } else {
10384 var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
10385 // Test `JSON.stringify`.
10386 if (name == "json-stringify") {
10387 var stringify = exports.stringify, stringifySupported = typeof stringify == "function" && isExtended;
10388 if (stringifySupported) {
10389 // A test function object with a custom `toJSON` method.
10390 (value = function () {
10391 return 1;
10392 }).toJSON = value;
10393 try {
10394 stringifySupported =
10395 // Firefox 3.1b1 and b2 serialize string, number, and boolean
10396 // primitives as object literals.
10397 stringify(0) === "0" &&
10398 // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
10399 // literals.
10400 stringify(new Number()) === "0" &&
10401 stringify(new String()) == '""' &&
10402 // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
10403 // does not define a canonical JSON representation (this applies to
10404 // objects with `toJSON` properties as well, *unless* they are nested
10405 // within an object or array).
10406 stringify(getClass) === undef &&
10407 // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
10408 // FF 3.1b3 pass this test.
10409 stringify(undef) === undef &&
10410 // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
10411 // respectively, if the value is omitted entirely.
10412 stringify() === undef &&
10413 // FF 3.1b1, 2 throw an error if the given value is not a number,
10414 // string, array, object, Boolean, or `null` literal. This applies to
10415 // objects with custom `toJSON` methods as well, unless they are nested
10416 // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
10417 // methods entirely.
10418 stringify(value) === "1" &&
10419 stringify([value]) == "[1]" &&
10420 // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
10421 // `"[null]"`.
10422 stringify([undef]) == "[null]" &&
10423 // YUI 3.0.0b1 fails to serialize `null` literals.
10424 stringify(null) == "null" &&
10425 // FF 3.1b1, 2 halts serialization if an array contains a function:
10426 // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
10427 // elides non-JSON values from objects and arrays, unless they
10428 // define custom `toJSON` methods.
10429 stringify([undef, getClass, null]) == "[null,null,null]" &&
10430 // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
10431 // where character escape codes are expected (e.g., `\b` => `\u0008`).
10432 stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
10433 // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
10434 stringify(null, value) === "1" &&
10435 stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
10436 // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
10437 // serialize extended years.
10438 stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
10439 // The milliseconds are optional in ES 5, but required in 5.1.
10440 stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
10441 // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
10442 // four-digit years instead of six-digit years. Credits: @Yaffle.
10443 stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
10444 // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
10445 // values less than 1000. Credits: @Yaffle.
10446 stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
10447 } catch (exception) {
10448 stringifySupported = false;
10449 }
10450 }
10451 isSupported = stringifySupported;
10452 }
10453 // Test `JSON.parse`.
10454 if (name == "json-parse") {
10455 var parse = exports.parse;
10456 if (typeof parse == "function") {
10457 try {
10458 // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
10459 // Conforming implementations should also coerce the initial argument to
10460 // a string prior to parsing.
10461 if (parse("0") === 0 && !parse(false)) {
10462 // Simple parsing test.
10463 value = parse(serialized);
10464 var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
10465 if (parseSupported) {
10466 try {
10467 // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
10468 parseSupported = !parse('"\t"');
10469 } catch (exception) {}
10470 if (parseSupported) {
10471 try {
10472 // FF 4.0 and 4.0.1 allow leading `+` signs and leading
10473 // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
10474 // certain octal literals.
10475 parseSupported = parse("01") !== 1;
10476 } catch (exception) {}
10477 }
10478 if (parseSupported) {
10479 try {
10480 // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
10481 // points. These environments, along with FF 3.1b1 and 2,
10482 // also allow trailing commas in JSON objects and arrays.
10483 parseSupported = parse("1.") !== 1;
10484 } catch (exception) {}
10485 }
10486 }
10487 }
10488 } catch (exception) {
10489 parseSupported = false;
10490 }
10491 }
10492 isSupported = parseSupported;
10493 }
10494 }
10495 return has[name] = !!isSupported;
10496 }
10497
10498 if (!has("json")) {
10499 // Common `[[Class]]` name aliases.
10500 var functionClass = "[object Function]",
10501 dateClass = "[object Date]",
10502 numberClass = "[object Number]",
10503 stringClass = "[object String]",
10504 arrayClass = "[object Array]",
10505 booleanClass = "[object Boolean]";
10506
10507 // Detect incomplete support for accessing string characters by index.
10508 var charIndexBuggy = has("bug-string-char-index");
10509
10510 // Define additional utility methods if the `Date` methods are buggy.
10511 if (!isExtended) {
10512 var floor = Math.floor;
10513 // A mapping between the months of the year and the number of days between
10514 // January 1st and the first of the respective month.
10515 var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
10516 // Internal: Calculates the number of days between the Unix epoch and the
10517 // first day of the given month.
10518 var getDay = function (year, month) {
10519 return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
10520 };
10521 }
10522
10523 // Internal: Determines if a property is a direct property of the given
10524 // object. Delegates to the native `Object#hasOwnProperty` method.
10525 if (!(isProperty = objectProto.hasOwnProperty)) {
10526 isProperty = function (property) {
10527 var members = {}, constructor;
10528 if ((members.__proto__ = null, members.__proto__ = {
10529 // The *proto* property cannot be set multiple times in recent
10530 // versions of Firefox and SeaMonkey.
10531 "toString": 1
10532 }, members).toString != getClass) {
10533 // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
10534 // supports the mutable *proto* property.
10535 isProperty = function (property) {
10536 // Capture and break the object's prototype chain (see section 8.6.2
10537 // of the ES 5.1 spec). The parenthesized expression prevents an
10538 // unsafe transformation by the Closure Compiler.
10539 var original = this.__proto__, result = property in (this.__proto__ = null, this);
10540 // Restore the original prototype chain.
10541 this.__proto__ = original;
10542 return result;
10543 };
10544 } else {
10545 // Capture a reference to the top-level `Object` constructor.
10546 constructor = members.constructor;
10547 // Use the `constructor` property to simulate `Object#hasOwnProperty` in
10548 // other environments.
10549 isProperty = function (property) {
10550 var parent = (this.constructor || constructor).prototype;
10551 return property in this && !(property in parent && this[property] === parent[property]);
10552 };
10553 }
10554 members = null;
10555 return isProperty.call(this, property);
10556 };
10557 }
10558
10559 // Internal: Normalizes the `for...in` iteration algorithm across
10560 // environments. Each enumerated key is yielded to a `callback` function.
10561 forEach = function (object, callback) {
10562 var size = 0, Properties, members, property;
10563
10564 // Tests for bugs in the current environment's `for...in` algorithm. The
10565 // `valueOf` property inherits the non-enumerable flag from
10566 // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
10567 (Properties = function () {
10568 this.valueOf = 0;
10569 }).prototype.valueOf = 0;
10570
10571 // Iterate over a new instance of the `Properties` class.
10572 members = new Properties();
10573 for (property in members) {
10574 // Ignore all properties inherited from `Object.prototype`.
10575 if (isProperty.call(members, property)) {
10576 size++;
10577 }
10578 }
10579 Properties = members = null;
10580
10581 // Normalize the iteration algorithm.
10582 if (!size) {
10583 // A list of non-enumerable properties inherited from `Object.prototype`.
10584 members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
10585 // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
10586 // properties.
10587 forEach = function (object, callback) {
10588 var isFunction = getClass.call(object) == functionClass, property, length;
10589 var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty;
10590 for (property in object) {
10591 // Gecko <= 1.0 enumerates the `prototype` property of functions under
10592 // certain conditions; IE does not.
10593 if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
10594 callback(property);
10595 }
10596 }
10597 // Manually invoke the callback for each non-enumerable property.
10598 for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
10599 };
10600 } else if (size == 2) {
10601 // Safari <= 2.0.4 enumerates shadowed properties twice.
10602 forEach = function (object, callback) {
10603 // Create a set of iterated properties.
10604 var members = {}, isFunction = getClass.call(object) == functionClass, property;
10605 for (property in object) {
10606 // Store each property name to prevent double enumeration. The
10607 // `prototype` property of functions is not enumerated due to cross-
10608 // environment inconsistencies.
10609 if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
10610 callback(property);
10611 }
10612 }
10613 };
10614 } else {
10615 // No bugs detected; use the standard `for...in` algorithm.
10616 forEach = function (object, callback) {
10617 var isFunction = getClass.call(object) == functionClass, property, isConstructor;
10618 for (property in object) {
10619 if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
10620 callback(property);
10621 }
10622 }
10623 // Manually invoke the callback for the `constructor` property due to
10624 // cross-environment inconsistencies.
10625 if (isConstructor || isProperty.call(object, (property = "constructor"))) {
10626 callback(property);
10627 }
10628 };
10629 }
10630 return forEach(object, callback);
10631 };
10632
10633 // Public: Serializes a JavaScript `value` as a JSON string. The optional
10634 // `filter` argument may specify either a function that alters how object and
10635 // array members are serialized, or an array of strings and numbers that
10636 // indicates which properties should be serialized. The optional `width`
10637 // argument may be either a string or number that specifies the indentation
10638 // level of the output.
10639 if (!has("json-stringify")) {
10640 // Internal: A map of control characters and their escaped equivalents.
10641 var Escapes = {
10642 92: "\\\\",
10643 34: '\\"',
10644 8: "\\b",
10645 12: "\\f",
10646 10: "\\n",
10647 13: "\\r",
10648 9: "\\t"
10649 };
10650
10651 // Internal: Converts `value` into a zero-padded string such that its
10652 // length is at least equal to `width`. The `width` must be <= 6.
10653 var leadingZeroes = "000000";
10654 var toPaddedString = function (width, value) {
10655 // The `|| 0` expression is necessary to work around a bug in
10656 // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
10657 return (leadingZeroes + (value || 0)).slice(-width);
10658 };
10659
10660 // Internal: Double-quotes a string `value`, replacing all ASCII control
10661 // characters (characters with code unit values between 0 and 31) with
10662 // their escaped equivalents. This is an implementation of the
10663 // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
10664 var unicodePrefix = "\\u00";
10665 var quote = function (value) {
10666 var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10;
10667 var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value);
10668 for (; index < length; index++) {
10669 var charCode = value.charCodeAt(index);
10670 // If the character is a control character, append its Unicode or
10671 // shorthand escape sequence; otherwise, append the character as-is.
10672 switch (charCode) {
10673 case 8: case 9: case 10: case 12: case 13: case 34: case 92:
10674 result += Escapes[charCode];
10675 break;
10676 default:
10677 if (charCode < 32) {
10678 result += unicodePrefix + toPaddedString(2, charCode.toString(16));
10679 break;
10680 }
10681 result += useCharIndex ? symbols[index] : value.charAt(index);
10682 }
10683 }
10684 return result + '"';
10685 };
10686
10687 // Internal: Recursively serializes an object. Implements the
10688 // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
10689 var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
10690 var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
10691 try {
10692 // Necessary for host object support.
10693 value = object[property];
10694 } catch (exception) {}
10695 if (typeof value == "object" && value) {
10696 className = getClass.call(value);
10697 if (className == dateClass && !isProperty.call(value, "toJSON")) {
10698 if (value > -1 / 0 && value < 1 / 0) {
10699 // Dates are serialized according to the `Date#toJSON` method
10700 // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
10701 // for the ISO 8601 date time string format.
10702 if (getDay) {
10703 // Manually compute the year, month, date, hours, minutes,
10704 // seconds, and milliseconds if the `getUTC*` methods are
10705 // buggy. Adapted from @Yaffle's `date-shim` project.
10706 date = floor(value / 864e5);
10707 for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
10708 for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
10709 date = 1 + date - getDay(year, month);
10710 // The `time` value specifies the time within the day (see ES
10711 // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
10712 // to compute `A modulo B`, as the `%` operator does not
10713 // correspond to the `modulo` operation for negative numbers.
10714 time = (value % 864e5 + 864e5) % 864e5;
10715 // The hours, minutes, seconds, and milliseconds are obtained by
10716 // decomposing the time within the day. See section 15.9.1.10.
10717 hours = floor(time / 36e5) % 24;
10718 minutes = floor(time / 6e4) % 60;
10719 seconds = floor(time / 1e3) % 60;
10720 milliseconds = time % 1e3;
10721 } else {
10722 year = value.getUTCFullYear();
10723 month = value.getUTCMonth();
10724 date = value.getUTCDate();
10725 hours = value.getUTCHours();
10726 minutes = value.getUTCMinutes();
10727 seconds = value.getUTCSeconds();
10728 milliseconds = value.getUTCMilliseconds();
10729 }
10730 // Serialize extended years correctly.
10731 value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
10732 "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
10733 // Months, dates, hours, minutes, and seconds should have two
10734 // digits; milliseconds should have three.
10735 "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
10736 // Milliseconds are optional in ES 5.0, but required in 5.1.
10737 "." + toPaddedString(3, milliseconds) + "Z";
10738 } else {
10739 value = null;
10740 }
10741 } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
10742 // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
10743 // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
10744 // ignores all `toJSON` methods on these objects unless they are
10745 // defined directly on an instance.
10746 value = value.toJSON(property);
10747 }
10748 }
10749 if (callback) {
10750 // If a replacement function was provided, call it to obtain the value
10751 // for serialization.
10752 value = callback.call(object, property, value);
10753 }
10754 if (value === null) {
10755 return "null";
10756 }
10757 className = getClass.call(value);
10758 if (className == booleanClass) {
10759 // Booleans are represented literally.
10760 return "" + value;
10761 } else if (className == numberClass) {
10762 // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
10763 // `"null"`.
10764 return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
10765 } else if (className == stringClass) {
10766 // Strings are double-quoted and escaped.
10767 return quote("" + value);
10768 }
10769 // Recursively serialize objects and arrays.
10770 if (typeof value == "object") {
10771 // Check for cyclic structures. This is a linear search; performance
10772 // is inversely proportional to the number of unique nested objects.
10773 for (length = stack.length; length--;) {
10774 if (stack[length] === value) {
10775 // Cyclic structures cannot be serialized by `JSON.stringify`.
10776 throw TypeError();
10777 }
10778 }
10779 // Add the object to the stack of traversed objects.
10780 stack.push(value);
10781 results = [];
10782 // Save the current indentation level and indent one additional level.
10783 prefix = indentation;
10784 indentation += whitespace;
10785 if (className == arrayClass) {
10786 // Recursively serialize array elements.
10787 for (index = 0, length = value.length; index < length; index++) {
10788 element = serialize(index, value, callback, properties, whitespace, indentation, stack);
10789 results.push(element === undef ? "null" : element);
10790 }
10791 result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
10792 } else {
10793 // Recursively serialize object members. Members are selected from
10794 // either a user-specified list of property names, or the object
10795 // itself.
10796 forEach(properties || value, function (property) {
10797 var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
10798 if (element !== undef) {
10799 // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
10800 // is not the empty string, let `member` {quote(property) + ":"}
10801 // be the concatenation of `member` and the `space` character."
10802 // The "`space` character" refers to the literal space
10803 // character, not the `space` {width} argument provided to
10804 // `JSON.stringify`.
10805 results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
10806 }
10807 });
10808 result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
10809 }
10810 // Remove the object from the traversed object stack.
10811 stack.pop();
10812 return result;
10813 }
10814 };
10815
10816 // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
10817 exports.stringify = function (source, filter, width) {
10818 var whitespace, callback, properties, className;
10819 if (objectTypes[typeof filter] && filter) {
10820 if ((className = getClass.call(filter)) == functionClass) {
10821 callback = filter;
10822 } else if (className == arrayClass) {
10823 // Convert the property names array into a makeshift set.
10824 properties = {};
10825 for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
10826 }
10827 }
10828 if (width) {
10829 if ((className = getClass.call(width)) == numberClass) {
10830 // Convert the `width` to an integer and create a string containing
10831 // `width` number of space characters.
10832 if ((width -= width % 1) > 0) {
10833 for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
10834 }
10835 } else if (className == stringClass) {
10836 whitespace = width.length <= 10 ? width : width.slice(0, 10);
10837 }
10838 }
10839 // Opera <= 7.54u2 discards the values associated with empty string keys
10840 // (`""`) only if they are used directly within an object member list
10841 // (e.g., `!("" in { "": 1})`).
10842 return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
10843 };
10844 }
10845
10846 // Public: Parses a JSON source string.
10847 if (!has("json-parse")) {
10848 var fromCharCode = String.fromCharCode;
10849
10850 // Internal: A map of escaped control characters and their unescaped
10851 // equivalents.
10852 var Unescapes = {
10853 92: "\\",
10854 34: '"',
10855 47: "/",
10856 98: "\b",
10857 116: "\t",
10858 110: "\n",
10859 102: "\f",
10860 114: "\r"
10861 };
10862
10863 // Internal: Stores the parser state.
10864 var Index, Source;
10865
10866 // Internal: Resets the parser state and throws a `SyntaxError`.
10867 var abort = function () {
10868 Index = Source = null;
10869 throw SyntaxError();
10870 };
10871
10872 // Internal: Returns the next token, or `"$"` if the parser has reached
10873 // the end of the source string. A token may be a string, number, `null`
10874 // literal, or Boolean literal.
10875 var lex = function () {
10876 var source = Source, length = source.length, value, begin, position, isSigned, charCode;
10877 while (Index < length) {
10878 charCode = source.charCodeAt(Index);
10879 switch (charCode) {
10880 case 9: case 10: case 13: case 32:
10881 // Skip whitespace tokens, including tabs, carriage returns, line
10882 // feeds, and space characters.
10883 Index++;
10884 break;
10885 case 123: case 125: case 91: case 93: case 58: case 44:
10886 // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
10887 // the current position.
10888 value = charIndexBuggy ? source.charAt(Index) : source[Index];
10889 Index++;
10890 return value;
10891 case 34:
10892 // `"` delimits a JSON string; advance to the next character and
10893 // begin parsing the string. String tokens are prefixed with the
10894 // sentinel `@` character to distinguish them from punctuators and
10895 // end-of-string tokens.
10896 for (value = "@", Index++; Index < length;) {
10897 charCode = source.charCodeAt(Index);
10898 if (charCode < 32) {
10899 // Unescaped ASCII control characters (those with a code unit
10900 // less than the space character) are not permitted.
10901 abort();
10902 } else if (charCode == 92) {
10903 // A reverse solidus (`\`) marks the beginning of an escaped
10904 // control character (including `"`, `\`, and `/`) or Unicode
10905 // escape sequence.
10906 charCode = source.charCodeAt(++Index);
10907 switch (charCode) {
10908 case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
10909 // Revive escaped control characters.
10910 value += Unescapes[charCode];
10911 Index++;
10912 break;
10913 case 117:
10914 // `\u` marks the beginning of a Unicode escape sequence.
10915 // Advance to the first character and validate the
10916 // four-digit code point.
10917 begin = ++Index;
10918 for (position = Index + 4; Index < position; Index++) {
10919 charCode = source.charCodeAt(Index);
10920 // A valid sequence comprises four hexdigits (case-
10921 // insensitive) that form a single hexadecimal value.
10922 if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
10923 // Invalid Unicode escape sequence.
10924 abort();
10925 }
10926 }
10927 // Revive the escaped character.
10928 value += fromCharCode("0x" + source.slice(begin, Index));
10929 break;
10930 default:
10931 // Invalid escape sequence.
10932 abort();
10933 }
10934 } else {
10935 if (charCode == 34) {
10936 // An unescaped double-quote character marks the end of the
10937 // string.
10938 break;
10939 }
10940 charCode = source.charCodeAt(Index);
10941 begin = Index;
10942 // Optimize for the common case where a string is valid.
10943 while (charCode >= 32 && charCode != 92 && charCode != 34) {
10944 charCode = source.charCodeAt(++Index);
10945 }
10946 // Append the string as-is.
10947 value += source.slice(begin, Index);
10948 }
10949 }
10950 if (source.charCodeAt(Index) == 34) {
10951 // Advance to the next character and return the revived string.
10952 Index++;
10953 return value;
10954 }
10955 // Unterminated string.
10956 abort();
10957 default:
10958 // Parse numbers and literals.
10959 begin = Index;
10960 // Advance past the negative sign, if one is specified.
10961 if (charCode == 45) {
10962 isSigned = true;
10963 charCode = source.charCodeAt(++Index);
10964 }
10965 // Parse an integer or floating-point value.
10966 if (charCode >= 48 && charCode <= 57) {
10967 // Leading zeroes are interpreted as octal literals.
10968 if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
10969 // Illegal octal literal.
10970 abort();
10971 }
10972 isSigned = false;
10973 // Parse the integer component.
10974 for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
10975 // Floats cannot contain a leading decimal point; however, this
10976 // case is already accounted for by the parser.
10977 if (source.charCodeAt(Index) == 46) {
10978 position = ++Index;
10979 // Parse the decimal component.
10980 for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
10981 if (position == Index) {
10982 // Illegal trailing decimal.
10983 abort();
10984 }
10985 Index = position;
10986 }
10987 // Parse exponents. The `e` denoting the exponent is
10988 // case-insensitive.
10989 charCode = source.charCodeAt(Index);
10990 if (charCode == 101 || charCode == 69) {
10991 charCode = source.charCodeAt(++Index);
10992 // Skip past the sign following the exponent, if one is
10993 // specified.
10994 if (charCode == 43 || charCode == 45) {
10995 Index++;
10996 }
10997 // Parse the exponential component.
10998 for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
10999 if (position == Index) {
11000 // Illegal empty exponent.
11001 abort();
11002 }
11003 Index = position;
11004 }
11005 // Coerce the parsed value to a JavaScript number.
11006 return +source.slice(begin, Index);
11007 }
11008 // A negative sign may only precede numbers.
11009 if (isSigned) {
11010 abort();
11011 }
11012 // `true`, `false`, and `null` literals.
11013 if (source.slice(Index, Index + 4) == "true") {
11014 Index += 4;
11015 return true;
11016 } else if (source.slice(Index, Index + 5) == "false") {
11017 Index += 5;
11018 return false;
11019 } else if (source.slice(Index, Index + 4) == "null") {
11020 Index += 4;
11021 return null;
11022 }
11023 // Unrecognized token.
11024 abort();
11025 }
11026 }
11027 // Return the sentinel `$` character if the parser has reached the end
11028 // of the source string.
11029 return "$";
11030 };
11031
11032 // Internal: Parses a JSON `value` token.
11033 var get = function (value) {
11034 var results, hasMembers;
11035 if (value == "$") {
11036 // Unexpected end of input.
11037 abort();
11038 }
11039 if (typeof value == "string") {
11040 if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
11041 // Remove the sentinel `@` character.
11042 return value.slice(1);
11043 }
11044 // Parse object and array literals.
11045 if (value == "[") {
11046 // Parses a JSON array, returning a new JavaScript array.
11047 results = [];
11048 for (;; hasMembers || (hasMembers = true)) {
11049 value = lex();
11050 // A closing square bracket marks the end of the array literal.
11051 if (value == "]") {
11052 break;
11053 }
11054 // If the array literal contains elements, the current token
11055 // should be a comma separating the previous element from the
11056 // next.
11057 if (hasMembers) {
11058 if (value == ",") {
11059 value = lex();
11060 if (value == "]") {
11061 // Unexpected trailing `,` in array literal.
11062 abort();
11063 }
11064 } else {
11065 // A `,` must separate each array element.
11066 abort();
11067 }
11068 }
11069 // Elisions and leading commas are not permitted.
11070 if (value == ",") {
11071 abort();
11072 }
11073 results.push(get(value));
11074 }
11075 return results;
11076 } else if (value == "{") {
11077 // Parses a JSON object, returning a new JavaScript object.
11078 results = {};
11079 for (;; hasMembers || (hasMembers = true)) {
11080 value = lex();
11081 // A closing curly brace marks the end of the object literal.
11082 if (value == "}") {
11083 break;
11084 }
11085 // If the object literal contains members, the current token
11086 // should be a comma separator.
11087 if (hasMembers) {
11088 if (value == ",") {
11089 value = lex();
11090 if (value == "}") {
11091 // Unexpected trailing `,` in object literal.
11092 abort();
11093 }
11094 } else {
11095 // A `,` must separate each object member.
11096 abort();
11097 }
11098 }
11099 // Leading commas are not permitted, object property names must be
11100 // double-quoted strings, and a `:` must separate each property
11101 // name and value.
11102 if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
11103 abort();
11104 }
11105 results[value.slice(1)] = get(lex());
11106 }
11107 return results;
11108 }
11109 // Unexpected token encountered.
11110 abort();
11111 }
11112 return value;
11113 };
11114
11115 // Internal: Updates a traversed object member.
11116 var update = function (source, property, callback) {
11117 var element = walk(source, property, callback);
11118 if (element === undef) {
11119 delete source[property];
11120 } else {
11121 source[property] = element;
11122 }
11123 };
11124
11125 // Internal: Recursively traverses a parsed JSON object, invoking the
11126 // `callback` function for each value. This is an implementation of the
11127 // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
11128 var walk = function (source, property, callback) {
11129 var value = source[property], length;
11130 if (typeof value == "object" && value) {
11131 // `forEach` can't be used to traverse an array in Opera <= 8.54
11132 // because its `Object#hasOwnProperty` implementation returns `false`
11133 // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
11134 if (getClass.call(value) == arrayClass) {
11135 for (length = value.length; length--;) {
11136 update(value, length, callback);
11137 }
11138 } else {
11139 forEach(value, function (property) {
11140 update(value, property, callback);
11141 });
11142 }
11143 }
11144 return callback.call(source, property, value);
11145 };
11146
11147 // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
11148 exports.parse = function (source, callback) {
11149 var result, value;
11150 Index = 0;
11151 Source = "" + source;
11152 result = get(lex());
11153 // If a JSON string contains multiple tokens, it is invalid.
11154 if (lex() != "$") {
11155 abort();
11156 }
11157 // Reset the parser state.
11158 Index = Source = null;
11159 return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
11160 };
11161 }
11162 }
11163
11164 exports["runInContext"] = runInContext;
11165 return exports;
11166 }
11167
11168 if (freeExports && !isLoader) {
11169 // Export for CommonJS environments.
11170 runInContext(root, freeExports);
11171 } else {
11172 // Export for web browsers and JavaScript engines.
11173 var nativeJSON = root.JSON,
11174 previousJSON = root["JSON3"],
11175 isRestored = false;
11176
11177 var JSON3 = runInContext(root, (root["JSON3"] = {
11178 // Public: Restores the original value of the global `JSON` object and
11179 // returns a reference to the `JSON3` object.
11180 "noConflict": function () {
11181 if (!isRestored) {
11182 isRestored = true;
11183 root.JSON = nativeJSON;
11184 root["JSON3"] = previousJSON;
11185 nativeJSON = previousJSON = null;
11186 }
11187 return JSON3;
11188 }
11189 }));
11190
11191 root.JSON = {
11192 "parse": JSON3.parse,
11193 "stringify": JSON3.stringify
11194 };
11195 }
11196
11197 // Export for asynchronous module loaders.
11198 if (isLoader) {
11199 define(function () {
11200 return JSON3;
11201 });
11202 }
11203}).call(this);
11204
11205}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
11206},{}],55:[function(require,module,exports){
11207/**
11208 * lodash 3.2.0 (Custom Build) <https://lodash.com/>
11209 * Build: `lodash modern modularize exports="npm" -o ./`
11210 * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
11211 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
11212 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
11213 * Available under MIT license <https://lodash.com/license>
11214 */
11215var baseCopy = require('lodash._basecopy'),
11216 keys = require('lodash.keys');
11217
11218/**
11219 * The base implementation of `_.assign` without support for argument juggling,
11220 * multiple sources, and `customizer` functions.
11221 *
11222 * @private
11223 * @param {Object} object The destination object.
11224 * @param {Object} source The source object.
11225 * @returns {Object} Returns `object`.
11226 */
11227function baseAssign(object, source) {
11228 return source == null
11229 ? object
11230 : baseCopy(source, keys(source), object);
11231}
11232
11233module.exports = baseAssign;
11234
11235},{"lodash._basecopy":56,"lodash.keys":63}],56:[function(require,module,exports){
11236/**
11237 * lodash 3.0.1 (Custom Build) <https://lodash.com/>
11238 * Build: `lodash modern modularize exports="npm" -o ./`
11239 * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
11240 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
11241 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
11242 * Available under MIT license <https://lodash.com/license>
11243 */
11244
11245/**
11246 * Copies properties of `source` to `object`.
11247 *
11248 * @private
11249 * @param {Object} source The object to copy properties from.
11250 * @param {Array} props The property names to copy.
11251 * @param {Object} [object={}] The object to copy properties to.
11252 * @returns {Object} Returns `object`.
11253 */
11254function baseCopy(source, props, object) {
11255 object || (object = {});
11256
11257 var index = -1,
11258 length = props.length;
11259
11260 while (++index < length) {
11261 var key = props[index];
11262 object[key] = source[key];
11263 }
11264 return object;
11265}
11266
11267module.exports = baseCopy;
11268
11269},{}],57:[function(require,module,exports){
11270/**
11271 * lodash 3.0.3 (Custom Build) <https://lodash.com/>
11272 * Build: `lodash modern modularize exports="npm" -o ./`
11273 * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
11274 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
11275 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
11276 * Available under MIT license <https://lodash.com/license>
11277 */
11278
11279/**
11280 * The base implementation of `_.create` without support for assigning
11281 * properties to the created object.
11282 *
11283 * @private
11284 * @param {Object} prototype The object to inherit from.
11285 * @returns {Object} Returns the new object.
11286 */
11287var baseCreate = (function() {
11288 function object() {}
11289 return function(prototype) {
11290 if (isObject(prototype)) {
11291 object.prototype = prototype;
11292 var result = new object;
11293 object.prototype = undefined;
11294 }
11295 return result || {};
11296 };
11297}());
11298
11299/**
11300 * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
11301 * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
11302 *
11303 * @static
11304 * @memberOf _
11305 * @category Lang
11306 * @param {*} value The value to check.
11307 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
11308 * @example
11309 *
11310 * _.isObject({});
11311 * // => true
11312 *
11313 * _.isObject([1, 2, 3]);
11314 * // => true
11315 *
11316 * _.isObject(1);
11317 * // => false
11318 */
11319function isObject(value) {
11320 // Avoid a V8 JIT bug in Chrome 19-20.
11321 // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
11322 var type = typeof value;
11323 return !!value && (type == 'object' || type == 'function');
11324}
11325
11326module.exports = baseCreate;
11327
11328},{}],58:[function(require,module,exports){
11329/**
11330 * lodash 3.9.1 (Custom Build) <https://lodash.com/>
11331 * Build: `lodash modern modularize exports="npm" -o ./`
11332 * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
11333 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
11334 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
11335 * Available under MIT license <https://lodash.com/license>
11336 */
11337
11338/** `Object#toString` result references. */
11339var funcTag = '[object Function]';
11340
11341/** Used to detect host constructors (Safari > 5). */
11342var reIsHostCtor = /^\[object .+?Constructor\]$/;
11343
11344/**
11345 * Checks if `value` is object-like.
11346 *
11347 * @private
11348 * @param {*} value The value to check.
11349 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
11350 */
11351function isObjectLike(value) {
11352 return !!value && typeof value == 'object';
11353}
11354
11355/** Used for native method references. */
11356var objectProto = Object.prototype;
11357
11358/** Used to resolve the decompiled source of functions. */
11359var fnToString = Function.prototype.toString;
11360
11361/** Used to check objects for own properties. */
11362var hasOwnProperty = objectProto.hasOwnProperty;
11363
11364/**
11365 * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
11366 * of values.
11367 */
11368var objToString = objectProto.toString;
11369
11370/** Used to detect if a method is native. */
11371var reIsNative = RegExp('^' +
11372 fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
11373 .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
11374);
11375
11376/**
11377 * Gets the native function at `key` of `object`.
11378 *
11379 * @private
11380 * @param {Object} object The object to query.
11381 * @param {string} key The key of the method to get.
11382 * @returns {*} Returns the function if it's native, else `undefined`.
11383 */
11384function getNative(object, key) {
11385 var value = object == null ? undefined : object[key];
11386 return isNative(value) ? value : undefined;
11387}
11388
11389/**
11390 * Checks if `value` is classified as a `Function` object.
11391 *
11392 * @static
11393 * @memberOf _
11394 * @category Lang
11395 * @param {*} value The value to check.
11396 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
11397 * @example
11398 *
11399 * _.isFunction(_);
11400 * // => true
11401 *
11402 * _.isFunction(/abc/);
11403 * // => false
11404 */
11405function isFunction(value) {
11406 // The use of `Object#toString` avoids issues with the `typeof` operator
11407 // in older versions of Chrome and Safari which return 'function' for regexes
11408 // and Safari 8 equivalents which return 'object' for typed array constructors.
11409 return isObject(value) && objToString.call(value) == funcTag;
11410}
11411
11412/**
11413 * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
11414 * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
11415 *
11416 * @static
11417 * @memberOf _
11418 * @category Lang
11419 * @param {*} value The value to check.
11420 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
11421 * @example
11422 *
11423 * _.isObject({});
11424 * // => true
11425 *
11426 * _.isObject([1, 2, 3]);
11427 * // => true
11428 *
11429 * _.isObject(1);
11430 * // => false
11431 */
11432function isObject(value) {
11433 // Avoid a V8 JIT bug in Chrome 19-20.
11434 // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
11435 var type = typeof value;
11436 return !!value && (type == 'object' || type == 'function');
11437}
11438
11439/**
11440 * Checks if `value` is a native function.
11441 *
11442 * @static
11443 * @memberOf _
11444 * @category Lang
11445 * @param {*} value The value to check.
11446 * @returns {boolean} Returns `true` if `value` is a native function, else `false`.
11447 * @example
11448 *
11449 * _.isNative(Array.prototype.push);
11450 * // => true
11451 *
11452 * _.isNative(_);
11453 * // => false
11454 */
11455function isNative(value) {
11456 if (value == null) {
11457 return false;
11458 }
11459 if (isFunction(value)) {
11460 return reIsNative.test(fnToString.call(value));
11461 }
11462 return isObjectLike(value) && reIsHostCtor.test(value);
11463}
11464
11465module.exports = getNative;
11466
11467},{}],59:[function(require,module,exports){
11468/**
11469 * lodash 3.0.9 (Custom Build) <https://lodash.com/>
11470 * Build: `lodash modern modularize exports="npm" -o ./`
11471 * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
11472 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
11473 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
11474 * Available under MIT license <https://lodash.com/license>
11475 */
11476
11477/** Used to detect unsigned integer values. */
11478var reIsUint = /^\d+$/;
11479
11480/**
11481 * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer)
11482 * of an array-like value.
11483 */
11484var MAX_SAFE_INTEGER = 9007199254740991;
11485
11486/**
11487 * The base implementation of `_.property` without support for deep paths.
11488 *
11489 * @private
11490 * @param {string} key The key of the property to get.
11491 * @returns {Function} Returns the new function.
11492 */
11493function baseProperty(key) {
11494 return function(object) {
11495 return object == null ? undefined : object[key];
11496 };
11497}
11498
11499/**
11500 * Gets the "length" property value of `object`.
11501 *
11502 * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
11503 * that affects Safari on at least iOS 8.1-8.3 ARM64.
11504 *
11505 * @private
11506 * @param {Object} object The object to query.
11507 * @returns {*} Returns the "length" value.
11508 */
11509var getLength = baseProperty('length');
11510
11511/**
11512 * Checks if `value` is array-like.
11513 *
11514 * @private
11515 * @param {*} value The value to check.
11516 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
11517 */
11518function isArrayLike(value) {
11519 return value != null && isLength(getLength(value));
11520}
11521
11522/**
11523 * Checks if `value` is a valid array-like index.
11524 *
11525 * @private
11526 * @param {*} value The value to check.
11527 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
11528 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
11529 */
11530function isIndex(value, length) {
11531 value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
11532 length = length == null ? MAX_SAFE_INTEGER : length;
11533 return value > -1 && value % 1 == 0 && value < length;
11534}
11535
11536/**
11537 * Checks if the provided arguments are from an iteratee call.
11538 *
11539 * @private
11540 * @param {*} value The potential iteratee value argument.
11541 * @param {*} index The potential iteratee index or key argument.
11542 * @param {*} object The potential iteratee object argument.
11543 * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
11544 */
11545function isIterateeCall(value, index, object) {
11546 if (!isObject(object)) {
11547 return false;
11548 }
11549 var type = typeof index;
11550 if (type == 'number'
11551 ? (isArrayLike(object) && isIndex(index, object.length))
11552 : (type == 'string' && index in object)) {
11553 var other = object[index];
11554 return value === value ? (value === other) : (other !== other);
11555 }
11556 return false;
11557}
11558
11559/**
11560 * Checks if `value` is a valid array-like length.
11561 *
11562 * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength).
11563 *
11564 * @private
11565 * @param {*} value The value to check.
11566 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
11567 */
11568function isLength(value) {
11569 return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
11570}
11571
11572/**
11573 * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
11574 * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
11575 *
11576 * @static
11577 * @memberOf _
11578 * @category Lang
11579 * @param {*} value The value to check.
11580 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
11581 * @example
11582 *
11583 * _.isObject({});
11584 * // => true
11585 *
11586 * _.isObject([1, 2, 3]);
11587 * // => true
11588 *
11589 * _.isObject(1);
11590 * // => false
11591 */
11592function isObject(value) {
11593 // Avoid a V8 JIT bug in Chrome 19-20.
11594 // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
11595 var type = typeof value;
11596 return !!value && (type == 'object' || type == 'function');
11597}
11598
11599module.exports = isIterateeCall;
11600
11601},{}],60:[function(require,module,exports){
11602/**
11603 * lodash 3.1.1 (Custom Build) <https://lodash.com/>
11604 * Build: `lodash modern modularize exports="npm" -o ./`
11605 * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
11606 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
11607 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
11608 * Available under MIT license <https://lodash.com/license>
11609 */
11610var baseAssign = require('lodash._baseassign'),
11611 baseCreate = require('lodash._basecreate'),
11612 isIterateeCall = require('lodash._isiterateecall');
11613
11614/**
11615 * Creates an object that inherits from the given `prototype` object. If a
11616 * `properties` object is provided its own enumerable properties are assigned
11617 * to the created object.
11618 *
11619 * @static
11620 * @memberOf _
11621 * @category Object
11622 * @param {Object} prototype The object to inherit from.
11623 * @param {Object} [properties] The properties to assign to the object.
11624 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
11625 * @returns {Object} Returns the new object.
11626 * @example
11627 *
11628 * function Shape() {
11629 * this.x = 0;
11630 * this.y = 0;
11631 * }
11632 *
11633 * function Circle() {
11634 * Shape.call(this);
11635 * }
11636 *
11637 * Circle.prototype = _.create(Shape.prototype, {
11638 * 'constructor': Circle
11639 * });
11640 *
11641 * var circle = new Circle;
11642 * circle instanceof Circle;
11643 * // => true
11644 *
11645 * circle instanceof Shape;
11646 * // => true
11647 */
11648function create(prototype, properties, guard) {
11649 var result = baseCreate(prototype);
11650 if (guard && isIterateeCall(prototype, properties, guard)) {
11651 properties = undefined;
11652 }
11653 return properties ? baseAssign(result, properties) : result;
11654}
11655
11656module.exports = create;
11657
11658},{"lodash._baseassign":55,"lodash._basecreate":57,"lodash._isiterateecall":59}],61:[function(require,module,exports){
11659/**
11660 * lodash (Custom Build) <https://lodash.com/>
11661 * Build: `lodash modularize exports="npm" -o ./`
11662 * Copyright jQuery Foundation and other contributors <https://jquery.org/>
11663 * Released under MIT license <https://lodash.com/license>
11664 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
11665 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
11666 */
11667
11668/** Used as references for various `Number` constants. */
11669var MAX_SAFE_INTEGER = 9007199254740991;
11670
11671/** `Object#toString` result references. */
11672var argsTag = '[object Arguments]',
11673 funcTag = '[object Function]',
11674 genTag = '[object GeneratorFunction]';
11675
11676/** Used for built-in method references. */
11677var objectProto = Object.prototype;
11678
11679/** Used to check objects for own properties. */
11680var hasOwnProperty = objectProto.hasOwnProperty;
11681
11682/**
11683 * Used to resolve the
11684 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
11685 * of values.
11686 */
11687var objectToString = objectProto.toString;
11688
11689/** Built-in value references. */
11690var propertyIsEnumerable = objectProto.propertyIsEnumerable;
11691
11692/**
11693 * Checks if `value` is likely an `arguments` object.
11694 *
11695 * @static
11696 * @memberOf _
11697 * @since 0.1.0
11698 * @category Lang
11699 * @param {*} value The value to check.
11700 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
11701 * else `false`.
11702 * @example
11703 *
11704 * _.isArguments(function() { return arguments; }());
11705 * // => true
11706 *
11707 * _.isArguments([1, 2, 3]);
11708 * // => false
11709 */
11710function isArguments(value) {
11711 // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
11712 return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
11713 (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
11714}
11715
11716/**
11717 * Checks if `value` is array-like. A value is considered array-like if it's
11718 * not a function and has a `value.length` that's an integer greater than or
11719 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
11720 *
11721 * @static
11722 * @memberOf _
11723 * @since 4.0.0
11724 * @category Lang
11725 * @param {*} value The value to check.
11726 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
11727 * @example
11728 *
11729 * _.isArrayLike([1, 2, 3]);
11730 * // => true
11731 *
11732 * _.isArrayLike(document.body.children);
11733 * // => true
11734 *
11735 * _.isArrayLike('abc');
11736 * // => true
11737 *
11738 * _.isArrayLike(_.noop);
11739 * // => false
11740 */
11741function isArrayLike(value) {
11742 return value != null && isLength(value.length) && !isFunction(value);
11743}
11744
11745/**
11746 * This method is like `_.isArrayLike` except that it also checks if `value`
11747 * is an object.
11748 *
11749 * @static
11750 * @memberOf _
11751 * @since 4.0.0
11752 * @category Lang
11753 * @param {*} value The value to check.
11754 * @returns {boolean} Returns `true` if `value` is an array-like object,
11755 * else `false`.
11756 * @example
11757 *
11758 * _.isArrayLikeObject([1, 2, 3]);
11759 * // => true
11760 *
11761 * _.isArrayLikeObject(document.body.children);
11762 * // => true
11763 *
11764 * _.isArrayLikeObject('abc');
11765 * // => false
11766 *
11767 * _.isArrayLikeObject(_.noop);
11768 * // => false
11769 */
11770function isArrayLikeObject(value) {
11771 return isObjectLike(value) && isArrayLike(value);
11772}
11773
11774/**
11775 * Checks if `value` is classified as a `Function` object.
11776 *
11777 * @static
11778 * @memberOf _
11779 * @since 0.1.0
11780 * @category Lang
11781 * @param {*} value The value to check.
11782 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
11783 * @example
11784 *
11785 * _.isFunction(_);
11786 * // => true
11787 *
11788 * _.isFunction(/abc/);
11789 * // => false
11790 */
11791function isFunction(value) {
11792 // The use of `Object#toString` avoids issues with the `typeof` operator
11793 // in Safari 8-9 which returns 'object' for typed array and other constructors.
11794 var tag = isObject(value) ? objectToString.call(value) : '';
11795 return tag == funcTag || tag == genTag;
11796}
11797
11798/**
11799 * Checks if `value` is a valid array-like length.
11800 *
11801 * **Note:** This method is loosely based on
11802 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
11803 *
11804 * @static
11805 * @memberOf _
11806 * @since 4.0.0
11807 * @category Lang
11808 * @param {*} value The value to check.
11809 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
11810 * @example
11811 *
11812 * _.isLength(3);
11813 * // => true
11814 *
11815 * _.isLength(Number.MIN_VALUE);
11816 * // => false
11817 *
11818 * _.isLength(Infinity);
11819 * // => false
11820 *
11821 * _.isLength('3');
11822 * // => false
11823 */
11824function isLength(value) {
11825 return typeof value == 'number' &&
11826 value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
11827}
11828
11829/**
11830 * Checks if `value` is the
11831 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
11832 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
11833 *
11834 * @static
11835 * @memberOf _
11836 * @since 0.1.0
11837 * @category Lang
11838 * @param {*} value The value to check.
11839 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
11840 * @example
11841 *
11842 * _.isObject({});
11843 * // => true
11844 *
11845 * _.isObject([1, 2, 3]);
11846 * // => true
11847 *
11848 * _.isObject(_.noop);
11849 * // => true
11850 *
11851 * _.isObject(null);
11852 * // => false
11853 */
11854function isObject(value) {
11855 var type = typeof value;
11856 return !!value && (type == 'object' || type == 'function');
11857}
11858
11859/**
11860 * Checks if `value` is object-like. A value is object-like if it's not `null`
11861 * and has a `typeof` result of "object".
11862 *
11863 * @static
11864 * @memberOf _
11865 * @since 4.0.0
11866 * @category Lang
11867 * @param {*} value The value to check.
11868 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
11869 * @example
11870 *
11871 * _.isObjectLike({});
11872 * // => true
11873 *
11874 * _.isObjectLike([1, 2, 3]);
11875 * // => true
11876 *
11877 * _.isObjectLike(_.noop);
11878 * // => false
11879 *
11880 * _.isObjectLike(null);
11881 * // => false
11882 */
11883function isObjectLike(value) {
11884 return !!value && typeof value == 'object';
11885}
11886
11887module.exports = isArguments;
11888
11889},{}],62:[function(require,module,exports){
11890/**
11891 * lodash 3.0.4 (Custom Build) <https://lodash.com/>
11892 * Build: `lodash modern modularize exports="npm" -o ./`
11893 * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
11894 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
11895 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
11896 * Available under MIT license <https://lodash.com/license>
11897 */
11898
11899/** `Object#toString` result references. */
11900var arrayTag = '[object Array]',
11901 funcTag = '[object Function]';
11902
11903/** Used to detect host constructors (Safari > 5). */
11904var reIsHostCtor = /^\[object .+?Constructor\]$/;
11905
11906/**
11907 * Checks if `value` is object-like.
11908 *
11909 * @private
11910 * @param {*} value The value to check.
11911 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
11912 */
11913function isObjectLike(value) {
11914 return !!value && typeof value == 'object';
11915}
11916
11917/** Used for native method references. */
11918var objectProto = Object.prototype;
11919
11920/** Used to resolve the decompiled source of functions. */
11921var fnToString = Function.prototype.toString;
11922
11923/** Used to check objects for own properties. */
11924var hasOwnProperty = objectProto.hasOwnProperty;
11925
11926/**
11927 * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
11928 * of values.
11929 */
11930var objToString = objectProto.toString;
11931
11932/** Used to detect if a method is native. */
11933var reIsNative = RegExp('^' +
11934 fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
11935 .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
11936);
11937
11938/* Native method references for those with the same name as other `lodash` methods. */
11939var nativeIsArray = getNative(Array, 'isArray');
11940
11941/**
11942 * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
11943 * of an array-like value.
11944 */
11945var MAX_SAFE_INTEGER = 9007199254740991;
11946
11947/**
11948 * Gets the native function at `key` of `object`.
11949 *
11950 * @private
11951 * @param {Object} object The object to query.
11952 * @param {string} key The key of the method to get.
11953 * @returns {*} Returns the function if it's native, else `undefined`.
11954 */
11955function getNative(object, key) {
11956 var value = object == null ? undefined : object[key];
11957 return isNative(value) ? value : undefined;
11958}
11959
11960/**
11961 * Checks if `value` is a valid array-like length.
11962 *
11963 * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
11964 *
11965 * @private
11966 * @param {*} value The value to check.
11967 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
11968 */
11969function isLength(value) {
11970 return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
11971}
11972
11973/**
11974 * Checks if `value` is classified as an `Array` object.
11975 *
11976 * @static
11977 * @memberOf _
11978 * @category Lang
11979 * @param {*} value The value to check.
11980 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
11981 * @example
11982 *
11983 * _.isArray([1, 2, 3]);
11984 * // => true
11985 *
11986 * _.isArray(function() { return arguments; }());
11987 * // => false
11988 */
11989var isArray = nativeIsArray || function(value) {
11990 return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag;
11991};
11992
11993/**
11994 * Checks if `value` is classified as a `Function` object.
11995 *
11996 * @static
11997 * @memberOf _
11998 * @category Lang
11999 * @param {*} value The value to check.
12000 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
12001 * @example
12002 *
12003 * _.isFunction(_);
12004 * // => true
12005 *
12006 * _.isFunction(/abc/);
12007 * // => false
12008 */
12009function isFunction(value) {
12010 // The use of `Object#toString` avoids issues with the `typeof` operator
12011 // in older versions of Chrome and Safari which return 'function' for regexes
12012 // and Safari 8 equivalents which return 'object' for typed array constructors.
12013 return isObject(value) && objToString.call(value) == funcTag;
12014}
12015
12016/**
12017 * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
12018 * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
12019 *
12020 * @static
12021 * @memberOf _
12022 * @category Lang
12023 * @param {*} value The value to check.
12024 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
12025 * @example
12026 *
12027 * _.isObject({});
12028 * // => true
12029 *
12030 * _.isObject([1, 2, 3]);
12031 * // => true
12032 *
12033 * _.isObject(1);
12034 * // => false
12035 */
12036function isObject(value) {
12037 // Avoid a V8 JIT bug in Chrome 19-20.
12038 // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
12039 var type = typeof value;
12040 return !!value && (type == 'object' || type == 'function');
12041}
12042
12043/**
12044 * Checks if `value` is a native function.
12045 *
12046 * @static
12047 * @memberOf _
12048 * @category Lang
12049 * @param {*} value The value to check.
12050 * @returns {boolean} Returns `true` if `value` is a native function, else `false`.
12051 * @example
12052 *
12053 * _.isNative(Array.prototype.push);
12054 * // => true
12055 *
12056 * _.isNative(_);
12057 * // => false
12058 */
12059function isNative(value) {
12060 if (value == null) {
12061 return false;
12062 }
12063 if (isFunction(value)) {
12064 return reIsNative.test(fnToString.call(value));
12065 }
12066 return isObjectLike(value) && reIsHostCtor.test(value);
12067}
12068
12069module.exports = isArray;
12070
12071},{}],63:[function(require,module,exports){
12072/**
12073 * lodash 3.1.2 (Custom Build) <https://lodash.com/>
12074 * Build: `lodash modern modularize exports="npm" -o ./`
12075 * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
12076 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
12077 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
12078 * Available under MIT license <https://lodash.com/license>
12079 */
12080var getNative = require('lodash._getnative'),
12081 isArguments = require('lodash.isarguments'),
12082 isArray = require('lodash.isarray');
12083
12084/** Used to detect unsigned integer values. */
12085var reIsUint = /^\d+$/;
12086
12087/** Used for native method references. */
12088var objectProto = Object.prototype;
12089
12090/** Used to check objects for own properties. */
12091var hasOwnProperty = objectProto.hasOwnProperty;
12092
12093/* Native method references for those with the same name as other `lodash` methods. */
12094var nativeKeys = getNative(Object, 'keys');
12095
12096/**
12097 * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
12098 * of an array-like value.
12099 */
12100var MAX_SAFE_INTEGER = 9007199254740991;
12101
12102/**
12103 * The base implementation of `_.property` without support for deep paths.
12104 *
12105 * @private
12106 * @param {string} key The key of the property to get.
12107 * @returns {Function} Returns the new function.
12108 */
12109function baseProperty(key) {
12110 return function(object) {
12111 return object == null ? undefined : object[key];
12112 };
12113}
12114
12115/**
12116 * Gets the "length" property value of `object`.
12117 *
12118 * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
12119 * that affects Safari on at least iOS 8.1-8.3 ARM64.
12120 *
12121 * @private
12122 * @param {Object} object The object to query.
12123 * @returns {*} Returns the "length" value.
12124 */
12125var getLength = baseProperty('length');
12126
12127/**
12128 * Checks if `value` is array-like.
12129 *
12130 * @private
12131 * @param {*} value The value to check.
12132 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
12133 */
12134function isArrayLike(value) {
12135 return value != null && isLength(getLength(value));
12136}
12137
12138/**
12139 * Checks if `value` is a valid array-like index.
12140 *
12141 * @private
12142 * @param {*} value The value to check.
12143 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
12144 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
12145 */
12146function isIndex(value, length) {
12147 value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
12148 length = length == null ? MAX_SAFE_INTEGER : length;
12149 return value > -1 && value % 1 == 0 && value < length;
12150}
12151
12152/**
12153 * Checks if `value` is a valid array-like length.
12154 *
12155 * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
12156 *
12157 * @private
12158 * @param {*} value The value to check.
12159 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
12160 */
12161function isLength(value) {
12162 return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
12163}
12164
12165/**
12166 * A fallback implementation of `Object.keys` which creates an array of the
12167 * own enumerable property names of `object`.
12168 *
12169 * @private
12170 * @param {Object} object The object to query.
12171 * @returns {Array} Returns the array of property names.
12172 */
12173function shimKeys(object) {
12174 var props = keysIn(object),
12175 propsLength = props.length,
12176 length = propsLength && object.length;
12177
12178 var allowIndexes = !!length && isLength(length) &&
12179 (isArray(object) || isArguments(object));
12180
12181 var index = -1,
12182 result = [];
12183
12184 while (++index < propsLength) {
12185 var key = props[index];
12186 if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) {
12187 result.push(key);
12188 }
12189 }
12190 return result;
12191}
12192
12193/**
12194 * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
12195 * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
12196 *
12197 * @static
12198 * @memberOf _
12199 * @category Lang
12200 * @param {*} value The value to check.
12201 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
12202 * @example
12203 *
12204 * _.isObject({});
12205 * // => true
12206 *
12207 * _.isObject([1, 2, 3]);
12208 * // => true
12209 *
12210 * _.isObject(1);
12211 * // => false
12212 */
12213function isObject(value) {
12214 // Avoid a V8 JIT bug in Chrome 19-20.
12215 // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
12216 var type = typeof value;
12217 return !!value && (type == 'object' || type == 'function');
12218}
12219
12220/**
12221 * Creates an array of the own enumerable property names of `object`.
12222 *
12223 * **Note:** Non-object values are coerced to objects. See the
12224 * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
12225 * for more details.
12226 *
12227 * @static
12228 * @memberOf _
12229 * @category Object
12230 * @param {Object} object The object to query.
12231 * @returns {Array} Returns the array of property names.
12232 * @example
12233 *
12234 * function Foo() {
12235 * this.a = 1;
12236 * this.b = 2;
12237 * }
12238 *
12239 * Foo.prototype.c = 3;
12240 *
12241 * _.keys(new Foo);
12242 * // => ['a', 'b'] (iteration order is not guaranteed)
12243 *
12244 * _.keys('hi');
12245 * // => ['0', '1']
12246 */
12247var keys = !nativeKeys ? shimKeys : function(object) {
12248 var Ctor = object == null ? undefined : object.constructor;
12249 if ((typeof Ctor == 'function' && Ctor.prototype === object) ||
12250 (typeof object != 'function' && isArrayLike(object))) {
12251 return shimKeys(object);
12252 }
12253 return isObject(object) ? nativeKeys(object) : [];
12254};
12255
12256/**
12257 * Creates an array of the own and inherited enumerable property names of `object`.
12258 *
12259 * **Note:** Non-object values are coerced to objects.
12260 *
12261 * @static
12262 * @memberOf _
12263 * @category Object
12264 * @param {Object} object The object to query.
12265 * @returns {Array} Returns the array of property names.
12266 * @example
12267 *
12268 * function Foo() {
12269 * this.a = 1;
12270 * this.b = 2;
12271 * }
12272 *
12273 * Foo.prototype.c = 3;
12274 *
12275 * _.keysIn(new Foo);
12276 * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
12277 */
12278function keysIn(object) {
12279 if (object == null) {
12280 return [];
12281 }
12282 if (!isObject(object)) {
12283 object = Object(object);
12284 }
12285 var length = object.length;
12286 length = (length && isLength(length) &&
12287 (isArray(object) || isArguments(object)) && length) || 0;
12288
12289 var Ctor = object.constructor,
12290 index = -1,
12291 isProto = typeof Ctor == 'function' && Ctor.prototype === object,
12292 result = Array(length),
12293 skipIndexes = length > 0;
12294
12295 while (++index < length) {
12296 result[index] = (index + '');
12297 }
12298 for (var key in object) {
12299 if (!(skipIndexes && isIndex(key, length)) &&
12300 !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
12301 result.push(key);
12302 }
12303 }
12304 return result;
12305}
12306
12307module.exports = keys;
12308
12309},{"lodash._getnative":58,"lodash.isarguments":61,"lodash.isarray":62}],64:[function(require,module,exports){
12310(function (process){
12311var path = require('path');
12312var fs = require('fs');
12313var _0777 = parseInt('0777', 8);
12314
12315module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;
12316
12317function mkdirP (p, opts, f, made) {
12318 if (typeof opts === 'function') {
12319 f = opts;
12320 opts = {};
12321 }
12322 else if (!opts || typeof opts !== 'object') {
12323 opts = { mode: opts };
12324 }
12325
12326 var mode = opts.mode;
12327 var xfs = opts.fs || fs;
12328
12329 if (mode === undefined) {
12330 mode = _0777 & (~process.umask());
12331 }
12332 if (!made) made = null;
12333
12334 var cb = f || function () {};
12335 p = path.resolve(p);
12336
12337 xfs.mkdir(p, mode, function (er) {
12338 if (!er) {
12339 made = made || p;
12340 return cb(null, made);
12341 }
12342 switch (er.code) {
12343 case 'ENOENT':
12344 mkdirP(path.dirname(p), opts, function (er, made) {
12345 if (er) cb(er, made);
12346 else mkdirP(p, opts, cb, made);
12347 });
12348 break;
12349
12350 // In the case of any other error, just see if there's a dir
12351 // there already. If so, then hooray! If not, then something
12352 // is borked.
12353 default:
12354 xfs.stat(p, function (er2, stat) {
12355 // if the stat fails, then that's super weird.
12356 // let the original error be the failure reason.
12357 if (er2 || !stat.isDirectory()) cb(er, made)
12358 else cb(null, made);
12359 });
12360 break;
12361 }
12362 });
12363}
12364
12365mkdirP.sync = function sync (p, opts, made) {
12366 if (!opts || typeof opts !== 'object') {
12367 opts = { mode: opts };
12368 }
12369
12370 var mode = opts.mode;
12371 var xfs = opts.fs || fs;
12372
12373 if (mode === undefined) {
12374 mode = _0777 & (~process.umask());
12375 }
12376 if (!made) made = null;
12377
12378 p = path.resolve(p);
12379
12380 try {
12381 xfs.mkdirSync(p, mode);
12382 made = made || p;
12383 }
12384 catch (err0) {
12385 switch (err0.code) {
12386 case 'ENOENT' :
12387 made = sync(path.dirname(p), opts, made);
12388 sync(p, opts, made);
12389 break;
12390
12391 // In the case of any other error, just see if there's a dir
12392 // there already. If so, then hooray! If not, then something
12393 // is borked.
12394 default:
12395 var stat;
12396 try {
12397 stat = xfs.statSync(p);
12398 }
12399 catch (err1) {
12400 throw err0;
12401 }
12402 if (!stat.isDirectory()) throw err0;
12403 break;
12404 }
12405 }
12406
12407 return made;
12408};
12409
12410}).call(this,require('_process'))
12411},{"_process":67,"fs":42,"path":42}],65:[function(require,module,exports){
12412exports.endianness = function () { return 'LE' };
12413
12414exports.hostname = function () {
12415 if (typeof location !== 'undefined') {
12416 return location.hostname
12417 }
12418 else return '';
12419};
12420
12421exports.loadavg = function () { return [] };
12422
12423exports.uptime = function () { return 0 };
12424
12425exports.freemem = function () {
12426 return Number.MAX_VALUE;
12427};
12428
12429exports.totalmem = function () {
12430 return Number.MAX_VALUE;
12431};
12432
12433exports.cpus = function () { return [] };
12434
12435exports.type = function () { return 'Browser' };
12436
12437exports.release = function () {
12438 if (typeof navigator !== 'undefined') {
12439 return navigator.appVersion;
12440 }
12441 return '';
12442};
12443
12444exports.networkInterfaces
12445= exports.getNetworkInterfaces
12446= function () { return {} };
12447
12448exports.arch = function () { return 'javascript' };
12449
12450exports.platform = function () { return 'browser' };
12451
12452exports.tmpdir = exports.tmpDir = function () {
12453 return '/tmp';
12454};
12455
12456exports.EOL = '\n';
12457
12458},{}],66:[function(require,module,exports){
12459(function (process){
12460'use strict';
12461
12462if (!process.version ||
12463 process.version.indexOf('v0.') === 0 ||
12464 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
12465 module.exports = nextTick;
12466} else {
12467 module.exports = process.nextTick;
12468}
12469
12470function nextTick(fn, arg1, arg2, arg3) {
12471 if (typeof fn !== 'function') {
12472 throw new TypeError('"callback" argument must be a function');
12473 }
12474 var len = arguments.length;
12475 var args, i;
12476 switch (len) {
12477 case 0:
12478 case 1:
12479 return process.nextTick(fn);
12480 case 2:
12481 return process.nextTick(function afterTickOne() {
12482 fn.call(null, arg1);
12483 });
12484 case 3:
12485 return process.nextTick(function afterTickTwo() {
12486 fn.call(null, arg1, arg2);
12487 });
12488 case 4:
12489 return process.nextTick(function afterTickThree() {
12490 fn.call(null, arg1, arg2, arg3);
12491 });
12492 default:
12493 args = new Array(len - 1);
12494 i = 0;
12495 while (i < args.length) {
12496 args[i++] = arguments[i];
12497 }
12498 return process.nextTick(function afterTick() {
12499 fn.apply(null, args);
12500 });
12501 }
12502}
12503
12504}).call(this,require('_process'))
12505},{"_process":67}],67:[function(require,module,exports){
12506// shim for using process in browser
12507var process = module.exports = {};
12508
12509// cached from whatever global is present so that test runners that stub it
12510// don't break things. But we need to wrap it in a try catch in case it is
12511// wrapped in strict mode code which doesn't define any globals. It's inside a
12512// function because try/catches deoptimize in certain engines.
12513
12514var cachedSetTimeout;
12515var cachedClearTimeout;
12516
12517function defaultSetTimout() {
12518 throw new Error('setTimeout has not been defined');
12519}
12520function defaultClearTimeout () {
12521 throw new Error('clearTimeout has not been defined');
12522}
12523(function () {
12524 try {
12525 if (typeof setTimeout === 'function') {
12526 cachedSetTimeout = setTimeout;
12527 } else {
12528 cachedSetTimeout = defaultSetTimout;
12529 }
12530 } catch (e) {
12531 cachedSetTimeout = defaultSetTimout;
12532 }
12533 try {
12534 if (typeof clearTimeout === 'function') {
12535 cachedClearTimeout = clearTimeout;
12536 } else {
12537 cachedClearTimeout = defaultClearTimeout;
12538 }
12539 } catch (e) {
12540 cachedClearTimeout = defaultClearTimeout;
12541 }
12542} ())
12543function runTimeout(fun) {
12544 if (cachedSetTimeout === setTimeout) {
12545 //normal enviroments in sane situations
12546 return setTimeout(fun, 0);
12547 }
12548 // if setTimeout wasn't available but was latter defined
12549 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
12550 cachedSetTimeout = setTimeout;
12551 return setTimeout(fun, 0);
12552 }
12553 try {
12554 // when when somebody has screwed with setTimeout but no I.E. maddness
12555 return cachedSetTimeout(fun, 0);
12556 } catch(e){
12557 try {
12558 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
12559 return cachedSetTimeout.call(null, fun, 0);
12560 } catch(e){
12561 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
12562 return cachedSetTimeout.call(this, fun, 0);
12563 }
12564 }
12565
12566
12567}
12568function runClearTimeout(marker) {
12569 if (cachedClearTimeout === clearTimeout) {
12570 //normal enviroments in sane situations
12571 return clearTimeout(marker);
12572 }
12573 // if clearTimeout wasn't available but was latter defined
12574 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
12575 cachedClearTimeout = clearTimeout;
12576 return clearTimeout(marker);
12577 }
12578 try {
12579 // when when somebody has screwed with setTimeout but no I.E. maddness
12580 return cachedClearTimeout(marker);
12581 } catch (e){
12582 try {
12583 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
12584 return cachedClearTimeout.call(null, marker);
12585 } catch (e){
12586 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
12587 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
12588 return cachedClearTimeout.call(this, marker);
12589 }
12590 }
12591
12592
12593
12594}
12595var queue = [];
12596var draining = false;
12597var currentQueue;
12598var queueIndex = -1;
12599
12600function cleanUpNextTick() {
12601 if (!draining || !currentQueue) {
12602 return;
12603 }
12604 draining = false;
12605 if (currentQueue.length) {
12606 queue = currentQueue.concat(queue);
12607 } else {
12608 queueIndex = -1;
12609 }
12610 if (queue.length) {
12611 drainQueue();
12612 }
12613}
12614
12615function drainQueue() {
12616 if (draining) {
12617 return;
12618 }
12619 var timeout = runTimeout(cleanUpNextTick);
12620 draining = true;
12621
12622 var len = queue.length;
12623 while(len) {
12624 currentQueue = queue;
12625 queue = [];
12626 while (++queueIndex < len) {
12627 if (currentQueue) {
12628 currentQueue[queueIndex].run();
12629 }
12630 }
12631 queueIndex = -1;
12632 len = queue.length;
12633 }
12634 currentQueue = null;
12635 draining = false;
12636 runClearTimeout(timeout);
12637}
12638
12639process.nextTick = function (fun) {
12640 var args = new Array(arguments.length - 1);
12641 if (arguments.length > 1) {
12642 for (var i = 1; i < arguments.length; i++) {
12643 args[i - 1] = arguments[i];
12644 }
12645 }
12646 queue.push(new Item(fun, args));
12647 if (queue.length === 1 && !draining) {
12648 runTimeout(drainQueue);
12649 }
12650};
12651
12652// v8 likes predictible objects
12653function Item(fun, array) {
12654 this.fun = fun;
12655 this.array = array;
12656}
12657Item.prototype.run = function () {
12658 this.fun.apply(null, this.array);
12659};
12660process.title = 'browser';
12661process.browser = true;
12662process.env = {};
12663process.argv = [];
12664process.version = ''; // empty string to avoid regexp issues
12665process.versions = {};
12666
12667function noop() {}
12668
12669process.on = noop;
12670process.addListener = noop;
12671process.once = noop;
12672process.off = noop;
12673process.removeListener = noop;
12674process.removeAllListeners = noop;
12675process.emit = noop;
12676
12677process.binding = function (name) {
12678 throw new Error('process.binding is not supported');
12679};
12680
12681process.cwd = function () { return '/' };
12682process.chdir = function (dir) {
12683 throw new Error('process.chdir is not supported');
12684};
12685process.umask = function() { return 0; };
12686
12687},{}],68:[function(require,module,exports){
12688module.exports = require("./lib/_stream_duplex.js")
12689
12690},{"./lib/_stream_duplex.js":69}],69:[function(require,module,exports){
12691// a duplex stream is just a stream that is both readable and writable.
12692// Since JS doesn't have multiple prototypal inheritance, this class
12693// prototypally inherits from Readable, and then parasitically from
12694// Writable.
12695
12696'use strict';
12697
12698/*<replacement>*/
12699
12700var objectKeys = Object.keys || function (obj) {
12701 var keys = [];
12702 for (var key in obj) {
12703 keys.push(key);
12704 }return keys;
12705};
12706/*</replacement>*/
12707
12708module.exports = Duplex;
12709
12710/*<replacement>*/
12711var processNextTick = require('process-nextick-args');
12712/*</replacement>*/
12713
12714/*<replacement>*/
12715var util = require('core-util-is');
12716util.inherits = require('inherits');
12717/*</replacement>*/
12718
12719var Readable = require('./_stream_readable');
12720var Writable = require('./_stream_writable');
12721
12722util.inherits(Duplex, Readable);
12723
12724var keys = objectKeys(Writable.prototype);
12725for (var v = 0; v < keys.length; v++) {
12726 var method = keys[v];
12727 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
12728}
12729
12730function Duplex(options) {
12731 if (!(this instanceof Duplex)) return new Duplex(options);
12732
12733 Readable.call(this, options);
12734 Writable.call(this, options);
12735
12736 if (options && options.readable === false) this.readable = false;
12737
12738 if (options && options.writable === false) this.writable = false;
12739
12740 this.allowHalfOpen = true;
12741 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
12742
12743 this.once('end', onend);
12744}
12745
12746// the no-half-open enforcer
12747function onend() {
12748 // if we allow half-open state, or if the writable side ended,
12749 // then we're ok.
12750 if (this.allowHalfOpen || this._writableState.ended) return;
12751
12752 // no more data can be written.
12753 // But allow more writes to happen in this tick.
12754 processNextTick(onEndNT, this);
12755}
12756
12757function onEndNT(self) {
12758 self.end();
12759}
12760
12761function forEach(xs, f) {
12762 for (var i = 0, l = xs.length; i < l; i++) {
12763 f(xs[i], i);
12764 }
12765}
12766},{"./_stream_readable":71,"./_stream_writable":73,"core-util-is":45,"inherits":51,"process-nextick-args":66}],70:[function(require,module,exports){
12767// a passthrough stream.
12768// basically just the most minimal sort of Transform stream.
12769// Every written chunk gets output as-is.
12770
12771'use strict';
12772
12773module.exports = PassThrough;
12774
12775var Transform = require('./_stream_transform');
12776
12777/*<replacement>*/
12778var util = require('core-util-is');
12779util.inherits = require('inherits');
12780/*</replacement>*/
12781
12782util.inherits(PassThrough, Transform);
12783
12784function PassThrough(options) {
12785 if (!(this instanceof PassThrough)) return new PassThrough(options);
12786
12787 Transform.call(this, options);
12788}
12789
12790PassThrough.prototype._transform = function (chunk, encoding, cb) {
12791 cb(null, chunk);
12792};
12793},{"./_stream_transform":72,"core-util-is":45,"inherits":51}],71:[function(require,module,exports){
12794(function (process){
12795'use strict';
12796
12797module.exports = Readable;
12798
12799/*<replacement>*/
12800var processNextTick = require('process-nextick-args');
12801/*</replacement>*/
12802
12803/*<replacement>*/
12804var isArray = require('isarray');
12805/*</replacement>*/
12806
12807Readable.ReadableState = ReadableState;
12808
12809/*<replacement>*/
12810var EE = require('events').EventEmitter;
12811
12812var EElistenerCount = function (emitter, type) {
12813 return emitter.listeners(type).length;
12814};
12815/*</replacement>*/
12816
12817/*<replacement>*/
12818var Stream;
12819(function () {
12820 try {
12821 Stream = require('st' + 'ream');
12822 } catch (_) {} finally {
12823 if (!Stream) Stream = require('events').EventEmitter;
12824 }
12825})();
12826/*</replacement>*/
12827
12828var Buffer = require('buffer').Buffer;
12829/*<replacement>*/
12830var bufferShim = require('buffer-shims');
12831/*</replacement>*/
12832
12833/*<replacement>*/
12834var util = require('core-util-is');
12835util.inherits = require('inherits');
12836/*</replacement>*/
12837
12838/*<replacement>*/
12839var debugUtil = require('util');
12840var debug = void 0;
12841if (debugUtil && debugUtil.debuglog) {
12842 debug = debugUtil.debuglog('stream');
12843} else {
12844 debug = function () {};
12845}
12846/*</replacement>*/
12847
12848var BufferList = require('./internal/streams/BufferList');
12849var StringDecoder;
12850
12851util.inherits(Readable, Stream);
12852
12853function prependListener(emitter, event, fn) {
12854 if (typeof emitter.prependListener === 'function') {
12855 return emitter.prependListener(event, fn);
12856 } else {
12857 // This is a hack to make sure that our error handler is attached before any
12858 // userland ones. NEVER DO THIS. This is here only because this code needs
12859 // to continue to work with older versions of Node.js that do not include
12860 // the prependListener() method. The goal is to eventually remove this hack.
12861 if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
12862 }
12863}
12864
12865var Duplex;
12866function ReadableState(options, stream) {
12867 Duplex = Duplex || require('./_stream_duplex');
12868
12869 options = options || {};
12870
12871 // object stream flag. Used to make read(n) ignore n and to
12872 // make all the buffer merging and length checks go away
12873 this.objectMode = !!options.objectMode;
12874
12875 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
12876
12877 // the point at which it stops calling _read() to fill the buffer
12878 // Note: 0 is a valid value, means "don't call _read preemptively ever"
12879 var hwm = options.highWaterMark;
12880 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
12881 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
12882
12883 // cast to ints.
12884 this.highWaterMark = ~ ~this.highWaterMark;
12885
12886 // A linked list is used to store data chunks instead of an array because the
12887 // linked list can remove elements from the beginning faster than
12888 // array.shift()
12889 this.buffer = new BufferList();
12890 this.length = 0;
12891 this.pipes = null;
12892 this.pipesCount = 0;
12893 this.flowing = null;
12894 this.ended = false;
12895 this.endEmitted = false;
12896 this.reading = false;
12897
12898 // a flag to be able to tell if the onwrite cb is called immediately,
12899 // or on a later tick. We set this to true at first, because any
12900 // actions that shouldn't happen until "later" should generally also
12901 // not happen before the first write call.
12902 this.sync = true;
12903
12904 // whenever we return null, then we set a flag to say
12905 // that we're awaiting a 'readable' event emission.
12906 this.needReadable = false;
12907 this.emittedReadable = false;
12908 this.readableListening = false;
12909 this.resumeScheduled = false;
12910
12911 // Crypto is kind of old and crusty. Historically, its default string
12912 // encoding is 'binary' so we have to make this configurable.
12913 // Everything else in the universe uses 'utf8', though.
12914 this.defaultEncoding = options.defaultEncoding || 'utf8';
12915
12916 // when piping, we only care about 'readable' events that happen
12917 // after read()ing all the bytes and not getting any pushback.
12918 this.ranOut = false;
12919
12920 // the number of writers that are awaiting a drain event in .pipe()s
12921 this.awaitDrain = 0;
12922
12923 // if true, a maybeReadMore has been scheduled
12924 this.readingMore = false;
12925
12926 this.decoder = null;
12927 this.encoding = null;
12928 if (options.encoding) {
12929 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
12930 this.decoder = new StringDecoder(options.encoding);
12931 this.encoding = options.encoding;
12932 }
12933}
12934
12935var Duplex;
12936function Readable(options) {
12937 Duplex = Duplex || require('./_stream_duplex');
12938
12939 if (!(this instanceof Readable)) return new Readable(options);
12940
12941 this._readableState = new ReadableState(options, this);
12942
12943 // legacy
12944 this.readable = true;
12945
12946 if (options && typeof options.read === 'function') this._read = options.read;
12947
12948 Stream.call(this);
12949}
12950
12951// Manually shove something into the read() buffer.
12952// This returns true if the highWaterMark has not been hit yet,
12953// similar to how Writable.write() returns true if you should
12954// write() some more.
12955Readable.prototype.push = function (chunk, encoding) {
12956 var state = this._readableState;
12957
12958 if (!state.objectMode && typeof chunk === 'string') {
12959 encoding = encoding || state.defaultEncoding;
12960 if (encoding !== state.encoding) {
12961 chunk = bufferShim.from(chunk, encoding);
12962 encoding = '';
12963 }
12964 }
12965
12966 return readableAddChunk(this, state, chunk, encoding, false);
12967};
12968
12969// Unshift should *always* be something directly out of read()
12970Readable.prototype.unshift = function (chunk) {
12971 var state = this._readableState;
12972 return readableAddChunk(this, state, chunk, '', true);
12973};
12974
12975Readable.prototype.isPaused = function () {
12976 return this._readableState.flowing === false;
12977};
12978
12979function readableAddChunk(stream, state, chunk, encoding, addToFront) {
12980 var er = chunkInvalid(state, chunk);
12981 if (er) {
12982 stream.emit('error', er);
12983 } else if (chunk === null) {
12984 state.reading = false;
12985 onEofChunk(stream, state);
12986 } else if (state.objectMode || chunk && chunk.length > 0) {
12987 if (state.ended && !addToFront) {
12988 var e = new Error('stream.push() after EOF');
12989 stream.emit('error', e);
12990 } else if (state.endEmitted && addToFront) {
12991 var _e = new Error('stream.unshift() after end event');
12992 stream.emit('error', _e);
12993 } else {
12994 var skipAdd;
12995 if (state.decoder && !addToFront && !encoding) {
12996 chunk = state.decoder.write(chunk);
12997 skipAdd = !state.objectMode && chunk.length === 0;
12998 }
12999
13000 if (!addToFront) state.reading = false;
13001
13002 // Don't add to the buffer if we've decoded to an empty string chunk and
13003 // we're not in object mode
13004 if (!skipAdd) {
13005 // if we want the data now, just emit it.
13006 if (state.flowing && state.length === 0 && !state.sync) {
13007 stream.emit('data', chunk);
13008 stream.read(0);
13009 } else {
13010 // update the buffer info.
13011 state.length += state.objectMode ? 1 : chunk.length;
13012 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
13013
13014 if (state.needReadable) emitReadable(stream);
13015 }
13016 }
13017
13018 maybeReadMore(stream, state);
13019 }
13020 } else if (!addToFront) {
13021 state.reading = false;
13022 }
13023
13024 return needMoreData(state);
13025}
13026
13027// if it's past the high water mark, we can push in some more.
13028// Also, if we have no data yet, we can stand some
13029// more bytes. This is to work around cases where hwm=0,
13030// such as the repl. Also, if the push() triggered a
13031// readable event, and the user called read(largeNumber) such that
13032// needReadable was set, then we ought to push more, so that another
13033// 'readable' event will be triggered.
13034function needMoreData(state) {
13035 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
13036}
13037
13038// backwards compatibility.
13039Readable.prototype.setEncoding = function (enc) {
13040 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
13041 this._readableState.decoder = new StringDecoder(enc);
13042 this._readableState.encoding = enc;
13043 return this;
13044};
13045
13046// Don't raise the hwm > 8MB
13047var MAX_HWM = 0x800000;
13048function computeNewHighWaterMark(n) {
13049 if (n >= MAX_HWM) {
13050 n = MAX_HWM;
13051 } else {
13052 // Get the next highest power of 2 to prevent increasing hwm excessively in
13053 // tiny amounts
13054 n--;
13055 n |= n >>> 1;
13056 n |= n >>> 2;
13057 n |= n >>> 4;
13058 n |= n >>> 8;
13059 n |= n >>> 16;
13060 n++;
13061 }
13062 return n;
13063}
13064
13065// This function is designed to be inlinable, so please take care when making
13066// changes to the function body.
13067function howMuchToRead(n, state) {
13068 if (n <= 0 || state.length === 0 && state.ended) return 0;
13069 if (state.objectMode) return 1;
13070 if (n !== n) {
13071 // Only flow one buffer at a time
13072 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
13073 }
13074 // If we're asking for more than the current hwm, then raise the hwm.
13075 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
13076 if (n <= state.length) return n;
13077 // Don't have enough
13078 if (!state.ended) {
13079 state.needReadable = true;
13080 return 0;
13081 }
13082 return state.length;
13083}
13084
13085// you can override either this method, or the async _read(n) below.
13086Readable.prototype.read = function (n) {
13087 debug('read', n);
13088 n = parseInt(n, 10);
13089 var state = this._readableState;
13090 var nOrig = n;
13091
13092 if (n !== 0) state.emittedReadable = false;
13093
13094 // if we're doing read(0) to trigger a readable event, but we
13095 // already have a bunch of data in the buffer, then just trigger
13096 // the 'readable' event and move on.
13097 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
13098 debug('read: emitReadable', state.length, state.ended);
13099 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
13100 return null;
13101 }
13102
13103 n = howMuchToRead(n, state);
13104
13105 // if we've ended, and we're now clear, then finish it up.
13106 if (n === 0 && state.ended) {
13107 if (state.length === 0) endReadable(this);
13108 return null;
13109 }
13110
13111 // All the actual chunk generation logic needs to be
13112 // *below* the call to _read. The reason is that in certain
13113 // synthetic stream cases, such as passthrough streams, _read
13114 // may be a completely synchronous operation which may change
13115 // the state of the read buffer, providing enough data when
13116 // before there was *not* enough.
13117 //
13118 // So, the steps are:
13119 // 1. Figure out what the state of things will be after we do
13120 // a read from the buffer.
13121 //
13122 // 2. If that resulting state will trigger a _read, then call _read.
13123 // Note that this may be asynchronous, or synchronous. Yes, it is
13124 // deeply ugly to write APIs this way, but that still doesn't mean
13125 // that the Readable class should behave improperly, as streams are
13126 // designed to be sync/async agnostic.
13127 // Take note if the _read call is sync or async (ie, if the read call
13128 // has returned yet), so that we know whether or not it's safe to emit
13129 // 'readable' etc.
13130 //
13131 // 3. Actually pull the requested chunks out of the buffer and return.
13132
13133 // if we need a readable event, then we need to do some reading.
13134 var doRead = state.needReadable;
13135 debug('need readable', doRead);
13136
13137 // if we currently have less than the highWaterMark, then also read some
13138 if (state.length === 0 || state.length - n < state.highWaterMark) {
13139 doRead = true;
13140 debug('length less than watermark', doRead);
13141 }
13142
13143 // however, if we've ended, then there's no point, and if we're already
13144 // reading, then it's unnecessary.
13145 if (state.ended || state.reading) {
13146 doRead = false;
13147 debug('reading or ended', doRead);
13148 } else if (doRead) {
13149 debug('do read');
13150 state.reading = true;
13151 state.sync = true;
13152 // if the length is currently zero, then we *need* a readable event.
13153 if (state.length === 0) state.needReadable = true;
13154 // call internal read method
13155 this._read(state.highWaterMark);
13156 state.sync = false;
13157 // If _read pushed data synchronously, then `reading` will be false,
13158 // and we need to re-evaluate how much data we can return to the user.
13159 if (!state.reading) n = howMuchToRead(nOrig, state);
13160 }
13161
13162 var ret;
13163 if (n > 0) ret = fromList(n, state);else ret = null;
13164
13165 if (ret === null) {
13166 state.needReadable = true;
13167 n = 0;
13168 } else {
13169 state.length -= n;
13170 }
13171
13172 if (state.length === 0) {
13173 // If we have nothing in the buffer, then we want to know
13174 // as soon as we *do* get something into the buffer.
13175 if (!state.ended) state.needReadable = true;
13176
13177 // If we tried to read() past the EOF, then emit end on the next tick.
13178 if (nOrig !== n && state.ended) endReadable(this);
13179 }
13180
13181 if (ret !== null) this.emit('data', ret);
13182
13183 return ret;
13184};
13185
13186function chunkInvalid(state, chunk) {
13187 var er = null;
13188 if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
13189 er = new TypeError('Invalid non-string/buffer chunk');
13190 }
13191 return er;
13192}
13193
13194function onEofChunk(stream, state) {
13195 if (state.ended) return;
13196 if (state.decoder) {
13197 var chunk = state.decoder.end();
13198 if (chunk && chunk.length) {
13199 state.buffer.push(chunk);
13200 state.length += state.objectMode ? 1 : chunk.length;
13201 }
13202 }
13203 state.ended = true;
13204
13205 // emit 'readable' now to make sure it gets picked up.
13206 emitReadable(stream);
13207}
13208
13209// Don't emit readable right away in sync mode, because this can trigger
13210// another read() call => stack overflow. This way, it might trigger
13211// a nextTick recursion warning, but that's not so bad.
13212function emitReadable(stream) {
13213 var state = stream._readableState;
13214 state.needReadable = false;
13215 if (!state.emittedReadable) {
13216 debug('emitReadable', state.flowing);
13217 state.emittedReadable = true;
13218 if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
13219 }
13220}
13221
13222function emitReadable_(stream) {
13223 debug('emit readable');
13224 stream.emit('readable');
13225 flow(stream);
13226}
13227
13228// at this point, the user has presumably seen the 'readable' event,
13229// and called read() to consume some data. that may have triggered
13230// in turn another _read(n) call, in which case reading = true if
13231// it's in progress.
13232// However, if we're not ended, or reading, and the length < hwm,
13233// then go ahead and try to read some more preemptively.
13234function maybeReadMore(stream, state) {
13235 if (!state.readingMore) {
13236 state.readingMore = true;
13237 processNextTick(maybeReadMore_, stream, state);
13238 }
13239}
13240
13241function maybeReadMore_(stream, state) {
13242 var len = state.length;
13243 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
13244 debug('maybeReadMore read 0');
13245 stream.read(0);
13246 if (len === state.length)
13247 // didn't get any data, stop spinning.
13248 break;else len = state.length;
13249 }
13250 state.readingMore = false;
13251}
13252
13253// abstract method. to be overridden in specific implementation classes.
13254// call cb(er, data) where data is <= n in length.
13255// for virtual (non-string, non-buffer) streams, "length" is somewhat
13256// arbitrary, and perhaps not very meaningful.
13257Readable.prototype._read = function (n) {
13258 this.emit('error', new Error('not implemented'));
13259};
13260
13261Readable.prototype.pipe = function (dest, pipeOpts) {
13262 var src = this;
13263 var state = this._readableState;
13264
13265 switch (state.pipesCount) {
13266 case 0:
13267 state.pipes = dest;
13268 break;
13269 case 1:
13270 state.pipes = [state.pipes, dest];
13271 break;
13272 default:
13273 state.pipes.push(dest);
13274 break;
13275 }
13276 state.pipesCount += 1;
13277 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
13278
13279 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
13280
13281 var endFn = doEnd ? onend : cleanup;
13282 if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
13283
13284 dest.on('unpipe', onunpipe);
13285 function onunpipe(readable) {
13286 debug('onunpipe');
13287 if (readable === src) {
13288 cleanup();
13289 }
13290 }
13291
13292 function onend() {
13293 debug('onend');
13294 dest.end();
13295 }
13296
13297 // when the dest drains, it reduces the awaitDrain counter
13298 // on the source. This would be more elegant with a .once()
13299 // handler in flow(), but adding and removing repeatedly is
13300 // too slow.
13301 var ondrain = pipeOnDrain(src);
13302 dest.on('drain', ondrain);
13303
13304 var cleanedUp = false;
13305 function cleanup() {
13306 debug('cleanup');
13307 // cleanup event handlers once the pipe is broken
13308 dest.removeListener('close', onclose);
13309 dest.removeListener('finish', onfinish);
13310 dest.removeListener('drain', ondrain);
13311 dest.removeListener('error', onerror);
13312 dest.removeListener('unpipe', onunpipe);
13313 src.removeListener('end', onend);
13314 src.removeListener('end', cleanup);
13315 src.removeListener('data', ondata);
13316
13317 cleanedUp = true;
13318
13319 // if the reader is waiting for a drain event from this
13320 // specific writer, then it would cause it to never start
13321 // flowing again.
13322 // So, if this is awaiting a drain, then we just call it now.
13323 // If we don't know, then assume that we are waiting for one.
13324 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
13325 }
13326
13327 // If the user pushes more data while we're writing to dest then we'll end up
13328 // in ondata again. However, we only want to increase awaitDrain once because
13329 // dest will only emit one 'drain' event for the multiple writes.
13330 // => Introduce a guard on increasing awaitDrain.
13331 var increasedAwaitDrain = false;
13332 src.on('data', ondata);
13333 function ondata(chunk) {
13334 debug('ondata');
13335 increasedAwaitDrain = false;
13336 var ret = dest.write(chunk);
13337 if (false === ret && !increasedAwaitDrain) {
13338 // If the user unpiped during `dest.write()`, it is possible
13339 // to get stuck in a permanently paused state if that write
13340 // also returned false.
13341 // => Check whether `dest` is still a piping destination.
13342 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
13343 debug('false write response, pause', src._readableState.awaitDrain);
13344 src._readableState.awaitDrain++;
13345 increasedAwaitDrain = true;
13346 }
13347 src.pause();
13348 }
13349 }
13350
13351 // if the dest has an error, then stop piping into it.
13352 // however, don't suppress the throwing behavior for this.
13353 function onerror(er) {
13354 debug('onerror', er);
13355 unpipe();
13356 dest.removeListener('error', onerror);
13357 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
13358 }
13359
13360 // Make sure our error handler is attached before userland ones.
13361 prependListener(dest, 'error', onerror);
13362
13363 // Both close and finish should trigger unpipe, but only once.
13364 function onclose() {
13365 dest.removeListener('finish', onfinish);
13366 unpipe();
13367 }
13368 dest.once('close', onclose);
13369 function onfinish() {
13370 debug('onfinish');
13371 dest.removeListener('close', onclose);
13372 unpipe();
13373 }
13374 dest.once('finish', onfinish);
13375
13376 function unpipe() {
13377 debug('unpipe');
13378 src.unpipe(dest);
13379 }
13380
13381 // tell the dest that it's being piped to
13382 dest.emit('pipe', src);
13383
13384 // start the flow if it hasn't been started already.
13385 if (!state.flowing) {
13386 debug('pipe resume');
13387 src.resume();
13388 }
13389
13390 return dest;
13391};
13392
13393function pipeOnDrain(src) {
13394 return function () {
13395 var state = src._readableState;
13396 debug('pipeOnDrain', state.awaitDrain);
13397 if (state.awaitDrain) state.awaitDrain--;
13398 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
13399 state.flowing = true;
13400 flow(src);
13401 }
13402 };
13403}
13404
13405Readable.prototype.unpipe = function (dest) {
13406 var state = this._readableState;
13407
13408 // if we're not piping anywhere, then do nothing.
13409 if (state.pipesCount === 0) return this;
13410
13411 // just one destination. most common case.
13412 if (state.pipesCount === 1) {
13413 // passed in one, but it's not the right one.
13414 if (dest && dest !== state.pipes) return this;
13415
13416 if (!dest) dest = state.pipes;
13417
13418 // got a match.
13419 state.pipes = null;
13420 state.pipesCount = 0;
13421 state.flowing = false;
13422 if (dest) dest.emit('unpipe', this);
13423 return this;
13424 }
13425
13426 // slow case. multiple pipe destinations.
13427
13428 if (!dest) {
13429 // remove all.
13430 var dests = state.pipes;
13431 var len = state.pipesCount;
13432 state.pipes = null;
13433 state.pipesCount = 0;
13434 state.flowing = false;
13435
13436 for (var _i = 0; _i < len; _i++) {
13437 dests[_i].emit('unpipe', this);
13438 }return this;
13439 }
13440
13441 // try to find the right one.
13442 var i = indexOf(state.pipes, dest);
13443 if (i === -1) return this;
13444
13445 state.pipes.splice(i, 1);
13446 state.pipesCount -= 1;
13447 if (state.pipesCount === 1) state.pipes = state.pipes[0];
13448
13449 dest.emit('unpipe', this);
13450
13451 return this;
13452};
13453
13454// set up data events if they are asked for
13455// Ensure readable listeners eventually get something
13456Readable.prototype.on = function (ev, fn) {
13457 var res = Stream.prototype.on.call(this, ev, fn);
13458
13459 if (ev === 'data') {
13460 // Start flowing on next tick if stream isn't explicitly paused
13461 if (this._readableState.flowing !== false) this.resume();
13462 } else if (ev === 'readable') {
13463 var state = this._readableState;
13464 if (!state.endEmitted && !state.readableListening) {
13465 state.readableListening = state.needReadable = true;
13466 state.emittedReadable = false;
13467 if (!state.reading) {
13468 processNextTick(nReadingNextTick, this);
13469 } else if (state.length) {
13470 emitReadable(this, state);
13471 }
13472 }
13473 }
13474
13475 return res;
13476};
13477Readable.prototype.addListener = Readable.prototype.on;
13478
13479function nReadingNextTick(self) {
13480 debug('readable nexttick read 0');
13481 self.read(0);
13482}
13483
13484// pause() and resume() are remnants of the legacy readable stream API
13485// If the user uses them, then switch into old mode.
13486Readable.prototype.resume = function () {
13487 var state = this._readableState;
13488 if (!state.flowing) {
13489 debug('resume');
13490 state.flowing = true;
13491 resume(this, state);
13492 }
13493 return this;
13494};
13495
13496function resume(stream, state) {
13497 if (!state.resumeScheduled) {
13498 state.resumeScheduled = true;
13499 processNextTick(resume_, stream, state);
13500 }
13501}
13502
13503function resume_(stream, state) {
13504 if (!state.reading) {
13505 debug('resume read 0');
13506 stream.read(0);
13507 }
13508
13509 state.resumeScheduled = false;
13510 state.awaitDrain = 0;
13511 stream.emit('resume');
13512 flow(stream);
13513 if (state.flowing && !state.reading) stream.read(0);
13514}
13515
13516Readable.prototype.pause = function () {
13517 debug('call pause flowing=%j', this._readableState.flowing);
13518 if (false !== this._readableState.flowing) {
13519 debug('pause');
13520 this._readableState.flowing = false;
13521 this.emit('pause');
13522 }
13523 return this;
13524};
13525
13526function flow(stream) {
13527 var state = stream._readableState;
13528 debug('flow', state.flowing);
13529 while (state.flowing && stream.read() !== null) {}
13530}
13531
13532// wrap an old-style stream as the async data source.
13533// This is *not* part of the readable stream interface.
13534// It is an ugly unfortunate mess of history.
13535Readable.prototype.wrap = function (stream) {
13536 var state = this._readableState;
13537 var paused = false;
13538
13539 var self = this;
13540 stream.on('end', function () {
13541 debug('wrapped end');
13542 if (state.decoder && !state.ended) {
13543 var chunk = state.decoder.end();
13544 if (chunk && chunk.length) self.push(chunk);
13545 }
13546
13547 self.push(null);
13548 });
13549
13550 stream.on('data', function (chunk) {
13551 debug('wrapped data');
13552 if (state.decoder) chunk = state.decoder.write(chunk);
13553
13554 // don't skip over falsy values in objectMode
13555 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
13556
13557 var ret = self.push(chunk);
13558 if (!ret) {
13559 paused = true;
13560 stream.pause();
13561 }
13562 });
13563
13564 // proxy all the other methods.
13565 // important when wrapping filters and duplexes.
13566 for (var i in stream) {
13567 if (this[i] === undefined && typeof stream[i] === 'function') {
13568 this[i] = function (method) {
13569 return function () {
13570 return stream[method].apply(stream, arguments);
13571 };
13572 }(i);
13573 }
13574 }
13575
13576 // proxy certain important events.
13577 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
13578 forEach(events, function (ev) {
13579 stream.on(ev, self.emit.bind(self, ev));
13580 });
13581
13582 // when we try to consume some more bytes, simply unpause the
13583 // underlying stream.
13584 self._read = function (n) {
13585 debug('wrapped _read', n);
13586 if (paused) {
13587 paused = false;
13588 stream.resume();
13589 }
13590 };
13591
13592 return self;
13593};
13594
13595// exposed for testing purposes only.
13596Readable._fromList = fromList;
13597
13598// Pluck off n bytes from an array of buffers.
13599// Length is the combined lengths of all the buffers in the list.
13600// This function is designed to be inlinable, so please take care when making
13601// changes to the function body.
13602function fromList(n, state) {
13603 // nothing buffered
13604 if (state.length === 0) return null;
13605
13606 var ret;
13607 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
13608 // read it all, truncate the list
13609 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
13610 state.buffer.clear();
13611 } else {
13612 // read part of list
13613 ret = fromListPartial(n, state.buffer, state.decoder);
13614 }
13615
13616 return ret;
13617}
13618
13619// Extracts only enough buffered data to satisfy the amount requested.
13620// This function is designed to be inlinable, so please take care when making
13621// changes to the function body.
13622function fromListPartial(n, list, hasStrings) {
13623 var ret;
13624 if (n < list.head.data.length) {
13625 // slice is the same for buffers and strings
13626 ret = list.head.data.slice(0, n);
13627 list.head.data = list.head.data.slice(n);
13628 } else if (n === list.head.data.length) {
13629 // first chunk is a perfect match
13630 ret = list.shift();
13631 } else {
13632 // result spans more than one buffer
13633 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
13634 }
13635 return ret;
13636}
13637
13638// Copies a specified amount of characters from the list of buffered data
13639// chunks.
13640// This function is designed to be inlinable, so please take care when making
13641// changes to the function body.
13642function copyFromBufferString(n, list) {
13643 var p = list.head;
13644 var c = 1;
13645 var ret = p.data;
13646 n -= ret.length;
13647 while (p = p.next) {
13648 var str = p.data;
13649 var nb = n > str.length ? str.length : n;
13650 if (nb === str.length) ret += str;else ret += str.slice(0, n);
13651 n -= nb;
13652 if (n === 0) {
13653 if (nb === str.length) {
13654 ++c;
13655 if (p.next) list.head = p.next;else list.head = list.tail = null;
13656 } else {
13657 list.head = p;
13658 p.data = str.slice(nb);
13659 }
13660 break;
13661 }
13662 ++c;
13663 }
13664 list.length -= c;
13665 return ret;
13666}
13667
13668// Copies a specified amount of bytes from the list of buffered data chunks.
13669// This function is designed to be inlinable, so please take care when making
13670// changes to the function body.
13671function copyFromBuffer(n, list) {
13672 var ret = bufferShim.allocUnsafe(n);
13673 var p = list.head;
13674 var c = 1;
13675 p.data.copy(ret);
13676 n -= p.data.length;
13677 while (p = p.next) {
13678 var buf = p.data;
13679 var nb = n > buf.length ? buf.length : n;
13680 buf.copy(ret, ret.length - n, 0, nb);
13681 n -= nb;
13682 if (n === 0) {
13683 if (nb === buf.length) {
13684 ++c;
13685 if (p.next) list.head = p.next;else list.head = list.tail = null;
13686 } else {
13687 list.head = p;
13688 p.data = buf.slice(nb);
13689 }
13690 break;
13691 }
13692 ++c;
13693 }
13694 list.length -= c;
13695 return ret;
13696}
13697
13698function endReadable(stream) {
13699 var state = stream._readableState;
13700
13701 // If we get here before consuming all the bytes, then that is a
13702 // bug in node. Should never happen.
13703 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
13704
13705 if (!state.endEmitted) {
13706 state.ended = true;
13707 processNextTick(endReadableNT, state, stream);
13708 }
13709}
13710
13711function endReadableNT(state, stream) {
13712 // Check that we didn't get one last unshift.
13713 if (!state.endEmitted && state.length === 0) {
13714 state.endEmitted = true;
13715 stream.readable = false;
13716 stream.emit('end');
13717 }
13718}
13719
13720function forEach(xs, f) {
13721 for (var i = 0, l = xs.length; i < l; i++) {
13722 f(xs[i], i);
13723 }
13724}
13725
13726function indexOf(xs, x) {
13727 for (var i = 0, l = xs.length; i < l; i++) {
13728 if (xs[i] === x) return i;
13729 }
13730 return -1;
13731}
13732}).call(this,require('_process'))
13733},{"./_stream_duplex":69,"./internal/streams/BufferList":74,"_process":67,"buffer":44,"buffer-shims":43,"core-util-is":45,"events":48,"inherits":51,"isarray":53,"process-nextick-args":66,"string_decoder/":80,"util":40}],72:[function(require,module,exports){
13734// a transform stream is a readable/writable stream where you do
13735// something with the data. Sometimes it's called a "filter",
13736// but that's not a great name for it, since that implies a thing where
13737// some bits pass through, and others are simply ignored. (That would
13738// be a valid example of a transform, of course.)
13739//
13740// While the output is causally related to the input, it's not a
13741// necessarily symmetric or synchronous transformation. For example,
13742// a zlib stream might take multiple plain-text writes(), and then
13743// emit a single compressed chunk some time in the future.
13744//
13745// Here's how this works:
13746//
13747// The Transform stream has all the aspects of the readable and writable
13748// stream classes. When you write(chunk), that calls _write(chunk,cb)
13749// internally, and returns false if there's a lot of pending writes
13750// buffered up. When you call read(), that calls _read(n) until
13751// there's enough pending readable data buffered up.
13752//
13753// In a transform stream, the written data is placed in a buffer. When
13754// _read(n) is called, it transforms the queued up data, calling the
13755// buffered _write cb's as it consumes chunks. If consuming a single
13756// written chunk would result in multiple output chunks, then the first
13757// outputted bit calls the readcb, and subsequent chunks just go into
13758// the read buffer, and will cause it to emit 'readable' if necessary.
13759//
13760// This way, back-pressure is actually determined by the reading side,
13761// since _read has to be called to start processing a new chunk. However,
13762// a pathological inflate type of transform can cause excessive buffering
13763// here. For example, imagine a stream where every byte of input is
13764// interpreted as an integer from 0-255, and then results in that many
13765// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
13766// 1kb of data being output. In this case, you could write a very small
13767// amount of input, and end up with a very large amount of output. In
13768// such a pathological inflating mechanism, there'd be no way to tell
13769// the system to stop doing the transform. A single 4MB write could
13770// cause the system to run out of memory.
13771//
13772// However, even in such a pathological case, only a single written chunk
13773// would be consumed, and then the rest would wait (un-transformed) until
13774// the results of the previous transformed chunk were consumed.
13775
13776'use strict';
13777
13778module.exports = Transform;
13779
13780var Duplex = require('./_stream_duplex');
13781
13782/*<replacement>*/
13783var util = require('core-util-is');
13784util.inherits = require('inherits');
13785/*</replacement>*/
13786
13787util.inherits(Transform, Duplex);
13788
13789function TransformState(stream) {
13790 this.afterTransform = function (er, data) {
13791 return afterTransform(stream, er, data);
13792 };
13793
13794 this.needTransform = false;
13795 this.transforming = false;
13796 this.writecb = null;
13797 this.writechunk = null;
13798 this.writeencoding = null;
13799}
13800
13801function afterTransform(stream, er, data) {
13802 var ts = stream._transformState;
13803 ts.transforming = false;
13804
13805 var cb = ts.writecb;
13806
13807 if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
13808
13809 ts.writechunk = null;
13810 ts.writecb = null;
13811
13812 if (data !== null && data !== undefined) stream.push(data);
13813
13814 cb(er);
13815
13816 var rs = stream._readableState;
13817 rs.reading = false;
13818 if (rs.needReadable || rs.length < rs.highWaterMark) {
13819 stream._read(rs.highWaterMark);
13820 }
13821}
13822
13823function Transform(options) {
13824 if (!(this instanceof Transform)) return new Transform(options);
13825
13826 Duplex.call(this, options);
13827
13828 this._transformState = new TransformState(this);
13829
13830 // when the writable side finishes, then flush out anything remaining.
13831 var stream = this;
13832
13833 // start out asking for a readable event once data is transformed.
13834 this._readableState.needReadable = true;
13835
13836 // we have implemented the _read method, and done the other things
13837 // that Readable wants before the first _read call, so unset the
13838 // sync guard flag.
13839 this._readableState.sync = false;
13840
13841 if (options) {
13842 if (typeof options.transform === 'function') this._transform = options.transform;
13843
13844 if (typeof options.flush === 'function') this._flush = options.flush;
13845 }
13846
13847 this.once('prefinish', function () {
13848 if (typeof this._flush === 'function') this._flush(function (er) {
13849 done(stream, er);
13850 });else done(stream);
13851 });
13852}
13853
13854Transform.prototype.push = function (chunk, encoding) {
13855 this._transformState.needTransform = false;
13856 return Duplex.prototype.push.call(this, chunk, encoding);
13857};
13858
13859// This is the part where you do stuff!
13860// override this function in implementation classes.
13861// 'chunk' is an input chunk.
13862//
13863// Call `push(newChunk)` to pass along transformed output
13864// to the readable side. You may call 'push' zero or more times.
13865//
13866// Call `cb(err)` when you are done with this chunk. If you pass
13867// an error, then that'll put the hurt on the whole operation. If you
13868// never call cb(), then you'll never get another chunk.
13869Transform.prototype._transform = function (chunk, encoding, cb) {
13870 throw new Error('Not implemented');
13871};
13872
13873Transform.prototype._write = function (chunk, encoding, cb) {
13874 var ts = this._transformState;
13875 ts.writecb = cb;
13876 ts.writechunk = chunk;
13877 ts.writeencoding = encoding;
13878 if (!ts.transforming) {
13879 var rs = this._readableState;
13880 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
13881 }
13882};
13883
13884// Doesn't matter what the args are here.
13885// _transform does all the work.
13886// That we got here means that the readable side wants more data.
13887Transform.prototype._read = function (n) {
13888 var ts = this._transformState;
13889
13890 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
13891 ts.transforming = true;
13892 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
13893 } else {
13894 // mark that we need a transform, so that any data that comes in
13895 // will get processed, now that we've asked for it.
13896 ts.needTransform = true;
13897 }
13898};
13899
13900function done(stream, er) {
13901 if (er) return stream.emit('error', er);
13902
13903 // if there's nothing in the write buffer, then that means
13904 // that nothing more will ever be provided
13905 var ws = stream._writableState;
13906 var ts = stream._transformState;
13907
13908 if (ws.length) throw new Error('Calling transform done when ws.length != 0');
13909
13910 if (ts.transforming) throw new Error('Calling transform done when still transforming');
13911
13912 return stream.push(null);
13913}
13914},{"./_stream_duplex":69,"core-util-is":45,"inherits":51}],73:[function(require,module,exports){
13915(function (process){
13916// A bit simpler than readable streams.
13917// Implement an async ._write(chunk, encoding, cb), and it'll handle all
13918// the drain event emission and buffering.
13919
13920'use strict';
13921
13922module.exports = Writable;
13923
13924/*<replacement>*/
13925var processNextTick = require('process-nextick-args');
13926/*</replacement>*/
13927
13928/*<replacement>*/
13929var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
13930/*</replacement>*/
13931
13932Writable.WritableState = WritableState;
13933
13934/*<replacement>*/
13935var util = require('core-util-is');
13936util.inherits = require('inherits');
13937/*</replacement>*/
13938
13939/*<replacement>*/
13940var internalUtil = {
13941 deprecate: require('util-deprecate')
13942};
13943/*</replacement>*/
13944
13945/*<replacement>*/
13946var Stream;
13947(function () {
13948 try {
13949 Stream = require('st' + 'ream');
13950 } catch (_) {} finally {
13951 if (!Stream) Stream = require('events').EventEmitter;
13952 }
13953})();
13954/*</replacement>*/
13955
13956var Buffer = require('buffer').Buffer;
13957/*<replacement>*/
13958var bufferShim = require('buffer-shims');
13959/*</replacement>*/
13960
13961util.inherits(Writable, Stream);
13962
13963function nop() {}
13964
13965function WriteReq(chunk, encoding, cb) {
13966 this.chunk = chunk;
13967 this.encoding = encoding;
13968 this.callback = cb;
13969 this.next = null;
13970}
13971
13972var Duplex;
13973function WritableState(options, stream) {
13974 Duplex = Duplex || require('./_stream_duplex');
13975
13976 options = options || {};
13977
13978 // object stream flag to indicate whether or not this stream
13979 // contains buffers or objects.
13980 this.objectMode = !!options.objectMode;
13981
13982 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
13983
13984 // the point at which write() starts returning false
13985 // Note: 0 is a valid value, means that we always return false if
13986 // the entire buffer is not flushed immediately on write()
13987 var hwm = options.highWaterMark;
13988 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
13989 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
13990
13991 // cast to ints.
13992 this.highWaterMark = ~ ~this.highWaterMark;
13993
13994 this.needDrain = false;
13995 // at the start of calling end()
13996 this.ending = false;
13997 // when end() has been called, and returned
13998 this.ended = false;
13999 // when 'finish' is emitted
14000 this.finished = false;
14001
14002 // should we decode strings into buffers before passing to _write?
14003 // this is here so that some node-core streams can optimize string
14004 // handling at a lower level.
14005 var noDecode = options.decodeStrings === false;
14006 this.decodeStrings = !noDecode;
14007
14008 // Crypto is kind of old and crusty. Historically, its default string
14009 // encoding is 'binary' so we have to make this configurable.
14010 // Everything else in the universe uses 'utf8', though.
14011 this.defaultEncoding = options.defaultEncoding || 'utf8';
14012
14013 // not an actual buffer we keep track of, but a measurement
14014 // of how much we're waiting to get pushed to some underlying
14015 // socket or file.
14016 this.length = 0;
14017
14018 // a flag to see when we're in the middle of a write.
14019 this.writing = false;
14020
14021 // when true all writes will be buffered until .uncork() call
14022 this.corked = 0;
14023
14024 // a flag to be able to tell if the onwrite cb is called immediately,
14025 // or on a later tick. We set this to true at first, because any
14026 // actions that shouldn't happen until "later" should generally also
14027 // not happen before the first write call.
14028 this.sync = true;
14029
14030 // a flag to know if we're processing previously buffered items, which
14031 // may call the _write() callback in the same tick, so that we don't
14032 // end up in an overlapped onwrite situation.
14033 this.bufferProcessing = false;
14034
14035 // the callback that's passed to _write(chunk,cb)
14036 this.onwrite = function (er) {
14037 onwrite(stream, er);
14038 };
14039
14040 // the callback that the user supplies to write(chunk,encoding,cb)
14041 this.writecb = null;
14042
14043 // the amount that is being written when _write is called.
14044 this.writelen = 0;
14045
14046 this.bufferedRequest = null;
14047 this.lastBufferedRequest = null;
14048
14049 // number of pending user-supplied write callbacks
14050 // this must be 0 before 'finish' can be emitted
14051 this.pendingcb = 0;
14052
14053 // emit prefinish if the only thing we're waiting for is _write cbs
14054 // This is relevant for synchronous Transform streams
14055 this.prefinished = false;
14056
14057 // True if the error was already emitted and should not be thrown again
14058 this.errorEmitted = false;
14059
14060 // count buffered requests
14061 this.bufferedRequestCount = 0;
14062
14063 // allocate the first CorkedRequest, there is always
14064 // one allocated and free to use, and we maintain at most two
14065 this.corkedRequestsFree = new CorkedRequest(this);
14066}
14067
14068WritableState.prototype.getBuffer = function writableStateGetBuffer() {
14069 var current = this.bufferedRequest;
14070 var out = [];
14071 while (current) {
14072 out.push(current);
14073 current = current.next;
14074 }
14075 return out;
14076};
14077
14078(function () {
14079 try {
14080 Object.defineProperty(WritableState.prototype, 'buffer', {
14081 get: internalUtil.deprecate(function () {
14082 return this.getBuffer();
14083 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
14084 });
14085 } catch (_) {}
14086})();
14087
14088var Duplex;
14089function Writable(options) {
14090 Duplex = Duplex || require('./_stream_duplex');
14091
14092 // Writable ctor is applied to Duplexes, though they're not
14093 // instanceof Writable, they're instanceof Readable.
14094 if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options);
14095
14096 this._writableState = new WritableState(options, this);
14097
14098 // legacy.
14099 this.writable = true;
14100
14101 if (options) {
14102 if (typeof options.write === 'function') this._write = options.write;
14103
14104 if (typeof options.writev === 'function') this._writev = options.writev;
14105 }
14106
14107 Stream.call(this);
14108}
14109
14110// Otherwise people can pipe Writable streams, which is just wrong.
14111Writable.prototype.pipe = function () {
14112 this.emit('error', new Error('Cannot pipe, not readable'));
14113};
14114
14115function writeAfterEnd(stream, cb) {
14116 var er = new Error('write after end');
14117 // TODO: defer error events consistently everywhere, not just the cb
14118 stream.emit('error', er);
14119 processNextTick(cb, er);
14120}
14121
14122// If we get something that is not a buffer, string, null, or undefined,
14123// and we're not in objectMode, then that's an error.
14124// Otherwise stream chunks are all considered to be of length=1, and the
14125// watermarks determine how many objects to keep in the buffer, rather than
14126// how many bytes or characters.
14127function validChunk(stream, state, chunk, cb) {
14128 var valid = true;
14129 var er = false;
14130 // Always throw error if a null is written
14131 // if we are not in object mode then throw
14132 // if it is not a buffer, string, or undefined.
14133 if (chunk === null) {
14134 er = new TypeError('May not write null values to stream');
14135 } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
14136 er = new TypeError('Invalid non-string/buffer chunk');
14137 }
14138 if (er) {
14139 stream.emit('error', er);
14140 processNextTick(cb, er);
14141 valid = false;
14142 }
14143 return valid;
14144}
14145
14146Writable.prototype.write = function (chunk, encoding, cb) {
14147 var state = this._writableState;
14148 var ret = false;
14149
14150 if (typeof encoding === 'function') {
14151 cb = encoding;
14152 encoding = null;
14153 }
14154
14155 if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
14156
14157 if (typeof cb !== 'function') cb = nop;
14158
14159 if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) {
14160 state.pendingcb++;
14161 ret = writeOrBuffer(this, state, chunk, encoding, cb);
14162 }
14163
14164 return ret;
14165};
14166
14167Writable.prototype.cork = function () {
14168 var state = this._writableState;
14169
14170 state.corked++;
14171};
14172
14173Writable.prototype.uncork = function () {
14174 var state = this._writableState;
14175
14176 if (state.corked) {
14177 state.corked--;
14178
14179 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
14180 }
14181};
14182
14183Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
14184 // node::ParseEncoding() requires lower case.
14185 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
14186 if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
14187 this._writableState.defaultEncoding = encoding;
14188 return this;
14189};
14190
14191function decodeChunk(state, chunk, encoding) {
14192 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
14193 chunk = bufferShim.from(chunk, encoding);
14194 }
14195 return chunk;
14196}
14197
14198// if we're already writing something, then just put this
14199// in the queue, and wait our turn. Otherwise, call _write
14200// If we return false, then we need a drain event, so set that flag.
14201function writeOrBuffer(stream, state, chunk, encoding, cb) {
14202 chunk = decodeChunk(state, chunk, encoding);
14203
14204 if (Buffer.isBuffer(chunk)) encoding = 'buffer';
14205 var len = state.objectMode ? 1 : chunk.length;
14206
14207 state.length += len;
14208
14209 var ret = state.length < state.highWaterMark;
14210 // we must ensure that previous needDrain will not be reset to false.
14211 if (!ret) state.needDrain = true;
14212
14213 if (state.writing || state.corked) {
14214 var last = state.lastBufferedRequest;
14215 state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
14216 if (last) {
14217 last.next = state.lastBufferedRequest;
14218 } else {
14219 state.bufferedRequest = state.lastBufferedRequest;
14220 }
14221 state.bufferedRequestCount += 1;
14222 } else {
14223 doWrite(stream, state, false, len, chunk, encoding, cb);
14224 }
14225
14226 return ret;
14227}
14228
14229function doWrite(stream, state, writev, len, chunk, encoding, cb) {
14230 state.writelen = len;
14231 state.writecb = cb;
14232 state.writing = true;
14233 state.sync = true;
14234 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
14235 state.sync = false;
14236}
14237
14238function onwriteError(stream, state, sync, er, cb) {
14239 --state.pendingcb;
14240 if (sync) processNextTick(cb, er);else cb(er);
14241
14242 stream._writableState.errorEmitted = true;
14243 stream.emit('error', er);
14244}
14245
14246function onwriteStateUpdate(state) {
14247 state.writing = false;
14248 state.writecb = null;
14249 state.length -= state.writelen;
14250 state.writelen = 0;
14251}
14252
14253function onwrite(stream, er) {
14254 var state = stream._writableState;
14255 var sync = state.sync;
14256 var cb = state.writecb;
14257
14258 onwriteStateUpdate(state);
14259
14260 if (er) onwriteError(stream, state, sync, er, cb);else {
14261 // Check if we're actually ready to finish, but don't emit yet
14262 var finished = needFinish(state);
14263
14264 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
14265 clearBuffer(stream, state);
14266 }
14267
14268 if (sync) {
14269 /*<replacement>*/
14270 asyncWrite(afterWrite, stream, state, finished, cb);
14271 /*</replacement>*/
14272 } else {
14273 afterWrite(stream, state, finished, cb);
14274 }
14275 }
14276}
14277
14278function afterWrite(stream, state, finished, cb) {
14279 if (!finished) onwriteDrain(stream, state);
14280 state.pendingcb--;
14281 cb();
14282 finishMaybe(stream, state);
14283}
14284
14285// Must force callback to be called on nextTick, so that we don't
14286// emit 'drain' before the write() consumer gets the 'false' return
14287// value, and has a chance to attach a 'drain' listener.
14288function onwriteDrain(stream, state) {
14289 if (state.length === 0 && state.needDrain) {
14290 state.needDrain = false;
14291 stream.emit('drain');
14292 }
14293}
14294
14295// if there's something in the buffer waiting, then process it
14296function clearBuffer(stream, state) {
14297 state.bufferProcessing = true;
14298 var entry = state.bufferedRequest;
14299
14300 if (stream._writev && entry && entry.next) {
14301 // Fast case, write everything using _writev()
14302 var l = state.bufferedRequestCount;
14303 var buffer = new Array(l);
14304 var holder = state.corkedRequestsFree;
14305 holder.entry = entry;
14306
14307 var count = 0;
14308 while (entry) {
14309 buffer[count] = entry;
14310 entry = entry.next;
14311 count += 1;
14312 }
14313
14314 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
14315
14316 // doWrite is almost always async, defer these to save a bit of time
14317 // as the hot path ends with doWrite
14318 state.pendingcb++;
14319 state.lastBufferedRequest = null;
14320 if (holder.next) {
14321 state.corkedRequestsFree = holder.next;
14322 holder.next = null;
14323 } else {
14324 state.corkedRequestsFree = new CorkedRequest(state);
14325 }
14326 } else {
14327 // Slow case, write chunks one-by-one
14328 while (entry) {
14329 var chunk = entry.chunk;
14330 var encoding = entry.encoding;
14331 var cb = entry.callback;
14332 var len = state.objectMode ? 1 : chunk.length;
14333
14334 doWrite(stream, state, false, len, chunk, encoding, cb);
14335 entry = entry.next;
14336 // if we didn't call the onwrite immediately, then
14337 // it means that we need to wait until it does.
14338 // also, that means that the chunk and cb are currently
14339 // being processed, so move the buffer counter past them.
14340 if (state.writing) {
14341 break;
14342 }
14343 }
14344
14345 if (entry === null) state.lastBufferedRequest = null;
14346 }
14347
14348 state.bufferedRequestCount = 0;
14349 state.bufferedRequest = entry;
14350 state.bufferProcessing = false;
14351}
14352
14353Writable.prototype._write = function (chunk, encoding, cb) {
14354 cb(new Error('not implemented'));
14355};
14356
14357Writable.prototype._writev = null;
14358
14359Writable.prototype.end = function (chunk, encoding, cb) {
14360 var state = this._writableState;
14361
14362 if (typeof chunk === 'function') {
14363 cb = chunk;
14364 chunk = null;
14365 encoding = null;
14366 } else if (typeof encoding === 'function') {
14367 cb = encoding;
14368 encoding = null;
14369 }
14370
14371 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
14372
14373 // .end() fully uncorks
14374 if (state.corked) {
14375 state.corked = 1;
14376 this.uncork();
14377 }
14378
14379 // ignore unnecessary end() calls.
14380 if (!state.ending && !state.finished) endWritable(this, state, cb);
14381};
14382
14383function needFinish(state) {
14384 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
14385}
14386
14387function prefinish(stream, state) {
14388 if (!state.prefinished) {
14389 state.prefinished = true;
14390 stream.emit('prefinish');
14391 }
14392}
14393
14394function finishMaybe(stream, state) {
14395 var need = needFinish(state);
14396 if (need) {
14397 if (state.pendingcb === 0) {
14398 prefinish(stream, state);
14399 state.finished = true;
14400 stream.emit('finish');
14401 } else {
14402 prefinish(stream, state);
14403 }
14404 }
14405 return need;
14406}
14407
14408function endWritable(stream, state, cb) {
14409 state.ending = true;
14410 finishMaybe(stream, state);
14411 if (cb) {
14412 if (state.finished) processNextTick(cb);else stream.once('finish', cb);
14413 }
14414 state.ended = true;
14415 stream.writable = false;
14416}
14417
14418// It seems a linked list but it is not
14419// there will be only 2 of these for each stream
14420function CorkedRequest(state) {
14421 var _this = this;
14422
14423 this.next = null;
14424 this.entry = null;
14425
14426 this.finish = function (err) {
14427 var entry = _this.entry;
14428 _this.entry = null;
14429 while (entry) {
14430 var cb = entry.callback;
14431 state.pendingcb--;
14432 cb(err);
14433 entry = entry.next;
14434 }
14435 if (state.corkedRequestsFree) {
14436 state.corkedRequestsFree.next = _this;
14437 } else {
14438 state.corkedRequestsFree = _this;
14439 }
14440 };
14441}
14442}).call(this,require('_process'))
14443},{"./_stream_duplex":69,"_process":67,"buffer":44,"buffer-shims":43,"core-util-is":45,"events":48,"inherits":51,"process-nextick-args":66,"util-deprecate":81}],74:[function(require,module,exports){
14444'use strict';
14445
14446var Buffer = require('buffer').Buffer;
14447/*<replacement>*/
14448var bufferShim = require('buffer-shims');
14449/*</replacement>*/
14450
14451module.exports = BufferList;
14452
14453function BufferList() {
14454 this.head = null;
14455 this.tail = null;
14456 this.length = 0;
14457}
14458
14459BufferList.prototype.push = function (v) {
14460 var entry = { data: v, next: null };
14461 if (this.length > 0) this.tail.next = entry;else this.head = entry;
14462 this.tail = entry;
14463 ++this.length;
14464};
14465
14466BufferList.prototype.unshift = function (v) {
14467 var entry = { data: v, next: this.head };
14468 if (this.length === 0) this.tail = entry;
14469 this.head = entry;
14470 ++this.length;
14471};
14472
14473BufferList.prototype.shift = function () {
14474 if (this.length === 0) return;
14475 var ret = this.head.data;
14476 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
14477 --this.length;
14478 return ret;
14479};
14480
14481BufferList.prototype.clear = function () {
14482 this.head = this.tail = null;
14483 this.length = 0;
14484};
14485
14486BufferList.prototype.join = function (s) {
14487 if (this.length === 0) return '';
14488 var p = this.head;
14489 var ret = '' + p.data;
14490 while (p = p.next) {
14491 ret += s + p.data;
14492 }return ret;
14493};
14494
14495BufferList.prototype.concat = function (n) {
14496 if (this.length === 0) return bufferShim.alloc(0);
14497 if (this.length === 1) return this.head.data;
14498 var ret = bufferShim.allocUnsafe(n >>> 0);
14499 var p = this.head;
14500 var i = 0;
14501 while (p) {
14502 p.data.copy(ret, i);
14503 i += p.data.length;
14504 p = p.next;
14505 }
14506 return ret;
14507};
14508},{"buffer":44,"buffer-shims":43}],75:[function(require,module,exports){
14509module.exports = require("./lib/_stream_passthrough.js")
14510
14511},{"./lib/_stream_passthrough.js":70}],76:[function(require,module,exports){
14512(function (process){
14513var Stream = (function (){
14514 try {
14515 return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify
14516 } catch(_){}
14517}());
14518exports = module.exports = require('./lib/_stream_readable.js');
14519exports.Stream = Stream || exports;
14520exports.Readable = exports;
14521exports.Writable = require('./lib/_stream_writable.js');
14522exports.Duplex = require('./lib/_stream_duplex.js');
14523exports.Transform = require('./lib/_stream_transform.js');
14524exports.PassThrough = require('./lib/_stream_passthrough.js');
14525
14526if (!process.browser && process.env.READABLE_STREAM === 'disable' && Stream) {
14527 module.exports = Stream;
14528}
14529
14530}).call(this,require('_process'))
14531},{"./lib/_stream_duplex.js":69,"./lib/_stream_passthrough.js":70,"./lib/_stream_readable.js":71,"./lib/_stream_transform.js":72,"./lib/_stream_writable.js":73,"_process":67}],77:[function(require,module,exports){
14532module.exports = require("./lib/_stream_transform.js")
14533
14534},{"./lib/_stream_transform.js":72}],78:[function(require,module,exports){
14535module.exports = require("./lib/_stream_writable.js")
14536
14537},{"./lib/_stream_writable.js":73}],79:[function(require,module,exports){
14538// Copyright Joyent, Inc. and other Node contributors.
14539//
14540// Permission is hereby granted, free of charge, to any person obtaining a
14541// copy of this software and associated documentation files (the
14542// "Software"), to deal in the Software without restriction, including
14543// without limitation the rights to use, copy, modify, merge, publish,
14544// distribute, sublicense, and/or sell copies of the Software, and to permit
14545// persons to whom the Software is furnished to do so, subject to the
14546// following conditions:
14547//
14548// The above copyright notice and this permission notice shall be included
14549// in all copies or substantial portions of the Software.
14550//
14551// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14552// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14553// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14554// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14555// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14556// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14557// USE OR OTHER DEALINGS IN THE SOFTWARE.
14558
14559module.exports = Stream;
14560
14561var EE = require('events').EventEmitter;
14562var inherits = require('inherits');
14563
14564inherits(Stream, EE);
14565Stream.Readable = require('readable-stream/readable.js');
14566Stream.Writable = require('readable-stream/writable.js');
14567Stream.Duplex = require('readable-stream/duplex.js');
14568Stream.Transform = require('readable-stream/transform.js');
14569Stream.PassThrough = require('readable-stream/passthrough.js');
14570
14571// Backwards-compat with node 0.4.x
14572Stream.Stream = Stream;
14573
14574
14575
14576// old-style streams. Note that the pipe method (the only relevant
14577// part of this class) is overridden in the Readable class.
14578
14579function Stream() {
14580 EE.call(this);
14581}
14582
14583Stream.prototype.pipe = function(dest, options) {
14584 var source = this;
14585
14586 function ondata(chunk) {
14587 if (dest.writable) {
14588 if (false === dest.write(chunk) && source.pause) {
14589 source.pause();
14590 }
14591 }
14592 }
14593
14594 source.on('data', ondata);
14595
14596 function ondrain() {
14597 if (source.readable && source.resume) {
14598 source.resume();
14599 }
14600 }
14601
14602 dest.on('drain', ondrain);
14603
14604 // If the 'end' option is not supplied, dest.end() will be called when
14605 // source gets the 'end' or 'close' events. Only dest.end() once.
14606 if (!dest._isStdio && (!options || options.end !== false)) {
14607 source.on('end', onend);
14608 source.on('close', onclose);
14609 }
14610
14611 var didOnEnd = false;
14612 function onend() {
14613 if (didOnEnd) return;
14614 didOnEnd = true;
14615
14616 dest.end();
14617 }
14618
14619
14620 function onclose() {
14621 if (didOnEnd) return;
14622 didOnEnd = true;
14623
14624 if (typeof dest.destroy === 'function') dest.destroy();
14625 }
14626
14627 // don't leave dangling pipes when there are errors.
14628 function onerror(er) {
14629 cleanup();
14630 if (EE.listenerCount(this, 'error') === 0) {
14631 throw er; // Unhandled stream error in pipe.
14632 }
14633 }
14634
14635 source.on('error', onerror);
14636 dest.on('error', onerror);
14637
14638 // remove all the event listeners that were added.
14639 function cleanup() {
14640 source.removeListener('data', ondata);
14641 dest.removeListener('drain', ondrain);
14642
14643 source.removeListener('end', onend);
14644 source.removeListener('close', onclose);
14645
14646 source.removeListener('error', onerror);
14647 dest.removeListener('error', onerror);
14648
14649 source.removeListener('end', cleanup);
14650 source.removeListener('close', cleanup);
14651
14652 dest.removeListener('close', cleanup);
14653 }
14654
14655 source.on('end', cleanup);
14656 source.on('close', cleanup);
14657
14658 dest.on('close', cleanup);
14659
14660 dest.emit('pipe', source);
14661
14662 // Allow for unix-like usage: A.pipe(B).pipe(C)
14663 return dest;
14664};
14665
14666},{"events":48,"inherits":51,"readable-stream/duplex.js":68,"readable-stream/passthrough.js":75,"readable-stream/readable.js":76,"readable-stream/transform.js":77,"readable-stream/writable.js":78}],80:[function(require,module,exports){
14667// Copyright Joyent, Inc. and other Node contributors.
14668//
14669// Permission is hereby granted, free of charge, to any person obtaining a
14670// copy of this software and associated documentation files (the
14671// "Software"), to deal in the Software without restriction, including
14672// without limitation the rights to use, copy, modify, merge, publish,
14673// distribute, sublicense, and/or sell copies of the Software, and to permit
14674// persons to whom the Software is furnished to do so, subject to the
14675// following conditions:
14676//
14677// The above copyright notice and this permission notice shall be included
14678// in all copies or substantial portions of the Software.
14679//
14680// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14681// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14682// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14683// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14684// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14685// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14686// USE OR OTHER DEALINGS IN THE SOFTWARE.
14687
14688var Buffer = require('buffer').Buffer;
14689
14690var isBufferEncoding = Buffer.isEncoding
14691 || function(encoding) {
14692 switch (encoding && encoding.toLowerCase()) {
14693 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;
14694 default: return false;
14695 }
14696 }
14697
14698
14699function assertEncoding(encoding) {
14700 if (encoding && !isBufferEncoding(encoding)) {
14701 throw new Error('Unknown encoding: ' + encoding);
14702 }
14703}
14704
14705// StringDecoder provides an interface for efficiently splitting a series of
14706// buffers into a series of JS strings without breaking apart multi-byte
14707// characters. CESU-8 is handled as part of the UTF-8 encoding.
14708//
14709// @TODO Handling all encodings inside a single object makes it very difficult
14710// to reason about this code, so it should be split up in the future.
14711// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
14712// points as used by CESU-8.
14713var StringDecoder = exports.StringDecoder = function(encoding) {
14714 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
14715 assertEncoding(encoding);
14716 switch (this.encoding) {
14717 case 'utf8':
14718 // CESU-8 represents each of Surrogate Pair by 3-bytes
14719 this.surrogateSize = 3;
14720 break;
14721 case 'ucs2':
14722 case 'utf16le':
14723 // UTF-16 represents each of Surrogate Pair by 2-bytes
14724 this.surrogateSize = 2;
14725 this.detectIncompleteChar = utf16DetectIncompleteChar;
14726 break;
14727 case 'base64':
14728 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
14729 this.surrogateSize = 3;
14730 this.detectIncompleteChar = base64DetectIncompleteChar;
14731 break;
14732 default:
14733 this.write = passThroughWrite;
14734 return;
14735 }
14736
14737 // Enough space to store all bytes of a single character. UTF-8 needs 4
14738 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
14739 this.charBuffer = new Buffer(6);
14740 // Number of bytes received for the current incomplete multi-byte character.
14741 this.charReceived = 0;
14742 // Number of bytes expected for the current incomplete multi-byte character.
14743 this.charLength = 0;
14744};
14745
14746
14747// write decodes the given buffer and returns it as JS string that is
14748// guaranteed to not contain any partial multi-byte characters. Any partial
14749// character found at the end of the buffer is buffered up, and will be
14750// returned when calling write again with the remaining bytes.
14751//
14752// Note: Converting a Buffer containing an orphan surrogate to a String
14753// currently works, but converting a String to a Buffer (via `new Buffer`, or
14754// Buffer#write) will replace incomplete surrogates with the unicode
14755// replacement character. See https://codereview.chromium.org/121173009/ .
14756StringDecoder.prototype.write = function(buffer) {
14757 var charStr = '';
14758 // if our last write ended with an incomplete multibyte character
14759 while (this.charLength) {
14760 // determine how many remaining bytes this buffer has to offer for this char
14761 var available = (buffer.length >= this.charLength - this.charReceived) ?
14762 this.charLength - this.charReceived :
14763 buffer.length;
14764
14765 // add the new bytes to the char buffer
14766 buffer.copy(this.charBuffer, this.charReceived, 0, available);
14767 this.charReceived += available;
14768
14769 if (this.charReceived < this.charLength) {
14770 // still not enough chars in this buffer? wait for more ...
14771 return '';
14772 }
14773
14774 // remove bytes belonging to the current character from the buffer
14775 buffer = buffer.slice(available, buffer.length);
14776
14777 // get the character that was split
14778 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
14779
14780 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
14781 var charCode = charStr.charCodeAt(charStr.length - 1);
14782 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
14783 this.charLength += this.surrogateSize;
14784 charStr = '';
14785 continue;
14786 }
14787 this.charReceived = this.charLength = 0;
14788
14789 // if there are no more bytes in this buffer, just emit our char
14790 if (buffer.length === 0) {
14791 return charStr;
14792 }
14793 break;
14794 }
14795
14796 // determine and set charLength / charReceived
14797 this.detectIncompleteChar(buffer);
14798
14799 var end = buffer.length;
14800 if (this.charLength) {
14801 // buffer the incomplete character bytes we got
14802 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
14803 end -= this.charReceived;
14804 }
14805
14806 charStr += buffer.toString(this.encoding, 0, end);
14807
14808 var end = charStr.length - 1;
14809 var charCode = charStr.charCodeAt(end);
14810 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
14811 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
14812 var size = this.surrogateSize;
14813 this.charLength += size;
14814 this.charReceived += size;
14815 this.charBuffer.copy(this.charBuffer, size, 0, size);
14816 buffer.copy(this.charBuffer, 0, 0, size);
14817 return charStr.substring(0, end);
14818 }
14819
14820 // or just emit the charStr
14821 return charStr;
14822};
14823
14824// detectIncompleteChar determines if there is an incomplete UTF-8 character at
14825// the end of the given buffer. If so, it sets this.charLength to the byte
14826// length that character, and sets this.charReceived to the number of bytes
14827// that are available for this character.
14828StringDecoder.prototype.detectIncompleteChar = function(buffer) {
14829 // determine how many bytes we have to check at the end of this buffer
14830 var i = (buffer.length >= 3) ? 3 : buffer.length;
14831
14832 // Figure out if one of the last i bytes of our buffer announces an
14833 // incomplete char.
14834 for (; i > 0; i--) {
14835 var c = buffer[buffer.length - i];
14836
14837 // See http://en.wikipedia.org/wiki/UTF-8#Description
14838
14839 // 110XXXXX
14840 if (i == 1 && c >> 5 == 0x06) {
14841 this.charLength = 2;
14842 break;
14843 }
14844
14845 // 1110XXXX
14846 if (i <= 2 && c >> 4 == 0x0E) {
14847 this.charLength = 3;
14848 break;
14849 }
14850
14851 // 11110XXX
14852 if (i <= 3 && c >> 3 == 0x1E) {
14853 this.charLength = 4;
14854 break;
14855 }
14856 }
14857 this.charReceived = i;
14858};
14859
14860StringDecoder.prototype.end = function(buffer) {
14861 var res = '';
14862 if (buffer && buffer.length)
14863 res = this.write(buffer);
14864
14865 if (this.charReceived) {
14866 var cr = this.charReceived;
14867 var buf = this.charBuffer;
14868 var enc = this.encoding;
14869 res += buf.slice(0, cr).toString(enc);
14870 }
14871
14872 return res;
14873};
14874
14875function passThroughWrite(buffer) {
14876 return buffer.toString(this.encoding);
14877}
14878
14879function utf16DetectIncompleteChar(buffer) {
14880 this.charReceived = buffer.length % 2;
14881 this.charLength = this.charReceived ? 2 : 0;
14882}
14883
14884function base64DetectIncompleteChar(buffer) {
14885 this.charReceived = buffer.length % 3;
14886 this.charLength = this.charReceived ? 3 : 0;
14887}
14888
14889},{"buffer":44}],81:[function(require,module,exports){
14890(function (global){
14891
14892/**
14893 * Module exports.
14894 */
14895
14896module.exports = deprecate;
14897
14898/**
14899 * Mark that a method should not be used.
14900 * Returns a modified function which warns once by default.
14901 *
14902 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
14903 *
14904 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
14905 * will throw an Error when invoked.
14906 *
14907 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
14908 * will invoke `console.trace()` instead of `console.error()`.
14909 *
14910 * @param {Function} fn - the function to deprecate
14911 * @param {String} msg - the string to print to the console when `fn` is invoked
14912 * @returns {Function} a new "deprecated" version of `fn`
14913 * @api public
14914 */
14915
14916function deprecate (fn, msg) {
14917 if (config('noDeprecation')) {
14918 return fn;
14919 }
14920
14921 var warned = false;
14922 function deprecated() {
14923 if (!warned) {
14924 if (config('throwDeprecation')) {
14925 throw new Error(msg);
14926 } else if (config('traceDeprecation')) {
14927 console.trace(msg);
14928 } else {
14929 console.warn(msg);
14930 }
14931 warned = true;
14932 }
14933 return fn.apply(this, arguments);
14934 }
14935
14936 return deprecated;
14937}
14938
14939/**
14940 * Checks `localStorage` for boolean values for the given `name`.
14941 *
14942 * @param {String} name
14943 * @returns {Boolean}
14944 * @api private
14945 */
14946
14947function config (name) {
14948 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
14949 try {
14950 if (!global.localStorage) return false;
14951 } catch (_) {
14952 return false;
14953 }
14954 var val = global.localStorage[name];
14955 if (null == val) return false;
14956 return String(val).toLowerCase() === 'true';
14957}
14958
14959}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
14960},{}],82:[function(require,module,exports){
14961arguments[4][51][0].apply(exports,arguments)
14962},{"dup":51}],83:[function(require,module,exports){
14963module.exports = function isBuffer(arg) {
14964 return arg && typeof arg === 'object'
14965 && typeof arg.copy === 'function'
14966 && typeof arg.fill === 'function'
14967 && typeof arg.readUInt8 === 'function';
14968}
14969},{}],84:[function(require,module,exports){
14970(function (process,global){
14971// Copyright Joyent, Inc. and other Node contributors.
14972//
14973// Permission is hereby granted, free of charge, to any person obtaining a
14974// copy of this software and associated documentation files (the
14975// "Software"), to deal in the Software without restriction, including
14976// without limitation the rights to use, copy, modify, merge, publish,
14977// distribute, sublicense, and/or sell copies of the Software, and to permit
14978// persons to whom the Software is furnished to do so, subject to the
14979// following conditions:
14980//
14981// The above copyright notice and this permission notice shall be included
14982// in all copies or substantial portions of the Software.
14983//
14984// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14985// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14986// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14987// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14988// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14989// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14990// USE OR OTHER DEALINGS IN THE SOFTWARE.
14991
14992var formatRegExp = /%[sdj%]/g;
14993exports.format = function(f) {
14994 if (!isString(f)) {
14995 var objects = [];
14996 for (var i = 0; i < arguments.length; i++) {
14997 objects.push(inspect(arguments[i]));
14998 }
14999 return objects.join(' ');
15000 }
15001
15002 var i = 1;
15003 var args = arguments;
15004 var len = args.length;
15005 var str = String(f).replace(formatRegExp, function(x) {
15006 if (x === '%%') return '%';
15007 if (i >= len) return x;
15008 switch (x) {
15009 case '%s': return String(args[i++]);
15010 case '%d': return Number(args[i++]);
15011 case '%j':
15012 try {
15013 return JSON.stringify(args[i++]);
15014 } catch (_) {
15015 return '[Circular]';
15016 }
15017 default:
15018 return x;
15019 }
15020 });
15021 for (var x = args[i]; i < len; x = args[++i]) {
15022 if (isNull(x) || !isObject(x)) {
15023 str += ' ' + x;
15024 } else {
15025 str += ' ' + inspect(x);
15026 }
15027 }
15028 return str;
15029};
15030
15031
15032// Mark that a method should not be used.
15033// Returns a modified function which warns once by default.
15034// If --no-deprecation is set, then it is a no-op.
15035exports.deprecate = function(fn, msg) {
15036 // Allow for deprecating things in the process of starting up.
15037 if (isUndefined(global.process)) {
15038 return function() {
15039 return exports.deprecate(fn, msg).apply(this, arguments);
15040 };
15041 }
15042
15043 if (process.noDeprecation === true) {
15044 return fn;
15045 }
15046
15047 var warned = false;
15048 function deprecated() {
15049 if (!warned) {
15050 if (process.throwDeprecation) {
15051 throw new Error(msg);
15052 } else if (process.traceDeprecation) {
15053 console.trace(msg);
15054 } else {
15055 console.error(msg);
15056 }
15057 warned = true;
15058 }
15059 return fn.apply(this, arguments);
15060 }
15061
15062 return deprecated;
15063};
15064
15065
15066var debugs = {};
15067var debugEnviron;
15068exports.debuglog = function(set) {
15069 if (isUndefined(debugEnviron))
15070 debugEnviron = process.env.NODE_DEBUG || '';
15071 set = set.toUpperCase();
15072 if (!debugs[set]) {
15073 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
15074 var pid = process.pid;
15075 debugs[set] = function() {
15076 var msg = exports.format.apply(exports, arguments);
15077 console.error('%s %d: %s', set, pid, msg);
15078 };
15079 } else {
15080 debugs[set] = function() {};
15081 }
15082 }
15083 return debugs[set];
15084};
15085
15086
15087/**
15088 * Echos the value of a value. Trys to print the value out
15089 * in the best way possible given the different types.
15090 *
15091 * @param {Object} obj The object to print out.
15092 * @param {Object} opts Optional options object that alters the output.
15093 */
15094/* legacy: obj, showHidden, depth, colors*/
15095function inspect(obj, opts) {
15096 // default options
15097 var ctx = {
15098 seen: [],
15099 stylize: stylizeNoColor
15100 };
15101 // legacy...
15102 if (arguments.length >= 3) ctx.depth = arguments[2];
15103 if (arguments.length >= 4) ctx.colors = arguments[3];
15104 if (isBoolean(opts)) {
15105 // legacy...
15106 ctx.showHidden = opts;
15107 } else if (opts) {
15108 // got an "options" object
15109 exports._extend(ctx, opts);
15110 }
15111 // set default options
15112 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
15113 if (isUndefined(ctx.depth)) ctx.depth = 2;
15114 if (isUndefined(ctx.colors)) ctx.colors = false;
15115 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
15116 if (ctx.colors) ctx.stylize = stylizeWithColor;
15117 return formatValue(ctx, obj, ctx.depth);
15118}
15119exports.inspect = inspect;
15120
15121
15122// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
15123inspect.colors = {
15124 'bold' : [1, 22],
15125 'italic' : [3, 23],
15126 'underline' : [4, 24],
15127 'inverse' : [7, 27],
15128 'white' : [37, 39],
15129 'grey' : [90, 39],
15130 'black' : [30, 39],
15131 'blue' : [34, 39],
15132 'cyan' : [36, 39],
15133 'green' : [32, 39],
15134 'magenta' : [35, 39],
15135 'red' : [31, 39],
15136 'yellow' : [33, 39]
15137};
15138
15139// Don't use 'blue' not visible on cmd.exe
15140inspect.styles = {
15141 'special': 'cyan',
15142 'number': 'yellow',
15143 'boolean': 'yellow',
15144 'undefined': 'grey',
15145 'null': 'bold',
15146 'string': 'green',
15147 'date': 'magenta',
15148 // "name": intentionally not styling
15149 'regexp': 'red'
15150};
15151
15152
15153function stylizeWithColor(str, styleType) {
15154 var style = inspect.styles[styleType];
15155
15156 if (style) {
15157 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
15158 '\u001b[' + inspect.colors[style][1] + 'm';
15159 } else {
15160 return str;
15161 }
15162}
15163
15164
15165function stylizeNoColor(str, styleType) {
15166 return str;
15167}
15168
15169
15170function arrayToHash(array) {
15171 var hash = {};
15172
15173 array.forEach(function(val, idx) {
15174 hash[val] = true;
15175 });
15176
15177 return hash;
15178}
15179
15180
15181function formatValue(ctx, value, recurseTimes) {
15182 // Provide a hook for user-specified inspect functions.
15183 // Check that value is an object with an inspect function on it
15184 if (ctx.customInspect &&
15185 value &&
15186 isFunction(value.inspect) &&
15187 // Filter out the util module, it's inspect function is special
15188 value.inspect !== exports.inspect &&
15189 // Also filter out any prototype objects using the circular check.
15190 !(value.constructor && value.constructor.prototype === value)) {
15191 var ret = value.inspect(recurseTimes, ctx);
15192 if (!isString(ret)) {
15193 ret = formatValue(ctx, ret, recurseTimes);
15194 }
15195 return ret;
15196 }
15197
15198 // Primitive types cannot have properties
15199 var primitive = formatPrimitive(ctx, value);
15200 if (primitive) {
15201 return primitive;
15202 }
15203
15204 // Look up the keys of the object.
15205 var keys = Object.keys(value);
15206 var visibleKeys = arrayToHash(keys);
15207
15208 if (ctx.showHidden) {
15209 keys = Object.getOwnPropertyNames(value);
15210 }
15211
15212 // IE doesn't make error fields non-enumerable
15213 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
15214 if (isError(value)
15215 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
15216 return formatError(value);
15217 }
15218
15219 // Some type of object without properties can be shortcutted.
15220 if (keys.length === 0) {
15221 if (isFunction(value)) {
15222 var name = value.name ? ': ' + value.name : '';
15223 return ctx.stylize('[Function' + name + ']', 'special');
15224 }
15225 if (isRegExp(value)) {
15226 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
15227 }
15228 if (isDate(value)) {
15229 return ctx.stylize(Date.prototype.toString.call(value), 'date');
15230 }
15231 if (isError(value)) {
15232 return formatError(value);
15233 }
15234 }
15235
15236 var base = '', array = false, braces = ['{', '}'];
15237
15238 // Make Array say that they are Array
15239 if (isArray(value)) {
15240 array = true;
15241 braces = ['[', ']'];
15242 }
15243
15244 // Make functions say that they are functions
15245 if (isFunction(value)) {
15246 var n = value.name ? ': ' + value.name : '';
15247 base = ' [Function' + n + ']';
15248 }
15249
15250 // Make RegExps say that they are RegExps
15251 if (isRegExp(value)) {
15252 base = ' ' + RegExp.prototype.toString.call(value);
15253 }
15254
15255 // Make dates with properties first say the date
15256 if (isDate(value)) {
15257 base = ' ' + Date.prototype.toUTCString.call(value);
15258 }
15259
15260 // Make error with message first say the error
15261 if (isError(value)) {
15262 base = ' ' + formatError(value);
15263 }
15264
15265 if (keys.length === 0 && (!array || value.length == 0)) {
15266 return braces[0] + base + braces[1];
15267 }
15268
15269 if (recurseTimes < 0) {
15270 if (isRegExp(value)) {
15271 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
15272 } else {
15273 return ctx.stylize('[Object]', 'special');
15274 }
15275 }
15276
15277 ctx.seen.push(value);
15278
15279 var output;
15280 if (array) {
15281 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
15282 } else {
15283 output = keys.map(function(key) {
15284 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
15285 });
15286 }
15287
15288 ctx.seen.pop();
15289
15290 return reduceToSingleString(output, base, braces);
15291}
15292
15293
15294function formatPrimitive(ctx, value) {
15295 if (isUndefined(value))
15296 return ctx.stylize('undefined', 'undefined');
15297 if (isString(value)) {
15298 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
15299 .replace(/'/g, "\\'")
15300 .replace(/\\"/g, '"') + '\'';
15301 return ctx.stylize(simple, 'string');
15302 }
15303 if (isNumber(value))
15304 return ctx.stylize('' + value, 'number');
15305 if (isBoolean(value))
15306 return ctx.stylize('' + value, 'boolean');
15307 // For some reason typeof null is "object", so special case here.
15308 if (isNull(value))
15309 return ctx.stylize('null', 'null');
15310}
15311
15312
15313function formatError(value) {
15314 return '[' + Error.prototype.toString.call(value) + ']';
15315}
15316
15317
15318function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
15319 var output = [];
15320 for (var i = 0, l = value.length; i < l; ++i) {
15321 if (hasOwnProperty(value, String(i))) {
15322 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
15323 String(i), true));
15324 } else {
15325 output.push('');
15326 }
15327 }
15328 keys.forEach(function(key) {
15329 if (!key.match(/^\d+$/)) {
15330 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
15331 key, true));
15332 }
15333 });
15334 return output;
15335}
15336
15337
15338function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
15339 var name, str, desc;
15340 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
15341 if (desc.get) {
15342 if (desc.set) {
15343 str = ctx.stylize('[Getter/Setter]', 'special');
15344 } else {
15345 str = ctx.stylize('[Getter]', 'special');
15346 }
15347 } else {
15348 if (desc.set) {
15349 str = ctx.stylize('[Setter]', 'special');
15350 }
15351 }
15352 if (!hasOwnProperty(visibleKeys, key)) {
15353 name = '[' + key + ']';
15354 }
15355 if (!str) {
15356 if (ctx.seen.indexOf(desc.value) < 0) {
15357 if (isNull(recurseTimes)) {
15358 str = formatValue(ctx, desc.value, null);
15359 } else {
15360 str = formatValue(ctx, desc.value, recurseTimes - 1);
15361 }
15362 if (str.indexOf('\n') > -1) {
15363 if (array) {
15364 str = str.split('\n').map(function(line) {
15365 return ' ' + line;
15366 }).join('\n').substr(2);
15367 } else {
15368 str = '\n' + str.split('\n').map(function(line) {
15369 return ' ' + line;
15370 }).join('\n');
15371 }
15372 }
15373 } else {
15374 str = ctx.stylize('[Circular]', 'special');
15375 }
15376 }
15377 if (isUndefined(name)) {
15378 if (array && key.match(/^\d+$/)) {
15379 return str;
15380 }
15381 name = JSON.stringify('' + key);
15382 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
15383 name = name.substr(1, name.length - 2);
15384 name = ctx.stylize(name, 'name');
15385 } else {
15386 name = name.replace(/'/g, "\\'")
15387 .replace(/\\"/g, '"')
15388 .replace(/(^"|"$)/g, "'");
15389 name = ctx.stylize(name, 'string');
15390 }
15391 }
15392
15393 return name + ': ' + str;
15394}
15395
15396
15397function reduceToSingleString(output, base, braces) {
15398 var numLinesEst = 0;
15399 var length = output.reduce(function(prev, cur) {
15400 numLinesEst++;
15401 if (cur.indexOf('\n') >= 0) numLinesEst++;
15402 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
15403 }, 0);
15404
15405 if (length > 60) {
15406 return braces[0] +
15407 (base === '' ? '' : base + '\n ') +
15408 ' ' +
15409 output.join(',\n ') +
15410 ' ' +
15411 braces[1];
15412 }
15413
15414 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
15415}
15416
15417
15418// NOTE: These type checking functions intentionally don't use `instanceof`
15419// because it is fragile and can be easily faked with `Object.create()`.
15420function isArray(ar) {
15421 return Array.isArray(ar);
15422}
15423exports.isArray = isArray;
15424
15425function isBoolean(arg) {
15426 return typeof arg === 'boolean';
15427}
15428exports.isBoolean = isBoolean;
15429
15430function isNull(arg) {
15431 return arg === null;
15432}
15433exports.isNull = isNull;
15434
15435function isNullOrUndefined(arg) {
15436 return arg == null;
15437}
15438exports.isNullOrUndefined = isNullOrUndefined;
15439
15440function isNumber(arg) {
15441 return typeof arg === 'number';
15442}
15443exports.isNumber = isNumber;
15444
15445function isString(arg) {
15446 return typeof arg === 'string';
15447}
15448exports.isString = isString;
15449
15450function isSymbol(arg) {
15451 return typeof arg === 'symbol';
15452}
15453exports.isSymbol = isSymbol;
15454
15455function isUndefined(arg) {
15456 return arg === void 0;
15457}
15458exports.isUndefined = isUndefined;
15459
15460function isRegExp(re) {
15461 return isObject(re) && objectToString(re) === '[object RegExp]';
15462}
15463exports.isRegExp = isRegExp;
15464
15465function isObject(arg) {
15466 return typeof arg === 'object' && arg !== null;
15467}
15468exports.isObject = isObject;
15469
15470function isDate(d) {
15471 return isObject(d) && objectToString(d) === '[object Date]';
15472}
15473exports.isDate = isDate;
15474
15475function isError(e) {
15476 return isObject(e) &&
15477 (objectToString(e) === '[object Error]' || e instanceof Error);
15478}
15479exports.isError = isError;
15480
15481function isFunction(arg) {
15482 return typeof arg === 'function';
15483}
15484exports.isFunction = isFunction;
15485
15486function isPrimitive(arg) {
15487 return arg === null ||
15488 typeof arg === 'boolean' ||
15489 typeof arg === 'number' ||
15490 typeof arg === 'string' ||
15491 typeof arg === 'symbol' || // ES6 symbol
15492 typeof arg === 'undefined';
15493}
15494exports.isPrimitive = isPrimitive;
15495
15496exports.isBuffer = require('./support/isBuffer');
15497
15498function objectToString(o) {
15499 return Object.prototype.toString.call(o);
15500}
15501
15502
15503function pad(n) {
15504 return n < 10 ? '0' + n.toString(10) : n.toString(10);
15505}
15506
15507
15508var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
15509 'Oct', 'Nov', 'Dec'];
15510
15511// 26 Feb 16:19:34
15512function timestamp() {
15513 var d = new Date();
15514 var time = [pad(d.getHours()),
15515 pad(d.getMinutes()),
15516 pad(d.getSeconds())].join(':');
15517 return [d.getDate(), months[d.getMonth()], time].join(' ');
15518}
15519
15520
15521// log is just a thin wrapper to console.log that prepends a timestamp
15522exports.log = function() {
15523 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
15524};
15525
15526
15527/**
15528 * Inherit the prototype methods from one constructor into another.
15529 *
15530 * The Function.prototype.inherits from lang.js rewritten as a standalone
15531 * function (not on Function.prototype). NOTE: If this file is to be loaded
15532 * during bootstrapping this function needs to be rewritten using some native
15533 * functions as prototype setup using normal JavaScript does not work as
15534 * expected during bootstrapping (see mirror.js in r114903).
15535 *
15536 * @param {function} ctor Constructor function which needs to inherit the
15537 * prototype.
15538 * @param {function} superCtor Constructor function to inherit prototype from.
15539 */
15540exports.inherits = require('inherits');
15541
15542exports._extend = function(origin, add) {
15543 // Don't do anything if add isn't an object
15544 if (!add || !isObject(add)) return origin;
15545
15546 var keys = Object.keys(add);
15547 var i = keys.length;
15548 while (i--) {
15549 origin[keys[i]] = add[keys[i]];
15550 }
15551 return origin;
15552};
15553
15554function hasOwnProperty(obj, prop) {
15555 return Object.prototype.hasOwnProperty.call(obj, prop);
15556}
15557
15558}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
15559},{"./support/isBuffer":83,"_process":67,"inherits":82}]},{},[1]);