Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(192)

Side by Side Diff: appengine/config_service/ui/bower_components/mocha/mocha.js

Issue 2923973003: Added base template for config ui. (Closed)
Patch Set: Created 3 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="fu nction"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Ca nnot 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.ex ports,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
12 process.stdout = require('browser-stdout')();
13
14 var Mocha = require('./lib/mocha');
15
16 /**
17 * Create a Mocha instance.
18 *
19 * @return {undefined}
20 */
21
22 var mocha = new Mocha({ reporter: 'html' });
23
24 /**
25 * Save timer references to avoid Sinon interfering (see GH-237).
26 */
27
28 var Date = global.Date;
29 var setTimeout = global.setTimeout;
30 var setInterval = global.setInterval;
31 var clearTimeout = global.clearTimeout;
32 var clearInterval = global.clearInterval;
33
34 var uncaughtExceptionHandlers = [];
35
36 var originalOnerrorHandler = global.onerror;
37
38 /**
39 * Remove uncaughtException listener.
40 * Revert to original onerror handler if previously defined.
41 */
42
43 process.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
61 process.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.
74 mocha.suite.removeAllListeners('pre-require');
75
76 var immediateQueue = [];
77 var immediateTimeout;
78
79 function 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
95 Mocha.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 */
107 mocha.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
119 mocha.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
129 mocha.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
145 mocha.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
177 Mocha.process = process;
178
179 /**
180 * Expose mocha.
181 */
182
183 global.Mocha = Mocha;
184 global.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
189 module.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":82,"browser-stdout":41}],2:[function(require,modu le,exports){
193 'use strict';
194
195 function noop () {}
196
197 module.exports = function () {
198 return noop;
199 };
200
201 },{}],3:[function(require,module,exports){
202 'use strict';
203
204 /**
205 * Module exports.
206 */
207
208 exports.EventEmitter = EventEmitter;
209
210 /**
211 * Object#toString reference.
212 */
213 var 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 */
222 function isArray (val) {
223 return objToString.call(val) === '[object Array]';
224 }
225
226 /**
227 * Event emitter constructor.
228 *
229 * @api public
230 */
231 function 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 */
241 EventEmitter.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
257 EventEmitter.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 */
267 EventEmitter.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 */
289 EventEmitter.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 */
327 EventEmitter.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 */
347 EventEmitter.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 */
370 EventEmitter.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
405 module.exports = Progress;
406
407 /**
408 * Initialize a new `Progress` indicator.
409 */
410 function 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 */
424 Progress.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 */
436 Progress.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 */
448 Progress.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 */
459 Progress.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 */
470 Progress.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 */
481 Progress.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
523 exports.isatty = function isatty () {
524 return true;
525 };
526
527 exports.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
543 var JSON = require('json3');
544
545 /**
546 * Expose `Context`.
547 */
548
549 module.exports = Context;
550
551 /**
552 * Initialize a new `Context`.
553 *
554 * @api private
555 */
556 function Context () {}
557
558 /**
559 * Set or get the context `Runnable` to `runnable`.
560 *
561 * @api private
562 * @param {Runnable} runnable
563 * @return {Context}
564 */
565 Context.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 */
580 Context.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 */
595 Context.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 */
607 Context.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 */
618 Context.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 */
630 Context.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 */
644 Context.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":69}],7:[function(require,module,exports){
651 'use strict';
652
653 /**
654 * Module dependencies.
655 */
656
657 var Runnable = require('./runnable');
658 var inherits = require('./utils').inherits;
659
660 /**
661 * Expose `Hook`.
662 */
663
664 module.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 */
673 function Hook (title, fn) {
674 Runnable.call(this, title, fn);
675 this.type = 'hook';
676 }
677
678 /**
679 * Inherit from `Runnable.prototype`.
680 */
681 inherits(Hook, Runnable);
682
683 /**
684 * Get or set the test `err`.
685 *
686 * @param {Error} err
687 * @return {Error}
688 * @api public
689 */
690 Hook.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
707 var 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 */
726 module.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 (tit le, 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
820 var 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 */
830 module.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
984 var Suite = require('../suite');
985 var 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 */
1004 module.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
1045 exports.bdd = require('./bdd');
1046 exports.tdd = require('./tdd');
1047 exports.qunit = require('./qunit');
1048 exports.exports = require('./exports');
1049
1050 },{"./bdd":8,"./exports":10,"./qunit":12,"./tdd":13}],12:[function(require,modul e,exports){
1051 'use strict';
1052
1053 /**
1054 * Module dependencies.
1055 */
1056
1057 var 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 */
1084 module.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
1158 var 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 */
1185 module.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
1273 var escapeRe = require('escape-string-regexp');
1274 var path = require('path');
1275 var reporters = require('./reporters');
1276 var utils = require('./utils');
1277
1278 /**
1279 * Expose `Mocha`.
1280 */
1281
1282 exports = module.exports = Mocha;
1283
1284 /**
1285 * To require local UIs and reporters when running in node.
1286 */
1287
1288 if (!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
1297 exports.utils = utils;
1298 exports.interfaces = require('./interfaces');
1299 exports.reporters = reporters;
1300 exports.Runnable = require('./runnable');
1301 exports.Context = require('./context');
1302 exports.Runner = require('./runner');
1303 exports.Suite = require('./suite');
1304 exports.Hook = require('./hook');
1305 exports.Test = require('./test');
1306
1307 /**
1308 * Return image `name` path.
1309 *
1310 * @api private
1311 * @param {string} name
1312 * @return {string}
1313 */
1314 function 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 */
1337 function 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 */
1372 Mocha.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 */
1386 Mocha.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 */
1400 Mocha.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 if (err.message.indexOf('Cannot find module') !== -1) {
1416 // Try to load reporters from a path (absolute or relative)
1417 try {
1418 _reporter = require(path.resolve(process.cwd(), reporter));
1419 } catch (_err) {
1420 err.message.indexOf('Cannot find module') !== -1 ? console.warn('"' + reporter + '" reporter not found')
1421 : console.warn('"' + reporter + '" reporter blew up with error:\n' + err.stack);
1422 }
1423 } else {
1424 console.warn('"' + reporter + '" reporter blew up with error:\n' + err .stack);
1425 }
1426 }
1427 }
1428 if (!_reporter && reporter === 'teamcity') {
1429 console.warn('The Teamcity reporter was moved to a package named ' +
1430 'mocha-teamcity-reporter ' +
1431 '(https://npmjs.org/package/mocha-teamcity-reporter).');
1432 }
1433 if (!_reporter) {
1434 throw new Error('invalid reporter "' + reporter + '"');
1435 }
1436 this._reporter = _reporter;
1437 }
1438 this.options.reporterOptions = reporterOptions;
1439 return this;
1440 };
1441
1442 /**
1443 * Set test UI `name`, defaults to "bdd".
1444 *
1445 * @api public
1446 * @param {string} bdd
1447 */
1448 Mocha.prototype.ui = function (name) {
1449 name = name || 'bdd';
1450 this._ui = exports.interfaces[name];
1451 if (!this._ui) {
1452 try {
1453 this._ui = require(name);
1454 } catch (err) {
1455 throw new Error('invalid interface "' + name + '"');
1456 }
1457 }
1458 this._ui = this._ui(this.suite);
1459
1460 this.suite.on('pre-require', function (context) {
1461 exports.afterEach = context.afterEach || context.teardown;
1462 exports.after = context.after || context.suiteTeardown;
1463 exports.beforeEach = context.beforeEach || context.setup;
1464 exports.before = context.before || context.suiteSetup;
1465 exports.describe = context.describe || context.suite;
1466 exports.it = context.it || context.test;
1467 exports.setup = context.setup || context.beforeEach;
1468 exports.suiteSetup = context.suiteSetup || context.before;
1469 exports.suiteTeardown = context.suiteTeardown || context.after;
1470 exports.suite = context.suite || context.describe;
1471 exports.teardown = context.teardown || context.afterEach;
1472 exports.test = context.test || context.it;
1473 exports.run = context.run;
1474 });
1475
1476 return this;
1477 };
1478
1479 /**
1480 * Load registered files.
1481 *
1482 * @api private
1483 */
1484 Mocha.prototype.loadFiles = function (fn) {
1485 var self = this;
1486 var suite = this.suite;
1487 this.files.forEach(function (file) {
1488 file = path.resolve(file);
1489 suite.emit('pre-require', global, file, self);
1490 suite.emit('require', require(file), file, self);
1491 suite.emit('post-require', global, file, self);
1492 });
1493 fn && fn();
1494 };
1495
1496 /**
1497 * Enable growl support.
1498 *
1499 * @api private
1500 */
1501 Mocha.prototype._growl = function (runner, reporter) {
1502 var notify = require('growl');
1503
1504 runner.on('end', function () {
1505 var stats = reporter.stats;
1506 if (stats.failures) {
1507 var msg = stats.failures + ' of ' + runner.total + ' tests failed';
1508 notify(msg, { name: 'mocha', title: 'Failed', image: image('error') });
1509 } else {
1510 notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', {
1511 name: 'mocha',
1512 title: 'Passed',
1513 image: image('ok')
1514 });
1515 }
1516 });
1517 };
1518
1519 /**
1520 * Escape string and add it to grep as a regexp.
1521 *
1522 * @api public
1523 * @param str
1524 * @returns {Mocha}
1525 */
1526 Mocha.prototype.fgrep = function (str) {
1527 return this.grep(new RegExp(escapeRe(str)));
1528 };
1529
1530 /**
1531 * Add regexp to grep, if `re` is a string it is escaped.
1532 *
1533 * @param {RegExp|String} re
1534 * @return {Mocha}
1535 * @api public
1536 * @param {RegExp|string} re
1537 * @return {Mocha}
1538 */
1539 Mocha.prototype.grep = function (re) {
1540 if (utils.isString(re)) {
1541 // extract args if it's regex-like, i.e: [string, pattern, flag]
1542 var arg = re.match(/^\/(.*)\/(g|i|)$|.*/);
1543 this.options.grep = new RegExp(arg[1] || arg[0], arg[2]);
1544 } else {
1545 this.options.grep = re;
1546 }
1547 return this;
1548 };
1549 /**
1550 * Invert `.grep()` matches.
1551 *
1552 * @return {Mocha}
1553 * @api public
1554 */
1555 Mocha.prototype.invert = function () {
1556 this.options.invert = true;
1557 return this;
1558 };
1559
1560 /**
1561 * Ignore global leaks.
1562 *
1563 * @param {Boolean} ignore
1564 * @return {Mocha}
1565 * @api public
1566 * @param {boolean} ignore
1567 * @return {Mocha}
1568 */
1569 Mocha.prototype.ignoreLeaks = function (ignore) {
1570 this.options.ignoreLeaks = Boolean(ignore);
1571 return this;
1572 };
1573
1574 /**
1575 * Enable global leak checking.
1576 *
1577 * @return {Mocha}
1578 * @api public
1579 */
1580 Mocha.prototype.checkLeaks = function () {
1581 this.options.ignoreLeaks = false;
1582 return this;
1583 };
1584
1585 /**
1586 * Display long stack-trace on failing
1587 *
1588 * @return {Mocha}
1589 * @api public
1590 */
1591 Mocha.prototype.fullTrace = function () {
1592 this.options.fullStackTrace = true;
1593 return this;
1594 };
1595
1596 /**
1597 * Enable growl support.
1598 *
1599 * @return {Mocha}
1600 * @api public
1601 */
1602 Mocha.prototype.growl = function () {
1603 this.options.growl = true;
1604 return this;
1605 };
1606
1607 /**
1608 * Ignore `globals` array or string.
1609 *
1610 * @param {Array|String} globals
1611 * @return {Mocha}
1612 * @api public
1613 * @param {Array|string} globals
1614 * @return {Mocha}
1615 */
1616 Mocha.prototype.globals = function (globals) {
1617 this.options.globals = (this.options.globals || []).concat(globals);
1618 return this;
1619 };
1620
1621 /**
1622 * Emit color output.
1623 *
1624 * @param {Boolean} colors
1625 * @return {Mocha}
1626 * @api public
1627 * @param {boolean} colors
1628 * @return {Mocha}
1629 */
1630 Mocha.prototype.useColors = function (colors) {
1631 if (colors !== undefined) {
1632 this.options.useColors = colors;
1633 }
1634 return this;
1635 };
1636
1637 /**
1638 * Use inline diffs rather than +/-.
1639 *
1640 * @param {Boolean} inlineDiffs
1641 * @return {Mocha}
1642 * @api public
1643 * @param {boolean} inlineDiffs
1644 * @return {Mocha}
1645 */
1646 Mocha.prototype.useInlineDiffs = function (inlineDiffs) {
1647 this.options.useInlineDiffs = inlineDiffs !== undefined && inlineDiffs;
1648 return this;
1649 };
1650
1651 /**
1652 * Set the timeout in milliseconds.
1653 *
1654 * @param {Number} timeout
1655 * @return {Mocha}
1656 * @api public
1657 * @param {number} timeout
1658 * @return {Mocha}
1659 */
1660 Mocha.prototype.timeout = function (timeout) {
1661 this.suite.timeout(timeout);
1662 return this;
1663 };
1664
1665 /**
1666 * Set the number of times to retry failed tests.
1667 *
1668 * @param {Number} retry times
1669 * @return {Mocha}
1670 * @api public
1671 */
1672 Mocha.prototype.retries = function (n) {
1673 this.suite.retries(n);
1674 return this;
1675 };
1676
1677 /**
1678 * Set slowness threshold in milliseconds.
1679 *
1680 * @param {Number} slow
1681 * @return {Mocha}
1682 * @api public
1683 * @param {number} slow
1684 * @return {Mocha}
1685 */
1686 Mocha.prototype.slow = function (slow) {
1687 this.suite.slow(slow);
1688 return this;
1689 };
1690
1691 /**
1692 * Enable timeouts.
1693 *
1694 * @param {Boolean} enabled
1695 * @return {Mocha}
1696 * @api public
1697 * @param {boolean} enabled
1698 * @return {Mocha}
1699 */
1700 Mocha.prototype.enableTimeouts = function (enabled) {
1701 this.suite.enableTimeouts(arguments.length && enabled !== undefined ? enabled : true);
1702 return this;
1703 };
1704
1705 /**
1706 * Makes all tests async (accepting a callback)
1707 *
1708 * @return {Mocha}
1709 * @api public
1710 */
1711 Mocha.prototype.asyncOnly = function () {
1712 this.options.asyncOnly = true;
1713 return this;
1714 };
1715
1716 /**
1717 * Disable syntax highlighting (in browser).
1718 *
1719 * @api public
1720 */
1721 Mocha.prototype.noHighlighting = function () {
1722 this.options.noHighlighting = true;
1723 return this;
1724 };
1725
1726 /**
1727 * Enable uncaught errors to propagate (in browser).
1728 *
1729 * @return {Mocha}
1730 * @api public
1731 */
1732 Mocha.prototype.allowUncaught = function () {
1733 this.options.allowUncaught = true;
1734 return this;
1735 };
1736
1737 /**
1738 * Delay root suite execution.
1739 * @returns {Mocha}
1740 */
1741 Mocha.prototype.delay = function delay () {
1742 this.options.delay = true;
1743 return this;
1744 };
1745
1746 /**
1747 * Run tests and invoke `fn()` when complete.
1748 *
1749 * @api public
1750 * @param {Function} fn
1751 * @return {Runner}
1752 */
1753 Mocha.prototype.run = function (fn) {
1754 if (this.files.length) {
1755 this.loadFiles();
1756 }
1757 var suite = this.suite;
1758 var options = this.options;
1759 options.files = this.files;
1760 var runner = new exports.Runner(suite, options.delay);
1761 var reporter = new this._reporter(runner, options);
1762 runner.ignoreLeaks = options.ignoreLeaks !== false;
1763 runner.fullStackTrace = options.fullStackTrace;
1764 runner.hasOnly = options.hasOnly;
1765 runner.asyncOnly = options.asyncOnly;
1766 runner.allowUncaught = options.allowUncaught;
1767 if (options.grep) {
1768 runner.grep(options.grep, options.invert);
1769 }
1770 if (options.globals) {
1771 runner.globals(options.globals);
1772 }
1773 if (options.growl) {
1774 this._growl(runner, reporter);
1775 }
1776 if (options.useColors !== undefined) {
1777 exports.reporters.Base.useColors = options.useColors;
1778 }
1779 exports.reporters.Base.inlineDiffs = options.useInlineDiffs;
1780
1781 function done (failures) {
1782 if (reporter.done) {
1783 reporter.done(failures, fn);
1784 } else {
1785 fn && fn(failures);
1786 }
1787 }
1788
1789 return runner.run(done);
1790 };
1791
1792 }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},"/lib ")
1793 },{"./context":6,"./hook":7,"./interfaces":11,"./reporters":21,"./runnable":33," ./runner":34,"./suite":35,"./test":36,"./utils":38,"_process":82,"escape-string- regexp":62,"growl":64,"path":42}],15:[function(require,module,exports){
1794 'use strict';
1795
1796 /**
1797 * Helpers.
1798 */
1799
1800 var s = 1000;
1801 var m = s * 60;
1802 var h = m * 60;
1803 var d = h * 24;
1804 var y = d * 365.25;
1805
1806 /**
1807 * Parse or format the given `val`.
1808 *
1809 * Options:
1810 *
1811 * - `long` verbose formatting [false]
1812 *
1813 * @api public
1814 * @param {string|number} val
1815 * @param {Object} options
1816 * @return {string|number}
1817 */
1818 module.exports = function (val, options) {
1819 options = options || {};
1820 if (typeof val === 'string') {
1821 return parse(val);
1822 }
1823 // https://github.com/mochajs/mocha/pull/1035
1824 return options['long'] ? longFormat(val) : shortFormat(val);
1825 };
1826
1827 /**
1828 * Parse the given `str` and return milliseconds.
1829 *
1830 * @api private
1831 * @param {string} str
1832 * @return {number}
1833 */
1834 function parse (str) {
1835 var match = (/^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|ye ars?|y)?$/i).exec(str);
1836 if (!match) {
1837 return;
1838 }
1839 var n = parseFloat(match[1]);
1840 var type = (match[2] || 'ms').toLowerCase();
1841 switch (type) {
1842 case 'years':
1843 case 'year':
1844 case 'y':
1845 return n * y;
1846 case 'days':
1847 case 'day':
1848 case 'd':
1849 return n * d;
1850 case 'hours':
1851 case 'hour':
1852 case 'h':
1853 return n * h;
1854 case 'minutes':
1855 case 'minute':
1856 case 'm':
1857 return n * m;
1858 case 'seconds':
1859 case 'second':
1860 case 's':
1861 return n * s;
1862 case 'ms':
1863 return n;
1864 default:
1865 // No default case
1866 }
1867 }
1868
1869 /**
1870 * Short format for `ms`.
1871 *
1872 * @api private
1873 * @param {number} ms
1874 * @return {string}
1875 */
1876 function shortFormat (ms) {
1877 if (ms >= d) {
1878 return Math.round(ms / d) + 'd';
1879 }
1880 if (ms >= h) {
1881 return Math.round(ms / h) + 'h';
1882 }
1883 if (ms >= m) {
1884 return Math.round(ms / m) + 'm';
1885 }
1886 if (ms >= s) {
1887 return Math.round(ms / s) + 's';
1888 }
1889 return ms + 'ms';
1890 }
1891
1892 /**
1893 * Long format for `ms`.
1894 *
1895 * @api private
1896 * @param {number} ms
1897 * @return {string}
1898 */
1899 function longFormat (ms) {
1900 return plural(ms, d, 'day') ||
1901 plural(ms, h, 'hour') ||
1902 plural(ms, m, 'minute') ||
1903 plural(ms, s, 'second') ||
1904 ms + ' ms';
1905 }
1906
1907 /**
1908 * Pluralization helper.
1909 *
1910 * @api private
1911 * @param {number} ms
1912 * @param {number} n
1913 * @param {string} name
1914 */
1915 function plural (ms, n, name) {
1916 if (ms < n) {
1917 return;
1918 }
1919 if (ms < n * 1.5) {
1920 return Math.floor(ms / n) + ' ' + name;
1921 }
1922 return Math.ceil(ms / n) + ' ' + name + 's';
1923 }
1924
1925 },{}],16:[function(require,module,exports){
1926 'use strict';
1927
1928 /**
1929 * Expose `Pending`.
1930 */
1931
1932 module.exports = Pending;
1933
1934 /**
1935 * Initialize a new `Pending` error with the given message.
1936 *
1937 * @param {string} message
1938 */
1939 function Pending (message) {
1940 this.message = message;
1941 }
1942
1943 },{}],17:[function(require,module,exports){
1944 (function (process,global){
1945 'use strict';
1946
1947 /**
1948 * Module dependencies.
1949 */
1950
1951 var tty = require('tty');
1952 var diff = require('diff');
1953 var ms = require('../ms');
1954 var utils = require('../utils');
1955 var supportsColor = process.browser ? null : require('supports-color');
1956
1957 /**
1958 * Expose `Base`.
1959 */
1960
1961 exports = module.exports = Base;
1962
1963 /**
1964 * Save timer references to avoid Sinon interfering.
1965 * See: https://github.com/mochajs/mocha/issues/237
1966 */
1967
1968 /* eslint-disable no-unused-vars, no-native-reassign */
1969 var Date = global.Date;
1970 var setTimeout = global.setTimeout;
1971 var setInterval = global.setInterval;
1972 var clearTimeout = global.clearTimeout;
1973 var clearInterval = global.clearInterval;
1974 /* eslint-enable no-unused-vars, no-native-reassign */
1975
1976 /**
1977 * Check if both stdio streams are associated with a tty.
1978 */
1979
1980 var isatty = tty.isatty(1) && tty.isatty(2);
1981
1982 /**
1983 * Enable coloring by default, except in the browser interface.
1984 */
1985
1986 exports.useColors = !process.browser && (supportsColor || (process.env.MOCHA_COL ORS !== undefined));
1987
1988 /**
1989 * Inline diffs instead of +/-
1990 */
1991
1992 exports.inlineDiffs = false;
1993
1994 /**
1995 * Default color map.
1996 */
1997
1998 exports.colors = {
1999 pass: 90,
2000 fail: 31,
2001 'bright pass': 92,
2002 'bright fail': 91,
2003 'bright yellow': 93,
2004 pending: 36,
2005 suite: 0,
2006 'error title': 0,
2007 'error message': 31,
2008 'error stack': 90,
2009 checkmark: 32,
2010 fast: 90,
2011 medium: 33,
2012 slow: 31,
2013 green: 32,
2014 light: 90,
2015 'diff gutter': 90,
2016 'diff added': 32,
2017 'diff removed': 31
2018 };
2019
2020 /**
2021 * Default symbol map.
2022 */
2023
2024 exports.symbols = {
2025 ok: '✓',
2026 err: '✖',
2027 dot: '․',
2028 comma: ',',
2029 bang: '!'
2030 };
2031
2032 // With node.js on Windows: use symbols available in terminal default fonts
2033 if (process.platform === 'win32') {
2034 exports.symbols.ok = '\u221A';
2035 exports.symbols.err = '\u00D7';
2036 exports.symbols.dot = '.';
2037 }
2038
2039 /**
2040 * Color `str` with the given `type`,
2041 * allowing colors to be disabled,
2042 * as well as user-defined color
2043 * schemes.
2044 *
2045 * @param {string} type
2046 * @param {string} str
2047 * @return {string}
2048 * @api private
2049 */
2050 var color = exports.color = function (type, str) {
2051 if (!exports.useColors) {
2052 return String(str);
2053 }
2054 return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m';
2055 };
2056
2057 /**
2058 * Expose term window size, with some defaults for when stderr is not a tty.
2059 */
2060
2061 exports.window = {
2062 width: 75
2063 };
2064
2065 if (isatty) {
2066 exports.window.width = process.stdout.getWindowSize
2067 ? process.stdout.getWindowSize(1)[0]
2068 : tty.getWindowSize()[1];
2069 }
2070
2071 /**
2072 * Expose some basic cursor interactions that are common among reporters.
2073 */
2074
2075 exports.cursor = {
2076 hide: function () {
2077 isatty && process.stdout.write('\u001b[?25l');
2078 },
2079
2080 show: function () {
2081 isatty && process.stdout.write('\u001b[?25h');
2082 },
2083
2084 deleteLine: function () {
2085 isatty && process.stdout.write('\u001b[2K');
2086 },
2087
2088 beginningOfLine: function () {
2089 isatty && process.stdout.write('\u001b[0G');
2090 },
2091
2092 CR: function () {
2093 if (isatty) {
2094 exports.cursor.deleteLine();
2095 exports.cursor.beginningOfLine();
2096 } else {
2097 process.stdout.write('\r');
2098 }
2099 }
2100 };
2101
2102 /**
2103 * Outut the given `failures` as a list.
2104 *
2105 * @param {Array} failures
2106 * @api public
2107 */
2108
2109 exports.list = function (failures) {
2110 console.log();
2111 failures.forEach(function (test, i) {
2112 // format
2113 var fmt = color('error title', ' %s) %s:\n') +
2114 color('error message', ' %s') +
2115 color('error stack', '\n%s\n');
2116
2117 // msg
2118 var msg;
2119 var err = test.err;
2120 var message;
2121 if (err.message && typeof err.message.toString === 'function') {
2122 message = err.message + '';
2123 } else if (typeof err.inspect === 'function') {
2124 message = err.inspect() + '';
2125 } else {
2126 message = '';
2127 }
2128 var stack = err.stack || message;
2129 var index = message ? stack.indexOf(message) : -1;
2130 var actual = err.actual;
2131 var expected = err.expected;
2132 var escape = true;
2133
2134 if (index === -1) {
2135 msg = message;
2136 } else {
2137 index += message.length;
2138 msg = stack.slice(0, index);
2139 // remove msg from stack
2140 stack = stack.slice(index + 1);
2141 }
2142
2143 // uncaught
2144 if (err.uncaught) {
2145 msg = 'Uncaught ' + msg;
2146 }
2147 // explicitly show diff
2148 if (err.showDiff !== false && sameType(actual, expected) && expected !== und efined) {
2149 escape = false;
2150 if (!(utils.isString(actual) && utils.isString(expected))) {
2151 err.actual = actual = utils.stringify(actual);
2152 err.expected = expected = utils.stringify(expected);
2153 }
2154
2155 fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n ');
2156 var match = message.match(/^([^:]+): expected/);
2157 msg = '\n ' + color('error message', match ? match[1] : msg);
2158
2159 if (exports.inlineDiffs) {
2160 msg += inlineDiff(err, escape);
2161 } else {
2162 msg += unifiedDiff(err, escape);
2163 }
2164 }
2165
2166 // indent stack trace
2167 stack = stack.replace(/^/gm, ' ');
2168
2169 console.log(fmt, (i + 1), test.fullTitle(), msg, stack);
2170 });
2171 };
2172
2173 /**
2174 * Initialize a new `Base` reporter.
2175 *
2176 * All other reporters generally
2177 * inherit from this reporter, providing
2178 * stats such as test duration, number
2179 * of tests passed / failed etc.
2180 *
2181 * @param {Runner} runner
2182 * @api public
2183 */
2184
2185 function Base (runner) {
2186 var stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failure s: 0 };
2187 var failures = this.failures = [];
2188
2189 if (!runner) {
2190 return;
2191 }
2192 this.runner = runner;
2193
2194 runner.stats = stats;
2195
2196 runner.on('start', function () {
2197 stats.start = new Date();
2198 });
2199
2200 runner.on('suite', function (suite) {
2201 stats.suites = stats.suites || 0;
2202 suite.root || stats.suites++;
2203 });
2204
2205 runner.on('test end', function () {
2206 stats.tests = stats.tests || 0;
2207 stats.tests++;
2208 });
2209
2210 runner.on('pass', function (test) {
2211 stats.passes = stats.passes || 0;
2212
2213 if (test.duration > test.slow()) {
2214 test.speed = 'slow';
2215 } else if (test.duration > test.slow() / 2) {
2216 test.speed = 'medium';
2217 } else {
2218 test.speed = 'fast';
2219 }
2220
2221 stats.passes++;
2222 });
2223
2224 runner.on('fail', function (test, err) {
2225 stats.failures = stats.failures || 0;
2226 stats.failures++;
2227 test.err = err;
2228 failures.push(test);
2229 });
2230
2231 runner.on('end', function () {
2232 stats.end = new Date();
2233 stats.duration = new Date() - stats.start;
2234 });
2235
2236 runner.on('pending', function () {
2237 stats.pending++;
2238 });
2239 }
2240
2241 /**
2242 * Output common epilogue used by many of
2243 * the bundled reporters.
2244 *
2245 * @api public
2246 */
2247 Base.prototype.epilogue = function () {
2248 var stats = this.stats;
2249 var fmt;
2250
2251 console.log();
2252
2253 // passes
2254 fmt = color('bright pass', ' ') +
2255 color('green', ' %d passing') +
2256 color('light', ' (%s)');
2257
2258 console.log(fmt,
2259 stats.passes || 0,
2260 ms(stats.duration));
2261
2262 // pending
2263 if (stats.pending) {
2264 fmt = color('pending', ' ') +
2265 color('pending', ' %d pending');
2266
2267 console.log(fmt, stats.pending);
2268 }
2269
2270 // failures
2271 if (stats.failures) {
2272 fmt = color('fail', ' %d failing');
2273
2274 console.log(fmt, stats.failures);
2275
2276 Base.list(this.failures);
2277 console.log();
2278 }
2279
2280 console.log();
2281 };
2282
2283 /**
2284 * Pad the given `str` to `len`.
2285 *
2286 * @api private
2287 * @param {string} str
2288 * @param {string} len
2289 * @return {string}
2290 */
2291 function pad (str, len) {
2292 str = String(str);
2293 return Array(len - str.length + 1).join(' ') + str;
2294 }
2295
2296 /**
2297 * Returns an inline diff between 2 strings with coloured ANSI output
2298 *
2299 * @api private
2300 * @param {Error} err with actual/expected
2301 * @param {boolean} escape
2302 * @return {string} Diff
2303 */
2304 function inlineDiff (err, escape) {
2305 var msg = errorDiff(err, 'WordsWithSpace', escape);
2306
2307 // linenos
2308 var lines = msg.split('\n');
2309 if (lines.length > 4) {
2310 var width = String(lines.length).length;
2311 msg = lines.map(function (str, i) {
2312 return pad(++i, width) + ' |' + ' ' + str;
2313 }).join('\n');
2314 }
2315
2316 // legend
2317 msg = '\n' +
2318 color('diff removed', 'actual') +
2319 ' ' +
2320 color('diff added', 'expected') +
2321 '\n\n' +
2322 msg +
2323 '\n';
2324
2325 // indent
2326 msg = msg.replace(/^/gm, ' ');
2327 return msg;
2328 }
2329
2330 /**
2331 * Returns a unified diff between two strings.
2332 *
2333 * @api private
2334 * @param {Error} err with actual/expected
2335 * @param {boolean} escape
2336 * @return {string} The diff.
2337 */
2338 function unifiedDiff (err, escape) {
2339 var indent = ' ';
2340 function cleanUp (line) {
2341 if (escape) {
2342 line = escapeInvisibles(line);
2343 }
2344 if (line[0] === '+') {
2345 return indent + colorLines('diff added', line);
2346 }
2347 if (line[0] === '-') {
2348 return indent + colorLines('diff removed', line);
2349 }
2350 if (line.match(/@@/)) {
2351 return null;
2352 }
2353 if (line.match(/\\ No newline/)) {
2354 return null;
2355 }
2356 return indent + line;
2357 }
2358 function notBlank (line) {
2359 return typeof line !== 'undefined' && line !== null;
2360 }
2361 var msg = diff.createPatch('string', err.actual, err.expected);
2362 var lines = msg.split('\n').splice(4);
2363 return '\n ' +
2364 colorLines('diff added', '+ expected') + ' ' +
2365 colorLines('diff removed', '- actual') +
2366 '\n\n' +
2367 lines.map(cleanUp).filter(notBlank).join('\n');
2368 }
2369
2370 /**
2371 * Return a character diff for `err`.
2372 *
2373 * @api private
2374 * @param {Error} err
2375 * @param {string} type
2376 * @param {boolean} escape
2377 * @return {string}
2378 */
2379 function errorDiff (err, type, escape) {
2380 var actual = escape ? escapeInvisibles(err.actual) : err.actual;
2381 var expected = escape ? escapeInvisibles(err.expected) : err.expected;
2382 return diff['diff' + type](actual, expected).map(function (str) {
2383 if (str.added) {
2384 return colorLines('diff added', str.value);
2385 }
2386 if (str.removed) {
2387 return colorLines('diff removed', str.value);
2388 }
2389 return str.value;
2390 }).join('');
2391 }
2392
2393 /**
2394 * Returns a string with all invisible characters in plain text
2395 *
2396 * @api private
2397 * @param {string} line
2398 * @return {string}
2399 */
2400 function escapeInvisibles (line) {
2401 return line.replace(/\t/g, '<tab>')
2402 .replace(/\r/g, '<CR>')
2403 .replace(/\n/g, '<LF>\n');
2404 }
2405
2406 /**
2407 * Color lines for `str`, using the color `name`.
2408 *
2409 * @api private
2410 * @param {string} name
2411 * @param {string} str
2412 * @return {string}
2413 */
2414 function colorLines (name, str) {
2415 return str.split('\n').map(function (str) {
2416 return color(name, str);
2417 }).join('\n');
2418 }
2419
2420 /**
2421 * Object#toString reference.
2422 */
2423 var objToString = Object.prototype.toString;
2424
2425 /**
2426 * Check that a / b have the same type.
2427 *
2428 * @api private
2429 * @param {Object} a
2430 * @param {Object} b
2431 * @return {boolean}
2432 */
2433 function sameType (a, b) {
2434 return objToString.call(a) === objToString.call(b);
2435 }
2436
2437 }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
2438 },{"../ms":15,"../utils":38,"_process":82,"diff":56,"supports-color":42,"tty":5} ],18:[function(require,module,exports){
2439 'use strict';
2440
2441 /**
2442 * Module dependencies.
2443 */
2444
2445 var Base = require('./base');
2446 var utils = require('../utils');
2447
2448 /**
2449 * Expose `Doc`.
2450 */
2451
2452 exports = module.exports = Doc;
2453
2454 /**
2455 * Initialize a new `Doc` reporter.
2456 *
2457 * @param {Runner} runner
2458 * @api public
2459 */
2460 function Doc (runner) {
2461 Base.call(this, runner);
2462
2463 var indents = 2;
2464
2465 function indent () {
2466 return Array(indents).join(' ');
2467 }
2468
2469 runner.on('suite', function (suite) {
2470 if (suite.root) {
2471 return;
2472 }
2473 ++indents;
2474 console.log('%s<section class="suite">', indent());
2475 ++indents;
2476 console.log('%s<h1>%s</h1>', indent(), utils.escape(suite.title));
2477 console.log('%s<dl>', indent());
2478 });
2479
2480 runner.on('suite end', function (suite) {
2481 if (suite.root) {
2482 return;
2483 }
2484 console.log('%s</dl>', indent());
2485 --indents;
2486 console.log('%s</section>', indent());
2487 --indents;
2488 });
2489
2490 runner.on('pass', function (test) {
2491 console.log('%s <dt>%s</dt>', indent(), utils.escape(test.title));
2492 var code = utils.escape(utils.clean(test.body));
2493 console.log('%s <dd><pre><code>%s</code></pre></dd>', indent(), code);
2494 });
2495
2496 runner.on('fail', function (test, err) {
2497 console.log('%s <dt class="error">%s</dt>', indent(), utils.escape(test.tit le));
2498 var code = utils.escape(utils.clean(test.body));
2499 console.log('%s <dd class="error"><pre><code>%s</code></pre></dd>', indent( ), code);
2500 console.log('%s <dd class="error">%s</dd>', indent(), utils.escape(err));
2501 });
2502 }
2503
2504 },{"../utils":38,"./base":17}],19:[function(require,module,exports){
2505 (function (process){
2506 'use strict';
2507
2508 /**
2509 * Module dependencies.
2510 */
2511
2512 var Base = require('./base');
2513 var inherits = require('../utils').inherits;
2514 var color = Base.color;
2515
2516 /**
2517 * Expose `Dot`.
2518 */
2519
2520 exports = module.exports = Dot;
2521
2522 /**
2523 * Initialize a new `Dot` matrix test reporter.
2524 *
2525 * @api public
2526 * @param {Runner} runner
2527 */
2528 function Dot (runner) {
2529 Base.call(this, runner);
2530
2531 var self = this;
2532 var width = Base.window.width * 0.75 | 0;
2533 var n = -1;
2534
2535 runner.on('start', function () {
2536 process.stdout.write('\n');
2537 });
2538
2539 runner.on('pending', function () {
2540 if (++n % width === 0) {
2541 process.stdout.write('\n ');
2542 }
2543 process.stdout.write(color('pending', Base.symbols.comma));
2544 });
2545
2546 runner.on('pass', function (test) {
2547 if (++n % width === 0) {
2548 process.stdout.write('\n ');
2549 }
2550 if (test.speed === 'slow') {
2551 process.stdout.write(color('bright yellow', Base.symbols.dot));
2552 } else {
2553 process.stdout.write(color(test.speed, Base.symbols.dot));
2554 }
2555 });
2556
2557 runner.on('fail', function () {
2558 if (++n % width === 0) {
2559 process.stdout.write('\n ');
2560 }
2561 process.stdout.write(color('fail', Base.symbols.bang));
2562 });
2563
2564 runner.on('end', function () {
2565 console.log();
2566 self.epilogue();
2567 });
2568 }
2569
2570 /**
2571 * Inherit from `Base.prototype`.
2572 */
2573 inherits(Dot, Base);
2574
2575 }).call(this,require('_process'))
2576 },{"../utils":38,"./base":17,"_process":82}],20:[function(require,module,exports ){
2577 (function (global){
2578 'use strict';
2579
2580 /* eslint-env browser */
2581
2582 /**
2583 * Module dependencies.
2584 */
2585
2586 var Base = require('./base');
2587 var utils = require('../utils');
2588 var Progress = require('../browser/progress');
2589 var escapeRe = require('escape-string-regexp');
2590 var escape = utils.escape;
2591
2592 /**
2593 * Save timer references to avoid Sinon interfering (see GH-237).
2594 */
2595
2596 /* eslint-disable no-unused-vars, no-native-reassign */
2597 var Date = global.Date;
2598 var setTimeout = global.setTimeout;
2599 var setInterval = global.setInterval;
2600 var clearTimeout = global.clearTimeout;
2601 var clearInterval = global.clearInterval;
2602 /* eslint-enable no-unused-vars, no-native-reassign */
2603
2604 /**
2605 * Expose `HTML`.
2606 */
2607
2608 exports = module.exports = HTML;
2609
2610 /**
2611 * Stats template.
2612 */
2613
2614 var statsTemplate = '<ul id="mocha-stats">' +
2615 '<li class="progress"><canvas width="40" height="40"></canvas></li>' +
2616 '<li class="passes"><a href="javascript:void(0);">passes:</a> <em>0</em></li>' +
2617 '<li class="failures"><a href="javascript:void(0);">failures:</a> <em>0</em></ li>' +
2618 '<li class="duration">duration: <em>0</em>s</li>' +
2619 '</ul>';
2620
2621 var playIcon = '&#x2023;';
2622
2623 /**
2624 * Initialize a new `HTML` reporter.
2625 *
2626 * @api public
2627 * @param {Runner} runner
2628 */
2629 function HTML (runner) {
2630 Base.call(this, runner);
2631
2632 var self = this;
2633 var stats = this.stats;
2634 var stat = fragment(statsTemplate);
2635 var items = stat.getElementsByTagName('li');
2636 var passes = items[1].getElementsByTagName('em')[0];
2637 var passesLink = items[1].getElementsByTagName('a')[0];
2638 var failures = items[2].getElementsByTagName('em')[0];
2639 var failuresLink = items[2].getElementsByTagName('a')[0];
2640 var duration = items[3].getElementsByTagName('em')[0];
2641 var canvas = stat.getElementsByTagName('canvas')[0];
2642 var report = fragment('<ul id="mocha-report"></ul>');
2643 var stack = [report];
2644 var progress;
2645 var ctx;
2646 var root = document.getElementById('mocha');
2647
2648 if (canvas.getContext) {
2649 var ratio = window.devicePixelRatio || 1;
2650 canvas.style.width = canvas.width;
2651 canvas.style.height = canvas.height;
2652 canvas.width *= ratio;
2653 canvas.height *= ratio;
2654 ctx = canvas.getContext('2d');
2655 ctx.scale(ratio, ratio);
2656 progress = new Progress();
2657 }
2658
2659 if (!root) {
2660 return error('#mocha div missing, add it to your document');
2661 }
2662
2663 // pass toggle
2664 on(passesLink, 'click', function (evt) {
2665 evt.preventDefault();
2666 unhide();
2667 var name = (/pass/).test(report.className) ? '' : ' pass';
2668 report.className = report.className.replace(/fail|pass/g, '') + name;
2669 if (report.className.trim()) {
2670 hideSuitesWithout('test pass');
2671 }
2672 });
2673
2674 // failure toggle
2675 on(failuresLink, 'click', function (evt) {
2676 evt.preventDefault();
2677 unhide();
2678 var name = (/fail/).test(report.className) ? '' : ' fail';
2679 report.className = report.className.replace(/fail|pass/g, '') + name;
2680 if (report.className.trim()) {
2681 hideSuitesWithout('test fail');
2682 }
2683 });
2684
2685 root.appendChild(stat);
2686 root.appendChild(report);
2687
2688 if (progress) {
2689 progress.size(40);
2690 }
2691
2692 runner.on('suite', function (suite) {
2693 if (suite.root) {
2694 return;
2695 }
2696
2697 // suite
2698 var url = self.suiteURL(suite);
2699 var el = fragment('<li class="suite"><h1><a href="%s">%s</a></h1></li>', url , escape(suite.title));
2700
2701 // container
2702 stack[0].appendChild(el);
2703 stack.unshift(document.createElement('ul'));
2704 el.appendChild(stack[0]);
2705 });
2706
2707 runner.on('suite end', function (suite) {
2708 if (suite.root) {
2709 updateStats();
2710 return;
2711 }
2712 stack.shift();
2713 });
2714
2715 runner.on('pass', function (test) {
2716 var url = self.testURL(test);
2717 var markup = '<li class="test pass %e"><h2>%e<span class="duration">%ems</sp an> ' +
2718 '<a href="%s" class="replay">' + playIcon + '</a></h2></li>';
2719 var el = fragment(markup, test.speed, test.title, test.duration, url);
2720 self.addCodeToggle(el, test.body);
2721 appendToStack(el);
2722 updateStats();
2723 });
2724
2725 runner.on('fail', function (test) {
2726 var el = fragment('<li class="test fail"><h2>%e <a href="%e" class="replay"> ' + playIcon + '</a></h2></li>',
2727 test.title, self.testURL(test));
2728 var stackString; // Note: Includes leading newline
2729 var message = test.err.toString();
2730
2731 // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we
2732 // check for the result of the stringifying.
2733 if (message === '[object Error]') {
2734 message = test.err.message;
2735 }
2736
2737 if (test.err.stack) {
2738 var indexOfMessage = test.err.stack.indexOf(test.err.message);
2739 if (indexOfMessage === -1) {
2740 stackString = test.err.stack;
2741 } else {
2742 stackString = test.err.stack.substr(test.err.message.length + indexOfMes sage);
2743 }
2744 } else if (test.err.sourceURL && test.err.line !== undefined) {
2745 // Safari doesn't give you a stack. Let's at least provide a source line.
2746 stackString = '\n(' + test.err.sourceURL + ':' + test.err.line + ')';
2747 }
2748
2749 stackString = stackString || '';
2750
2751 if (test.err.htmlMessage && stackString) {
2752 el.appendChild(fragment('<div class="html-error">%s\n<pre class="error">%e </pre></div>',
2753 test.err.htmlMessage, stackString));
2754 } else if (test.err.htmlMessage) {
2755 el.appendChild(fragment('<div class="html-error">%s</div>', test.err.htmlM essage));
2756 } else {
2757 el.appendChild(fragment('<pre class="error">%e%e</pre>', message, stackStr ing));
2758 }
2759
2760 self.addCodeToggle(el, test.body);
2761 appendToStack(el);
2762 updateStats();
2763 });
2764
2765 runner.on('pending', function (test) {
2766 var el = fragment('<li class="test pass pending"><h2>%e</h2></li>', test.tit le);
2767 appendToStack(el);
2768 updateStats();
2769 });
2770
2771 function appendToStack (el) {
2772 // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack.
2773 if (stack[0]) {
2774 stack[0].appendChild(el);
2775 }
2776 }
2777
2778 function updateStats () {
2779 // TODO: add to stats
2780 var percent = stats.tests / runner.total * 100 | 0;
2781 if (progress) {
2782 progress.update(percent).draw(ctx);
2783 }
2784
2785 // update stats
2786 var ms = new Date() - stats.start;
2787 text(passes, stats.passes);
2788 text(failures, stats.failures);
2789 text(duration, (ms / 1000).toFixed(2));
2790 }
2791 }
2792
2793 /**
2794 * Makes a URL, preserving querystring ("search") parameters.
2795 *
2796 * @param {string} s
2797 * @return {string} A new URL.
2798 */
2799 function makeUrl (s) {
2800 var search = window.location.search;
2801
2802 // Remove previous grep query parameter if present
2803 if (search) {
2804 search = search.replace(/[?&]grep=[^&\s]*/g, '').replace(/^&/, '?');
2805 }
2806
2807 return window.location.pathname + (search ? search + '&' : '?') + 'grep=' + en codeURIComponent(escapeRe(s));
2808 }
2809
2810 /**
2811 * Provide suite URL.
2812 *
2813 * @param {Object} [suite]
2814 */
2815 HTML.prototype.suiteURL = function (suite) {
2816 return makeUrl(suite.fullTitle());
2817 };
2818
2819 /**
2820 * Provide test URL.
2821 *
2822 * @param {Object} [test]
2823 */
2824 HTML.prototype.testURL = function (test) {
2825 return makeUrl(test.fullTitle());
2826 };
2827
2828 /**
2829 * Adds code toggle functionality for the provided test's list element.
2830 *
2831 * @param {HTMLLIElement} el
2832 * @param {string} contents
2833 */
2834 HTML.prototype.addCodeToggle = function (el, contents) {
2835 var h2 = el.getElementsByTagName('h2')[0];
2836
2837 on(h2, 'click', function () {
2838 pre.style.display = pre.style.display === 'none' ? 'block' : 'none';
2839 });
2840
2841 var pre = fragment('<pre><code>%e</code></pre>', utils.clean(contents));
2842 el.appendChild(pre);
2843 pre.style.display = 'none';
2844 };
2845
2846 /**
2847 * Display error `msg`.
2848 *
2849 * @param {string} msg
2850 */
2851 function error (msg) {
2852 document.body.appendChild(fragment('<div id="mocha-error">%s</div>', msg));
2853 }
2854
2855 /**
2856 * Return a DOM fragment from `html`.
2857 *
2858 * @param {string} html
2859 */
2860 function fragment (html) {
2861 var args = arguments;
2862 var div = document.createElement('div');
2863 var i = 1;
2864
2865 div.innerHTML = html.replace(/%([se])/g, function (_, type) {
2866 switch (type) {
2867 case 's': return String(args[i++]);
2868 case 'e': return escape(args[i++]);
2869 // no default
2870 }
2871 });
2872
2873 return div.firstChild;
2874 }
2875
2876 /**
2877 * Check for suites that do not have elements
2878 * with `classname`, and hide them.
2879 *
2880 * @param {text} classname
2881 */
2882 function hideSuitesWithout (classname) {
2883 var suites = document.getElementsByClassName('suite');
2884 for (var i = 0; i < suites.length; i++) {
2885 var els = suites[i].getElementsByClassName(classname);
2886 if (!els.length) {
2887 suites[i].className += ' hidden';
2888 }
2889 }
2890 }
2891
2892 /**
2893 * Unhide .hidden suites.
2894 */
2895 function unhide () {
2896 var els = document.getElementsByClassName('suite hidden');
2897 for (var i = 0; i < els.length; ++i) {
2898 els[i].className = els[i].className.replace('suite hidden', 'suite');
2899 }
2900 }
2901
2902 /**
2903 * Set an element's text contents.
2904 *
2905 * @param {HTMLElement} el
2906 * @param {string} contents
2907 */
2908 function text (el, contents) {
2909 if (el.textContent) {
2910 el.textContent = contents;
2911 } else {
2912 el.innerText = contents;
2913 }
2914 }
2915
2916 /**
2917 * Listen on `event` with callback `fn`.
2918 */
2919 function on (el, event, fn) {
2920 if (el.addEventListener) {
2921 el.addEventListener(event, fn, false);
2922 } else {
2923 el.attachEvent('on' + event, fn);
2924 }
2925 }
2926
2927 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined " ? self : typeof window !== "undefined" ? window : {})
2928 },{"../browser/progress":4,"../utils":38,"./base":17,"escape-string-regexp":62}] ,21:[function(require,module,exports){
2929 'use strict';
2930
2931 // Alias exports to a their normalized format Mocha#reporter to prevent a need
2932 // for dynamic (try/catch) requires, which Browserify doesn't handle.
2933 exports.Base = exports.base = require('./base');
2934 exports.Dot = exports.dot = require('./dot');
2935 exports.Doc = exports.doc = require('./doc');
2936 exports.TAP = exports.tap = require('./tap');
2937 exports.JSON = exports.json = require('./json');
2938 exports.HTML = exports.html = require('./html');
2939 exports.List = exports.list = require('./list');
2940 exports.Min = exports.min = require('./min');
2941 exports.Spec = exports.spec = require('./spec');
2942 exports.Nyan = exports.nyan = require('./nyan');
2943 exports.XUnit = exports.xunit = require('./xunit');
2944 exports.Markdown = exports.markdown = require('./markdown');
2945 exports.Progress = exports.progress = require('./progress');
2946 exports.Landing = exports.landing = require('./landing');
2947 exports.JSONStream = exports['json-stream'] = require('./json-stream');
2948
2949 },{"./base":17,"./doc":18,"./dot":19,"./html":20,"./json":23,"./json-stream":22, "./landing":24,"./list":25,"./markdown":26,"./min":27,"./nyan":28,"./progress":2 9,"./spec":30,"./tap":31,"./xunit":32}],22:[function(require,module,exports){
2950 (function (process){
2951 'use strict';
2952
2953 /**
2954 * Module dependencies.
2955 */
2956
2957 var Base = require('./base');
2958 var JSON = require('json3');
2959
2960 /**
2961 * Expose `List`.
2962 */
2963
2964 exports = module.exports = List;
2965
2966 /**
2967 * Initialize a new `List` test reporter.
2968 *
2969 * @api public
2970 * @param {Runner} runner
2971 */
2972 function List (runner) {
2973 Base.call(this, runner);
2974
2975 var self = this;
2976 var total = runner.total;
2977
2978 runner.on('start', function () {
2979 console.log(JSON.stringify(['start', { total: total }]));
2980 });
2981
2982 runner.on('pass', function (test) {
2983 console.log(JSON.stringify(['pass', clean(test)]));
2984 });
2985
2986 runner.on('fail', function (test, err) {
2987 test = clean(test);
2988 test.err = err.message;
2989 test.stack = err.stack || null;
2990 console.log(JSON.stringify(['fail', test]));
2991 });
2992
2993 runner.on('end', function () {
2994 process.stdout.write(JSON.stringify(['end', self.stats]));
2995 });
2996 }
2997
2998 /**
2999 * Return a plain-object representation of `test`
3000 * free of cyclic properties etc.
3001 *
3002 * @api private
3003 * @param {Object} test
3004 * @return {Object}
3005 */
3006 function clean (test) {
3007 return {
3008 title: test.title,
3009 fullTitle: test.fullTitle(),
3010 duration: test.duration,
3011 currentRetry: test.currentRetry()
3012 };
3013 }
3014
3015 }).call(this,require('_process'))
3016 },{"./base":17,"_process":82,"json3":69}],23:[function(require,module,exports){
3017 (function (process){
3018 'use strict';
3019
3020 /**
3021 * Module dependencies.
3022 */
3023
3024 var Base = require('./base');
3025
3026 /**
3027 * Expose `JSON`.
3028 */
3029
3030 exports = module.exports = JSONReporter;
3031
3032 /**
3033 * Initialize a new `JSON` reporter.
3034 *
3035 * @api public
3036 * @param {Runner} runner
3037 */
3038 function JSONReporter (runner) {
3039 Base.call(this, runner);
3040
3041 var self = this;
3042 var tests = [];
3043 var pending = [];
3044 var failures = [];
3045 var passes = [];
3046
3047 runner.on('test end', function (test) {
3048 tests.push(test);
3049 });
3050
3051 runner.on('pass', function (test) {
3052 passes.push(test);
3053 });
3054
3055 runner.on('fail', function (test) {
3056 failures.push(test);
3057 });
3058
3059 runner.on('pending', function (test) {
3060 pending.push(test);
3061 });
3062
3063 runner.on('end', function () {
3064 var obj = {
3065 stats: self.stats,
3066 tests: tests.map(clean),
3067 pending: pending.map(clean),
3068 failures: failures.map(clean),
3069 passes: passes.map(clean)
3070 };
3071
3072 runner.testResults = obj;
3073
3074 process.stdout.write(JSON.stringify(obj, null, 2));
3075 });
3076 }
3077
3078 /**
3079 * Return a plain-object representation of `test`
3080 * free of cyclic properties etc.
3081 *
3082 * @api private
3083 * @param {Object} test
3084 * @return {Object}
3085 */
3086 function clean (test) {
3087 return {
3088 title: test.title,
3089 fullTitle: test.fullTitle(),
3090 duration: test.duration,
3091 currentRetry: test.currentRetry(),
3092 err: errorJSON(test.err || {})
3093 };
3094 }
3095
3096 /**
3097 * Transform `error` into a JSON object.
3098 *
3099 * @api private
3100 * @param {Error} err
3101 * @return {Object}
3102 */
3103 function errorJSON (err) {
3104 var res = {};
3105 Object.getOwnPropertyNames(err).forEach(function (key) {
3106 res[key] = err[key];
3107 }, err);
3108 return res;
3109 }
3110
3111 }).call(this,require('_process'))
3112 },{"./base":17,"_process":82}],24:[function(require,module,exports){
3113 (function (process){
3114 'use strict';
3115
3116 /**
3117 * Module dependencies.
3118 */
3119
3120 var Base = require('./base');
3121 var inherits = require('../utils').inherits;
3122 var cursor = Base.cursor;
3123 var color = Base.color;
3124
3125 /**
3126 * Expose `Landing`.
3127 */
3128
3129 exports = module.exports = Landing;
3130
3131 /**
3132 * Airplane color.
3133 */
3134
3135 Base.colors.plane = 0;
3136
3137 /**
3138 * Airplane crash color.
3139 */
3140
3141 Base.colors['plane crash'] = 31;
3142
3143 /**
3144 * Runway color.
3145 */
3146
3147 Base.colors.runway = 90;
3148
3149 /**
3150 * Initialize a new `Landing` reporter.
3151 *
3152 * @api public
3153 * @param {Runner} runner
3154 */
3155 function Landing (runner) {
3156 Base.call(this, runner);
3157
3158 var self = this;
3159 var width = Base.window.width * 0.75 | 0;
3160 var total = runner.total;
3161 var stream = process.stdout;
3162 var plane = color('plane', '✈');
3163 var crashed = -1;
3164 var n = 0;
3165
3166 function runway () {
3167 var buf = Array(width).join('-');
3168 return ' ' + color('runway', buf);
3169 }
3170
3171 runner.on('start', function () {
3172 stream.write('\n\n\n ');
3173 cursor.hide();
3174 });
3175
3176 runner.on('test end', function (test) {
3177 // check if the plane crashed
3178 var col = crashed === -1 ? width * ++n / total | 0 : crashed;
3179
3180 // show the crash
3181 if (test.state === 'failed') {
3182 plane = color('plane crash', '✈');
3183 crashed = col;
3184 }
3185
3186 // render landing strip
3187 stream.write('\u001b[' + (width + 1) + 'D\u001b[2A');
3188 stream.write(runway());
3189 stream.write('\n ');
3190 stream.write(color('runway', Array(col).join('⋅')));
3191 stream.write(plane);
3192 stream.write(color('runway', Array(width - col).join('⋅') + '\n'));
3193 stream.write(runway());
3194 stream.write('\u001b[0m');
3195 });
3196
3197 runner.on('end', function () {
3198 cursor.show();
3199 console.log();
3200 self.epilogue();
3201 });
3202 }
3203
3204 /**
3205 * Inherit from `Base.prototype`.
3206 */
3207 inherits(Landing, Base);
3208
3209 }).call(this,require('_process'))
3210 },{"../utils":38,"./base":17,"_process":82}],25:[function(require,module,exports ){
3211 (function (process){
3212 'use strict';
3213
3214 /**
3215 * Module dependencies.
3216 */
3217
3218 var Base = require('./base');
3219 var inherits = require('../utils').inherits;
3220 var color = Base.color;
3221 var cursor = Base.cursor;
3222
3223 /**
3224 * Expose `List`.
3225 */
3226
3227 exports = module.exports = List;
3228
3229 /**
3230 * Initialize a new `List` test reporter.
3231 *
3232 * @api public
3233 * @param {Runner} runner
3234 */
3235 function List (runner) {
3236 Base.call(this, runner);
3237
3238 var self = this;
3239 var n = 0;
3240
3241 runner.on('start', function () {
3242 console.log();
3243 });
3244
3245 runner.on('test', function (test) {
3246 process.stdout.write(color('pass', ' ' + test.fullTitle() + ': '));
3247 });
3248
3249 runner.on('pending', function (test) {
3250 var fmt = color('checkmark', ' -') +
3251 color('pending', ' %s');
3252 console.log(fmt, test.fullTitle());
3253 });
3254
3255 runner.on('pass', function (test) {
3256 var fmt = color('checkmark', ' ' + Base.symbols.ok) +
3257 color('pass', ' %s: ') +
3258 color(test.speed, '%dms');
3259 cursor.CR();
3260 console.log(fmt, test.fullTitle(), test.duration);
3261 });
3262
3263 runner.on('fail', function (test) {
3264 cursor.CR();
3265 console.log(color('fail', ' %d) %s'), ++n, test.fullTitle());
3266 });
3267
3268 runner.on('end', self.epilogue.bind(self));
3269 }
3270
3271 /**
3272 * Inherit from `Base.prototype`.
3273 */
3274 inherits(List, Base);
3275
3276 }).call(this,require('_process'))
3277 },{"../utils":38,"./base":17,"_process":82}],26:[function(require,module,exports ){
3278 (function (process){
3279 'use strict';
3280
3281 /**
3282 * Module dependencies.
3283 */
3284
3285 var Base = require('./base');
3286 var utils = require('../utils');
3287
3288 /**
3289 * Constants
3290 */
3291
3292 var SUITE_PREFIX = '$';
3293
3294 /**
3295 * Expose `Markdown`.
3296 */
3297
3298 exports = module.exports = Markdown;
3299
3300 /**
3301 * Initialize a new `Markdown` reporter.
3302 *
3303 * @api public
3304 * @param {Runner} runner
3305 */
3306 function Markdown (runner) {
3307 Base.call(this, runner);
3308
3309 var level = 0;
3310 var buf = '';
3311
3312 function title (str) {
3313 return Array(level).join('#') + ' ' + str;
3314 }
3315
3316 function mapTOC (suite, obj) {
3317 var ret = obj;
3318 var key = SUITE_PREFIX + suite.title;
3319
3320 obj = obj[key] = obj[key] || { suite: suite };
3321 suite.suites.forEach(function (suite) {
3322 mapTOC(suite, obj);
3323 });
3324
3325 return ret;
3326 }
3327
3328 function stringifyTOC (obj, level) {
3329 ++level;
3330 var buf = '';
3331 var link;
3332 for (var key in obj) {
3333 if (key === 'suite') {
3334 continue;
3335 }
3336 if (key !== SUITE_PREFIX) {
3337 link = ' - [' + key.substring(1) + ']';
3338 link += '(#' + utils.slug(obj[key].suite.fullTitle()) + ')\n';
3339 buf += Array(level).join(' ') + link;
3340 }
3341 buf += stringifyTOC(obj[key], level);
3342 }
3343 return buf;
3344 }
3345
3346 function generateTOC (suite) {
3347 var obj = mapTOC(suite, {});
3348 return stringifyTOC(obj, 0);
3349 }
3350
3351 generateTOC(runner.suite);
3352
3353 runner.on('suite', function (suite) {
3354 ++level;
3355 var slug = utils.slug(suite.fullTitle());
3356 buf += '<a name="' + slug + '"></a>' + '\n';
3357 buf += title(suite.title) + '\n';
3358 });
3359
3360 runner.on('suite end', function () {
3361 --level;
3362 });
3363
3364 runner.on('pass', function (test) {
3365 var code = utils.clean(test.body);
3366 buf += test.title + '.\n';
3367 buf += '\n```js\n';
3368 buf += code + '\n';
3369 buf += '```\n\n';
3370 });
3371
3372 runner.on('end', function () {
3373 process.stdout.write('# TOC\n');
3374 process.stdout.write(generateTOC(runner.suite));
3375 process.stdout.write(buf);
3376 });
3377 }
3378
3379 }).call(this,require('_process'))
3380 },{"../utils":38,"./base":17,"_process":82}],27:[function(require,module,exports ){
3381 (function (process){
3382 'use strict';
3383
3384 /**
3385 * Module dependencies.
3386 */
3387
3388 var Base = require('./base');
3389 var inherits = require('../utils').inherits;
3390
3391 /**
3392 * Expose `Min`.
3393 */
3394
3395 exports = module.exports = Min;
3396
3397 /**
3398 * Initialize a new `Min` minimal test reporter (best used with --watch).
3399 *
3400 * @api public
3401 * @param {Runner} runner
3402 */
3403 function Min (runner) {
3404 Base.call(this, runner);
3405
3406 runner.on('start', function () {
3407 // clear screen
3408 process.stdout.write('\u001b[2J');
3409 // set cursor position
3410 process.stdout.write('\u001b[1;3H');
3411 });
3412
3413 runner.on('end', this.epilogue.bind(this));
3414 }
3415
3416 /**
3417 * Inherit from `Base.prototype`.
3418 */
3419 inherits(Min, Base);
3420
3421 }).call(this,require('_process'))
3422 },{"../utils":38,"./base":17,"_process":82}],28:[function(require,module,exports ){
3423 (function (process){
3424 'use strict';
3425
3426 /**
3427 * Module dependencies.
3428 */
3429
3430 var Base = require('./base');
3431 var inherits = require('../utils').inherits;
3432
3433 /**
3434 * Expose `Dot`.
3435 */
3436
3437 exports = module.exports = NyanCat;
3438
3439 /**
3440 * Initialize a new `Dot` matrix test reporter.
3441 *
3442 * @param {Runner} runner
3443 * @api public
3444 */
3445
3446 function NyanCat (runner) {
3447 Base.call(this, runner);
3448
3449 var self = this;
3450 var width = Base.window.width * 0.75 | 0;
3451 var nyanCatWidth = this.nyanCatWidth = 11;
3452
3453 this.colorIndex = 0;
3454 this.numberOfLines = 4;
3455 this.rainbowColors = self.generateColors();
3456 this.scoreboardWidth = 5;
3457 this.tick = 0;
3458 this.trajectories = [[], [], [], []];
3459 this.trajectoryWidthMax = (width - nyanCatWidth);
3460
3461 runner.on('start', function () {
3462 Base.cursor.hide();
3463 self.draw();
3464 });
3465
3466 runner.on('pending', function () {
3467 self.draw();
3468 });
3469
3470 runner.on('pass', function () {
3471 self.draw();
3472 });
3473
3474 runner.on('fail', function () {
3475 self.draw();
3476 });
3477
3478 runner.on('end', function () {
3479 Base.cursor.show();
3480 for (var i = 0; i < self.numberOfLines; i++) {
3481 write('\n');
3482 }
3483 self.epilogue();
3484 });
3485 }
3486
3487 /**
3488 * Inherit from `Base.prototype`.
3489 */
3490 inherits(NyanCat, Base);
3491
3492 /**
3493 * Draw the nyan cat
3494 *
3495 * @api private
3496 */
3497
3498 NyanCat.prototype.draw = function () {
3499 this.appendRainbow();
3500 this.drawScoreboard();
3501 this.drawRainbow();
3502 this.drawNyanCat();
3503 this.tick = !this.tick;
3504 };
3505
3506 /**
3507 * Draw the "scoreboard" showing the number
3508 * of passes, failures and pending tests.
3509 *
3510 * @api private
3511 */
3512
3513 NyanCat.prototype.drawScoreboard = function () {
3514 var stats = this.stats;
3515
3516 function draw (type, n) {
3517 write(' ');
3518 write(Base.color(type, n));
3519 write('\n');
3520 }
3521
3522 draw('green', stats.passes);
3523 draw('fail', stats.failures);
3524 draw('pending', stats.pending);
3525 write('\n');
3526
3527 this.cursorUp(this.numberOfLines);
3528 };
3529
3530 /**
3531 * Append the rainbow.
3532 *
3533 * @api private
3534 */
3535
3536 NyanCat.prototype.appendRainbow = function () {
3537 var segment = this.tick ? '_' : '-';
3538 var rainbowified = this.rainbowify(segment);
3539
3540 for (var index = 0; index < this.numberOfLines; index++) {
3541 var trajectory = this.trajectories[index];
3542 if (trajectory.length >= this.trajectoryWidthMax) {
3543 trajectory.shift();
3544 }
3545 trajectory.push(rainbowified);
3546 }
3547 };
3548
3549 /**
3550 * Draw the rainbow.
3551 *
3552 * @api private
3553 */
3554
3555 NyanCat.prototype.drawRainbow = function () {
3556 var self = this;
3557
3558 this.trajectories.forEach(function (line) {
3559 write('\u001b[' + self.scoreboardWidth + 'C');
3560 write(line.join(''));
3561 write('\n');
3562 });
3563
3564 this.cursorUp(this.numberOfLines);
3565 };
3566
3567 /**
3568 * Draw the nyan cat
3569 *
3570 * @api private
3571 */
3572 NyanCat.prototype.drawNyanCat = function () {
3573 var self = this;
3574 var startWidth = this.scoreboardWidth + this.trajectories[0].length;
3575 var dist = '\u001b[' + startWidth + 'C';
3576 var padding = '';
3577
3578 write(dist);
3579 write('_,------,');
3580 write('\n');
3581
3582 write(dist);
3583 padding = self.tick ? ' ' : ' ';
3584 write('_|' + padding + '/\\_/\\ ');
3585 write('\n');
3586
3587 write(dist);
3588 padding = self.tick ? '_' : '__';
3589 var tail = self.tick ? '~' : '^';
3590 write(tail + '|' + padding + this.face() + ' ');
3591 write('\n');
3592
3593 write(dist);
3594 padding = self.tick ? ' ' : ' ';
3595 write(padding + '"" "" ');
3596 write('\n');
3597
3598 this.cursorUp(this.numberOfLines);
3599 };
3600
3601 /**
3602 * Draw nyan cat face.
3603 *
3604 * @api private
3605 * @return {string}
3606 */
3607
3608 NyanCat.prototype.face = function () {
3609 var stats = this.stats;
3610 if (stats.failures) {
3611 return '( x .x)';
3612 } else if (stats.pending) {
3613 return '( o .o)';
3614 } else if (stats.passes) {
3615 return '( ^ .^)';
3616 }
3617 return '( - .-)';
3618 };
3619
3620 /**
3621 * Move cursor up `n`.
3622 *
3623 * @api private
3624 * @param {number} n
3625 */
3626
3627 NyanCat.prototype.cursorUp = function (n) {
3628 write('\u001b[' + n + 'A');
3629 };
3630
3631 /**
3632 * Move cursor down `n`.
3633 *
3634 * @api private
3635 * @param {number} n
3636 */
3637
3638 NyanCat.prototype.cursorDown = function (n) {
3639 write('\u001b[' + n + 'B');
3640 };
3641
3642 /**
3643 * Generate rainbow colors.
3644 *
3645 * @api private
3646 * @return {Array}
3647 */
3648 NyanCat.prototype.generateColors = function () {
3649 var colors = [];
3650
3651 for (var i = 0; i < (6 * 7); i++) {
3652 var pi3 = Math.floor(Math.PI / 3);
3653 var n = (i * (1.0 / 6));
3654 var r = Math.floor(3 * Math.sin(n) + 3);
3655 var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3);
3656 var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3);
3657 colors.push(36 * r + 6 * g + b + 16);
3658 }
3659
3660 return colors;
3661 };
3662
3663 /**
3664 * Apply rainbow to the given `str`.
3665 *
3666 * @api private
3667 * @param {string} str
3668 * @return {string}
3669 */
3670 NyanCat.prototype.rainbowify = function (str) {
3671 if (!Base.useColors) {
3672 return str;
3673 }
3674 var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length];
3675 this.colorIndex += 1;
3676 return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m';
3677 };
3678
3679 /**
3680 * Stdout helper.
3681 *
3682 * @param {string} string A message to write to stdout.
3683 */
3684 function write (string) {
3685 process.stdout.write(string);
3686 }
3687
3688 }).call(this,require('_process'))
3689 },{"../utils":38,"./base":17,"_process":82}],29:[function(require,module,exports ){
3690 (function (process){
3691 'use strict';
3692
3693 /**
3694 * Module dependencies.
3695 */
3696
3697 var Base = require('./base');
3698 var inherits = require('../utils').inherits;
3699 var color = Base.color;
3700 var cursor = Base.cursor;
3701
3702 /**
3703 * Expose `Progress`.
3704 */
3705
3706 exports = module.exports = Progress;
3707
3708 /**
3709 * General progress bar color.
3710 */
3711
3712 Base.colors.progress = 90;
3713
3714 /**
3715 * Initialize a new `Progress` bar test reporter.
3716 *
3717 * @api public
3718 * @param {Runner} runner
3719 * @param {Object} options
3720 */
3721 function Progress (runner, options) {
3722 Base.call(this, runner);
3723
3724 var self = this;
3725 var width = Base.window.width * 0.50 | 0;
3726 var total = runner.total;
3727 var complete = 0;
3728 var lastN = -1;
3729
3730 // default chars
3731 options = options || {};
3732 options.open = options.open || '[';
3733 options.complete = options.complete || '▬';
3734 options.incomplete = options.incomplete || Base.symbols.dot;
3735 options.close = options.close || ']';
3736 options.verbose = false;
3737
3738 // tests started
3739 runner.on('start', function () {
3740 console.log();
3741 cursor.hide();
3742 });
3743
3744 // tests complete
3745 runner.on('test end', function () {
3746 complete++;
3747
3748 var percent = complete / total;
3749 var n = width * percent | 0;
3750 var i = width - n;
3751
3752 if (n === lastN && !options.verbose) {
3753 // Don't re-render the line if it hasn't changed
3754 return;
3755 }
3756 lastN = n;
3757
3758 cursor.CR();
3759 process.stdout.write('\u001b[J');
3760 process.stdout.write(color('progress', ' ' + options.open));
3761 process.stdout.write(Array(n).join(options.complete));
3762 process.stdout.write(Array(i).join(options.incomplete));
3763 process.stdout.write(color('progress', options.close));
3764 if (options.verbose) {
3765 process.stdout.write(color('progress', ' ' + complete + ' of ' + total));
3766 }
3767 });
3768
3769 // tests are complete, output some stats
3770 // and the failures if any
3771 runner.on('end', function () {
3772 cursor.show();
3773 console.log();
3774 self.epilogue();
3775 });
3776 }
3777
3778 /**
3779 * Inherit from `Base.prototype`.
3780 */
3781 inherits(Progress, Base);
3782
3783 }).call(this,require('_process'))
3784 },{"../utils":38,"./base":17,"_process":82}],30:[function(require,module,exports ){
3785 'use strict';
3786
3787 /**
3788 * Module dependencies.
3789 */
3790
3791 var Base = require('./base');
3792 var inherits = require('../utils').inherits;
3793 var color = Base.color;
3794
3795 /**
3796 * Expose `Spec`.
3797 */
3798
3799 exports = module.exports = Spec;
3800
3801 /**
3802 * Initialize a new `Spec` test reporter.
3803 *
3804 * @api public
3805 * @param {Runner} runner
3806 */
3807 function Spec (runner) {
3808 Base.call(this, runner);
3809
3810 var self = this;
3811 var indents = 0;
3812 var n = 0;
3813
3814 function indent () {
3815 return Array(indents).join(' ');
3816 }
3817
3818 runner.on('start', function () {
3819 console.log();
3820 });
3821
3822 runner.on('suite', function (suite) {
3823 ++indents;
3824 console.log(color('suite', '%s%s'), indent(), suite.title);
3825 });
3826
3827 runner.on('suite end', function () {
3828 --indents;
3829 if (indents === 1) {
3830 console.log();
3831 }
3832 });
3833
3834 runner.on('pending', function (test) {
3835 var fmt = indent() + color('pending', ' - %s');
3836 console.log(fmt, test.title);
3837 });
3838
3839 runner.on('pass', function (test) {
3840 var fmt;
3841 if (test.speed === 'fast') {
3842 fmt = indent() +
3843 color('checkmark', ' ' + Base.symbols.ok) +
3844 color('pass', ' %s');
3845 console.log(fmt, test.title);
3846 } else {
3847 fmt = indent() +
3848 color('checkmark', ' ' + Base.symbols.ok) +
3849 color('pass', ' %s') +
3850 color(test.speed, ' (%dms)');
3851 console.log(fmt, test.title, test.duration);
3852 }
3853 });
3854
3855 runner.on('fail', function (test) {
3856 console.log(indent() + color('fail', ' %d) %s'), ++n, test.title);
3857 });
3858
3859 runner.on('end', self.epilogue.bind(self));
3860 }
3861
3862 /**
3863 * Inherit from `Base.prototype`.
3864 */
3865 inherits(Spec, Base);
3866
3867 },{"../utils":38,"./base":17}],31:[function(require,module,exports){
3868 'use strict';
3869
3870 /**
3871 * Module dependencies.
3872 */
3873
3874 var Base = require('./base');
3875
3876 /**
3877 * Expose `TAP`.
3878 */
3879
3880 exports = module.exports = TAP;
3881
3882 /**
3883 * Initialize a new `TAP` reporter.
3884 *
3885 * @api public
3886 * @param {Runner} runner
3887 */
3888 function TAP (runner) {
3889 Base.call(this, runner);
3890
3891 var n = 1;
3892 var passes = 0;
3893 var failures = 0;
3894
3895 runner.on('start', function () {
3896 var total = runner.grepTotal(runner.suite);
3897 console.log('%d..%d', 1, total);
3898 });
3899
3900 runner.on('test end', function () {
3901 ++n;
3902 });
3903
3904 runner.on('pending', function (test) {
3905 console.log('ok %d %s # SKIP -', n, title(test));
3906 });
3907
3908 runner.on('pass', function (test) {
3909 passes++;
3910 console.log('ok %d %s', n, title(test));
3911 });
3912
3913 runner.on('fail', function (test, err) {
3914 failures++;
3915 console.log('not ok %d %s', n, title(test));
3916 if (err.stack) {
3917 console.log(err.stack.replace(/^/gm, ' '));
3918 }
3919 });
3920
3921 runner.on('end', function () {
3922 console.log('# tests ' + (passes + failures));
3923 console.log('# pass ' + passes);
3924 console.log('# fail ' + failures);
3925 });
3926 }
3927
3928 /**
3929 * Return a TAP-safe title of `test`
3930 *
3931 * @api private
3932 * @param {Object} test
3933 * @return {String}
3934 */
3935 function title (test) {
3936 return test.fullTitle().replace(/#/g, '');
3937 }
3938
3939 },{"./base":17}],32:[function(require,module,exports){
3940 (function (process,global){
3941 'use strict';
3942
3943 /**
3944 * Module dependencies.
3945 */
3946
3947 var Base = require('./base');
3948 var utils = require('../utils');
3949 var inherits = utils.inherits;
3950 var fs = require('fs');
3951 var escape = utils.escape;
3952 var mkdirp = require('mkdirp');
3953 var path = require('path');
3954
3955 /**
3956 * Save timer references to avoid Sinon interfering (see GH-237).
3957 */
3958
3959 /* eslint-disable no-unused-vars, no-native-reassign */
3960 var Date = global.Date;
3961 var setTimeout = global.setTimeout;
3962 var setInterval = global.setInterval;
3963 var clearTimeout = global.clearTimeout;
3964 var clearInterval = global.clearInterval;
3965 /* eslint-enable no-unused-vars, no-native-reassign */
3966
3967 /**
3968 * Expose `XUnit`.
3969 */
3970
3971 exports = module.exports = XUnit;
3972
3973 /**
3974 * Initialize a new `XUnit` reporter.
3975 *
3976 * @api public
3977 * @param {Runner} runner
3978 */
3979 function XUnit (runner, options) {
3980 Base.call(this, runner);
3981
3982 var stats = this.stats;
3983 var tests = [];
3984 var self = this;
3985
3986 if (options && options.reporterOptions && options.reporterOptions.output) {
3987 if (!fs.createWriteStream) {
3988 throw new Error('file output not supported in browser');
3989 }
3990 mkdirp.sync(path.dirname(options.reporterOptions.output));
3991 self.fileStream = fs.createWriteStream(options.reporterOptions.output);
3992 }
3993
3994 runner.on('pending', function (test) {
3995 tests.push(test);
3996 });
3997
3998 runner.on('pass', function (test) {
3999 tests.push(test);
4000 });
4001
4002 runner.on('fail', function (test) {
4003 tests.push(test);
4004 });
4005
4006 runner.on('end', function () {
4007 self.write(tag('testsuite', {
4008 name: 'Mocha Tests',
4009 tests: stats.tests,
4010 failures: stats.failures,
4011 errors: stats.failures,
4012 skipped: stats.tests - stats.failures - stats.passes,
4013 timestamp: (new Date()).toUTCString(),
4014 time: (stats.duration / 1000) || 0
4015 }, false));
4016
4017 tests.forEach(function (t) {
4018 self.test(t);
4019 });
4020
4021 self.write('</testsuite>');
4022 });
4023 }
4024
4025 /**
4026 * Inherit from `Base.prototype`.
4027 */
4028 inherits(XUnit, Base);
4029
4030 /**
4031 * Override done to close the stream (if it's a file).
4032 *
4033 * @param failures
4034 * @param {Function} fn
4035 */
4036 XUnit.prototype.done = function (failures, fn) {
4037 if (this.fileStream) {
4038 this.fileStream.end(function () {
4039 fn(failures);
4040 });
4041 } else {
4042 fn(failures);
4043 }
4044 };
4045
4046 /**
4047 * Write out the given line.
4048 *
4049 * @param {string} line
4050 */
4051 XUnit.prototype.write = function (line) {
4052 if (this.fileStream) {
4053 this.fileStream.write(line + '\n');
4054 } else if (typeof process === 'object' && process.stdout) {
4055 process.stdout.write(line + '\n');
4056 } else {
4057 console.log(line);
4058 }
4059 };
4060
4061 /**
4062 * Output tag for the given `test.`
4063 *
4064 * @param {Test} test
4065 */
4066 XUnit.prototype.test = function (test) {
4067 var attrs = {
4068 classname: test.parent.fullTitle(),
4069 name: test.title,
4070 time: (test.duration / 1000) || 0
4071 };
4072
4073 if (test.state === 'failed') {
4074 var err = test.err;
4075 this.write(tag('testcase', attrs, false, tag('failure', {}, false, escape(er r.message) + '\n' + escape(err.stack))));
4076 } else if (test.isPending()) {
4077 this.write(tag('testcase', attrs, false, tag('skipped', {}, true)));
4078 } else {
4079 this.write(tag('testcase', attrs, true));
4080 }
4081 };
4082
4083 /**
4084 * HTML tag helper.
4085 *
4086 * @param name
4087 * @param attrs
4088 * @param close
4089 * @param content
4090 * @return {string}
4091 */
4092 function tag (name, attrs, close, content) {
4093 var end = close ? '/>' : '>';
4094 var pairs = [];
4095 var tag;
4096
4097 for (var key in attrs) {
4098 if (Object.prototype.hasOwnProperty.call(attrs, key)) {
4099 pairs.push(key + '="' + escape(attrs[key]) + '"');
4100 }
4101 }
4102
4103 tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end;
4104 if (content) {
4105 tag += content + '</' + name + end;
4106 }
4107 return tag;
4108 }
4109
4110 }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
4111 },{"../utils":38,"./base":17,"_process":82,"fs":42,"mkdirp":79,"path":42}],33:[f unction(require,module,exports){
4112 (function (global){
4113 'use strict';
4114
4115 /**
4116 * Module dependencies.
4117 */
4118
4119 var EventEmitter = require('events').EventEmitter;
4120 var JSON = require('json3');
4121 var Pending = require('./pending');
4122 var debug = require('debug')('mocha:runnable');
4123 var milliseconds = require('./ms');
4124 var utils = require('./utils');
4125 var create = require('lodash.create');
4126
4127 /**
4128 * Save timer references to avoid Sinon interfering (see GH-237).
4129 */
4130
4131 /* eslint-disable no-unused-vars, no-native-reassign */
4132 var Date = global.Date;
4133 var setTimeout = global.setTimeout;
4134 var setInterval = global.setInterval;
4135 var clearTimeout = global.clearTimeout;
4136 var clearInterval = global.clearInterval;
4137 /* eslint-enable no-unused-vars, no-native-reassign */
4138
4139 /**
4140 * Object#toString().
4141 */
4142
4143 var toString = Object.prototype.toString;
4144
4145 /**
4146 * Expose `Runnable`.
4147 */
4148
4149 module.exports = Runnable;
4150
4151 /**
4152 * Initialize a new `Runnable` with the given `title` and callback `fn`.
4153 *
4154 * @param {String} title
4155 * @param {Function} fn
4156 * @api private
4157 * @param {string} title
4158 * @param {Function} fn
4159 */
4160 function Runnable (title, fn) {
4161 this.title = title;
4162 this.fn = fn;
4163 this.body = (fn || '').toString();
4164 this.async = fn && fn.length;
4165 this.sync = !this.async;
4166 this._timeout = 2000;
4167 this._slow = 75;
4168 this._enableTimeouts = true;
4169 this.timedOut = false;
4170 this._trace = new Error('done() called multiple times');
4171 this._retries = -1;
4172 this._currentRetry = 0;
4173 this.pending = false;
4174 }
4175
4176 /**
4177 * Inherit from `EventEmitter.prototype`.
4178 */
4179 Runnable.prototype = create(EventEmitter.prototype, {
4180 constructor: Runnable
4181 });
4182
4183 /**
4184 * Set & get timeout `ms`.
4185 *
4186 * @api private
4187 * @param {number|string} ms
4188 * @return {Runnable|number} ms or Runnable instance.
4189 */
4190 Runnable.prototype.timeout = function (ms) {
4191 if (!arguments.length) {
4192 return this._timeout;
4193 }
4194 // see #1652 for reasoning
4195 if (ms === 0 || ms > Math.pow(2, 31)) {
4196 this._enableTimeouts = false;
4197 }
4198 if (typeof ms === 'string') {
4199 ms = milliseconds(ms);
4200 }
4201 debug('timeout %d', ms);
4202 this._timeout = ms;
4203 if (this.timer) {
4204 this.resetTimeout();
4205 }
4206 return this;
4207 };
4208
4209 /**
4210 * Set & get slow `ms`.
4211 *
4212 * @api private
4213 * @param {number|string} ms
4214 * @return {Runnable|number} ms or Runnable instance.
4215 */
4216 Runnable.prototype.slow = function (ms) {
4217 if (typeof ms === 'undefined') {
4218 return this._slow;
4219 }
4220 if (typeof ms === 'string') {
4221 ms = milliseconds(ms);
4222 }
4223 debug('timeout %d', ms);
4224 this._slow = ms;
4225 return this;
4226 };
4227
4228 /**
4229 * Set and get whether timeout is `enabled`.
4230 *
4231 * @api private
4232 * @param {boolean} enabled
4233 * @return {Runnable|boolean} enabled or Runnable instance.
4234 */
4235 Runnable.prototype.enableTimeouts = function (enabled) {
4236 if (!arguments.length) {
4237 return this._enableTimeouts;
4238 }
4239 debug('enableTimeouts %s', enabled);
4240 this._enableTimeouts = enabled;
4241 return this;
4242 };
4243
4244 /**
4245 * Halt and mark as pending.
4246 *
4247 * @api public
4248 */
4249 Runnable.prototype.skip = function () {
4250 throw new Pending('sync skip');
4251 };
4252
4253 /**
4254 * Check if this runnable or its parent suite is marked as pending.
4255 *
4256 * @api private
4257 */
4258 Runnable.prototype.isPending = function () {
4259 return this.pending || (this.parent && this.parent.isPending());
4260 };
4261
4262 /**
4263 * Set number of retries.
4264 *
4265 * @api private
4266 */
4267 Runnable.prototype.retries = function (n) {
4268 if (!arguments.length) {
4269 return this._retries;
4270 }
4271 this._retries = n;
4272 };
4273
4274 /**
4275 * Get current retry
4276 *
4277 * @api private
4278 */
4279 Runnable.prototype.currentRetry = function (n) {
4280 if (!arguments.length) {
4281 return this._currentRetry;
4282 }
4283 this._currentRetry = n;
4284 };
4285
4286 /**
4287 * Return the full title generated by recursively concatenating the parent's
4288 * full title.
4289 *
4290 * @api public
4291 * @return {string}
4292 */
4293 Runnable.prototype.fullTitle = function () {
4294 return this.parent.fullTitle() + ' ' + this.title;
4295 };
4296
4297 /**
4298 * Clear the timeout.
4299 *
4300 * @api private
4301 */
4302 Runnable.prototype.clearTimeout = function () {
4303 clearTimeout(this.timer);
4304 };
4305
4306 /**
4307 * Inspect the runnable void of private properties.
4308 *
4309 * @api private
4310 * @return {string}
4311 */
4312 Runnable.prototype.inspect = function () {
4313 return JSON.stringify(this, function (key, val) {
4314 if (key[0] === '_') {
4315 return;
4316 }
4317 if (key === 'parent') {
4318 return '#<Suite>';
4319 }
4320 if (key === 'ctx') {
4321 return '#<Context>';
4322 }
4323 return val;
4324 }, 2);
4325 };
4326
4327 /**
4328 * Reset the timeout.
4329 *
4330 * @api private
4331 */
4332 Runnable.prototype.resetTimeout = function () {
4333 var self = this;
4334 var ms = this.timeout() || 1e9;
4335
4336 if (!this._enableTimeouts) {
4337 return;
4338 }
4339 this.clearTimeout();
4340 this.timer = setTimeout(function () {
4341 if (!self._enableTimeouts) {
4342 return;
4343 }
4344 self.callback(new Error('Timeout of ' + ms +
4345 'ms exceeded. For async tests and hooks, ensure "done()" is called; if ret urning a Promise, ensure it resolves.'));
4346 self.timedOut = true;
4347 }, ms);
4348 };
4349
4350 /**
4351 * Whitelist a list of globals for this test run.
4352 *
4353 * @api private
4354 * @param {string[]} globals
4355 */
4356 Runnable.prototype.globals = function (globals) {
4357 if (!arguments.length) {
4358 return this._allowedGlobals;
4359 }
4360 this._allowedGlobals = globals;
4361 };
4362
4363 /**
4364 * Run the test and invoke `fn(err)`.
4365 *
4366 * @param {Function} fn
4367 * @api private
4368 */
4369 Runnable.prototype.run = function (fn) {
4370 var self = this;
4371 var start = new Date();
4372 var ctx = this.ctx;
4373 var finished;
4374 var emitted;
4375
4376 // Sometimes the ctx exists, but it is not runnable
4377 if (ctx && ctx.runnable) {
4378 ctx.runnable(this);
4379 }
4380
4381 // called multiple times
4382 function multiple (err) {
4383 if (emitted) {
4384 return;
4385 }
4386 emitted = true;
4387 self.emit('error', err || new Error('done() called multiple times; stacktrac e may be inaccurate'));
4388 }
4389
4390 // finished
4391 function done (err) {
4392 var ms = self.timeout();
4393 if (self.timedOut) {
4394 return;
4395 }
4396 if (finished) {
4397 return multiple(err || self._trace);
4398 }
4399
4400 self.clearTimeout();
4401 self.duration = new Date() - start;
4402 finished = true;
4403 if (!err && self.duration > ms && self._enableTimeouts) {
4404 err = new Error('Timeout of ' + ms +
4405 'ms exceeded. For async tests and hooks, ensure "done()" is called; if ret urning a Promise, ensure it resolves.');
4406 }
4407 fn(err);
4408 }
4409
4410 // for .resetTimeout()
4411 this.callback = done;
4412
4413 // explicit async with `done` argument
4414 if (this.async) {
4415 this.resetTimeout();
4416
4417 // allows skip() to be used in an explicit async context
4418 this.skip = function asyncSkip () {
4419 done(new Pending('async skip call'));
4420 // halt execution. the Runnable will be marked pending
4421 // by the previous call, and the uncaught handler will ignore
4422 // the failure.
4423 throw new Pending('async skip; aborting execution');
4424 };
4425
4426 if (this.allowUncaught) {
4427 return callFnAsync(this.fn);
4428 }
4429 try {
4430 callFnAsync(this.fn);
4431 } catch (err) {
4432 emitted = true;
4433 done(utils.getError(err));
4434 }
4435 return;
4436 }
4437
4438 if (this.allowUncaught) {
4439 if (this.isPending()) {
4440 done();
4441 } else {
4442 callFn(this.fn);
4443 }
4444 return;
4445 }
4446
4447 // sync or promise-returning
4448 try {
4449 if (this.isPending()) {
4450 done();
4451 } else {
4452 callFn(this.fn);
4453 }
4454 } catch (err) {
4455 emitted = true;
4456 done(utils.getError(err));
4457 }
4458
4459 function callFn (fn) {
4460 var result = fn.call(ctx);
4461 if (result && typeof result.then === 'function') {
4462 self.resetTimeout();
4463 result
4464 .then(function () {
4465 done();
4466 // Return null so libraries like bluebird do not warn about
4467 // subsequently constructed Promises.
4468 return null;
4469 },
4470 function (reason) {
4471 done(reason || new Error('Promise rejected with no or falsy reason'));
4472 });
4473 } else {
4474 if (self.asyncOnly) {
4475 return done(new Error('--async-only option in use without declaring `don e()` or returning a promise'));
4476 }
4477
4478 done();
4479 }
4480 }
4481
4482 function callFnAsync (fn) {
4483 var result = fn.call(ctx, function (err) {
4484 if (err instanceof Error || toString.call(err) === '[object Error]') {
4485 return done(err);
4486 }
4487 if (err) {
4488 if (Object.prototype.toString.call(err) === '[object Object]') {
4489 return done(new Error('done() invoked with non-Error: ' +
4490 JSON.stringify(err)));
4491 }
4492 return done(new Error('done() invoked with non-Error: ' + err));
4493 }
4494 if (result && utils.isPromise(result)) {
4495 return done(new Error('Resolution method is overspecified. Specify a cal lback *or* return a Promise; not both.'));
4496 }
4497
4498 done();
4499 });
4500 }
4501 };
4502
4503 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined " ? self : typeof window !== "undefined" ? window : {})
4504 },{"./ms":15,"./pending":16,"./utils":38,"debug":2,"events":3,"json3":69,"lodash .create":75}],34:[function(require,module,exports){
4505 (function (process,global){
4506 'use strict';
4507
4508 /**
4509 * Module dependencies.
4510 */
4511
4512 var EventEmitter = require('events').EventEmitter;
4513 var Pending = require('./pending');
4514 var utils = require('./utils');
4515 var inherits = utils.inherits;
4516 var debug = require('debug')('mocha:runner');
4517 var Runnable = require('./runnable');
4518 var filter = utils.filter;
4519 var indexOf = utils.indexOf;
4520 var some = utils.some;
4521 var keys = utils.keys;
4522 var stackFilter = utils.stackTraceFilter();
4523 var stringify = utils.stringify;
4524 var type = utils.type;
4525 var undefinedError = utils.undefinedError;
4526 var isArray = utils.isArray;
4527
4528 /**
4529 * Non-enumerable globals.
4530 */
4531
4532 var globals = [
4533 'setTimeout',
4534 'clearTimeout',
4535 'setInterval',
4536 'clearInterval',
4537 'XMLHttpRequest',
4538 'Date',
4539 'setImmediate',
4540 'clearImmediate'
4541 ];
4542
4543 /**
4544 * Expose `Runner`.
4545 */
4546
4547 module.exports = Runner;
4548
4549 /**
4550 * Initialize a `Runner` for the given `suite`.
4551 *
4552 * Events:
4553 *
4554 * - `start` execution started
4555 * - `end` execution complete
4556 * - `suite` (suite) test suite execution started
4557 * - `suite end` (suite) all tests (and sub-suites) have finished
4558 * - `test` (test) test execution started
4559 * - `test end` (test) test completed
4560 * - `hook` (hook) hook execution started
4561 * - `hook end` (hook) hook complete
4562 * - `pass` (test) test passed
4563 * - `fail` (test, err) test failed
4564 * - `pending` (test) test pending
4565 *
4566 * @api public
4567 * @param {Suite} suite Root suite
4568 * @param {boolean} [delay] Whether or not to delay execution of root suite
4569 * until ready.
4570 */
4571 function Runner (suite, delay) {
4572 var self = this;
4573 this._globals = [];
4574 this._abort = false;
4575 this._delay = delay;
4576 this.suite = suite;
4577 this.started = false;
4578 this.total = suite.total();
4579 this.failures = 0;
4580 this.on('test end', function (test) {
4581 self.checkGlobals(test);
4582 });
4583 this.on('hook end', function (hook) {
4584 self.checkGlobals(hook);
4585 });
4586 this._defaultGrep = /.*/;
4587 this.grep(this._defaultGrep);
4588 this.globals(this.globalProps().concat(extraGlobals()));
4589 }
4590
4591 /**
4592 * Wrapper for setImmediate, process.nextTick, or browser polyfill.
4593 *
4594 * @param {Function} fn
4595 * @api private
4596 */
4597 Runner.immediately = global.setImmediate || process.nextTick;
4598
4599 /**
4600 * Inherit from `EventEmitter.prototype`.
4601 */
4602 inherits(Runner, EventEmitter);
4603
4604 /**
4605 * Run tests with full titles matching `re`. Updates runner.total
4606 * with number of tests matched.
4607 *
4608 * @param {RegExp} re
4609 * @param {Boolean} invert
4610 * @return {Runner} for chaining
4611 * @api public
4612 * @param {RegExp} re
4613 * @param {boolean} invert
4614 * @return {Runner} Runner instance.
4615 */
4616 Runner.prototype.grep = function (re, invert) {
4617 debug('grep %s', re);
4618 this._grep = re;
4619 this._invert = invert;
4620 this.total = this.grepTotal(this.suite);
4621 return this;
4622 };
4623
4624 /**
4625 * Returns the number of tests matching the grep search for the
4626 * given suite.
4627 *
4628 * @param {Suite} suite
4629 * @return {Number}
4630 * @api public
4631 * @param {Suite} suite
4632 * @return {number}
4633 */
4634 Runner.prototype.grepTotal = function (suite) {
4635 var self = this;
4636 var total = 0;
4637
4638 suite.eachTest(function (test) {
4639 var match = self._grep.test(test.fullTitle());
4640 if (self._invert) {
4641 match = !match;
4642 }
4643 if (match) {
4644 total++;
4645 }
4646 });
4647
4648 return total;
4649 };
4650
4651 /**
4652 * Return a list of global properties.
4653 *
4654 * @return {Array}
4655 * @api private
4656 */
4657 Runner.prototype.globalProps = function () {
4658 var props = keys(global);
4659
4660 // non-enumerables
4661 for (var i = 0; i < globals.length; ++i) {
4662 if (~indexOf(props, globals[i])) {
4663 continue;
4664 }
4665 props.push(globals[i]);
4666 }
4667
4668 return props;
4669 };
4670
4671 /**
4672 * Allow the given `arr` of globals.
4673 *
4674 * @param {Array} arr
4675 * @return {Runner} for chaining
4676 * @api public
4677 * @param {Array} arr
4678 * @return {Runner} Runner instance.
4679 */
4680 Runner.prototype.globals = function (arr) {
4681 if (!arguments.length) {
4682 return this._globals;
4683 }
4684 debug('globals %j', arr);
4685 this._globals = this._globals.concat(arr);
4686 return this;
4687 };
4688
4689 /**
4690 * Check for global variable leaks.
4691 *
4692 * @api private
4693 */
4694 Runner.prototype.checkGlobals = function (test) {
4695 if (this.ignoreLeaks) {
4696 return;
4697 }
4698 var ok = this._globals;
4699
4700 var globals = this.globalProps();
4701 var leaks;
4702
4703 if (test) {
4704 ok = ok.concat(test._allowedGlobals || []);
4705 }
4706
4707 if (this.prevGlobalsLength === globals.length) {
4708 return;
4709 }
4710 this.prevGlobalsLength = globals.length;
4711
4712 leaks = filterLeaks(ok, globals);
4713 this._globals = this._globals.concat(leaks);
4714
4715 if (leaks.length > 1) {
4716 this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + '') );
4717 } else if (leaks.length) {
4718 this.fail(test, new Error('global leak detected: ' + leaks[0]));
4719 }
4720 };
4721
4722 /**
4723 * Fail the given `test`.
4724 *
4725 * @api private
4726 * @param {Test} test
4727 * @param {Error} err
4728 */
4729 Runner.prototype.fail = function (test, err) {
4730 if (test.isPending()) {
4731 return;
4732 }
4733
4734 ++this.failures;
4735 test.state = 'failed';
4736
4737 if (!(err instanceof Error || err && typeof err.message === 'string')) {
4738 err = new Error('the ' + type(err) + ' ' + stringify(err) + ' was thrown, th row an Error :)');
4739 }
4740
4741 try {
4742 err.stack = (this.fullStackTrace || !err.stack)
4743 ? err.stack
4744 : stackFilter(err.stack);
4745 } catch (ignored) {
4746 // some environments do not take kindly to monkeying with the stack
4747 }
4748
4749 this.emit('fail', test, err);
4750 };
4751
4752 /**
4753 * Fail the given `hook` with `err`.
4754 *
4755 * Hook failures work in the following pattern:
4756 * - If bail, then exit
4757 * - Failed `before` hook skips all tests in a suite and subsuites,
4758 * but jumps to corresponding `after` hook
4759 * - Failed `before each` hook skips remaining tests in a
4760 * suite and jumps to corresponding `after each` hook,
4761 * which is run only once
4762 * - Failed `after` hook does not alter
4763 * execution order
4764 * - Failed `after each` hook skips remaining tests in a
4765 * suite and subsuites, but executes other `after each`
4766 * hooks
4767 *
4768 * @api private
4769 * @param {Hook} hook
4770 * @param {Error} err
4771 */
4772 Runner.prototype.failHook = function (hook, err) {
4773 if (hook.ctx && hook.ctx.currentTest) {
4774 hook.originalTitle = hook.originalTitle || hook.title;
4775 hook.title = hook.originalTitle + ' for "' + hook.ctx.currentTest.title + '" ';
4776 }
4777
4778 this.fail(hook, err);
4779 if (this.suite.bail()) {
4780 this.emit('end');
4781 }
4782 };
4783
4784 /**
4785 * Run hook `name` callbacks and then invoke `fn()`.
4786 *
4787 * @api private
4788 * @param {string} name
4789 * @param {Function} fn
4790 */
4791
4792 Runner.prototype.hook = function (name, fn) {
4793 var suite = this.suite;
4794 var hooks = suite['_' + name];
4795 var self = this;
4796
4797 function next (i) {
4798 var hook = hooks[i];
4799 if (!hook) {
4800 return fn();
4801 }
4802 self.currentRunnable = hook;
4803
4804 hook.ctx.currentTest = self.test;
4805
4806 self.emit('hook', hook);
4807
4808 if (!hook.listeners('error').length) {
4809 hook.on('error', function (err) {
4810 self.failHook(hook, err);
4811 });
4812 }
4813
4814 hook.run(function (err) {
4815 var testError = hook.error();
4816 if (testError) {
4817 self.fail(self.test, testError);
4818 }
4819 if (err) {
4820 if (err instanceof Pending) {
4821 if (name === 'beforeEach' || name === 'afterEach') {
4822 self.test.pending = true;
4823 } else {
4824 utils.forEach(suite.tests, function (test) {
4825 test.pending = true;
4826 });
4827 // a pending hook won't be executed twice.
4828 hook.pending = true;
4829 }
4830 } else {
4831 self.failHook(hook, err);
4832
4833 // stop executing hooks, notify callee of hook err
4834 return fn(err);
4835 }
4836 }
4837 self.emit('hook end', hook);
4838 delete hook.ctx.currentTest;
4839 next(++i);
4840 });
4841 }
4842
4843 Runner.immediately(function () {
4844 next(0);
4845 });
4846 };
4847
4848 /**
4849 * Run hook `name` for the given array of `suites`
4850 * in order, and callback `fn(err, errSuite)`.
4851 *
4852 * @api private
4853 * @param {string} name
4854 * @param {Array} suites
4855 * @param {Function} fn
4856 */
4857 Runner.prototype.hooks = function (name, suites, fn) {
4858 var self = this;
4859 var orig = this.suite;
4860
4861 function next (suite) {
4862 self.suite = suite;
4863
4864 if (!suite) {
4865 self.suite = orig;
4866 return fn();
4867 }
4868
4869 self.hook(name, function (err) {
4870 if (err) {
4871 var errSuite = self.suite;
4872 self.suite = orig;
4873 return fn(err, errSuite);
4874 }
4875
4876 next(suites.pop());
4877 });
4878 }
4879
4880 next(suites.pop());
4881 };
4882
4883 /**
4884 * Run hooks from the top level down.
4885 *
4886 * @param {String} name
4887 * @param {Function} fn
4888 * @api private
4889 */
4890 Runner.prototype.hookUp = function (name, fn) {
4891 var suites = [this.suite].concat(this.parents()).reverse();
4892 this.hooks(name, suites, fn);
4893 };
4894
4895 /**
4896 * Run hooks from the bottom up.
4897 *
4898 * @param {String} name
4899 * @param {Function} fn
4900 * @api private
4901 */
4902 Runner.prototype.hookDown = function (name, fn) {
4903 var suites = [this.suite].concat(this.parents());
4904 this.hooks(name, suites, fn);
4905 };
4906
4907 /**
4908 * Return an array of parent Suites from
4909 * closest to furthest.
4910 *
4911 * @return {Array}
4912 * @api private
4913 */
4914 Runner.prototype.parents = function () {
4915 var suite = this.suite;
4916 var suites = [];
4917 while (suite.parent) {
4918 suite = suite.parent;
4919 suites.push(suite);
4920 }
4921 return suites;
4922 };
4923
4924 /**
4925 * Run the current test and callback `fn(err)`.
4926 *
4927 * @param {Function} fn
4928 * @api private
4929 */
4930 Runner.prototype.runTest = function (fn) {
4931 var self = this;
4932 var test = this.test;
4933
4934 if (!test) {
4935 return;
4936 }
4937 if (this.asyncOnly) {
4938 test.asyncOnly = true;
4939 }
4940 test.on('error', function (err) {
4941 self.fail(test, err);
4942 });
4943 if (this.allowUncaught) {
4944 test.allowUncaught = true;
4945 return test.run(fn);
4946 }
4947 try {
4948 test.run(fn);
4949 } catch (err) {
4950 fn(err);
4951 }
4952 };
4953
4954 /**
4955 * Run tests in the given `suite` and invoke the callback `fn()` when complete.
4956 *
4957 * @api private
4958 * @param {Suite} suite
4959 * @param {Function} fn
4960 */
4961 Runner.prototype.runTests = function (suite, fn) {
4962 var self = this;
4963 var tests = suite.tests.slice();
4964 var test;
4965
4966 function hookErr (_, errSuite, after) {
4967 // before/after Each hook for errSuite failed:
4968 var orig = self.suite;
4969
4970 // for failed 'after each' hook start from errSuite parent,
4971 // otherwise start from errSuite itself
4972 self.suite = after ? errSuite.parent : errSuite;
4973
4974 if (self.suite) {
4975 // call hookUp afterEach
4976 self.hookUp('afterEach', function (err2, errSuite2) {
4977 self.suite = orig;
4978 // some hooks may fail even now
4979 if (err2) {
4980 return hookErr(err2, errSuite2, true);
4981 }
4982 // report error suite
4983 fn(errSuite);
4984 });
4985 } else {
4986 // there is no need calling other 'after each' hooks
4987 self.suite = orig;
4988 fn(errSuite);
4989 }
4990 }
4991
4992 function next (err, errSuite) {
4993 // if we bail after first err
4994 if (self.failures && suite._bail) {
4995 return fn();
4996 }
4997
4998 if (self._abort) {
4999 return fn();
5000 }
5001
5002 if (err) {
5003 return hookErr(err, errSuite, true);
5004 }
5005
5006 // next test
5007 test = tests.shift();
5008
5009 // all done
5010 if (!test) {
5011 return fn();
5012 }
5013
5014 // grep
5015 var match = self._grep.test(test.fullTitle());
5016 if (self._invert) {
5017 match = !match;
5018 }
5019 if (!match) {
5020 // Run immediately only if we have defined a grep. When we
5021 // define a grep — It can cause maximum callstack error if
5022 // the grep is doing a large recursive loop by neglecting
5023 // all tests. The run immediately function also comes with
5024 // a performance cost. So we don't want to run immediately
5025 // if we run the whole test suite, because running the whole
5026 // test suite don't do any immediate recursive loops. Thus,
5027 // allowing a JS runtime to breathe.
5028 if (self._grep !== self._defaultGrep) {
5029 Runner.immediately(next);
5030 } else {
5031 next();
5032 }
5033 return;
5034 }
5035
5036 if (test.isPending()) {
5037 self.emit('pending', test);
5038 self.emit('test end', test);
5039 return next();
5040 }
5041
5042 // execute test and hook(s)
5043 self.emit('test', self.test = test);
5044 self.hookDown('beforeEach', function (err, errSuite) {
5045 if (test.isPending()) {
5046 self.emit('pending', test);
5047 self.emit('test end', test);
5048 return next();
5049 }
5050 if (err) {
5051 return hookErr(err, errSuite, false);
5052 }
5053 self.currentRunnable = self.test;
5054 self.runTest(function (err) {
5055 test = self.test;
5056 if (err) {
5057 var retry = test.currentRetry();
5058 if (err instanceof Pending) {
5059 test.pending = true;
5060 self.emit('pending', test);
5061 } else if (retry < test.retries()) {
5062 var clonedTest = test.clone();
5063 clonedTest.currentRetry(retry + 1);
5064 tests.unshift(clonedTest);
5065
5066 // Early return + hook trigger so that it doesn't
5067 // increment the count wrong
5068 return self.hookUp('afterEach', next);
5069 } else {
5070 self.fail(test, err);
5071 }
5072 self.emit('test end', test);
5073
5074 if (err instanceof Pending) {
5075 return next();
5076 }
5077
5078 return self.hookUp('afterEach', next);
5079 }
5080
5081 test.state = 'passed';
5082 self.emit('pass', test);
5083 self.emit('test end', test);
5084 self.hookUp('afterEach', next);
5085 });
5086 });
5087 }
5088
5089 this.next = next;
5090 this.hookErr = hookErr;
5091 next();
5092 };
5093
5094 /**
5095 * Run the given `suite` and invoke the callback `fn()` when complete.
5096 *
5097 * @api private
5098 * @param {Suite} suite
5099 * @param {Function} fn
5100 */
5101 Runner.prototype.runSuite = function (suite, fn) {
5102 var i = 0;
5103 var self = this;
5104 var total = this.grepTotal(suite);
5105 var afterAllHookCalled = false;
5106
5107 debug('run suite %s', suite.fullTitle());
5108
5109 if (!total || (self.failures && suite._bail)) {
5110 return fn();
5111 }
5112
5113 this.emit('suite', this.suite = suite);
5114
5115 function next (errSuite) {
5116 if (errSuite) {
5117 // current suite failed on a hook from errSuite
5118 if (errSuite === suite) {
5119 // if errSuite is current suite
5120 // continue to the next sibling suite
5121 return done();
5122 }
5123 // errSuite is among the parents of current suite
5124 // stop execution of errSuite and all sub-suites
5125 return done(errSuite);
5126 }
5127
5128 if (self._abort) {
5129 return done();
5130 }
5131
5132 var curr = suite.suites[i++];
5133 if (!curr) {
5134 return done();
5135 }
5136
5137 // Avoid grep neglecting large number of tests causing a
5138 // huge recursive loop and thus a maximum call stack error.
5139 // See comment in `this.runTests()` for more information.
5140 if (self._grep !== self._defaultGrep) {
5141 Runner.immediately(function () {
5142 self.runSuite(curr, next);
5143 });
5144 } else {
5145 self.runSuite(curr, next);
5146 }
5147 }
5148
5149 function done (errSuite) {
5150 self.suite = suite;
5151 self.nextSuite = next;
5152
5153 if (afterAllHookCalled) {
5154 fn(errSuite);
5155 } else {
5156 // mark that the afterAll block has been called once
5157 // and so can be skipped if there is an error in it.
5158 afterAllHookCalled = true;
5159
5160 // remove reference to test
5161 delete self.test;
5162
5163 self.hook('afterAll', function () {
5164 self.emit('suite end', suite);
5165 fn(errSuite);
5166 });
5167 }
5168 }
5169
5170 this.nextSuite = next;
5171
5172 this.hook('beforeAll', function (err) {
5173 if (err) {
5174 return done();
5175 }
5176 self.runTests(suite, next);
5177 });
5178 };
5179
5180 /**
5181 * Handle uncaught exceptions.
5182 *
5183 * @param {Error} err
5184 * @api private
5185 */
5186 Runner.prototype.uncaught = function (err) {
5187 if (err) {
5188 debug('uncaught exception %s', err === (function () {
5189 return this;
5190 }.call(err)) ? (err.message || err) : err);
5191 } else {
5192 debug('uncaught undefined exception');
5193 err = undefinedError();
5194 }
5195 err.uncaught = true;
5196
5197 var runnable = this.currentRunnable;
5198
5199 if (!runnable) {
5200 runnable = new Runnable('Uncaught error outside test suite');
5201 runnable.parent = this.suite;
5202
5203 if (this.started) {
5204 this.fail(runnable, err);
5205 } else {
5206 // Can't recover from this failure
5207 this.emit('start');
5208 this.fail(runnable, err);
5209 this.emit('end');
5210 }
5211
5212 return;
5213 }
5214
5215 runnable.clearTimeout();
5216
5217 // Ignore errors if complete or pending
5218 if (runnable.state || runnable.isPending()) {
5219 return;
5220 }
5221 this.fail(runnable, err);
5222
5223 // recover from test
5224 if (runnable.type === 'test') {
5225 this.emit('test end', runnable);
5226 this.hookUp('afterEach', this.next);
5227 return;
5228 }
5229
5230 // recover from hooks
5231 if (runnable.type === 'hook') {
5232 var errSuite = this.suite;
5233 // if hook failure is in afterEach block
5234 if (runnable.fullTitle().indexOf('after each') > -1) {
5235 return this.hookErr(err, errSuite, true);
5236 }
5237 // if hook failure is in beforeEach block
5238 if (runnable.fullTitle().indexOf('before each') > -1) {
5239 return this.hookErr(err, errSuite, false);
5240 }
5241 // if hook failure is in after or before blocks
5242 return this.nextSuite(errSuite);
5243 }
5244
5245 // bail
5246 this.emit('end');
5247 };
5248
5249 /**
5250 * Cleans up the references to all the deferred functions
5251 * (before/after/beforeEach/afterEach) and tests of a Suite.
5252 * These must be deleted otherwise a memory leak can happen,
5253 * as those functions may reference variables from closures,
5254 * thus those variables can never be garbage collected as long
5255 * as the deferred functions exist.
5256 *
5257 * @param {Suite} suite
5258 */
5259 function cleanSuiteReferences (suite) {
5260 function cleanArrReferences (arr) {
5261 for (var i = 0; i < arr.length; i++) {
5262 delete arr[i].fn;
5263 }
5264 }
5265
5266 if (isArray(suite._beforeAll)) {
5267 cleanArrReferences(suite._beforeAll);
5268 }
5269
5270 if (isArray(suite._beforeEach)) {
5271 cleanArrReferences(suite._beforeEach);
5272 }
5273
5274 if (isArray(suite._afterAll)) {
5275 cleanArrReferences(suite._afterAll);
5276 }
5277
5278 if (isArray(suite._afterEach)) {
5279 cleanArrReferences(suite._afterEach);
5280 }
5281
5282 for (var i = 0; i < suite.tests.length; i++) {
5283 delete suite.tests[i].fn;
5284 }
5285 }
5286
5287 /**
5288 * Run the root suite and invoke `fn(failures)`
5289 * on completion.
5290 *
5291 * @param {Function} fn
5292 * @return {Runner} for chaining
5293 * @api public
5294 * @param {Function} fn
5295 * @return {Runner} Runner instance.
5296 */
5297 Runner.prototype.run = function (fn) {
5298 var self = this;
5299 var rootSuite = this.suite;
5300
5301 // If there is an `only` filter
5302 if (this.hasOnly) {
5303 filterOnly(rootSuite);
5304 }
5305
5306 fn = fn || function () {};
5307
5308 function uncaught (err) {
5309 self.uncaught(err);
5310 }
5311
5312 function start () {
5313 self.started = true;
5314 self.emit('start');
5315 self.runSuite(rootSuite, function () {
5316 debug('finished running');
5317 self.emit('end');
5318 });
5319 }
5320
5321 debug('start');
5322
5323 // references cleanup to avoid memory leaks
5324 this.on('suite end', cleanSuiteReferences);
5325
5326 // callback
5327 this.on('end', function () {
5328 debug('end');
5329 process.removeListener('uncaughtException', uncaught);
5330 fn(self.failures);
5331 });
5332
5333 // uncaught exception
5334 process.on('uncaughtException', uncaught);
5335
5336 if (this._delay) {
5337 // for reporters, I guess.
5338 // might be nice to debounce some dots while we wait.
5339 this.emit('waiting', rootSuite);
5340 rootSuite.once('run', start);
5341 } else {
5342 start();
5343 }
5344
5345 return this;
5346 };
5347
5348 /**
5349 * Cleanly abort execution.
5350 *
5351 * @api public
5352 * @return {Runner} Runner instance.
5353 */
5354 Runner.prototype.abort = function () {
5355 debug('aborting');
5356 this._abort = true;
5357
5358 return this;
5359 };
5360
5361 /**
5362 * Filter suites based on `isOnly` logic.
5363 *
5364 * @param {Array} suite
5365 * @returns {Boolean}
5366 * @api private
5367 */
5368 function filterOnly (suite) {
5369 if (suite._onlyTests.length) {
5370 // If the suite contains `only` tests, run those and ignore any nested suite s.
5371 suite.tests = suite._onlyTests;
5372 suite.suites = [];
5373 } else {
5374 // Otherwise, do not run any of the tests in this suite.
5375 suite.tests = [];
5376 utils.forEach(suite._onlySuites, function (onlySuite) {
5377 // If there are other `only` tests/suites nested in the current `only` sui te, then filter that `only` suite.
5378 // Otherwise, all of the tests on this `only` suite should be run, so don' t filter it.
5379 if (hasOnly(onlySuite)) {
5380 filterOnly(onlySuite);
5381 }
5382 });
5383 // Run the `only` suites, as well as any other suites that have `only` tests /suites as descendants.
5384 suite.suites = filter(suite.suites, function (childSuite) {
5385 return indexOf(suite._onlySuites, childSuite) !== -1 || filterOnly(childSu ite);
5386 });
5387 }
5388 // Keep the suite only if there is something to run
5389 return suite.tests.length || suite.suites.length;
5390 }
5391
5392 /**
5393 * Determines whether a suite has an `only` test or suite as a descendant.
5394 *
5395 * @param {Array} suite
5396 * @returns {Boolean}
5397 * @api private
5398 */
5399 function hasOnly (suite) {
5400 return suite._onlyTests.length || suite._onlySuites.length || some(suite.suite s, hasOnly);
5401 }
5402
5403 /**
5404 * Filter leaks with the given globals flagged as `ok`.
5405 *
5406 * @api private
5407 * @param {Array} ok
5408 * @param {Array} globals
5409 * @return {Array}
5410 */
5411 function filterLeaks (ok, globals) {
5412 return filter(globals, function (key) {
5413 // Firefox and Chrome exposes iframes as index inside the window object
5414 if (/^\d+/.test(key)) {
5415 return false;
5416 }
5417
5418 // in firefox
5419 // if runner runs in an iframe, this iframe's window.getInterface method
5420 // not init at first it is assigned in some seconds
5421 if (global.navigator && (/^getInterface/).test(key)) {
5422 return false;
5423 }
5424
5425 // an iframe could be approached by window[iframeIndex]
5426 // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak
5427 if (global.navigator && (/^\d+/).test(key)) {
5428 return false;
5429 }
5430
5431 // Opera and IE expose global variables for HTML element IDs (issue #243)
5432 if (/^mocha-/.test(key)) {
5433 return false;
5434 }
5435
5436 var matched = filter(ok, function (ok) {
5437 if (~ok.indexOf('*')) {
5438 return key.indexOf(ok.split('*')[0]) === 0;
5439 }
5440 return key === ok;
5441 });
5442 return !matched.length && (!global.navigator || key !== 'onerror');
5443 });
5444 }
5445
5446 /**
5447 * Array of globals dependent on the environment.
5448 *
5449 * @return {Array}
5450 * @api private
5451 */
5452 function extraGlobals () {
5453 if (typeof process === 'object' && typeof process.version === 'string') {
5454 var parts = process.version.split('.');
5455 var nodeVersion = utils.reduce(parts, function (a, v) {
5456 return a << 8 | v;
5457 });
5458
5459 // 'errno' was renamed to process._errno in v0.9.11.
5460
5461 if (nodeVersion < 0x00090B) {
5462 return ['errno'];
5463 }
5464 }
5465
5466 return [];
5467 }
5468
5469 }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5470 },{"./pending":16,"./runnable":33,"./utils":38,"_process":82,"debug":2,"events": 3}],35:[function(require,module,exports){
5471 'use strict';
5472
5473 /**
5474 * Module dependencies.
5475 */
5476
5477 var EventEmitter = require('events').EventEmitter;
5478 var Hook = require('./hook');
5479 var utils = require('./utils');
5480 var inherits = utils.inherits;
5481 var debug = require('debug')('mocha:suite');
5482 var milliseconds = require('./ms');
5483
5484 /**
5485 * Expose `Suite`.
5486 */
5487
5488 exports = module.exports = Suite;
5489
5490 /**
5491 * Create a new `Suite` with the given `title` and parent `Suite`. When a suite
5492 * with the same title is already present, that suite is returned to provide
5493 * nicer reporter and more flexible meta-testing.
5494 *
5495 * @api public
5496 * @param {Suite} parent
5497 * @param {string} title
5498 * @return {Suite}
5499 */
5500 exports.create = function (parent, title) {
5501 var suite = new Suite(title, parent.ctx);
5502 suite.parent = parent;
5503 title = suite.fullTitle();
5504 parent.addSuite(suite);
5505 return suite;
5506 };
5507
5508 /**
5509 * Initialize a new `Suite` with the given `title` and `ctx`.
5510 *
5511 * @api private
5512 * @param {string} title
5513 * @param {Context} parentContext
5514 */
5515 function Suite (title, parentContext) {
5516 if (!utils.isString(title)) {
5517 throw new Error('Suite `title` should be a "string" but "' + typeof title + '" was given instead.');
5518 }
5519 this.title = title;
5520 function Context () {}
5521 Context.prototype = parentContext;
5522 this.ctx = new Context();
5523 this.suites = [];
5524 this.tests = [];
5525 this.pending = false;
5526 this._beforeEach = [];
5527 this._beforeAll = [];
5528 this._afterEach = [];
5529 this._afterAll = [];
5530 this.root = !title;
5531 this._timeout = 2000;
5532 this._enableTimeouts = true;
5533 this._slow = 75;
5534 this._bail = false;
5535 this._retries = -1;
5536 this._onlyTests = [];
5537 this._onlySuites = [];
5538 this.delayed = false;
5539 }
5540
5541 /**
5542 * Inherit from `EventEmitter.prototype`.
5543 */
5544 inherits(Suite, EventEmitter);
5545
5546 /**
5547 * Return a clone of this `Suite`.
5548 *
5549 * @api private
5550 * @return {Suite}
5551 */
5552 Suite.prototype.clone = function () {
5553 var suite = new Suite(this.title);
5554 debug('clone');
5555 suite.ctx = this.ctx;
5556 suite.timeout(this.timeout());
5557 suite.retries(this.retries());
5558 suite.enableTimeouts(this.enableTimeouts());
5559 suite.slow(this.slow());
5560 suite.bail(this.bail());
5561 return suite;
5562 };
5563
5564 /**
5565 * Set timeout `ms` or short-hand such as "2s".
5566 *
5567 * @api private
5568 * @param {number|string} ms
5569 * @return {Suite|number} for chaining
5570 */
5571 Suite.prototype.timeout = function (ms) {
5572 if (!arguments.length) {
5573 return this._timeout;
5574 }
5575 if (ms.toString() === '0') {
5576 this._enableTimeouts = false;
5577 }
5578 if (typeof ms === 'string') {
5579 ms = milliseconds(ms);
5580 }
5581 debug('timeout %d', ms);
5582 this._timeout = parseInt(ms, 10);
5583 return this;
5584 };
5585
5586 /**
5587 * Set number of times to retry a failed test.
5588 *
5589 * @api private
5590 * @param {number|string} n
5591 * @return {Suite|number} for chaining
5592 */
5593 Suite.prototype.retries = function (n) {
5594 if (!arguments.length) {
5595 return this._retries;
5596 }
5597 debug('retries %d', n);
5598 this._retries = parseInt(n, 10) || 0;
5599 return this;
5600 };
5601
5602 /**
5603 * Set timeout to `enabled`.
5604 *
5605 * @api private
5606 * @param {boolean} enabled
5607 * @return {Suite|boolean} self or enabled
5608 */
5609 Suite.prototype.enableTimeouts = function (enabled) {
5610 if (!arguments.length) {
5611 return this._enableTimeouts;
5612 }
5613 debug('enableTimeouts %s', enabled);
5614 this._enableTimeouts = enabled;
5615 return this;
5616 };
5617
5618 /**
5619 * Set slow `ms` or short-hand such as "2s".
5620 *
5621 * @api private
5622 * @param {number|string} ms
5623 * @return {Suite|number} for chaining
5624 */
5625 Suite.prototype.slow = function (ms) {
5626 if (!arguments.length) {
5627 return this._slow;
5628 }
5629 if (typeof ms === 'string') {
5630 ms = milliseconds(ms);
5631 }
5632 debug('slow %d', ms);
5633 this._slow = ms;
5634 return this;
5635 };
5636
5637 /**
5638 * Sets whether to bail after first error.
5639 *
5640 * @api private
5641 * @param {boolean} bail
5642 * @return {Suite|number} for chaining
5643 */
5644 Suite.prototype.bail = function (bail) {
5645 if (!arguments.length) {
5646 return this._bail;
5647 }
5648 debug('bail %s', bail);
5649 this._bail = bail;
5650 return this;
5651 };
5652
5653 /**
5654 * Check if this suite or its parent suite is marked as pending.
5655 *
5656 * @api private
5657 */
5658 Suite.prototype.isPending = function () {
5659 return this.pending || (this.parent && this.parent.isPending());
5660 };
5661
5662 /**
5663 * Run `fn(test[, done])` before running tests.
5664 *
5665 * @api private
5666 * @param {string} title
5667 * @param {Function} fn
5668 * @return {Suite} for chaining
5669 */
5670 Suite.prototype.beforeAll = function (title, fn) {
5671 if (this.isPending()) {
5672 return this;
5673 }
5674 if (typeof title === 'function') {
5675 fn = title;
5676 title = fn.name;
5677 }
5678 title = '"before all" hook' + (title ? ': ' + title : '');
5679
5680 var hook = new Hook(title, fn);
5681 hook.parent = this;
5682 hook.timeout(this.timeout());
5683 hook.retries(this.retries());
5684 hook.enableTimeouts(this.enableTimeouts());
5685 hook.slow(this.slow());
5686 hook.ctx = this.ctx;
5687 this._beforeAll.push(hook);
5688 this.emit('beforeAll', hook);
5689 return this;
5690 };
5691
5692 /**
5693 * Run `fn(test[, done])` after running tests.
5694 *
5695 * @api private
5696 * @param {string} title
5697 * @param {Function} fn
5698 * @return {Suite} for chaining
5699 */
5700 Suite.prototype.afterAll = function (title, fn) {
5701 if (this.isPending()) {
5702 return this;
5703 }
5704 if (typeof title === 'function') {
5705 fn = title;
5706 title = fn.name;
5707 }
5708 title = '"after all" hook' + (title ? ': ' + title : '');
5709
5710 var hook = new Hook(title, fn);
5711 hook.parent = this;
5712 hook.timeout(this.timeout());
5713 hook.retries(this.retries());
5714 hook.enableTimeouts(this.enableTimeouts());
5715 hook.slow(this.slow());
5716 hook.ctx = this.ctx;
5717 this._afterAll.push(hook);
5718 this.emit('afterAll', hook);
5719 return this;
5720 };
5721
5722 /**
5723 * Run `fn(test[, done])` before each test case.
5724 *
5725 * @api private
5726 * @param {string} title
5727 * @param {Function} fn
5728 * @return {Suite} for chaining
5729 */
5730 Suite.prototype.beforeEach = function (title, fn) {
5731 if (this.isPending()) {
5732 return this;
5733 }
5734 if (typeof title === 'function') {
5735 fn = title;
5736 title = fn.name;
5737 }
5738 title = '"before each" hook' + (title ? ': ' + title : '');
5739
5740 var hook = new Hook(title, fn);
5741 hook.parent = this;
5742 hook.timeout(this.timeout());
5743 hook.retries(this.retries());
5744 hook.enableTimeouts(this.enableTimeouts());
5745 hook.slow(this.slow());
5746 hook.ctx = this.ctx;
5747 this._beforeEach.push(hook);
5748 this.emit('beforeEach', hook);
5749 return this;
5750 };
5751
5752 /**
5753 * Run `fn(test[, done])` after each test case.
5754 *
5755 * @api private
5756 * @param {string} title
5757 * @param {Function} fn
5758 * @return {Suite} for chaining
5759 */
5760 Suite.prototype.afterEach = function (title, fn) {
5761 if (this.isPending()) {
5762 return this;
5763 }
5764 if (typeof title === 'function') {
5765 fn = title;
5766 title = fn.name;
5767 }
5768 title = '"after each" hook' + (title ? ': ' + title : '');
5769
5770 var hook = new Hook(title, fn);
5771 hook.parent = this;
5772 hook.timeout(this.timeout());
5773 hook.retries(this.retries());
5774 hook.enableTimeouts(this.enableTimeouts());
5775 hook.slow(this.slow());
5776 hook.ctx = this.ctx;
5777 this._afterEach.push(hook);
5778 this.emit('afterEach', hook);
5779 return this;
5780 };
5781
5782 /**
5783 * Add a test `suite`.
5784 *
5785 * @api private
5786 * @param {Suite} suite
5787 * @return {Suite} for chaining
5788 */
5789 Suite.prototype.addSuite = function (suite) {
5790 suite.parent = this;
5791 suite.timeout(this.timeout());
5792 suite.retries(this.retries());
5793 suite.enableTimeouts(this.enableTimeouts());
5794 suite.slow(this.slow());
5795 suite.bail(this.bail());
5796 this.suites.push(suite);
5797 this.emit('suite', suite);
5798 return this;
5799 };
5800
5801 /**
5802 * Add a `test` to this suite.
5803 *
5804 * @api private
5805 * @param {Test} test
5806 * @return {Suite} for chaining
5807 */
5808 Suite.prototype.addTest = function (test) {
5809 test.parent = this;
5810 test.timeout(this.timeout());
5811 test.retries(this.retries());
5812 test.enableTimeouts(this.enableTimeouts());
5813 test.slow(this.slow());
5814 test.ctx = this.ctx;
5815 this.tests.push(test);
5816 this.emit('test', test);
5817 return this;
5818 };
5819
5820 /**
5821 * Return the full title generated by recursively concatenating the parent's
5822 * full title.
5823 *
5824 * @api public
5825 * @return {string}
5826 */
5827 Suite.prototype.fullTitle = function () {
5828 if (this.parent) {
5829 var full = this.parent.fullTitle();
5830 if (full) {
5831 return full + ' ' + this.title;
5832 }
5833 }
5834 return this.title;
5835 };
5836
5837 /**
5838 * Return the total number of tests.
5839 *
5840 * @api public
5841 * @return {number}
5842 */
5843 Suite.prototype.total = function () {
5844 return utils.reduce(this.suites, function (sum, suite) {
5845 return sum + suite.total();
5846 }, 0) + this.tests.length;
5847 };
5848
5849 /**
5850 * Iterates through each suite recursively to find all tests. Applies a
5851 * function in the format `fn(test)`.
5852 *
5853 * @api private
5854 * @param {Function} fn
5855 * @return {Suite}
5856 */
5857 Suite.prototype.eachTest = function (fn) {
5858 utils.forEach(this.tests, fn);
5859 utils.forEach(this.suites, function (suite) {
5860 suite.eachTest(fn);
5861 });
5862 return this;
5863 };
5864
5865 /**
5866 * This will run the root suite if we happen to be running in delayed mode.
5867 */
5868 Suite.prototype.run = function run () {
5869 if (this.root) {
5870 this.emit('run');
5871 }
5872 };
5873
5874 },{"./hook":7,"./ms":15,"./utils":38,"debug":2,"events":3}],36:[function(require ,module,exports){
5875 'use strict';
5876
5877 /**
5878 * Module dependencies.
5879 */
5880
5881 var Runnable = require('./runnable');
5882 var create = require('lodash.create');
5883 var isString = require('./utils').isString;
5884
5885 /**
5886 * Expose `Test`.
5887 */
5888
5889 module.exports = Test;
5890
5891 /**
5892 * Initialize a new `Test` with the given `title` and callback `fn`.
5893 *
5894 * @api private
5895 * @param {String} title
5896 * @param {Function} fn
5897 */
5898 function Test (title, fn) {
5899 if (!isString(title)) {
5900 throw new Error('Test `title` should be a "string" but "' + typeof title + ' " was given instead.');
5901 }
5902 Runnable.call(this, title, fn);
5903 this.pending = !fn;
5904 this.type = 'test';
5905 }
5906
5907 /**
5908 * Inherit from `Runnable.prototype`.
5909 */
5910 Test.prototype = create(Runnable.prototype, {
5911 constructor: Test
5912 });
5913
5914 Test.prototype.clone = function () {
5915 var test = new Test(this.title, this.fn);
5916 test.timeout(this.timeout());
5917 test.slow(this.slow());
5918 test.enableTimeouts(this.enableTimeouts());
5919 test.retries(this.retries());
5920 test.currentRetry(this.currentRetry());
5921 test.globals(this.globals());
5922 test.parent = this.parent;
5923 test.file = this.file;
5924 test.ctx = this.ctx;
5925 return test;
5926 };
5927
5928 },{"./runnable":33,"./utils":38,"lodash.create":75}],37:[function(require,module ,exports){
5929 'use strict';
5930
5931 /**
5932 * Pad a `number` with a ten's place zero.
5933 *
5934 * @param {number} number
5935 * @return {string}
5936 */
5937 function pad(number) {
5938 var n = number.toString();
5939 return n.length === 1 ? '0' + n : n;
5940 }
5941
5942 /**
5943 * Turn a `date` into an ISO string.
5944 *
5945 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Obje cts/Date/toISOString
5946 *
5947 * @param {Date} date
5948 * @return {string}
5949 */
5950 function toISOString(date) {
5951 return date.getUTCFullYear()
5952 + '-' + pad(date.getUTCMonth() + 1)
5953 + '-' + pad(date.getUTCDate())
5954 + 'T' + pad(date.getUTCHours())
5955 + ':' + pad(date.getUTCMinutes())
5956 + ':' + pad(date.getUTCSeconds())
5957 + '.' + String((date.getUTCMilliseconds()/1000).toFixed(3)).slice(2, 5)
5958 + 'Z';
5959 }
5960
5961 /*
5962 * Exports.
5963 */
5964
5965 module.exports = toISOString;
5966
5967 },{}],38:[function(require,module,exports){
5968 (function (process,Buffer){
5969 'use strict';
5970
5971 /* eslint-env browser */
5972
5973 /**
5974 * Module dependencies.
5975 */
5976
5977 var JSON = require('json3');
5978 var basename = require('path').basename;
5979 var debug = require('debug')('mocha:watch');
5980 var exists = require('fs').existsSync || require('path').existsSync;
5981 var glob = require('glob');
5982 var path = require('path');
5983 var join = path.join;
5984 var readdirSync = require('fs').readdirSync;
5985 var statSync = require('fs').statSync;
5986 var watchFile = require('fs').watchFile;
5987 var lstatSync = require('fs').lstatSync;
5988 var toISOString = require('./to-iso-string');
5989
5990 /**
5991 * Ignored directories.
5992 */
5993
5994 var ignore = ['node_modules', '.git'];
5995
5996 exports.inherits = require('util').inherits;
5997
5998 /**
5999 * Escape special characters in the given string of html.
6000 *
6001 * @api private
6002 * @param {string} html
6003 * @return {string}
6004 */
6005 exports.escape = function (html) {
6006 return String(html)
6007 .replace(/&/g, '&amp;')
6008 .replace(/"/g, '&quot;')
6009 .replace(/</g, '&lt;')
6010 .replace(/>/g, '&gt;');
6011 };
6012
6013 /**
6014 * Array#forEach (<=IE8)
6015 *
6016 * @api private
6017 * @param {Array} arr
6018 * @param {Function} fn
6019 * @param {Object} scope
6020 */
6021 exports.forEach = function (arr, fn, scope) {
6022 for (var i = 0, l = arr.length; i < l; i++) {
6023 fn.call(scope, arr[i], i);
6024 }
6025 };
6026
6027 /**
6028 * Test if the given obj is type of string.
6029 *
6030 * @api private
6031 * @param {Object} obj
6032 * @return {boolean}
6033 */
6034 exports.isString = function (obj) {
6035 return typeof obj === 'string';
6036 };
6037
6038 /**
6039 * Array#map (<=IE8)
6040 *
6041 * @api private
6042 * @param {Array} arr
6043 * @param {Function} fn
6044 * @param {Object} scope
6045 * @return {Array}
6046 */
6047 exports.map = function (arr, fn, scope) {
6048 var result = [];
6049 for (var i = 0, l = arr.length; i < l; i++) {
6050 result.push(fn.call(scope, arr[i], i, arr));
6051 }
6052 return result;
6053 };
6054
6055 /**
6056 * Array#indexOf (<=IE8)
6057 *
6058 * @api private
6059 * @param {Array} arr
6060 * @param {Object} obj to find index of
6061 * @param {number} start
6062 * @return {number}
6063 */
6064 var indexOf = exports.indexOf = function (arr, obj, start) {
6065 for (var i = start || 0, l = arr.length; i < l; i++) {
6066 if (arr[i] === obj) {
6067 return i;
6068 }
6069 }
6070 return -1;
6071 };
6072
6073 /**
6074 * Array#reduce (<=IE8)
6075 *
6076 * @api private
6077 * @param {Array} arr
6078 * @param {Function} fn
6079 * @param {Object} val Initial value.
6080 * @return {*}
6081 */
6082 var reduce = exports.reduce = function (arr, fn, val) {
6083 var rval = val;
6084
6085 for (var i = 0, l = arr.length; i < l; i++) {
6086 rval = fn(rval, arr[i], i, arr);
6087 }
6088
6089 return rval;
6090 };
6091
6092 /**
6093 * Array#filter (<=IE8)
6094 *
6095 * @api private
6096 * @param {Array} arr
6097 * @param {Function} fn
6098 * @return {Array}
6099 */
6100 exports.filter = function (arr, fn) {
6101 var ret = [];
6102
6103 for (var i = 0, l = arr.length; i < l; i++) {
6104 var val = arr[i];
6105 if (fn(val, i, arr)) {
6106 ret.push(val);
6107 }
6108 }
6109
6110 return ret;
6111 };
6112
6113 /**
6114 * Array#some (<=IE8)
6115 *
6116 * @api private
6117 * @param {Array} arr
6118 * @param {Function} fn
6119 * @return {Array}
6120 */
6121 exports.some = function (arr, fn) {
6122 for (var i = 0, l = arr.length; i < l; i++) {
6123 if (fn(arr[i])) {
6124 return true;
6125 }
6126 }
6127 return false;
6128 };
6129
6130 /**
6131 * Object.keys (<=IE8)
6132 *
6133 * @api private
6134 * @param {Object} obj
6135 * @return {Array} keys
6136 */
6137 exports.keys = typeof Object.keys === 'function' ? Object.keys : function (obj) {
6138 var keys = [];
6139 var has = Object.prototype.hasOwnProperty; // for `window` on <=IE8
6140
6141 for (var key in obj) {
6142 if (has.call(obj, key)) {
6143 keys.push(key);
6144 }
6145 }
6146
6147 return keys;
6148 };
6149
6150 /**
6151 * Watch the given `files` for changes
6152 * and invoke `fn(file)` on modification.
6153 *
6154 * @api private
6155 * @param {Array} files
6156 * @param {Function} fn
6157 */
6158 exports.watch = function (files, fn) {
6159 var options = { interval: 100 };
6160 files.forEach(function (file) {
6161 debug('file %s', file);
6162 watchFile(file, options, function (curr, prev) {
6163 if (prev.mtime < curr.mtime) {
6164 fn(file);
6165 }
6166 });
6167 });
6168 };
6169
6170 /**
6171 * Array.isArray (<=IE8)
6172 *
6173 * @api private
6174 * @param {Object} obj
6175 * @return {Boolean}
6176 */
6177 var isArray = typeof Array.isArray === 'function' ? Array.isArray : function (ob j) {
6178 return Object.prototype.toString.call(obj) === '[object Array]';
6179 };
6180
6181 exports.isArray = isArray;
6182
6183 /**
6184 * Buffer.prototype.toJSON polyfill.
6185 *
6186 * @type {Function}
6187 */
6188 if (typeof Buffer !== 'undefined' && Buffer.prototype) {
6189 Buffer.prototype.toJSON = Buffer.prototype.toJSON || function () {
6190 return Array.prototype.slice.call(this, 0);
6191 };
6192 }
6193
6194 /**
6195 * Ignored files.
6196 *
6197 * @api private
6198 * @param {string} path
6199 * @return {boolean}
6200 */
6201 function ignored (path) {
6202 return !~ignore.indexOf(path);
6203 }
6204
6205 /**
6206 * Lookup files in the given `dir`.
6207 *
6208 * @api private
6209 * @param {string} dir
6210 * @param {string[]} [ext=['.js']]
6211 * @param {Array} [ret=[]]
6212 * @return {Array}
6213 */
6214 exports.files = function (dir, ext, ret) {
6215 ret = ret || [];
6216 ext = ext || ['js'];
6217
6218 var re = new RegExp('\\.(' + ext.join('|') + ')$');
6219
6220 readdirSync(dir)
6221 .filter(ignored)
6222 .forEach(function (path) {
6223 path = join(dir, path);
6224 if (lstatSync(path).isDirectory()) {
6225 exports.files(path, ext, ret);
6226 } else if (path.match(re)) {
6227 ret.push(path);
6228 }
6229 });
6230
6231 return ret;
6232 };
6233
6234 /**
6235 * Compute a slug from the given `str`.
6236 *
6237 * @api private
6238 * @param {string} str
6239 * @return {string}
6240 */
6241 exports.slug = function (str) {
6242 return str
6243 .toLowerCase()
6244 .replace(/ +/g, '-')
6245 .replace(/[^-\w]/g, '');
6246 };
6247
6248 /**
6249 * Strip the function definition from `str`, and re-indent for pre whitespace.
6250 *
6251 * @param {string} str
6252 * @return {string}
6253 */
6254 exports.clean = function (str) {
6255 str = str
6256 .replace(/\r\n?|[\n\u2028\u2029]/g, '\n').replace(/^\uFEFF/, '')
6257 // (traditional)-> space/name parameters body (lambda)-> paramet ers body multi-statement/single keep body content
6258 .replace(/^function(?:\s*|\s+[^(]*)\([^)]*\)\s*\{((?:.|\n)*?)\s*\}$|^\([^)]* \)\s*=>\s*(?:\{((?:.|\n)*?)\s*\}|((?:.|\n)*))$/, '$1$2$3');
6259
6260 var spaces = str.match(/^\n?( *)/)[1].length;
6261 var tabs = str.match(/^\n?(\t*)/)[1].length;
6262 var re = new RegExp('^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs || spaces) + '} ', 'gm');
6263
6264 str = str.replace(re, '');
6265
6266 return exports.trim(str);
6267 };
6268
6269 /**
6270 * Trim the given `str`.
6271 *
6272 * @api private
6273 * @param {string} str
6274 * @return {string}
6275 */
6276 exports.trim = function (str) {
6277 return str.replace(/^\s+|\s+$/g, '');
6278 };
6279
6280 /**
6281 * Parse the given `qs`.
6282 *
6283 * @api private
6284 * @param {string} qs
6285 * @return {Object}
6286 */
6287 exports.parseQuery = function (qs) {
6288 return reduce(qs.replace('?', '').split('&'), function (obj, pair) {
6289 var i = pair.indexOf('=');
6290 var key = pair.slice(0, i);
6291 var val = pair.slice(++i);
6292
6293 // Due to how the URLSearchParams API treats spaces
6294 obj[key] = decodeURIComponent(val.replace(/\+/g, '%20'));
6295
6296 return obj;
6297 }, {});
6298 };
6299
6300 /**
6301 * Highlight the given string of `js`.
6302 *
6303 * @api private
6304 * @param {string} js
6305 * @return {string}
6306 */
6307 function highlight (js) {
6308 return js
6309 .replace(/</g, '&lt;')
6310 .replace(/>/g, '&gt;')
6311 .replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>')
6312 .replace(/('.*?')/gm, '<span class="string">$1</span>')
6313 .replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>')
6314 .replace(/(\d+)/gm, '<span class="number">$1</span>')
6315 .replace(/\bnew[ \t]+(\w+)/gm, '<span class="keyword">new</span> <span class ="init">$1</span>')
6316 .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyw ord">$1</span>');
6317 }
6318
6319 /**
6320 * Highlight the contents of tag `name`.
6321 *
6322 * @api private
6323 * @param {string} name
6324 */
6325 exports.highlightTags = function (name) {
6326 var code = document.getElementById('mocha').getElementsByTagName(name);
6327 for (var i = 0, len = code.length; i < len; ++i) {
6328 code[i].innerHTML = highlight(code[i].innerHTML);
6329 }
6330 };
6331
6332 /**
6333 * If a value could have properties, and has none, this function is called,
6334 * which returns a string representation of the empty value.
6335 *
6336 * Functions w/ no properties return `'[Function]'`
6337 * Arrays w/ length === 0 return `'[]'`
6338 * Objects w/ no properties return `'{}'`
6339 * All else: return result of `value.toString()`
6340 *
6341 * @api private
6342 * @param {*} value The value to inspect.
6343 * @param {string} typeHint The type of the value
6344 * @returns {string}
6345 */
6346 function emptyRepresentation (value, typeHint) {
6347 switch (typeHint) {
6348 case 'function':
6349 return '[Function]';
6350 case 'object':
6351 return '{}';
6352 case 'array':
6353 return '[]';
6354 default:
6355 return value.toString();
6356 }
6357 }
6358
6359 /**
6360 * Takes some variable and asks `Object.prototype.toString()` what it thinks it
6361 * is.
6362 *
6363 * @api private
6364 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global _Objects/Object/toString
6365 * @param {*} value The value to test.
6366 * @returns {string} Computed type
6367 * @example
6368 * type({}) // 'object'
6369 * type([]) // 'array'
6370 * type(1) // 'number'
6371 * type(false) // 'boolean'
6372 * type(Infinity) // 'number'
6373 * type(null) // 'null'
6374 * type(new Date()) // 'date'
6375 * type(/foo/) // 'regexp'
6376 * type('type') // 'string'
6377 * type(global) // 'global'
6378 * type(new String('foo') // 'object'
6379 */
6380 var type = exports.type = function type (value) {
6381 if (value === undefined) {
6382 return 'undefined';
6383 } else if (value === null) {
6384 return 'null';
6385 } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {
6386 return 'buffer';
6387 }
6388 return Object.prototype.toString.call(value)
6389 .replace(/^\[.+\s(.+?)]$/, '$1')
6390 .toLowerCase();
6391 };
6392
6393 /**
6394 * Stringify `value`. Different behavior depending on type of value:
6395 *
6396 * - If `value` is undefined or null, return `'[undefined]'` or `'[null]'`, resp ectively.
6397 * - If `value` is not an object, function or array, return result of `value.toS tring()` wrapped in double-quotes.
6398 * - If `value` is an *empty* object, function, or array, return result of funct ion
6399 * {@link emptyRepresentation}.
6400 * - If `value` has properties, call {@link exports.canonicalize} on it, then re turn result of
6401 * JSON.stringify().
6402 *
6403 * @api private
6404 * @see exports.type
6405 * @param {*} value
6406 * @return {string}
6407 */
6408 exports.stringify = function (value) {
6409 var typeHint = type(value);
6410
6411 if (!~indexOf(['object', 'array', 'function'], typeHint)) {
6412 if (typeHint === 'buffer') {
6413 var json = value.toJSON();
6414 // Based on the toJSON result
6415 return jsonStringify(json.data && json.type ? json.data : json, 2)
6416 .replace(/,(\n|$)/g, '$1');
6417 }
6418
6419 // IE7/IE8 has a bizarre String constructor; needs to be coerced
6420 // into an array and back to obj.
6421 if (typeHint === 'string' && typeof value === 'object') {
6422 value = reduce(value.split(''), function (acc, char, idx) {
6423 acc[idx] = char;
6424 return acc;
6425 }, {});
6426 typeHint = 'object';
6427 } else {
6428 return jsonStringify(value);
6429 }
6430 }
6431
6432 for (var prop in value) {
6433 if (Object.prototype.hasOwnProperty.call(value, prop)) {
6434 return jsonStringify(exports.canonicalize(value, null, typeHint), 2).repla ce(/,(\n|$)/g, '$1');
6435 }
6436 }
6437
6438 return emptyRepresentation(value, typeHint);
6439 };
6440
6441 /**
6442 * like JSON.stringify but more sense.
6443 *
6444 * @api private
6445 * @param {Object} object
6446 * @param {number=} spaces
6447 * @param {number=} depth
6448 * @returns {*}
6449 */
6450 function jsonStringify (object, spaces, depth) {
6451 if (typeof spaces === 'undefined') {
6452 // primitive types
6453 return _stringify(object);
6454 }
6455
6456 depth = depth || 1;
6457 var space = spaces * depth;
6458 var str = isArray(object) ? '[' : '{';
6459 var end = isArray(object) ? ']' : '}';
6460 var length = typeof object.length === 'number' ? object.length : exports.keys( object).length;
6461 // `.repeat()` polyfill
6462 function repeat (s, n) {
6463 return new Array(n).join(s);
6464 }
6465
6466 function _stringify (val) {
6467 switch (type(val)) {
6468 case 'null':
6469 case 'undefined':
6470 val = '[' + val + ']';
6471 break;
6472 case 'array':
6473 case 'object':
6474 val = jsonStringify(val, spaces, depth + 1);
6475 break;
6476 case 'boolean':
6477 case 'regexp':
6478 case 'symbol':
6479 case 'number':
6480 val = val === 0 && (1 / val) === -Infinity // `-0`
6481 ? '-0'
6482 : val.toString();
6483 break;
6484 case 'date':
6485 var sDate;
6486 if (isNaN(val.getTime())) { // Invalid date
6487 sDate = val.toString();
6488 } else {
6489 sDate = val.toISOString ? val.toISOString() : toISOString(val);
6490 }
6491 val = '[Date: ' + sDate + ']';
6492 break;
6493 case 'buffer':
6494 var json = val.toJSON();
6495 // Based on the toJSON result
6496 json = json.data && json.type ? json.data : json;
6497 val = '[Buffer: ' + jsonStringify(json, 2, depth + 1) + ']';
6498 break;
6499 default:
6500 val = (val === '[Function]' || val === '[Circular]')
6501 ? val
6502 : JSON.stringify(val); // string
6503 }
6504 return val;
6505 }
6506
6507 for (var i in object) {
6508 if (!Object.prototype.hasOwnProperty.call(object, i)) {
6509 continue; // not my business
6510 }
6511 --length;
6512 str += '\n ' + repeat(' ', space) +
6513 (isArray(object) ? '' : '"' + i + '": ') + // key
6514 _stringify(object[i]) + // value
6515 (length ? ',' : ''); // comma
6516 }
6517
6518 return str +
6519 // [], {}
6520 (str.length !== 1 ? '\n' + repeat(' ', --space) + end : end);
6521 }
6522
6523 /**
6524 * Test if a value is a buffer.
6525 *
6526 * @api private
6527 * @param {*} value The value to test.
6528 * @return {boolean} True if `value` is a buffer, otherwise false
6529 */
6530 exports.isBuffer = function (value) {
6531 return typeof Buffer !== 'undefined' && Buffer.isBuffer(value);
6532 };
6533
6534 /**
6535 * Return a new Thing that has the keys in sorted order. Recursive.
6536 *
6537 * If the Thing...
6538 * - has already been seen, return string `'[Circular]'`
6539 * - is `undefined`, return string `'[undefined]'`
6540 * - is `null`, return value `null`
6541 * - is some other primitive, return the value
6542 * - is not a primitive or an `Array`, `Object`, or `Function`, return the value of the Thing's `toString()` method
6543 * - is a non-empty `Array`, `Object`, or `Function`, return the result of calli ng this function again.
6544 * - is an empty `Array`, `Object`, or `Function`, return the result of calling `emptyRepresentation()`
6545 *
6546 * @api private
6547 * @see {@link exports.stringify}
6548 * @param {*} value Thing to inspect. May or may not have properties.
6549 * @param {Array} [stack=[]] Stack of seen values
6550 * @param {string} [typeHint] Type hint
6551 * @return {(Object|Array|Function|string|undefined)}
6552 */
6553 exports.canonicalize = function canonicalize (value, stack, typeHint) {
6554 var canonicalizedObj;
6555 /* eslint-disable no-unused-vars */
6556 var prop;
6557 /* eslint-enable no-unused-vars */
6558 typeHint = typeHint || type(value);
6559 function withStack (value, fn) {
6560 stack.push(value);
6561 fn();
6562 stack.pop();
6563 }
6564
6565 stack = stack || [];
6566
6567 if (indexOf(stack, value) !== -1) {
6568 return '[Circular]';
6569 }
6570
6571 switch (typeHint) {
6572 case 'undefined':
6573 case 'buffer':
6574 case 'null':
6575 canonicalizedObj = value;
6576 break;
6577 case 'array':
6578 withStack(value, function () {
6579 canonicalizedObj = exports.map(value, function (item) {
6580 return exports.canonicalize(item, stack);
6581 });
6582 });
6583 break;
6584 case 'function':
6585 /* eslint-disable guard-for-in */
6586 for (prop in value) {
6587 canonicalizedObj = {};
6588 break;
6589 }
6590 /* eslint-enable guard-for-in */
6591 if (!canonicalizedObj) {
6592 canonicalizedObj = emptyRepresentation(value, typeHint);
6593 break;
6594 }
6595 /* falls through */
6596 case 'object':
6597 canonicalizedObj = canonicalizedObj || {};
6598 withStack(value, function () {
6599 exports.forEach(exports.keys(value).sort(), function (key) {
6600 canonicalizedObj[key] = exports.canonicalize(value[key], stack);
6601 });
6602 });
6603 break;
6604 case 'date':
6605 case 'number':
6606 case 'regexp':
6607 case 'boolean':
6608 case 'symbol':
6609 canonicalizedObj = value;
6610 break;
6611 default:
6612 canonicalizedObj = value + '';
6613 }
6614
6615 return canonicalizedObj;
6616 };
6617
6618 /**
6619 * Lookup file names at the given `path`.
6620 *
6621 * @api public
6622 * @param {string} path Base path to start searching from.
6623 * @param {string[]} extensions File extensions to look for.
6624 * @param {boolean} recursive Whether or not to recurse into subdirectories.
6625 * @return {string[]} An array of paths.
6626 */
6627 exports.lookupFiles = function lookupFiles (path, extensions, recursive) {
6628 var files = [];
6629 var re = new RegExp('\\.(' + extensions.join('|') + ')$');
6630
6631 if (!exists(path)) {
6632 if (exists(path + '.js')) {
6633 path += '.js';
6634 } else {
6635 files = glob.sync(path);
6636 if (!files.length) {
6637 throw new Error("cannot resolve path (or pattern) '" + path + "'");
6638 }
6639 return files;
6640 }
6641 }
6642
6643 try {
6644 var stat = statSync(path);
6645 if (stat.isFile()) {
6646 return path;
6647 }
6648 } catch (err) {
6649 // ignore error
6650 return;
6651 }
6652
6653 readdirSync(path).forEach(function (file) {
6654 file = join(path, file);
6655 try {
6656 var stat = statSync(file);
6657 if (stat.isDirectory()) {
6658 if (recursive) {
6659 files = files.concat(lookupFiles(file, extensions, recursive));
6660 }
6661 return;
6662 }
6663 } catch (err) {
6664 // ignore error
6665 return;
6666 }
6667 if (!stat.isFile() || !re.test(file) || basename(file)[0] === '.') {
6668 return;
6669 }
6670 files.push(file);
6671 });
6672
6673 return files;
6674 };
6675
6676 /**
6677 * Generate an undefined error with a message warning the user.
6678 *
6679 * @return {Error}
6680 */
6681
6682 exports.undefinedError = function () {
6683 return new Error('Caught undefined error, did you throw without specifying wha t?');
6684 };
6685
6686 /**
6687 * Generate an undefined error if `err` is not defined.
6688 *
6689 * @param {Error} err
6690 * @return {Error}
6691 */
6692
6693 exports.getError = function (err) {
6694 return err || exports.undefinedError();
6695 };
6696
6697 /**
6698 * @summary
6699 * This Filter based on `mocha-clean` module.(see: `github.com/rstacruz/mocha-cl ean`)
6700 * @description
6701 * When invoking this function you get a filter function that get the Error.stac k as an input,
6702 * and return a prettify output.
6703 * (i.e: strip Mocha and internal node functions from stack trace).
6704 * @returns {Function}
6705 */
6706 exports.stackTraceFilter = function () {
6707 // TODO: Replace with `process.browser`
6708 var is = typeof document === 'undefined' ? { node: true } : { browser: true };
6709 var slash = path.sep;
6710 var cwd;
6711 if (is.node) {
6712 cwd = process.cwd() + slash;
6713 } else {
6714 cwd = (typeof location === 'undefined'
6715 ? window.location
6716 : location).href.replace(/\/[^/]*$/, '/');
6717 slash = '/';
6718 }
6719
6720 function isMochaInternal (line) {
6721 return (~line.indexOf('node_modules' + slash + 'mocha' + slash)) ||
6722 (~line.indexOf('node_modules' + slash + 'mocha.js')) ||
6723 (~line.indexOf('bower_components' + slash + 'mocha.js')) ||
6724 (~line.indexOf(slash + 'mocha.js'));
6725 }
6726
6727 function isNodeInternal (line) {
6728 return (~line.indexOf('(timers.js:')) ||
6729 (~line.indexOf('(events.js:')) ||
6730 (~line.indexOf('(node.js:')) ||
6731 (~line.indexOf('(module.js:')) ||
6732 (~line.indexOf('GeneratorFunctionPrototype.next (native)')) ||
6733 false;
6734 }
6735
6736 return function (stack) {
6737 stack = stack.split('\n');
6738
6739 stack = reduce(stack, function (list, line) {
6740 if (isMochaInternal(line)) {
6741 return list;
6742 }
6743
6744 if (is.node && isNodeInternal(line)) {
6745 return list;
6746 }
6747
6748 // Clean up cwd(absolute)
6749 if (/\(?.+:\d+:\d+\)?$/.test(line)) {
6750 line = line.replace(cwd, '');
6751 }
6752
6753 list.push(line);
6754 return list;
6755 }, []);
6756
6757 return stack.join('\n');
6758 };
6759 };
6760
6761 /**
6762 * Crude, but effective.
6763 * @api
6764 * @param {*} value
6765 * @returns {boolean} Whether or not `value` is a Promise
6766 */
6767 exports.isPromise = function isPromise (value) {
6768 return typeof value === 'object' && typeof value.then === 'function';
6769 };
6770
6771 /**
6772 * It's a noop.
6773 * @api
6774 */
6775 exports.noop = function () {};
6776
6777 }).call(this,require('_process'),require("buffer").Buffer)
6778 },{"./to-iso-string":37,"_process":82,"buffer":44,"debug":2,"fs":42,"glob":42,"j son3":69,"path":42,"util":99}],39:[function(require,module,exports){
6779 'use strict'
6780
6781 exports.byteLength = byteLength
6782 exports.toByteArray = toByteArray
6783 exports.fromByteArray = fromByteArray
6784
6785 var lookup = []
6786 var revLookup = []
6787 var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
6788
6789 var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
6790 for (var i = 0, len = code.length; i < len; ++i) {
6791 lookup[i] = code[i]
6792 revLookup[code.charCodeAt(i)] = i
6793 }
6794
6795 revLookup['-'.charCodeAt(0)] = 62
6796 revLookup['_'.charCodeAt(0)] = 63
6797
6798 function placeHoldersCount (b64) {
6799 var len = b64.length
6800 if (len % 4 > 0) {
6801 throw new Error('Invalid string. Length must be a multiple of 4')
6802 }
6803
6804 // the number of equal signs (place holders)
6805 // if there are two placeholders, than the two characters before it
6806 // represent one byte
6807 // if there is only one, then the three characters before it represent 2 bytes
6808 // this is just a cheap hack to not do indexOf twice
6809 return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
6810 }
6811
6812 function byteLength (b64) {
6813 // base64 is 4/3 + up to two characters of the original data
6814 return b64.length * 3 / 4 - placeHoldersCount(b64)
6815 }
6816
6817 function toByteArray (b64) {
6818 var i, j, l, tmp, placeHolders, arr
6819 var len = b64.length
6820 placeHolders = placeHoldersCount(b64)
6821
6822 arr = new Arr(len * 3 / 4 - placeHolders)
6823
6824 // if there are placeholders, only get up to the last complete 4 chars
6825 l = placeHolders > 0 ? len - 4 : len
6826
6827 var L = 0
6828
6829 for (i = 0, j = 0; i < l; i += 4, j += 3) {
6830 tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1 )] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
6831 arr[L++] = (tmp >> 16) & 0xFF
6832 arr[L++] = (tmp >> 8) & 0xFF
6833 arr[L++] = tmp & 0xFF
6834 }
6835
6836 if (placeHolders === 2) {
6837 tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1) ] >> 4)
6838 arr[L++] = tmp & 0xFF
6839 } else if (placeHolders === 1) {
6840 tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1 )] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
6841 arr[L++] = (tmp >> 8) & 0xFF
6842 arr[L++] = tmp & 0xFF
6843 }
6844
6845 return arr
6846 }
6847
6848 function tripletToBase64 (num) {
6849 return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
6850 }
6851
6852 function encodeChunk (uint8, start, end) {
6853 var tmp
6854 var output = []
6855 for (var i = start; i < end; i += 3) {
6856 tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
6857 output.push(tripletToBase64(tmp))
6858 }
6859 return output.join('')
6860 }
6861
6862 function fromByteArray (uint8) {
6863 var tmp
6864 var len = uint8.length
6865 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
6866 var output = ''
6867 var parts = []
6868 var maxChunkLength = 16383 // must be multiple of 3
6869
6870 // go through the array every three bytes, we'll deal with trailing stuff late r
6871 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
6872 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + m axChunkLength)))
6873 }
6874
6875 // pad the end with zeros, but make sure to not forget the extra bytes
6876 if (extraBytes === 1) {
6877 tmp = uint8[len - 1]
6878 output += lookup[tmp >> 2]
6879 output += lookup[(tmp << 4) & 0x3F]
6880 output += '=='
6881 } else if (extraBytes === 2) {
6882 tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
6883 output += lookup[tmp >> 10]
6884 output += lookup[(tmp >> 4) & 0x3F]
6885 output += lookup[(tmp << 2) & 0x3F]
6886 output += '='
6887 }
6888
6889 parts.push(output)
6890
6891 return parts.join('')
6892 }
6893
6894 },{}],40:[function(require,module,exports){
6895
6896 },{}],41:[function(require,module,exports){
6897 (function (process){
6898 var WritableStream = require('stream').Writable
6899 var inherits = require('util').inherits
6900
6901 module.exports = BrowserStdout
6902
6903
6904 inherits(BrowserStdout, WritableStream)
6905
6906 function BrowserStdout(opts) {
6907 if (!(this instanceof BrowserStdout)) return new BrowserStdout(opts)
6908
6909 opts = opts || {}
6910 WritableStream.call(this, opts)
6911 this.label = (opts.label !== undefined) ? opts.label : 'stdout'
6912 }
6913
6914 BrowserStdout.prototype._write = function(chunks, encoding, cb) {
6915 var output = chunks.toString ? chunks.toString() : chunks
6916 if (this.label === false) {
6917 console.log(output)
6918 } else {
6919 console.log(this.label+':', output)
6920 }
6921 process.nextTick(cb)
6922 }
6923
6924 }).call(this,require('_process'))
6925 },{"_process":82,"stream":94,"util":99}],42:[function(require,module,exports){
6926 arguments[4][40][0].apply(exports,arguments)
6927 },{"dup":40}],43:[function(require,module,exports){
6928 (function (global){
6929 'use strict';
6930
6931 var buffer = require('buffer');
6932 var Buffer = buffer.Buffer;
6933 var SlowBuffer = buffer.SlowBuffer;
6934 var MAX_LEN = buffer.kMaxLength || 2147483647;
6935 exports.alloc = function alloc(size, fill, encoding) {
6936 if (typeof Buffer.alloc === 'function') {
6937 return Buffer.alloc(size, fill, encoding);
6938 }
6939 if (typeof encoding === 'number') {
6940 throw new TypeError('encoding must not be number');
6941 }
6942 if (typeof size !== 'number') {
6943 throw new TypeError('size must be a number');
6944 }
6945 if (size > MAX_LEN) {
6946 throw new RangeError('size is too large');
6947 }
6948 var enc = encoding;
6949 var _fill = fill;
6950 if (_fill === undefined) {
6951 enc = undefined;
6952 _fill = 0;
6953 }
6954 var buf = new Buffer(size);
6955 if (typeof _fill === 'string') {
6956 var fillBuf = new Buffer(_fill, enc);
6957 var flen = fillBuf.length;
6958 var i = -1;
6959 while (++i < size) {
6960 buf[i] = fillBuf[i % flen];
6961 }
6962 } else {
6963 buf.fill(_fill);
6964 }
6965 return buf;
6966 }
6967 exports.allocUnsafe = function allocUnsafe(size) {
6968 if (typeof Buffer.allocUnsafe === 'function') {
6969 return Buffer.allocUnsafe(size);
6970 }
6971 if (typeof size !== 'number') {
6972 throw new TypeError('size must be a number');
6973 }
6974 if (size > MAX_LEN) {
6975 throw new RangeError('size is too large');
6976 }
6977 return new Buffer(size);
6978 }
6979 exports.from = function from(value, encodingOrOffset, length) {
6980 if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.fro m !== Buffer.from)) {
6981 return Buffer.from(value, encodingOrOffset, length);
6982 }
6983 if (typeof value === 'number') {
6984 throw new TypeError('"value" argument must not be a number');
6985 }
6986 if (typeof value === 'string') {
6987 return new Buffer(value, encodingOrOffset);
6988 }
6989 if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
6990 var offset = encodingOrOffset;
6991 if (arguments.length === 1) {
6992 return new Buffer(value);
6993 }
6994 if (typeof offset === 'undefined') {
6995 offset = 0;
6996 }
6997 var len = length;
6998 if (typeof len === 'undefined') {
6999 len = value.byteLength - offset;
7000 }
7001 if (offset >= value.byteLength) {
7002 throw new RangeError('\'offset\' is out of bounds');
7003 }
7004 if (len > value.byteLength - offset) {
7005 throw new RangeError('\'length\' is out of bounds');
7006 }
7007 return new Buffer(value.slice(offset, offset + len));
7008 }
7009 if (Buffer.isBuffer(value)) {
7010 var out = new Buffer(value.length);
7011 value.copy(out, 0, 0, value.length);
7012 return out;
7013 }
7014 if (value) {
7015 if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buf fer instanceof ArrayBuffer) || 'length' in value) {
7016 return new Buffer(value);
7017 }
7018 if (value.type === 'Buffer' && Array.isArray(value.data)) {
7019 return new Buffer(value.data);
7020 }
7021 }
7022
7023 throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer , Array, or array-like object.');
7024 }
7025 exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
7026 if (typeof Buffer.allocUnsafeSlow === 'function') {
7027 return Buffer.allocUnsafeSlow(size);
7028 }
7029 if (typeof size !== 'number') {
7030 throw new TypeError('size must be a number');
7031 }
7032 if (size >= MAX_LEN) {
7033 throw new RangeError('size is too large');
7034 }
7035 return new SlowBuffer(size);
7036 }
7037
7038 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined " ? self : typeof window !== "undefined" ? window : {})
7039 },{"buffer":44}],44:[function(require,module,exports){
7040 (function (global){
7041 /*!
7042 * The buffer module from node.js, for the browser.
7043 *
7044 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
7045 * @license MIT
7046 */
7047 /* eslint-disable no-proto */
7048
7049 'use strict'
7050
7051 var base64 = require('base64-js')
7052 var ieee754 = require('ieee754')
7053 var isArray = require('isarray')
7054
7055 exports.Buffer = Buffer
7056 exports.SlowBuffer = SlowBuffer
7057 exports.INSPECT_MAX_BYTES = 50
7058
7059 /**
7060 * If `Buffer.TYPED_ARRAY_SUPPORT`:
7061 * === true Use Uint8Array implementation (fastest)
7062 * === false Use Object implementation (most compatible, even IE6)
7063 *
7064 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
7065 * Opera 11.6+, iOS 4.2+.
7066 *
7067 * Due to various browser bugs, sometimes the Object implementation will be used even
7068 * when the browser supports typed arrays.
7069 *
7070 * Note:
7071 *
7072 * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` inst ances,
7073 * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
7074 *
7075 * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
7076 *
7077 * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
7078 * incorrect length in some situations.
7079
7080 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false ` so they
7081 * get the Object implementation, which is slower but behaves correctly.
7082 */
7083 Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
7084 ? global.TYPED_ARRAY_SUPPORT
7085 : typedArraySupport()
7086
7087 /*
7088 * Export kMaxLength after typed array support is determined.
7089 */
7090 exports.kMaxLength = kMaxLength()
7091
7092 function typedArraySupport () {
7093 try {
7094 var arr = new Uint8Array(1)
7095 arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
7096 return arr.foo() === 42 && // typed array instances can be augmented
7097 typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
7098 arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
7099 } catch (e) {
7100 return false
7101 }
7102 }
7103
7104 function kMaxLength () {
7105 return Buffer.TYPED_ARRAY_SUPPORT
7106 ? 0x7fffffff
7107 : 0x3fffffff
7108 }
7109
7110 function createBuffer (that, length) {
7111 if (kMaxLength() < length) {
7112 throw new RangeError('Invalid typed array length')
7113 }
7114 if (Buffer.TYPED_ARRAY_SUPPORT) {
7115 // Return an augmented `Uint8Array` instance, for best performance
7116 that = new Uint8Array(length)
7117 that.__proto__ = Buffer.prototype
7118 } else {
7119 // Fallback: Return an object instance of the Buffer class
7120 if (that === null) {
7121 that = new Buffer(length)
7122 }
7123 that.length = length
7124 }
7125
7126 return that
7127 }
7128
7129 /**
7130 * The Buffer constructor returns instances of `Uint8Array` that have their
7131 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
7132 * `Uint8Array`, so the returned instances will have all the node `Buffer` metho ds
7133 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
7134 * returns a single octet.
7135 *
7136 * The `Uint8Array` prototype remains unmodified.
7137 */
7138
7139 function Buffer (arg, encodingOrOffset, length) {
7140 if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
7141 return new Buffer(arg, encodingOrOffset, length)
7142 }
7143
7144 // Common case.
7145 if (typeof arg === 'number') {
7146 if (typeof encodingOrOffset === 'string') {
7147 throw new Error(
7148 'If encoding is specified then the first argument must be a string'
7149 )
7150 }
7151 return allocUnsafe(this, arg)
7152 }
7153 return from(this, arg, encodingOrOffset, length)
7154 }
7155
7156 Buffer.poolSize = 8192 // not used by this implementation
7157
7158 // TODO: Legacy, not needed anymore. Remove in next major version.
7159 Buffer._augment = function (arr) {
7160 arr.__proto__ = Buffer.prototype
7161 return arr
7162 }
7163
7164 function from (that, value, encodingOrOffset, length) {
7165 if (typeof value === 'number') {
7166 throw new TypeError('"value" argument must not be a number')
7167 }
7168
7169 if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
7170 return fromArrayBuffer(that, value, encodingOrOffset, length)
7171 }
7172
7173 if (typeof value === 'string') {
7174 return fromString(that, value, encodingOrOffset)
7175 }
7176
7177 return fromObject(that, value)
7178 }
7179
7180 /**
7181 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
7182 * if value is a number.
7183 * Buffer.from(str[, encoding])
7184 * Buffer.from(array)
7185 * Buffer.from(buffer)
7186 * Buffer.from(arrayBuffer[, byteOffset[, length]])
7187 **/
7188 Buffer.from = function (value, encodingOrOffset, length) {
7189 return from(null, value, encodingOrOffset, length)
7190 }
7191
7192 if (Buffer.TYPED_ARRAY_SUPPORT) {
7193 Buffer.prototype.__proto__ = Uint8Array.prototype
7194 Buffer.__proto__ = Uint8Array
7195 if (typeof Symbol !== 'undefined' && Symbol.species &&
7196 Buffer[Symbol.species] === Buffer) {
7197 // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
7198 Object.defineProperty(Buffer, Symbol.species, {
7199 value: null,
7200 configurable: true
7201 })
7202 }
7203 }
7204
7205 function assertSize (size) {
7206 if (typeof size !== 'number') {
7207 throw new TypeError('"size" argument must be a number')
7208 } else if (size < 0) {
7209 throw new RangeError('"size" argument must not be negative')
7210 }
7211 }
7212
7213 function alloc (that, size, fill, encoding) {
7214 assertSize(size)
7215 if (size <= 0) {
7216 return createBuffer(that, size)
7217 }
7218 if (fill !== undefined) {
7219 // Only pay attention to encoding if it's a string. This
7220 // prevents accidentally sending in a number that would
7221 // be interpretted as a start offset.
7222 return typeof encoding === 'string'
7223 ? createBuffer(that, size).fill(fill, encoding)
7224 : createBuffer(that, size).fill(fill)
7225 }
7226 return createBuffer(that, size)
7227 }
7228
7229 /**
7230 * Creates a new filled Buffer instance.
7231 * alloc(size[, fill[, encoding]])
7232 **/
7233 Buffer.alloc = function (size, fill, encoding) {
7234 return alloc(null, size, fill, encoding)
7235 }
7236
7237 function allocUnsafe (that, size) {
7238 assertSize(size)
7239 that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
7240 if (!Buffer.TYPED_ARRAY_SUPPORT) {
7241 for (var i = 0; i < size; ++i) {
7242 that[i] = 0
7243 }
7244 }
7245 return that
7246 }
7247
7248 /**
7249 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instan ce.
7250 * */
7251 Buffer.allocUnsafe = function (size) {
7252 return allocUnsafe(null, size)
7253 }
7254 /**
7255 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer in stance.
7256 */
7257 Buffer.allocUnsafeSlow = function (size) {
7258 return allocUnsafe(null, size)
7259 }
7260
7261 function fromString (that, string, encoding) {
7262 if (typeof encoding !== 'string' || encoding === '') {
7263 encoding = 'utf8'
7264 }
7265
7266 if (!Buffer.isEncoding(encoding)) {
7267 throw new TypeError('"encoding" must be a valid string encoding')
7268 }
7269
7270 var length = byteLength(string, encoding) | 0
7271 that = createBuffer(that, length)
7272
7273 var actual = that.write(string, encoding)
7274
7275 if (actual !== length) {
7276 // Writing a hex string, for example, that contains invalid characters will
7277 // cause everything after the first invalid character to be ignored. (e.g.
7278 // 'abxxcd' will be treated as 'ab')
7279 that = that.slice(0, actual)
7280 }
7281
7282 return that
7283 }
7284
7285 function fromArrayLike (that, array) {
7286 var length = array.length < 0 ? 0 : checked(array.length) | 0
7287 that = createBuffer(that, length)
7288 for (var i = 0; i < length; i += 1) {
7289 that[i] = array[i] & 255
7290 }
7291 return that
7292 }
7293
7294 function fromArrayBuffer (that, array, byteOffset, length) {
7295 array.byteLength // this throws if `array` is not a valid ArrayBuffer
7296
7297 if (byteOffset < 0 || array.byteLength < byteOffset) {
7298 throw new RangeError('\'offset\' is out of bounds')
7299 }
7300
7301 if (array.byteLength < byteOffset + (length || 0)) {
7302 throw new RangeError('\'length\' is out of bounds')
7303 }
7304
7305 if (byteOffset === undefined && length === undefined) {
7306 array = new Uint8Array(array)
7307 } else if (length === undefined) {
7308 array = new Uint8Array(array, byteOffset)
7309 } else {
7310 array = new Uint8Array(array, byteOffset, length)
7311 }
7312
7313 if (Buffer.TYPED_ARRAY_SUPPORT) {
7314 // Return an augmented `Uint8Array` instance, for best performance
7315 that = array
7316 that.__proto__ = Buffer.prototype
7317 } else {
7318 // Fallback: Return an object instance of the Buffer class
7319 that = fromArrayLike(that, array)
7320 }
7321 return that
7322 }
7323
7324 function fromObject (that, obj) {
7325 if (Buffer.isBuffer(obj)) {
7326 var len = checked(obj.length) | 0
7327 that = createBuffer(that, len)
7328
7329 if (that.length === 0) {
7330 return that
7331 }
7332
7333 obj.copy(that, 0, 0, len)
7334 return that
7335 }
7336
7337 if (obj) {
7338 if ((typeof ArrayBuffer !== 'undefined' &&
7339 obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
7340 if (typeof obj.length !== 'number' || isnan(obj.length)) {
7341 return createBuffer(that, 0)
7342 }
7343 return fromArrayLike(that, obj)
7344 }
7345
7346 if (obj.type === 'Buffer' && isArray(obj.data)) {
7347 return fromArrayLike(that, obj.data)
7348 }
7349 }
7350
7351 throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Arr ay, or array-like object.')
7352 }
7353
7354 function checked (length) {
7355 // Note: cannot use `length < kMaxLength()` here because that fails when
7356 // length is NaN (which is otherwise coerced to zero.)
7357 if (length >= kMaxLength()) {
7358 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
7359 'size: 0x' + kMaxLength().toString(16) + ' bytes')
7360 }
7361 return length | 0
7362 }
7363
7364 function SlowBuffer (length) {
7365 if (+length != length) { // eslint-disable-line eqeqeq
7366 length = 0
7367 }
7368 return Buffer.alloc(+length)
7369 }
7370
7371 Buffer.isBuffer = function isBuffer (b) {
7372 return !!(b != null && b._isBuffer)
7373 }
7374
7375 Buffer.compare = function compare (a, b) {
7376 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
7377 throw new TypeError('Arguments must be Buffers')
7378 }
7379
7380 if (a === b) return 0
7381
7382 var x = a.length
7383 var y = b.length
7384
7385 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
7386 if (a[i] !== b[i]) {
7387 x = a[i]
7388 y = b[i]
7389 break
7390 }
7391 }
7392
7393 if (x < y) return -1
7394 if (y < x) return 1
7395 return 0
7396 }
7397
7398 Buffer.isEncoding = function isEncoding (encoding) {
7399 switch (String(encoding).toLowerCase()) {
7400 case 'hex':
7401 case 'utf8':
7402 case 'utf-8':
7403 case 'ascii':
7404 case 'latin1':
7405 case 'binary':
7406 case 'base64':
7407 case 'ucs2':
7408 case 'ucs-2':
7409 case 'utf16le':
7410 case 'utf-16le':
7411 return true
7412 default:
7413 return false
7414 }
7415 }
7416
7417 Buffer.concat = function concat (list, length) {
7418 if (!isArray(list)) {
7419 throw new TypeError('"list" argument must be an Array of Buffers')
7420 }
7421
7422 if (list.length === 0) {
7423 return Buffer.alloc(0)
7424 }
7425
7426 var i
7427 if (length === undefined) {
7428 length = 0
7429 for (i = 0; i < list.length; ++i) {
7430 length += list[i].length
7431 }
7432 }
7433
7434 var buffer = Buffer.allocUnsafe(length)
7435 var pos = 0
7436 for (i = 0; i < list.length; ++i) {
7437 var buf = list[i]
7438 if (!Buffer.isBuffer(buf)) {
7439 throw new TypeError('"list" argument must be an Array of Buffers')
7440 }
7441 buf.copy(buffer, pos)
7442 pos += buf.length
7443 }
7444 return buffer
7445 }
7446
7447 function byteLength (string, encoding) {
7448 if (Buffer.isBuffer(string)) {
7449 return string.length
7450 }
7451 if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'funct ion' &&
7452 (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
7453 return string.byteLength
7454 }
7455 if (typeof string !== 'string') {
7456 string = '' + string
7457 }
7458
7459 var len = string.length
7460 if (len === 0) return 0
7461
7462 // Use a for loop to avoid recursion
7463 var loweredCase = false
7464 for (;;) {
7465 switch (encoding) {
7466 case 'ascii':
7467 case 'latin1':
7468 case 'binary':
7469 return len
7470 case 'utf8':
7471 case 'utf-8':
7472 case undefined:
7473 return utf8ToBytes(string).length
7474 case 'ucs2':
7475 case 'ucs-2':
7476 case 'utf16le':
7477 case 'utf-16le':
7478 return len * 2
7479 case 'hex':
7480 return len >>> 1
7481 case 'base64':
7482 return base64ToBytes(string).length
7483 default:
7484 if (loweredCase) return utf8ToBytes(string).length // assume utf8
7485 encoding = ('' + encoding).toLowerCase()
7486 loweredCase = true
7487 }
7488 }
7489 }
7490 Buffer.byteLength = byteLength
7491
7492 function slowToString (encoding, start, end) {
7493 var loweredCase = false
7494
7495 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
7496 // property of a typed array.
7497
7498 // This behaves neither like String nor Uint8Array in that we set start/end
7499 // to their upper/lower bounds if the value passed is out of range.
7500 // undefined is handled specially as per ECMA-262 6th Edition,
7501 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
7502 if (start === undefined || start < 0) {
7503 start = 0
7504 }
7505 // Return early if start > this.length. Done here to prevent potential uint32
7506 // coercion fail below.
7507 if (start > this.length) {
7508 return ''
7509 }
7510
7511 if (end === undefined || end > this.length) {
7512 end = this.length
7513 }
7514
7515 if (end <= 0) {
7516 return ''
7517 }
7518
7519 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
7520 end >>>= 0
7521 start >>>= 0
7522
7523 if (end <= start) {
7524 return ''
7525 }
7526
7527 if (!encoding) encoding = 'utf8'
7528
7529 while (true) {
7530 switch (encoding) {
7531 case 'hex':
7532 return hexSlice(this, start, end)
7533
7534 case 'utf8':
7535 case 'utf-8':
7536 return utf8Slice(this, start, end)
7537
7538 case 'ascii':
7539 return asciiSlice(this, start, end)
7540
7541 case 'latin1':
7542 case 'binary':
7543 return latin1Slice(this, start, end)
7544
7545 case 'base64':
7546 return base64Slice(this, start, end)
7547
7548 case 'ucs2':
7549 case 'ucs-2':
7550 case 'utf16le':
7551 case 'utf-16le':
7552 return utf16leSlice(this, start, end)
7553
7554 default:
7555 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
7556 encoding = (encoding + '').toLowerCase()
7557 loweredCase = true
7558 }
7559 }
7560 }
7561
7562 // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
7563 // Buffer instances.
7564 Buffer.prototype._isBuffer = true
7565
7566 function swap (b, n, m) {
7567 var i = b[n]
7568 b[n] = b[m]
7569 b[m] = i
7570 }
7571
7572 Buffer.prototype.swap16 = function swap16 () {
7573 var len = this.length
7574 if (len % 2 !== 0) {
7575 throw new RangeError('Buffer size must be a multiple of 16-bits')
7576 }
7577 for (var i = 0; i < len; i += 2) {
7578 swap(this, i, i + 1)
7579 }
7580 return this
7581 }
7582
7583 Buffer.prototype.swap32 = function swap32 () {
7584 var len = this.length
7585 if (len % 4 !== 0) {
7586 throw new RangeError('Buffer size must be a multiple of 32-bits')
7587 }
7588 for (var i = 0; i < len; i += 4) {
7589 swap(this, i, i + 3)
7590 swap(this, i + 1, i + 2)
7591 }
7592 return this
7593 }
7594
7595 Buffer.prototype.swap64 = function swap64 () {
7596 var len = this.length
7597 if (len % 8 !== 0) {
7598 throw new RangeError('Buffer size must be a multiple of 64-bits')
7599 }
7600 for (var i = 0; i < len; i += 8) {
7601 swap(this, i, i + 7)
7602 swap(this, i + 1, i + 6)
7603 swap(this, i + 2, i + 5)
7604 swap(this, i + 3, i + 4)
7605 }
7606 return this
7607 }
7608
7609 Buffer.prototype.toString = function toString () {
7610 var length = this.length | 0
7611 if (length === 0) return ''
7612 if (arguments.length === 0) return utf8Slice(this, 0, length)
7613 return slowToString.apply(this, arguments)
7614 }
7615
7616 Buffer.prototype.equals = function equals (b) {
7617 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
7618 if (this === b) return true
7619 return Buffer.compare(this, b) === 0
7620 }
7621
7622 Buffer.prototype.inspect = function inspect () {
7623 var str = ''
7624 var max = exports.INSPECT_MAX_BYTES
7625 if (this.length > 0) {
7626 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
7627 if (this.length > max) str += ' ... '
7628 }
7629 return '<Buffer ' + str + '>'
7630 }
7631
7632 Buffer.prototype.compare = function compare (target, start, end, thisStart, this End) {
7633 if (!Buffer.isBuffer(target)) {
7634 throw new TypeError('Argument must be a Buffer')
7635 }
7636
7637 if (start === undefined) {
7638 start = 0
7639 }
7640 if (end === undefined) {
7641 end = target ? target.length : 0
7642 }
7643 if (thisStart === undefined) {
7644 thisStart = 0
7645 }
7646 if (thisEnd === undefined) {
7647 thisEnd = this.length
7648 }
7649
7650 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length ) {
7651 throw new RangeError('out of range index')
7652 }
7653
7654 if (thisStart >= thisEnd && start >= end) {
7655 return 0
7656 }
7657 if (thisStart >= thisEnd) {
7658 return -1
7659 }
7660 if (start >= end) {
7661 return 1
7662 }
7663
7664 start >>>= 0
7665 end >>>= 0
7666 thisStart >>>= 0
7667 thisEnd >>>= 0
7668
7669 if (this === target) return 0
7670
7671 var x = thisEnd - thisStart
7672 var y = end - start
7673 var len = Math.min(x, y)
7674
7675 var thisCopy = this.slice(thisStart, thisEnd)
7676 var targetCopy = target.slice(start, end)
7677
7678 for (var i = 0; i < len; ++i) {
7679 if (thisCopy[i] !== targetCopy[i]) {
7680 x = thisCopy[i]
7681 y = targetCopy[i]
7682 break
7683 }
7684 }
7685
7686 if (x < y) return -1
7687 if (y < x) return 1
7688 return 0
7689 }
7690
7691 // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
7692 // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
7693 //
7694 // Arguments:
7695 // - buffer - a Buffer to search
7696 // - val - a string, Buffer, or number
7697 // - byteOffset - an index into `buffer`; will be clamped to an int32
7698 // - encoding - an optional encoding, relevant is val is a string
7699 // - dir - true for indexOf, false for lastIndexOf
7700 function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
7701 // Empty buffer means no match
7702 if (buffer.length === 0) return -1
7703
7704 // Normalize byteOffset
7705 if (typeof byteOffset === 'string') {
7706 encoding = byteOffset
7707 byteOffset = 0
7708 } else if (byteOffset > 0x7fffffff) {
7709 byteOffset = 0x7fffffff
7710 } else if (byteOffset < -0x80000000) {
7711 byteOffset = -0x80000000
7712 }
7713 byteOffset = +byteOffset // Coerce to Number.
7714 if (isNaN(byteOffset)) {
7715 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
7716 byteOffset = dir ? 0 : (buffer.length - 1)
7717 }
7718
7719 // Normalize byteOffset: negative offsets start from the end of the buffer
7720 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
7721 if (byteOffset >= buffer.length) {
7722 if (dir) return -1
7723 else byteOffset = buffer.length - 1
7724 } else if (byteOffset < 0) {
7725 if (dir) byteOffset = 0
7726 else return -1
7727 }
7728
7729 // Normalize val
7730 if (typeof val === 'string') {
7731 val = Buffer.from(val, encoding)
7732 }
7733
7734 // Finally, search either indexOf (if dir is true) or lastIndexOf
7735 if (Buffer.isBuffer(val)) {
7736 // Special case: looking for empty string/buffer always fails
7737 if (val.length === 0) {
7738 return -1
7739 }
7740 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
7741 } else if (typeof val === 'number') {
7742 val = val & 0xFF // Search for a byte value [0-255]
7743 if (Buffer.TYPED_ARRAY_SUPPORT &&
7744 typeof Uint8Array.prototype.indexOf === 'function') {
7745 if (dir) {
7746 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
7747 } else {
7748 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
7749 }
7750 }
7751 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
7752 }
7753
7754 throw new TypeError('val must be string, number or Buffer')
7755 }
7756
7757 function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
7758 var indexSize = 1
7759 var arrLength = arr.length
7760 var valLength = val.length
7761
7762 if (encoding !== undefined) {
7763 encoding = String(encoding).toLowerCase()
7764 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
7765 encoding === 'utf16le' || encoding === 'utf-16le') {
7766 if (arr.length < 2 || val.length < 2) {
7767 return -1
7768 }
7769 indexSize = 2
7770 arrLength /= 2
7771 valLength /= 2
7772 byteOffset /= 2
7773 }
7774 }
7775
7776 function read (buf, i) {
7777 if (indexSize === 1) {
7778 return buf[i]
7779 } else {
7780 return buf.readUInt16BE(i * indexSize)
7781 }
7782 }
7783
7784 var i
7785 if (dir) {
7786 var foundIndex = -1
7787 for (i = byteOffset; i < arrLength; i++) {
7788 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
7789 if (foundIndex === -1) foundIndex = i
7790 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
7791 } else {
7792 if (foundIndex !== -1) i -= i - foundIndex
7793 foundIndex = -1
7794 }
7795 }
7796 } else {
7797 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
7798 for (i = byteOffset; i >= 0; i--) {
7799 var found = true
7800 for (var j = 0; j < valLength; j++) {
7801 if (read(arr, i + j) !== read(val, j)) {
7802 found = false
7803 break
7804 }
7805 }
7806 if (found) return i
7807 }
7808 }
7809
7810 return -1
7811 }
7812
7813 Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
7814 return this.indexOf(val, byteOffset, encoding) !== -1
7815 }
7816
7817 Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
7818 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
7819 }
7820
7821 Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
7822 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
7823 }
7824
7825 function hexWrite (buf, string, offset, length) {
7826 offset = Number(offset) || 0
7827 var remaining = buf.length - offset
7828 if (!length) {
7829 length = remaining
7830 } else {
7831 length = Number(length)
7832 if (length > remaining) {
7833 length = remaining
7834 }
7835 }
7836
7837 // must be an even number of digits
7838 var strLen = string.length
7839 if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
7840
7841 if (length > strLen / 2) {
7842 length = strLen / 2
7843 }
7844 for (var i = 0; i < length; ++i) {
7845 var parsed = parseInt(string.substr(i * 2, 2), 16)
7846 if (isNaN(parsed)) return i
7847 buf[offset + i] = parsed
7848 }
7849 return i
7850 }
7851
7852 function utf8Write (buf, string, offset, length) {
7853 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, lengt h)
7854 }
7855
7856 function asciiWrite (buf, string, offset, length) {
7857 return blitBuffer(asciiToBytes(string), buf, offset, length)
7858 }
7859
7860 function latin1Write (buf, string, offset, length) {
7861 return asciiWrite(buf, string, offset, length)
7862 }
7863
7864 function base64Write (buf, string, offset, length) {
7865 return blitBuffer(base64ToBytes(string), buf, offset, length)
7866 }
7867
7868 function ucs2Write (buf, string, offset, length) {
7869 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, le ngth)
7870 }
7871
7872 Buffer.prototype.write = function write (string, offset, length, encoding) {
7873 // Buffer#write(string)
7874 if (offset === undefined) {
7875 encoding = 'utf8'
7876 length = this.length
7877 offset = 0
7878 // Buffer#write(string, encoding)
7879 } else if (length === undefined && typeof offset === 'string') {
7880 encoding = offset
7881 length = this.length
7882 offset = 0
7883 // Buffer#write(string, offset[, length][, encoding])
7884 } else if (isFinite(offset)) {
7885 offset = offset | 0
7886 if (isFinite(length)) {
7887 length = length | 0
7888 if (encoding === undefined) encoding = 'utf8'
7889 } else {
7890 encoding = length
7891 length = undefined
7892 }
7893 // legacy write(string, encoding, offset, length) - remove in v0.13
7894 } else {
7895 throw new Error(
7896 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
7897 )
7898 }
7899
7900 var remaining = this.length - offset
7901 if (length === undefined || length > remaining) length = remaining
7902
7903 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
7904 throw new RangeError('Attempt to write outside buffer bounds')
7905 }
7906
7907 if (!encoding) encoding = 'utf8'
7908
7909 var loweredCase = false
7910 for (;;) {
7911 switch (encoding) {
7912 case 'hex':
7913 return hexWrite(this, string, offset, length)
7914
7915 case 'utf8':
7916 case 'utf-8':
7917 return utf8Write(this, string, offset, length)
7918
7919 case 'ascii':
7920 return asciiWrite(this, string, offset, length)
7921
7922 case 'latin1':
7923 case 'binary':
7924 return latin1Write(this, string, offset, length)
7925
7926 case 'base64':
7927 // Warning: maxLength not taken into account in base64Write
7928 return base64Write(this, string, offset, length)
7929
7930 case 'ucs2':
7931 case 'ucs-2':
7932 case 'utf16le':
7933 case 'utf-16le':
7934 return ucs2Write(this, string, offset, length)
7935
7936 default:
7937 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
7938 encoding = ('' + encoding).toLowerCase()
7939 loweredCase = true
7940 }
7941 }
7942 }
7943
7944 Buffer.prototype.toJSON = function toJSON () {
7945 return {
7946 type: 'Buffer',
7947 data: Array.prototype.slice.call(this._arr || this, 0)
7948 }
7949 }
7950
7951 function base64Slice (buf, start, end) {
7952 if (start === 0 && end === buf.length) {
7953 return base64.fromByteArray(buf)
7954 } else {
7955 return base64.fromByteArray(buf.slice(start, end))
7956 }
7957 }
7958
7959 function utf8Slice (buf, start, end) {
7960 end = Math.min(buf.length, end)
7961 var res = []
7962
7963 var i = start
7964 while (i < end) {
7965 var firstByte = buf[i]
7966 var codePoint = null
7967 var bytesPerSequence = (firstByte > 0xEF) ? 4
7968 : (firstByte > 0xDF) ? 3
7969 : (firstByte > 0xBF) ? 2
7970 : 1
7971
7972 if (i + bytesPerSequence <= end) {
7973 var secondByte, thirdByte, fourthByte, tempCodePoint
7974
7975 switch (bytesPerSequence) {
7976 case 1:
7977 if (firstByte < 0x80) {
7978 codePoint = firstByte
7979 }
7980 break
7981 case 2:
7982 secondByte = buf[i + 1]
7983 if ((secondByte & 0xC0) === 0x80) {
7984 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
7985 if (tempCodePoint > 0x7F) {
7986 codePoint = tempCodePoint
7987 }
7988 }
7989 break
7990 case 3:
7991 secondByte = buf[i + 1]
7992 thirdByte = buf[i + 2]
7993 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
7994 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x 6 | (thirdByte & 0x3F)
7995 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoin t > 0xDFFF)) {
7996 codePoint = tempCodePoint
7997 }
7998 }
7999 break
8000 case 4:
8001 secondByte = buf[i + 1]
8002 thirdByte = buf[i + 2]
8003 fourthByte = buf[i + 3]
8004 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fo urthByte & 0xC0) === 0x80) {
8005 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0 xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
8006 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
8007 codePoint = tempCodePoint
8008 }
8009 }
8010 }
8011 }
8012
8013 if (codePoint === null) {
8014 // we did not generate a valid codePoint so insert a
8015 // replacement char (U+FFFD) and advance only 1 byte
8016 codePoint = 0xFFFD
8017 bytesPerSequence = 1
8018 } else if (codePoint > 0xFFFF) {
8019 // encode to utf16 (surrogate pair dance)
8020 codePoint -= 0x10000
8021 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
8022 codePoint = 0xDC00 | codePoint & 0x3FF
8023 }
8024
8025 res.push(codePoint)
8026 i += bytesPerSequence
8027 }
8028
8029 return decodeCodePointsArray(res)
8030 }
8031
8032 // Based on http://stackoverflow.com/a/22747272/680742, the browser with
8033 // the lowest limit is Chrome, with 0x10000 args.
8034 // We go 1 magnitude less, for safety
8035 var MAX_ARGUMENTS_LENGTH = 0x1000
8036
8037 function decodeCodePointsArray (codePoints) {
8038 var len = codePoints.length
8039 if (len <= MAX_ARGUMENTS_LENGTH) {
8040 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
8041 }
8042
8043 // Decode in chunks to avoid "call stack size exceeded".
8044 var res = ''
8045 var i = 0
8046 while (i < len) {
8047 res += String.fromCharCode.apply(
8048 String,
8049 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
8050 )
8051 }
8052 return res
8053 }
8054
8055 function asciiSlice (buf, start, end) {
8056 var ret = ''
8057 end = Math.min(buf.length, end)
8058
8059 for (var i = start; i < end; ++i) {
8060 ret += String.fromCharCode(buf[i] & 0x7F)
8061 }
8062 return ret
8063 }
8064
8065 function latin1Slice (buf, start, end) {
8066 var ret = ''
8067 end = Math.min(buf.length, end)
8068
8069 for (var i = start; i < end; ++i) {
8070 ret += String.fromCharCode(buf[i])
8071 }
8072 return ret
8073 }
8074
8075 function hexSlice (buf, start, end) {
8076 var len = buf.length
8077
8078 if (!start || start < 0) start = 0
8079 if (!end || end < 0 || end > len) end = len
8080
8081 var out = ''
8082 for (var i = start; i < end; ++i) {
8083 out += toHex(buf[i])
8084 }
8085 return out
8086 }
8087
8088 function utf16leSlice (buf, start, end) {
8089 var bytes = buf.slice(start, end)
8090 var res = ''
8091 for (var i = 0; i < bytes.length; i += 2) {
8092 res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
8093 }
8094 return res
8095 }
8096
8097 Buffer.prototype.slice = function slice (start, end) {
8098 var len = this.length
8099 start = ~~start
8100 end = end === undefined ? len : ~~end
8101
8102 if (start < 0) {
8103 start += len
8104 if (start < 0) start = 0
8105 } else if (start > len) {
8106 start = len
8107 }
8108
8109 if (end < 0) {
8110 end += len
8111 if (end < 0) end = 0
8112 } else if (end > len) {
8113 end = len
8114 }
8115
8116 if (end < start) end = start
8117
8118 var newBuf
8119 if (Buffer.TYPED_ARRAY_SUPPORT) {
8120 newBuf = this.subarray(start, end)
8121 newBuf.__proto__ = Buffer.prototype
8122 } else {
8123 var sliceLen = end - start
8124 newBuf = new Buffer(sliceLen, undefined)
8125 for (var i = 0; i < sliceLen; ++i) {
8126 newBuf[i] = this[i + start]
8127 }
8128 }
8129
8130 return newBuf
8131 }
8132
8133 /*
8134 * Need to make sure that buffer isn't trying to write out of bounds.
8135 */
8136 function checkOffset (offset, ext, length) {
8137 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint ')
8138 if (offset + ext > length) throw new RangeError('Trying to access beyond buffe r length')
8139 }
8140
8141 Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
8142 offset = offset | 0
8143 byteLength = byteLength | 0
8144 if (!noAssert) checkOffset(offset, byteLength, this.length)
8145
8146 var val = this[offset]
8147 var mul = 1
8148 var i = 0
8149 while (++i < byteLength && (mul *= 0x100)) {
8150 val += this[offset + i] * mul
8151 }
8152
8153 return val
8154 }
8155
8156 Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
8157 offset = offset | 0
8158 byteLength = byteLength | 0
8159 if (!noAssert) {
8160 checkOffset(offset, byteLength, this.length)
8161 }
8162
8163 var val = this[offset + --byteLength]
8164 var mul = 1
8165 while (byteLength > 0 && (mul *= 0x100)) {
8166 val += this[offset + --byteLength] * mul
8167 }
8168
8169 return val
8170 }
8171
8172 Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
8173 if (!noAssert) checkOffset(offset, 1, this.length)
8174 return this[offset]
8175 }
8176
8177 Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
8178 if (!noAssert) checkOffset(offset, 2, this.length)
8179 return this[offset] | (this[offset + 1] << 8)
8180 }
8181
8182 Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
8183 if (!noAssert) checkOffset(offset, 2, this.length)
8184 return (this[offset] << 8) | this[offset + 1]
8185 }
8186
8187 Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
8188 if (!noAssert) checkOffset(offset, 4, this.length)
8189
8190 return ((this[offset]) |
8191 (this[offset + 1] << 8) |
8192 (this[offset + 2] << 16)) +
8193 (this[offset + 3] * 0x1000000)
8194 }
8195
8196 Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
8197 if (!noAssert) checkOffset(offset, 4, this.length)
8198
8199 return (this[offset] * 0x1000000) +
8200 ((this[offset + 1] << 16) |
8201 (this[offset + 2] << 8) |
8202 this[offset + 3])
8203 }
8204
8205 Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
8206 offset = offset | 0
8207 byteLength = byteLength | 0
8208 if (!noAssert) checkOffset(offset, byteLength, this.length)
8209
8210 var val = this[offset]
8211 var mul = 1
8212 var i = 0
8213 while (++i < byteLength && (mul *= 0x100)) {
8214 val += this[offset + i] * mul
8215 }
8216 mul *= 0x80
8217
8218 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
8219
8220 return val
8221 }
8222
8223 Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
8224 offset = offset | 0
8225 byteLength = byteLength | 0
8226 if (!noAssert) checkOffset(offset, byteLength, this.length)
8227
8228 var i = byteLength
8229 var mul = 1
8230 var val = this[offset + --i]
8231 while (i > 0 && (mul *= 0x100)) {
8232 val += this[offset + --i] * mul
8233 }
8234 mul *= 0x80
8235
8236 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
8237
8238 return val
8239 }
8240
8241 Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
8242 if (!noAssert) checkOffset(offset, 1, this.length)
8243 if (!(this[offset] & 0x80)) return (this[offset])
8244 return ((0xff - this[offset] + 1) * -1)
8245 }
8246
8247 Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
8248 if (!noAssert) checkOffset(offset, 2, this.length)
8249 var val = this[offset] | (this[offset + 1] << 8)
8250 return (val & 0x8000) ? val | 0xFFFF0000 : val
8251 }
8252
8253 Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
8254 if (!noAssert) checkOffset(offset, 2, this.length)
8255 var val = this[offset + 1] | (this[offset] << 8)
8256 return (val & 0x8000) ? val | 0xFFFF0000 : val
8257 }
8258
8259 Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
8260 if (!noAssert) checkOffset(offset, 4, this.length)
8261
8262 return (this[offset]) |
8263 (this[offset + 1] << 8) |
8264 (this[offset + 2] << 16) |
8265 (this[offset + 3] << 24)
8266 }
8267
8268 Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
8269 if (!noAssert) checkOffset(offset, 4, this.length)
8270
8271 return (this[offset] << 24) |
8272 (this[offset + 1] << 16) |
8273 (this[offset + 2] << 8) |
8274 (this[offset + 3])
8275 }
8276
8277 Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
8278 if (!noAssert) checkOffset(offset, 4, this.length)
8279 return ieee754.read(this, offset, true, 23, 4)
8280 }
8281
8282 Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
8283 if (!noAssert) checkOffset(offset, 4, this.length)
8284 return ieee754.read(this, offset, false, 23, 4)
8285 }
8286
8287 Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
8288 if (!noAssert) checkOffset(offset, 8, this.length)
8289 return ieee754.read(this, offset, true, 52, 8)
8290 }
8291
8292 Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
8293 if (!noAssert) checkOffset(offset, 8, this.length)
8294 return ieee754.read(this, offset, false, 52, 8)
8295 }
8296
8297 function checkInt (buf, value, offset, ext, max, min) {
8298 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Bu ffer instance')
8299 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
8300 if (offset + ext > buf.length) throw new RangeError('Index out of range')
8301 }
8302
8303 Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
8304 value = +value
8305 offset = offset | 0
8306 byteLength = byteLength | 0
8307 if (!noAssert) {
8308 var maxBytes = Math.pow(2, 8 * byteLength) - 1
8309 checkInt(this, value, offset, byteLength, maxBytes, 0)
8310 }
8311
8312 var mul = 1
8313 var i = 0
8314 this[offset] = value & 0xFF
8315 while (++i < byteLength && (mul *= 0x100)) {
8316 this[offset + i] = (value / mul) & 0xFF
8317 }
8318
8319 return offset + byteLength
8320 }
8321
8322 Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
8323 value = +value
8324 offset = offset | 0
8325 byteLength = byteLength | 0
8326 if (!noAssert) {
8327 var maxBytes = Math.pow(2, 8 * byteLength) - 1
8328 checkInt(this, value, offset, byteLength, maxBytes, 0)
8329 }
8330
8331 var i = byteLength - 1
8332 var mul = 1
8333 this[offset + i] = value & 0xFF
8334 while (--i >= 0 && (mul *= 0x100)) {
8335 this[offset + i] = (value / mul) & 0xFF
8336 }
8337
8338 return offset + byteLength
8339 }
8340
8341 Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
8342 value = +value
8343 offset = offset | 0
8344 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
8345 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
8346 this[offset] = (value & 0xff)
8347 return offset + 1
8348 }
8349
8350 function objectWriteUInt16 (buf, value, offset, littleEndian) {
8351 if (value < 0) value = 0xffff + value + 1
8352 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
8353 buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
8354 (littleEndian ? i : 1 - i) * 8
8355 }
8356 }
8357
8358 Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert ) {
8359 value = +value
8360 offset = offset | 0
8361 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
8362 if (Buffer.TYPED_ARRAY_SUPPORT) {
8363 this[offset] = (value & 0xff)
8364 this[offset + 1] = (value >>> 8)
8365 } else {
8366 objectWriteUInt16(this, value, offset, true)
8367 }
8368 return offset + 2
8369 }
8370
8371 Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert ) {
8372 value = +value
8373 offset = offset | 0
8374 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
8375 if (Buffer.TYPED_ARRAY_SUPPORT) {
8376 this[offset] = (value >>> 8)
8377 this[offset + 1] = (value & 0xff)
8378 } else {
8379 objectWriteUInt16(this, value, offset, false)
8380 }
8381 return offset + 2
8382 }
8383
8384 function objectWriteUInt32 (buf, value, offset, littleEndian) {
8385 if (value < 0) value = 0xffffffff + value + 1
8386 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
8387 buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
8388 }
8389 }
8390
8391 Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert ) {
8392 value = +value
8393 offset = offset | 0
8394 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
8395 if (Buffer.TYPED_ARRAY_SUPPORT) {
8396 this[offset + 3] = (value >>> 24)
8397 this[offset + 2] = (value >>> 16)
8398 this[offset + 1] = (value >>> 8)
8399 this[offset] = (value & 0xff)
8400 } else {
8401 objectWriteUInt32(this, value, offset, true)
8402 }
8403 return offset + 4
8404 }
8405
8406 Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert ) {
8407 value = +value
8408 offset = offset | 0
8409 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
8410 if (Buffer.TYPED_ARRAY_SUPPORT) {
8411 this[offset] = (value >>> 24)
8412 this[offset + 1] = (value >>> 16)
8413 this[offset + 2] = (value >>> 8)
8414 this[offset + 3] = (value & 0xff)
8415 } else {
8416 objectWriteUInt32(this, value, offset, false)
8417 }
8418 return offset + 4
8419 }
8420
8421 Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, no Assert) {
8422 value = +value
8423 offset = offset | 0
8424 if (!noAssert) {
8425 var limit = Math.pow(2, 8 * byteLength - 1)
8426
8427 checkInt(this, value, offset, byteLength, limit - 1, -limit)
8428 }
8429
8430 var i = 0
8431 var mul = 1
8432 var sub = 0
8433 this[offset] = value & 0xFF
8434 while (++i < byteLength && (mul *= 0x100)) {
8435 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
8436 sub = 1
8437 }
8438 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
8439 }
8440
8441 return offset + byteLength
8442 }
8443
8444 Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, no Assert) {
8445 value = +value
8446 offset = offset | 0
8447 if (!noAssert) {
8448 var limit = Math.pow(2, 8 * byteLength - 1)
8449
8450 checkInt(this, value, offset, byteLength, limit - 1, -limit)
8451 }
8452
8453 var i = byteLength - 1
8454 var mul = 1
8455 var sub = 0
8456 this[offset + i] = value & 0xFF
8457 while (--i >= 0 && (mul *= 0x100)) {
8458 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
8459 sub = 1
8460 }
8461 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
8462 }
8463
8464 return offset + byteLength
8465 }
8466
8467 Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
8468 value = +value
8469 offset = offset | 0
8470 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
8471 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
8472 if (value < 0) value = 0xff + value + 1
8473 this[offset] = (value & 0xff)
8474 return offset + 1
8475 }
8476
8477 Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
8478 value = +value
8479 offset = offset | 0
8480 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
8481 if (Buffer.TYPED_ARRAY_SUPPORT) {
8482 this[offset] = (value & 0xff)
8483 this[offset + 1] = (value >>> 8)
8484 } else {
8485 objectWriteUInt16(this, value, offset, true)
8486 }
8487 return offset + 2
8488 }
8489
8490 Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
8491 value = +value
8492 offset = offset | 0
8493 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
8494 if (Buffer.TYPED_ARRAY_SUPPORT) {
8495 this[offset] = (value >>> 8)
8496 this[offset + 1] = (value & 0xff)
8497 } else {
8498 objectWriteUInt16(this, value, offset, false)
8499 }
8500 return offset + 2
8501 }
8502
8503 Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
8504 value = +value
8505 offset = offset | 0
8506 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
8507 if (Buffer.TYPED_ARRAY_SUPPORT) {
8508 this[offset] = (value & 0xff)
8509 this[offset + 1] = (value >>> 8)
8510 this[offset + 2] = (value >>> 16)
8511 this[offset + 3] = (value >>> 24)
8512 } else {
8513 objectWriteUInt32(this, value, offset, true)
8514 }
8515 return offset + 4
8516 }
8517
8518 Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
8519 value = +value
8520 offset = offset | 0
8521 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
8522 if (value < 0) value = 0xffffffff + value + 1
8523 if (Buffer.TYPED_ARRAY_SUPPORT) {
8524 this[offset] = (value >>> 24)
8525 this[offset + 1] = (value >>> 16)
8526 this[offset + 2] = (value >>> 8)
8527 this[offset + 3] = (value & 0xff)
8528 } else {
8529 objectWriteUInt32(this, value, offset, false)
8530 }
8531 return offset + 4
8532 }
8533
8534 function checkIEEE754 (buf, value, offset, ext, max, min) {
8535 if (offset + ext > buf.length) throw new RangeError('Index out of range')
8536 if (offset < 0) throw new RangeError('Index out of range')
8537 }
8538
8539 function writeFloat (buf, value, offset, littleEndian, noAssert) {
8540 if (!noAssert) {
8541 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852 886e+38)
8542 }
8543 ieee754.write(buf, value, offset, littleEndian, 23, 4)
8544 return offset + 4
8545 }
8546
8547 Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
8548 return writeFloat(this, value, offset, true, noAssert)
8549 }
8550
8551 Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
8552 return writeFloat(this, value, offset, false, noAssert)
8553 }
8554
8555 function writeDouble (buf, value, offset, littleEndian, noAssert) {
8556 if (!noAssert) {
8557 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.797693134862 3157E+308)
8558 }
8559 ieee754.write(buf, value, offset, littleEndian, 52, 8)
8560 return offset + 8
8561 }
8562
8563 Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert ) {
8564 return writeDouble(this, value, offset, true, noAssert)
8565 }
8566
8567 Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert ) {
8568 return writeDouble(this, value, offset, false, noAssert)
8569 }
8570
8571 // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
8572 Buffer.prototype.copy = function copy (target, targetStart, start, end) {
8573 if (!start) start = 0
8574 if (!end && end !== 0) end = this.length
8575 if (targetStart >= target.length) targetStart = target.length
8576 if (!targetStart) targetStart = 0
8577 if (end > 0 && end < start) end = start
8578
8579 // Copy 0 bytes; we're done
8580 if (end === start) return 0
8581 if (target.length === 0 || this.length === 0) return 0
8582
8583 // Fatal error conditions
8584 if (targetStart < 0) {
8585 throw new RangeError('targetStart out of bounds')
8586 }
8587 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out o f bounds')
8588 if (end < 0) throw new RangeError('sourceEnd out of bounds')
8589
8590 // Are we oob?
8591 if (end > this.length) end = this.length
8592 if (target.length - targetStart < end - start) {
8593 end = target.length - targetStart + start
8594 }
8595
8596 var len = end - start
8597 var i
8598
8599 if (this === target && start < targetStart && targetStart < end) {
8600 // descending copy from end
8601 for (i = len - 1; i >= 0; --i) {
8602 target[i + targetStart] = this[i + start]
8603 }
8604 } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
8605 // ascending copy from start
8606 for (i = 0; i < len; ++i) {
8607 target[i + targetStart] = this[i + start]
8608 }
8609 } else {
8610 Uint8Array.prototype.set.call(
8611 target,
8612 this.subarray(start, start + len),
8613 targetStart
8614 )
8615 }
8616
8617 return len
8618 }
8619
8620 // Usage:
8621 // buffer.fill(number[, offset[, end]])
8622 // buffer.fill(buffer[, offset[, end]])
8623 // buffer.fill(string[, offset[, end]][, encoding])
8624 Buffer.prototype.fill = function fill (val, start, end, encoding) {
8625 // Handle string cases:
8626 if (typeof val === 'string') {
8627 if (typeof start === 'string') {
8628 encoding = start
8629 start = 0
8630 end = this.length
8631 } else if (typeof end === 'string') {
8632 encoding = end
8633 end = this.length
8634 }
8635 if (val.length === 1) {
8636 var code = val.charCodeAt(0)
8637 if (code < 256) {
8638 val = code
8639 }
8640 }
8641 if (encoding !== undefined && typeof encoding !== 'string') {
8642 throw new TypeError('encoding must be a string')
8643 }
8644 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
8645 throw new TypeError('Unknown encoding: ' + encoding)
8646 }
8647 } else if (typeof val === 'number') {
8648 val = val & 255
8649 }
8650
8651 // Invalid ranges are not set to a default, so can range check early.
8652 if (start < 0 || this.length < start || this.length < end) {
8653 throw new RangeError('Out of range index')
8654 }
8655
8656 if (end <= start) {
8657 return this
8658 }
8659
8660 start = start >>> 0
8661 end = end === undefined ? this.length : end >>> 0
8662
8663 if (!val) val = 0
8664
8665 var i
8666 if (typeof val === 'number') {
8667 for (i = start; i < end; ++i) {
8668 this[i] = val
8669 }
8670 } else {
8671 var bytes = Buffer.isBuffer(val)
8672 ? val
8673 : utf8ToBytes(new Buffer(val, encoding).toString())
8674 var len = bytes.length
8675 for (i = 0; i < end - start; ++i) {
8676 this[i + start] = bytes[i % len]
8677 }
8678 }
8679
8680 return this
8681 }
8682
8683 // HELPER FUNCTIONS
8684 // ================
8685
8686 var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
8687
8688 function base64clean (str) {
8689 // Node strips out invalid characters like \n and \t from the string, base64-j s does not
8690 str = stringtrim(str).replace(INVALID_BASE64_RE, '')
8691 // Node converts strings with length < 2 to ''
8692 if (str.length < 2) return ''
8693 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
8694 while (str.length % 4 !== 0) {
8695 str = str + '='
8696 }
8697 return str
8698 }
8699
8700 function stringtrim (str) {
8701 if (str.trim) return str.trim()
8702 return str.replace(/^\s+|\s+$/g, '')
8703 }
8704
8705 function toHex (n) {
8706 if (n < 16) return '0' + n.toString(16)
8707 return n.toString(16)
8708 }
8709
8710 function utf8ToBytes (string, units) {
8711 units = units || Infinity
8712 var codePoint
8713 var length = string.length
8714 var leadSurrogate = null
8715 var bytes = []
8716
8717 for (var i = 0; i < length; ++i) {
8718 codePoint = string.charCodeAt(i)
8719
8720 // is surrogate component
8721 if (codePoint > 0xD7FF && codePoint < 0xE000) {
8722 // last char was a lead
8723 if (!leadSurrogate) {
8724 // no lead yet
8725 if (codePoint > 0xDBFF) {
8726 // unexpected trail
8727 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
8728 continue
8729 } else if (i + 1 === length) {
8730 // unpaired lead
8731 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
8732 continue
8733 }
8734
8735 // valid lead
8736 leadSurrogate = codePoint
8737
8738 continue
8739 }
8740
8741 // 2 leads in a row
8742 if (codePoint < 0xDC00) {
8743 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
8744 leadSurrogate = codePoint
8745 continue
8746 }
8747
8748 // valid surrogate pair
8749 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
8750 } else if (leadSurrogate) {
8751 // valid bmp char, but last char was a lead
8752 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
8753 }
8754
8755 leadSurrogate = null
8756
8757 // encode utf8
8758 if (codePoint < 0x80) {
8759 if ((units -= 1) < 0) break
8760 bytes.push(codePoint)
8761 } else if (codePoint < 0x800) {
8762 if ((units -= 2) < 0) break
8763 bytes.push(
8764 codePoint >> 0x6 | 0xC0,
8765 codePoint & 0x3F | 0x80
8766 )
8767 } else if (codePoint < 0x10000) {
8768 if ((units -= 3) < 0) break
8769 bytes.push(
8770 codePoint >> 0xC | 0xE0,
8771 codePoint >> 0x6 & 0x3F | 0x80,
8772 codePoint & 0x3F | 0x80
8773 )
8774 } else if (codePoint < 0x110000) {
8775 if ((units -= 4) < 0) break
8776 bytes.push(
8777 codePoint >> 0x12 | 0xF0,
8778 codePoint >> 0xC & 0x3F | 0x80,
8779 codePoint >> 0x6 & 0x3F | 0x80,
8780 codePoint & 0x3F | 0x80
8781 )
8782 } else {
8783 throw new Error('Invalid code point')
8784 }
8785 }
8786
8787 return bytes
8788 }
8789
8790 function asciiToBytes (str) {
8791 var byteArray = []
8792 for (var i = 0; i < str.length; ++i) {
8793 // Node's code seems to be doing this and not & 0x7F..
8794 byteArray.push(str.charCodeAt(i) & 0xFF)
8795 }
8796 return byteArray
8797 }
8798
8799 function utf16leToBytes (str, units) {
8800 var c, hi, lo
8801 var byteArray = []
8802 for (var i = 0; i < str.length; ++i) {
8803 if ((units -= 2) < 0) break
8804
8805 c = str.charCodeAt(i)
8806 hi = c >> 8
8807 lo = c % 256
8808 byteArray.push(lo)
8809 byteArray.push(hi)
8810 }
8811
8812 return byteArray
8813 }
8814
8815 function base64ToBytes (str) {
8816 return base64.toByteArray(base64clean(str))
8817 }
8818
8819 function blitBuffer (src, dst, offset, length) {
8820 for (var i = 0; i < length; ++i) {
8821 if ((i + offset >= dst.length) || (i >= src.length)) break
8822 dst[i + offset] = src[i]
8823 }
8824 return i
8825 }
8826
8827 function isnan (val) {
8828 return val !== val // eslint-disable-line no-self-compare
8829 }
8830
8831 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined " ? self : typeof window !== "undefined" ? window : {})
8832 },{"base64-js":39,"ieee754":65,"isarray":68}],45:[function(require,module,export s){
8833 (function (Buffer){
8834 // Copyright Joyent, Inc. and other Node contributors.
8835 //
8836 // Permission is hereby granted, free of charge, to any person obtaining a
8837 // copy of this software and associated documentation files (the
8838 // "Software"), to deal in the Software without restriction, including
8839 // without limitation the rights to use, copy, modify, merge, publish,
8840 // distribute, sublicense, and/or sell copies of the Software, and to permit
8841 // persons to whom the Software is furnished to do so, subject to the
8842 // following conditions:
8843 //
8844 // The above copyright notice and this permission notice shall be included
8845 // in all copies or substantial portions of the Software.
8846 //
8847 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
8848 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
8849 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
8850 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
8851 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
8852 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
8853 // USE OR OTHER DEALINGS IN THE SOFTWARE.
8854
8855 // NOTE: These type checking functions intentionally don't use `instanceof`
8856 // because it is fragile and can be easily faked with `Object.create()`.
8857
8858 function isArray(arg) {
8859 if (Array.isArray) {
8860 return Array.isArray(arg);
8861 }
8862 return objectToString(arg) === '[object Array]';
8863 }
8864 exports.isArray = isArray;
8865
8866 function isBoolean(arg) {
8867 return typeof arg === 'boolean';
8868 }
8869 exports.isBoolean = isBoolean;
8870
8871 function isNull(arg) {
8872 return arg === null;
8873 }
8874 exports.isNull = isNull;
8875
8876 function isNullOrUndefined(arg) {
8877 return arg == null;
8878 }
8879 exports.isNullOrUndefined = isNullOrUndefined;
8880
8881 function isNumber(arg) {
8882 return typeof arg === 'number';
8883 }
8884 exports.isNumber = isNumber;
8885
8886 function isString(arg) {
8887 return typeof arg === 'string';
8888 }
8889 exports.isString = isString;
8890
8891 function isSymbol(arg) {
8892 return typeof arg === 'symbol';
8893 }
8894 exports.isSymbol = isSymbol;
8895
8896 function isUndefined(arg) {
8897 return arg === void 0;
8898 }
8899 exports.isUndefined = isUndefined;
8900
8901 function isRegExp(re) {
8902 return objectToString(re) === '[object RegExp]';
8903 }
8904 exports.isRegExp = isRegExp;
8905
8906 function isObject(arg) {
8907 return typeof arg === 'object' && arg !== null;
8908 }
8909 exports.isObject = isObject;
8910
8911 function isDate(d) {
8912 return objectToString(d) === '[object Date]';
8913 }
8914 exports.isDate = isDate;
8915
8916 function isError(e) {
8917 return (objectToString(e) === '[object Error]' || e instanceof Error);
8918 }
8919 exports.isError = isError;
8920
8921 function isFunction(arg) {
8922 return typeof arg === 'function';
8923 }
8924 exports.isFunction = isFunction;
8925
8926 function isPrimitive(arg) {
8927 return arg === null ||
8928 typeof arg === 'boolean' ||
8929 typeof arg === 'number' ||
8930 typeof arg === 'string' ||
8931 typeof arg === 'symbol' || // ES6 symbol
8932 typeof arg === 'undefined';
8933 }
8934 exports.isPrimitive = isPrimitive;
8935
8936 exports.isBuffer = Buffer.isBuffer;
8937
8938 function objectToString(o) {
8939 return Object.prototype.toString.call(o);
8940 }
8941
8942 }).call(this,{"isBuffer":require("../../is-buffer/index.js")})
8943 },{"../../is-buffer/index.js":67}],46:[function(require,module,exports){
8944 /*istanbul ignore start*/"use strict";
8945
8946 exports.__esModule = true;
8947 exports. /*istanbul ignore end*/convertChangesToDMP = convertChangesToDMP;
8948 // See: http://code.google.com/p/google-diff-match-patch/wiki/API
8949 function convertChangesToDMP(changes) {
8950 var ret = [],
8951 change = /*istanbul ignore start*/void 0 /*istanbul ignore end*/,
8952 operation = /*istanbul ignore start*/void 0 /*istanbul ignore end*/;
8953 for (var i = 0; i < changes.length; i++) {
8954 change = changes[i];
8955 if (change.added) {
8956 operation = 1;
8957 } else if (change.removed) {
8958 operation = -1;
8959 } else {
8960 operation = 0;
8961 }
8962
8963 ret.push([operation, change.value]);
8964 }
8965 return ret;
8966 }
8967
8968
8969 },{}],47:[function(require,module,exports){
8970 /*istanbul ignore start*/'use strict';
8971
8972 exports.__esModule = true;
8973 exports. /*istanbul ignore end*/convertChangesToXML = convertChangesToXML;
8974 function convertChangesToXML(changes) {
8975 var ret = [];
8976 for (var i = 0; i < changes.length; i++) {
8977 var change = changes[i];
8978 if (change.added) {
8979 ret.push('<ins>');
8980 } else if (change.removed) {
8981 ret.push('<del>');
8982 }
8983
8984 ret.push(escapeHTML(change.value));
8985
8986 if (change.added) {
8987 ret.push('</ins>');
8988 } else if (change.removed) {
8989 ret.push('</del>');
8990 }
8991 }
8992 return ret.join('');
8993 }
8994
8995 function escapeHTML(s) {
8996 var n = s;
8997 n = n.replace(/&/g, '&amp;');
8998 n = n.replace(/</g, '&lt;');
8999 n = n.replace(/>/g, '&gt;');
9000 n = n.replace(/"/g, '&quot;');
9001
9002 return n;
9003 }
9004
9005
9006 },{}],48:[function(require,module,exports){
9007 /*istanbul ignore start*/'use strict';
9008
9009 exports.__esModule = true;
9010 exports.arrayDiff = undefined;
9011 exports. /*istanbul ignore end*/diffArrays = diffArrays;
9012
9013 var /*istanbul ignore start*/_base = require('./base') /*istanbul ignore end*/;
9014
9015 /*istanbul ignore start*/
9016 var _base2 = _interopRequireDefault(_base);
9017
9018 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'd efault': obj }; }
9019
9020 /*istanbul ignore end*/var arrayDiff = /*istanbul ignore start*/exports. /*istan bul ignore end*/arrayDiff = new /*istanbul ignore start*/_base2['default']() /*i stanbul ignore end*/;
9021 arrayDiff.tokenize = arrayDiff.join = function (value) {
9022 return value.slice();
9023 };
9024
9025 function diffArrays(oldArr, newArr, callback) {
9026 return arrayDiff.diff(oldArr, newArr, callback);
9027 }
9028
9029
9030 },{"./base":49}],49:[function(require,module,exports){
9031 /*istanbul ignore start*/'use strict';
9032
9033 exports.__esModule = true;
9034 exports['default'] = /*istanbul ignore end*/Diff;
9035 function Diff() {}
9036
9037 Diff.prototype = { /*istanbul ignore start*/
9038 /*istanbul ignore end*/diff: function diff(oldString, newString) {
9039 /*istanbul ignore start*/var /*istanbul ignore end*/options = arguments.leng th <= 2 || arguments[2] === undefined ? {} : arguments[2];
9040
9041 var callback = options.callback;
9042 if (typeof options === 'function') {
9043 callback = options;
9044 options = {};
9045 }
9046 this.options = options;
9047
9048 var self = this;
9049
9050 function done(value) {
9051 if (callback) {
9052 setTimeout(function () {
9053 callback(undefined, value);
9054 }, 0);
9055 return true;
9056 } else {
9057 return value;
9058 }
9059 }
9060
9061 // Allow subclasses to massage the input prior to running
9062 oldString = this.castInput(oldString);
9063 newString = this.castInput(newString);
9064
9065 oldString = this.removeEmpty(this.tokenize(oldString));
9066 newString = this.removeEmpty(this.tokenize(newString));
9067
9068 var newLen = newString.length,
9069 oldLen = oldString.length;
9070 var editLength = 1;
9071 var maxEditLength = newLen + oldLen;
9072 var bestPath = [{ newPos: -1, components: [] }];
9073
9074 // Seed editLength = 0, i.e. the content starts with the same values
9075 var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
9076 if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
9077 // Identity per the equality and tokenizer
9078 return done([{ value: this.join(newString), count: newString.length }]);
9079 }
9080
9081 // Main worker method. checks all permutations of a given edit length for ac ceptance.
9082 function execEditLength() {
9083 for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diago nalPath += 2) {
9084 var basePath = /*istanbul ignore start*/void 0 /*istanbul ignore end*/;
9085 var addPath = bestPath[diagonalPath - 1],
9086 removePath = bestPath[diagonalPath + 1],
9087 _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
9088 if (addPath) {
9089 // No one else is going to attempt to use this value, clear it
9090 bestPath[diagonalPath - 1] = undefined;
9091 }
9092
9093 var canAdd = addPath && addPath.newPos + 1 < newLen,
9094 canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
9095 if (!canAdd && !canRemove) {
9096 // If this path is a terminal then prune
9097 bestPath[diagonalPath] = undefined;
9098 continue;
9099 }
9100
9101 // Select the diagonal that we want to branch from. We select the prior
9102 // path whose position in the new string is the farthest from the origin
9103 // and does not pass the bounds of the diff graph
9104 if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
9105 basePath = clonePath(removePath);
9106 self.pushComponent(basePath.components, undefined, true);
9107 } else {
9108 basePath = addPath; // No need to clone, we've pulled it from the list
9109 basePath.newPos++;
9110 self.pushComponent(basePath.components, true, undefined);
9111 }
9112
9113 _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPat h);
9114
9115 // If we have hit the end of both strings, then we are done
9116 if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
9117 return done(buildValues(self, basePath.components, newString, oldStrin g, self.useLongestToken));
9118 } else {
9119 // Otherwise track this path as a potential candidate and continue.
9120 bestPath[diagonalPath] = basePath;
9121 }
9122 }
9123
9124 editLength++;
9125 }
9126
9127 // Performs the length of edit iteration. Is a bit fugly as this has to supp ort the
9128 // sync and async mode which is never fun. Loops over execEditLength until a value
9129 // is produced.
9130 if (callback) {
9131 (function exec() {
9132 setTimeout(function () {
9133 // This should not happen, but we want to be safe.
9134 /* istanbul ignore next */
9135 if (editLength > maxEditLength) {
9136 return callback();
9137 }
9138
9139 if (!execEditLength()) {
9140 exec();
9141 }
9142 }, 0);
9143 })();
9144 } else {
9145 while (editLength <= maxEditLength) {
9146 var ret = execEditLength();
9147 if (ret) {
9148 return ret;
9149 }
9150 }
9151 }
9152 },
9153 /*istanbul ignore start*/ /*istanbul ignore end*/pushComponent: function pushC omponent(components, added, removed) {
9154 var last = components[components.length - 1];
9155 if (last && last.added === added && last.removed === removed) {
9156 // We need to clone here as the component clone operation is just
9157 // as shallow array clone
9158 components[components.length - 1] = { count: last.count + 1, added: added, removed: removed };
9159 } else {
9160 components.push({ count: 1, added: added, removed: removed });
9161 }
9162 },
9163 /*istanbul ignore start*/ /*istanbul ignore end*/extractCommon: function extra ctCommon(basePath, newString, oldString, diagonalPath) {
9164 var newLen = newString.length,
9165 oldLen = oldString.length,
9166 newPos = basePath.newPos,
9167 oldPos = newPos - diagonalPath,
9168 commonCount = 0;
9169 while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[n ewPos + 1], oldString[oldPos + 1])) {
9170 newPos++;
9171 oldPos++;
9172 commonCount++;
9173 }
9174
9175 if (commonCount) {
9176 basePath.components.push({ count: commonCount });
9177 }
9178
9179 basePath.newPos = newPos;
9180 return oldPos;
9181 },
9182 /*istanbul ignore start*/ /*istanbul ignore end*/equals: function equals(left, right) {
9183 return left === right;
9184 },
9185 /*istanbul ignore start*/ /*istanbul ignore end*/removeEmpty: function removeE mpty(array) {
9186 var ret = [];
9187 for (var i = 0; i < array.length; i++) {
9188 if (array[i]) {
9189 ret.push(array[i]);
9190 }
9191 }
9192 return ret;
9193 },
9194 /*istanbul ignore start*/ /*istanbul ignore end*/castInput: function castInput (value) {
9195 return value;
9196 },
9197 /*istanbul ignore start*/ /*istanbul ignore end*/tokenize: function tokenize(v alue) {
9198 return value.split('');
9199 },
9200 /*istanbul ignore start*/ /*istanbul ignore end*/join: function join(chars) {
9201 return chars.join('');
9202 }
9203 };
9204
9205 function buildValues(diff, components, newString, oldString, useLongestToken) {
9206 var componentPos = 0,
9207 componentLen = components.length,
9208 newPos = 0,
9209 oldPos = 0;
9210
9211 for (; componentPos < componentLen; componentPos++) {
9212 var component = components[componentPos];
9213 if (!component.removed) {
9214 if (!component.added && useLongestToken) {
9215 var value = newString.slice(newPos, newPos + component.count);
9216 value = value.map(function (value, i) {
9217 var oldValue = oldString[oldPos + i];
9218 return oldValue.length > value.length ? oldValue : value;
9219 });
9220
9221 component.value = diff.join(value);
9222 } else {
9223 component.value = diff.join(newString.slice(newPos, newPos + component.c ount));
9224 }
9225 newPos += component.count;
9226
9227 // Common case
9228 if (!component.added) {
9229 oldPos += component.count;
9230 }
9231 } else {
9232 component.value = diff.join(oldString.slice(oldPos, oldPos + component.cou nt));
9233 oldPos += component.count;
9234
9235 // Reverse add and remove so removes are output first to match common conv ention
9236 // The diffing algorithm is tied to add then remove output and this is the simplest
9237 // route to get the desired output with minimal overhead.
9238 if (componentPos && components[componentPos - 1].added) {
9239 var tmp = components[componentPos - 1];
9240 components[componentPos - 1] = components[componentPos];
9241 components[componentPos] = tmp;
9242 }
9243 }
9244 }
9245
9246 // Special case handle for when one terminal is ignored. For this case we merg e the
9247 // terminal into the prior string and drop the change.
9248 var lastComponent = components[componentLen - 1];
9249 if (componentLen > 1 && (lastComponent.added || lastComponent.removed) && diff .equals('', lastComponent.value)) {
9250 components[componentLen - 2].value += lastComponent.value;
9251 components.pop();
9252 }
9253
9254 return components;
9255 }
9256
9257 function clonePath(path) {
9258 return { newPos: path.newPos, components: path.components.slice(0) };
9259 }
9260
9261
9262 },{}],50:[function(require,module,exports){
9263 /*istanbul ignore start*/'use strict';
9264
9265 exports.__esModule = true;
9266 exports.characterDiff = undefined;
9267 exports. /*istanbul ignore end*/diffChars = diffChars;
9268
9269 var /*istanbul ignore start*/_base = require('./base') /*istanbul ignore end*/;
9270
9271 /*istanbul ignore start*/
9272 var _base2 = _interopRequireDefault(_base);
9273
9274 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'd efault': obj }; }
9275
9276 /*istanbul ignore end*/var characterDiff = /*istanbul ignore start*/exports. /*i stanbul ignore end*/characterDiff = new /*istanbul ignore start*/_base2['default ']() /*istanbul ignore end*/;
9277 function diffChars(oldStr, newStr, callback) {
9278 return characterDiff.diff(oldStr, newStr, callback);
9279 }
9280
9281
9282 },{"./base":49}],51:[function(require,module,exports){
9283 /*istanbul ignore start*/'use strict';
9284
9285 exports.__esModule = true;
9286 exports.cssDiff = undefined;
9287 exports. /*istanbul ignore end*/diffCss = diffCss;
9288
9289 var /*istanbul ignore start*/_base = require('./base') /*istanbul ignore end*/;
9290
9291 /*istanbul ignore start*/
9292 var _base2 = _interopRequireDefault(_base);
9293
9294 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'd efault': obj }; }
9295
9296 /*istanbul ignore end*/var cssDiff = /*istanbul ignore start*/exports. /*istanbu l ignore end*/cssDiff = new /*istanbul ignore start*/_base2['default']() /*istan bul ignore end*/;
9297 cssDiff.tokenize = function (value) {
9298 return value.split(/([{}:;,]|\s+)/);
9299 };
9300
9301 function diffCss(oldStr, newStr, callback) {
9302 return cssDiff.diff(oldStr, newStr, callback);
9303 }
9304
9305
9306 },{"./base":49}],52:[function(require,module,exports){
9307 /*istanbul ignore start*/'use strict';
9308
9309 exports.__esModule = true;
9310 exports.jsonDiff = undefined;
9311
9312 var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol " ? function (obj) { return typeof obj; } : function (obj) { return obj && typeo f Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; } ;
9313
9314 exports. /*istanbul ignore end*/diffJson = diffJson;
9315 /*istanbul ignore start*/exports. /*istanbul ignore end*/canonicalize = canonica lize;
9316
9317 var /*istanbul ignore start*/_base = require('./base') /*istanbul ignore end*/;
9318
9319 /*istanbul ignore start*/
9320 var _base2 = _interopRequireDefault(_base);
9321
9322 /*istanbul ignore end*/
9323 var /*istanbul ignore start*/_line = require('./line') /*istanbul ignore end*/;
9324
9325 /*istanbul ignore start*/
9326 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'd efault': obj }; }
9327
9328 /*istanbul ignore end*/
9329
9330 var objectPrototypeToString = Object.prototype.toString;
9331
9332 var jsonDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/jsonDiff = new /*istanbul ignore start*/_base2['default']() /*istanbul ignore end*/;
9333 // Discriminate between two lines of pretty-printed, serialized JSON where one o f them has a
9334 // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
9335 jsonDiff.useLongestToken = true;
9336
9337 jsonDiff.tokenize = /*istanbul ignore start*/_line.lineDiff. /*istanbul ignore e nd*/tokenize;
9338 jsonDiff.castInput = function (value) {
9339 /*istanbul ignore start*/var /*istanbul ignore end*/undefinedReplacement = thi s.options.undefinedReplacement;
9340
9341
9342 return typeof value === 'string' ? value : JSON.stringify(canonicalize(value), function (k, v) {
9343 if (typeof v === 'undefined') {
9344 return undefinedReplacement;
9345 }
9346
9347 return v;
9348 }, ' ');
9349 };
9350 jsonDiff.equals = function (left, right) {
9351 return (/*istanbul ignore start*/_base2['default']. /*istanbul ignore end*/pro totype.equals(left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1' ))
9352 );
9353 };
9354
9355 function diffJson(oldObj, newObj, options) {
9356 return jsonDiff.diff(oldObj, newObj, options);
9357 }
9358
9359 // This function handles the presence of circular references by bailing out when encountering an
9360 // object that is already on the "stack" of items being processed.
9361 function canonicalize(obj, stack, replacementStack) {
9362 stack = stack || [];
9363 replacementStack = replacementStack || [];
9364
9365 var i = /*istanbul ignore start*/void 0 /*istanbul ignore end*/;
9366
9367 for (i = 0; i < stack.length; i += 1) {
9368 if (stack[i] === obj) {
9369 return replacementStack[i];
9370 }
9371 }
9372
9373 var canonicalizedObj = /*istanbul ignore start*/void 0 /*istanbul ignore end*/ ;
9374
9375 if ('[object Array]' === objectPrototypeToString.call(obj)) {
9376 stack.push(obj);
9377 canonicalizedObj = new Array(obj.length);
9378 replacementStack.push(canonicalizedObj);
9379 for (i = 0; i < obj.length; i += 1) {
9380 canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack);
9381 }
9382 stack.pop();
9383 replacementStack.pop();
9384 return canonicalizedObj;
9385 }
9386
9387 if (obj && obj.toJSON) {
9388 obj = obj.toJSON();
9389 }
9390
9391 if ( /*istanbul ignore start*/(typeof /*istanbul ignore end*/obj === 'undefine d' ? 'undefined' : _typeof(obj)) === 'object' && obj !== null) {
9392 stack.push(obj);
9393 canonicalizedObj = {};
9394 replacementStack.push(canonicalizedObj);
9395 var sortedKeys = [],
9396 key = /*istanbul ignore start*/void 0 /*istanbul ignore end*/;
9397 for (key in obj) {
9398 /* istanbul ignore else */
9399 if (obj.hasOwnProperty(key)) {
9400 sortedKeys.push(key);
9401 }
9402 }
9403 sortedKeys.sort();
9404 for (i = 0; i < sortedKeys.length; i += 1) {
9405 key = sortedKeys[i];
9406 canonicalizedObj[key] = canonicalize(obj[key], stack, replacementStack);
9407 }
9408 stack.pop();
9409 replacementStack.pop();
9410 } else {
9411 canonicalizedObj = obj;
9412 }
9413 return canonicalizedObj;
9414 }
9415
9416
9417 },{"./base":49,"./line":53}],53:[function(require,module,exports){
9418 /*istanbul ignore start*/'use strict';
9419
9420 exports.__esModule = true;
9421 exports.lineDiff = undefined;
9422 exports. /*istanbul ignore end*/diffLines = diffLines;
9423 /*istanbul ignore start*/exports. /*istanbul ignore end*/diffTrimmedLines = diff TrimmedLines;
9424
9425 var /*istanbul ignore start*/_base = require('./base') /*istanbul ignore end*/;
9426
9427 /*istanbul ignore start*/
9428 var _base2 = _interopRequireDefault(_base);
9429
9430 /*istanbul ignore end*/
9431 var /*istanbul ignore start*/_params = require('../util/params') /*istanbul igno re end*/;
9432
9433 /*istanbul ignore start*/
9434 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'd efault': obj }; }
9435
9436 /*istanbul ignore end*/var lineDiff = /*istanbul ignore start*/exports. /*istanb ul ignore end*/lineDiff = new /*istanbul ignore start*/_base2['default']() /*ist anbul ignore end*/;
9437 lineDiff.tokenize = function (value) {
9438 var retLines = [],
9439 linesAndNewlines = value.split(/(\n|\r\n)/);
9440
9441 // Ignore the final empty token that occurs if the string ends with a new line
9442 if (!linesAndNewlines[linesAndNewlines.length - 1]) {
9443 linesAndNewlines.pop();
9444 }
9445
9446 // Merge the content and line separators into single tokens
9447 for (var i = 0; i < linesAndNewlines.length; i++) {
9448 var line = linesAndNewlines[i];
9449
9450 if (i % 2 && !this.options.newlineIsToken) {
9451 retLines[retLines.length - 1] += line;
9452 } else {
9453 if (this.options.ignoreWhitespace) {
9454 line = line.trim();
9455 }
9456 retLines.push(line);
9457 }
9458 }
9459
9460 return retLines;
9461 };
9462
9463 function diffLines(oldStr, newStr, callback) {
9464 return lineDiff.diff(oldStr, newStr, callback);
9465 }
9466 function diffTrimmedLines(oldStr, newStr, callback) {
9467 var options = /*istanbul ignore start*/(0, _params.generateOptions) /*istanbul ignore end*/(callback, { ignoreWhitespace: true });
9468 return lineDiff.diff(oldStr, newStr, options);
9469 }
9470
9471
9472 },{"../util/params":61,"./base":49}],54:[function(require,module,exports){
9473 /*istanbul ignore start*/'use strict';
9474
9475 exports.__esModule = true;
9476 exports.sentenceDiff = undefined;
9477 exports. /*istanbul ignore end*/diffSentences = diffSentences;
9478
9479 var /*istanbul ignore start*/_base = require('./base') /*istanbul ignore end*/;
9480
9481 /*istanbul ignore start*/
9482 var _base2 = _interopRequireDefault(_base);
9483
9484 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'd efault': obj }; }
9485
9486 /*istanbul ignore end*/var sentenceDiff = /*istanbul ignore start*/exports. /*is tanbul ignore end*/sentenceDiff = new /*istanbul ignore start*/_base2['default'] () /*istanbul ignore end*/;
9487 sentenceDiff.tokenize = function (value) {
9488 return value.split(/(\S.+?[.!?])(?=\s+|$)/);
9489 };
9490
9491 function diffSentences(oldStr, newStr, callback) {
9492 return sentenceDiff.diff(oldStr, newStr, callback);
9493 }
9494
9495
9496 },{"./base":49}],55:[function(require,module,exports){
9497 /*istanbul ignore start*/'use strict';
9498
9499 exports.__esModule = true;
9500 exports.wordDiff = undefined;
9501 exports. /*istanbul ignore end*/diffWords = diffWords;
9502 /*istanbul ignore start*/exports. /*istanbul ignore end*/diffWordsWithSpace = di ffWordsWithSpace;
9503
9504 var /*istanbul ignore start*/_base = require('./base') /*istanbul ignore end*/;
9505
9506 /*istanbul ignore start*/
9507 var _base2 = _interopRequireDefault(_base);
9508
9509 /*istanbul ignore end*/
9510 var /*istanbul ignore start*/_params = require('../util/params') /*istanbul igno re end*/;
9511
9512 /*istanbul ignore start*/
9513 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'd efault': obj }; }
9514
9515 /*istanbul ignore end*/
9516
9517 // Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode
9518 //
9519 // Ranges and exceptions:
9520 // Latin-1 Supplement, 0080–00FF
9521 // - U+00D7 × Multiplication sign
9522 // - U+00F7 ÷ Division sign
9523 // Latin Extended-A, 0100–017F
9524 // Latin Extended-B, 0180–024F
9525 // IPA Extensions, 0250–02AF
9526 // Spacing Modifier Letters, 02B0–02FF
9527 // - U+02C7 ˇ &#711; Caron
9528 // - U+02D8 ˘ &#728; Breve
9529 // - U+02D9 ˙ &#729; Dot Above
9530 // - U+02DA ˚ &#730; Ring Above
9531 // - U+02DB ˛ &#731; Ogonek
9532 // - U+02DC ˜ &#732; Small Tilde
9533 // - U+02DD ˝ &#733; Double Acute Accent
9534 // Latin Extended Additional, 1E00–1EFF
9535 var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1 EFF]+$/;
9536
9537 var reWhitespace = /\S/;
9538
9539 var wordDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/wordDiff = new /*istanbul ignore start*/_base2['default']() /*istanbul ignore end*/;
9540 wordDiff.equals = function (left, right) {
9541 return left === right || this.options.ignoreWhitespace && !reWhitespace.test(l eft) && !reWhitespace.test(right);
9542 };
9543 wordDiff.tokenize = function (value) {
9544 var tokens = value.split(/(\s+|\b)/);
9545
9546 // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set.
9547 for (var i = 0; i < tokens.length - 1; i++) {
9548 // If we have an empty string in the next field and we have only word chars before and after, merge
9549 if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
9550 tokens[i] += tokens[i + 2];
9551 tokens.splice(i + 1, 2);
9552 i--;
9553 }
9554 }
9555
9556 return tokens;
9557 };
9558
9559 function diffWords(oldStr, newStr, callback) {
9560 var options = /*istanbul ignore start*/(0, _params.generateOptions) /*istanbul ignore end*/(callback, { ignoreWhitespace: true });
9561 return wordDiff.diff(oldStr, newStr, options);
9562 }
9563 function diffWordsWithSpace(oldStr, newStr, callback) {
9564 return wordDiff.diff(oldStr, newStr, callback);
9565 }
9566
9567
9568 },{"../util/params":61,"./base":49}],56:[function(require,module,exports){
9569 /*istanbul ignore start*/'use strict';
9570
9571 exports.__esModule = true;
9572 exports.canonicalize = exports.convertChangesToXML = exports.convertChangesToDMP = exports.parsePatch = exports.applyPatches = exports.applyPatch = exports.crea tePatch = exports.createTwoFilesPatch = exports.structuredPatch = exports.diffAr rays = exports.diffJson = exports.diffCss = exports.diffSentences = exports.diff TrimmedLines = exports.diffLines = exports.diffWordsWithSpace = exports.diffWord s = exports.diffChars = exports.Diff = undefined;
9573 /*istanbul ignore end*/
9574 var /*istanbul ignore start*/_base = require('./diff/base') /*istanbul ignore en d*/;
9575
9576 /*istanbul ignore start*/
9577 var _base2 = _interopRequireDefault(_base);
9578
9579 /*istanbul ignore end*/
9580 var /*istanbul ignore start*/_character = require('./diff/character') /*istanbul ignore end*/;
9581
9582 var /*istanbul ignore start*/_word = require('./diff/word') /*istanbul ignore en d*/;
9583
9584 var /*istanbul ignore start*/_line = require('./diff/line') /*istanbul ignore en d*/;
9585
9586 var /*istanbul ignore start*/_sentence = require('./diff/sentence') /*istanbul i gnore end*/;
9587
9588 var /*istanbul ignore start*/_css = require('./diff/css') /*istanbul ignore end* /;
9589
9590 var /*istanbul ignore start*/_json = require('./diff/json') /*istanbul ignore en d*/;
9591
9592 var /*istanbul ignore start*/_array = require('./diff/array') /*istanbul ignore end*/;
9593
9594 var /*istanbul ignore start*/_apply = require('./patch/apply') /*istanbul ignore end*/;
9595
9596 var /*istanbul ignore start*/_parse = require('./patch/parse') /*istanbul ignore end*/;
9597
9598 var /*istanbul ignore start*/_create = require('./patch/create') /*istanbul igno re end*/;
9599
9600 var /*istanbul ignore start*/_dmp = require('./convert/dmp') /*istanbul ignore e nd*/;
9601
9602 var /*istanbul ignore start*/_xml = require('./convert/xml') /*istanbul ignore e nd*/;
9603
9604 /*istanbul ignore start*/
9605 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'd efault': obj }; }
9606
9607 exports. /*istanbul ignore end*/Diff = _base2['default'];
9608 /*istanbul ignore start*/exports. /*istanbul ignore end*/diffChars = _character. diffChars;
9609 /*istanbul ignore start*/exports. /*istanbul ignore end*/diffWords = _word.diffW ords;
9610 /*istanbul ignore start*/exports. /*istanbul ignore end*/diffWordsWithSpace = _w ord.diffWordsWithSpace;
9611 /*istanbul ignore start*/exports. /*istanbul ignore end*/diffLines = _line.diffL ines;
9612 /*istanbul ignore start*/exports. /*istanbul ignore end*/diffTrimmedLines = _lin e.diffTrimmedLines;
9613 /*istanbul ignore start*/exports. /*istanbul ignore end*/diffSentences = _senten ce.diffSentences;
9614 /*istanbul ignore start*/exports. /*istanbul ignore end*/diffCss = _css.diffCss;
9615 /*istanbul ignore start*/exports. /*istanbul ignore end*/diffJson = _json.diffJs on;
9616 /*istanbul ignore start*/exports. /*istanbul ignore end*/diffArrays = _array.dif fArrays;
9617 /*istanbul ignore start*/exports. /*istanbul ignore end*/structuredPatch = _crea te.structuredPatch;
9618 /*istanbul ignore start*/exports. /*istanbul ignore end*/createTwoFilesPatch = _ create.createTwoFilesPatch;
9619 /*istanbul ignore start*/exports. /*istanbul ignore end*/createPatch = _create.c reatePatch;
9620 /*istanbul ignore start*/exports. /*istanbul ignore end*/applyPatch = _apply.app lyPatch;
9621 /*istanbul ignore start*/exports. /*istanbul ignore end*/applyPatches = _apply.a pplyPatches;
9622 /*istanbul ignore start*/exports. /*istanbul ignore end*/parsePatch = _parse.par sePatch;
9623 /*istanbul ignore start*/exports. /*istanbul ignore end*/convertChangesToDMP = _ dmp.convertChangesToDMP;
9624 /*istanbul ignore start*/exports. /*istanbul ignore end*/convertChangesToXML = _ xml.convertChangesToXML;
9625 /*istanbul ignore start*/exports. /*istanbul ignore end*/canonicalize = _json.ca nonicalize; /* See LICENSE file for terms of use */
9626
9627 /*
9628 * Text diff implementation.
9629 *
9630 * This library supports the following APIS:
9631 * JsDiff.diffChars: Character by character diff
9632 * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
9633 * JsDiff.diffLines: Line based diff
9634 *
9635 * JsDiff.diffCss: Diff targeted at CSS content
9636 *
9637 * These methods are based on the implementation proposed in
9638 * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
9639 * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
9640 */
9641
9642
9643 },{"./convert/dmp":46,"./convert/xml":47,"./diff/array":48,"./diff/base":49,"./d iff/character":50,"./diff/css":51,"./diff/json":52,"./diff/line":53,"./diff/sent ence":54,"./diff/word":55,"./patch/apply":57,"./patch/create":58,"./patch/parse" :59}],57:[function(require,module,exports){
9644 /*istanbul ignore start*/'use strict';
9645
9646 exports.__esModule = true;
9647 exports. /*istanbul ignore end*/applyPatch = applyPatch;
9648 /*istanbul ignore start*/exports. /*istanbul ignore end*/applyPatches = applyPat ches;
9649
9650 var /*istanbul ignore start*/_parse = require('./parse') /*istanbul ignore end*/ ;
9651
9652 var /*istanbul ignore start*/_distanceIterator = require('../util/distance-itera tor') /*istanbul ignore end*/;
9653
9654 /*istanbul ignore start*/
9655 var _distanceIterator2 = _interopRequireDefault(_distanceIterator);
9656
9657 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'd efault': obj }; }
9658
9659 /*istanbul ignore end*/function applyPatch(source, uniDiff) {
9660 /*istanbul ignore start*/var /*istanbul ignore end*/options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
9661
9662 if (typeof uniDiff === 'string') {
9663 uniDiff = /*istanbul ignore start*/(0, _parse.parsePatch) /*istanbul ignore end*/(uniDiff);
9664 }
9665
9666 if (Array.isArray(uniDiff)) {
9667 if (uniDiff.length > 1) {
9668 throw new Error('applyPatch only works with a single input.');
9669 }
9670
9671 uniDiff = uniDiff[0];
9672 }
9673
9674 // Apply the diff to the input
9675 var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
9676 delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
9677 hunks = uniDiff.hunks,
9678 compareLine = options.compareLine || function (lineNumber, line, operation , patchContent) /*istanbul ignore start*/{
9679 return (/*istanbul ignore end*/line === patchContent
9680 );
9681 },
9682 errorCount = 0,
9683 fuzzFactor = options.fuzzFactor || 0,
9684 minLine = 0,
9685 offset = 0,
9686 removeEOFNL = /*istanbul ignore start*/void 0 /*istanbul ignore end*/,
9687 addEOFNL = /*istanbul ignore start*/void 0 /*istanbul ignore end*/;
9688
9689 /**
9690 * Checks if the hunk exactly fits on the provided location
9691 */
9692 function hunkFits(hunk, toPos) {
9693 for (var j = 0; j < hunk.lines.length; j++) {
9694 var line = hunk.lines[j],
9695 operation = line[0],
9696 content = line.substr(1);
9697
9698 if (operation === ' ' || operation === '-') {
9699 // Context sanity check
9700 if (!compareLine(toPos + 1, lines[toPos], operation, content)) {
9701 errorCount++;
9702
9703 if (errorCount > fuzzFactor) {
9704 return false;
9705 }
9706 }
9707 toPos++;
9708 }
9709 }
9710
9711 return true;
9712 }
9713
9714 // Search best fit offsets for each hunk based on the previous ones
9715 for (var i = 0; i < hunks.length; i++) {
9716 var hunk = hunks[i],
9717 maxLine = lines.length - hunk.oldLines,
9718 localOffset = 0,
9719 toPos = offset + hunk.oldStart - 1;
9720
9721 var iterator = /*istanbul ignore start*/(0, _distanceIterator2['default']) / *istanbul ignore end*/(toPos, minLine, maxLine);
9722
9723 for (; localOffset !== undefined; localOffset = iterator()) {
9724 if (hunkFits(hunk, toPos + localOffset)) {
9725 hunk.offset = offset += localOffset;
9726 break;
9727 }
9728 }
9729
9730 if (localOffset === undefined) {
9731 return false;
9732 }
9733
9734 // Set lower text limit to end of the current hunk, so next ones don't try
9735 // to fit over already patched text
9736 minLine = hunk.offset + hunk.oldStart + hunk.oldLines;
9737 }
9738
9739 // Apply patch hunks
9740 for (var _i = 0; _i < hunks.length; _i++) {
9741 var _hunk = hunks[_i],
9742 _toPos = _hunk.offset + _hunk.newStart - 1;
9743 if (_hunk.newLines == 0) {
9744 _toPos++;
9745 }
9746
9747 for (var j = 0; j < _hunk.lines.length; j++) {
9748 var line = _hunk.lines[j],
9749 operation = line[0],
9750 content = line.substr(1),
9751 delimiter = _hunk.linedelimiters[j];
9752
9753 if (operation === ' ') {
9754 _toPos++;
9755 } else if (operation === '-') {
9756 lines.splice(_toPos, 1);
9757 delimiters.splice(_toPos, 1);
9758 /* istanbul ignore else */
9759 } else if (operation === '+') {
9760 lines.splice(_toPos, 0, content);
9761 delimiters.splice(_toPos, 0, delimiter);
9762 _toPos++;
9763 } else if (operation === '\\') {
9764 var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : n ull;
9765 if (previousOperation === '+') {
9766 removeEOFNL = true;
9767 } else if (previousOperation === '-') {
9768 addEOFNL = true;
9769 }
9770 }
9771 }
9772 }
9773
9774 // Handle EOFNL insertion/removal
9775 if (removeEOFNL) {
9776 while (!lines[lines.length - 1]) {
9777 lines.pop();
9778 delimiters.pop();
9779 }
9780 } else if (addEOFNL) {
9781 lines.push('');
9782 delimiters.push('\n');
9783 }
9784 for (var _k = 0; _k < lines.length - 1; _k++) {
9785 lines[_k] = lines[_k] + delimiters[_k];
9786 }
9787 return lines.join('');
9788 }
9789
9790 // Wrapper that supports multiple file patches via callbacks.
9791 function applyPatches(uniDiff, options) {
9792 if (typeof uniDiff === 'string') {
9793 uniDiff = /*istanbul ignore start*/(0, _parse.parsePatch) /*istanbul ignore end*/(uniDiff);
9794 }
9795
9796 var currentIndex = 0;
9797 function processIndex() {
9798 var index = uniDiff[currentIndex++];
9799 if (!index) {
9800 return options.complete();
9801 }
9802
9803 options.loadFile(index, function (err, data) {
9804 if (err) {
9805 return options.complete(err);
9806 }
9807
9808 var updatedContent = applyPatch(data, index, options);
9809 options.patched(index, updatedContent, function (err) {
9810 if (err) {
9811 return options.complete(err);
9812 }
9813
9814 processIndex();
9815 });
9816 });
9817 }
9818 processIndex();
9819 }
9820
9821
9822 },{"../util/distance-iterator":60,"./parse":59}],58:[function(require,module,exp orts){
9823 /*istanbul ignore start*/'use strict';
9824
9825 exports.__esModule = true;
9826 exports. /*istanbul ignore end*/structuredPatch = structuredPatch;
9827 /*istanbul ignore start*/exports. /*istanbul ignore end*/createTwoFilesPatch = c reateTwoFilesPatch;
9828 /*istanbul ignore start*/exports. /*istanbul ignore end*/createPatch = createPat ch;
9829
9830 var /*istanbul ignore start*/_line = require('../diff/line') /*istanbul ignore e nd*/;
9831
9832 /*istanbul ignore start*/
9833 function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr 2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
9834
9835 /*istanbul ignore end*/function structuredPatch(oldFileName, newFileName, oldStr , newStr, oldHeader, newHeader, options) {
9836 if (!options) {
9837 options = {};
9838 }
9839 if (typeof options.context === 'undefined') {
9840 options.context = 4;
9841 }
9842
9843 var diff = /*istanbul ignore start*/(0, _line.diffLines) /*istanbul ignore end */(oldStr, newStr, options);
9844 diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier
9845
9846 function contextLines(lines) {
9847 return lines.map(function (entry) {
9848 return ' ' + entry;
9849 });
9850 }
9851
9852 var hunks = [];
9853 var oldRangeStart = 0,
9854 newRangeStart = 0,
9855 curRange = [],
9856 oldLine = 1,
9857 newLine = 1;
9858 /*istanbul ignore start*/
9859 var _loop = function _loop( /*istanbul ignore end*/i) {
9860 var current = diff[i],
9861 lines = current.lines || current.value.replace(/\n$/, '').split('\n');
9862 current.lines = lines;
9863
9864 if (current.added || current.removed) {
9865 /*istanbul ignore start*/
9866 var _curRange;
9867
9868 /*istanbul ignore end*/
9869 // If we have previous context, start with that
9870 if (!oldRangeStart) {
9871 var prev = diff[i - 1];
9872 oldRangeStart = oldLine;
9873 newRangeStart = newLine;
9874
9875 if (prev) {
9876 curRange = options.context > 0 ? contextLines(prev.lines.slice(-option s.context)) : [];
9877 oldRangeStart -= curRange.length;
9878 newRangeStart -= curRange.length;
9879 }
9880 }
9881
9882 // Output our changes
9883 /*istanbul ignore start*/(_curRange = /*istanbul ignore end*/curRange).pus h. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore sta rt*/_curRange /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArr ay( /*istanbul ignore end*/lines.map(function (entry) {
9884 return (current.added ? '+' : '-') + entry;
9885 })));
9886
9887 // Track the updated file position
9888 if (current.added) {
9889 newLine += lines.length;
9890 } else {
9891 oldLine += lines.length;
9892 }
9893 } else {
9894 // Identical context lines. Track line changes
9895 if (oldRangeStart) {
9896 // Close out any changes that have been output (or join overlapping)
9897 if (lines.length <= options.context * 2 && i < diff.length - 2) {
9898 /*istanbul ignore start*/
9899 var _curRange2;
9900
9901 /*istanbul ignore end*/
9902 // Overlapping
9903 /*istanbul ignore start*/(_curRange2 = /*istanbul ignore end*/curRange ).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignor e start*/_curRange2 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsuma bleArray( /*istanbul ignore end*/contextLines(lines)));
9904 } else {
9905 /*istanbul ignore start*/
9906 var _curRange3;
9907
9908 /*istanbul ignore end*/
9909 // end the range and output
9910 var contextSize = Math.min(lines.length, options.context);
9911 /*istanbul ignore start*/(_curRange3 = /*istanbul ignore end*/curRange ).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignor e start*/_curRange3 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsuma bleArray( /*istanbul ignore end*/contextLines(lines.slice(0, contextSize))));
9912
9913 var hunk = {
9914 oldStart: oldRangeStart,
9915 oldLines: oldLine - oldRangeStart + contextSize,
9916 newStart: newRangeStart,
9917 newLines: newLine - newRangeStart + contextSize,
9918 lines: curRange
9919 };
9920 if (i >= diff.length - 2 && lines.length <= options.context) {
9921 // EOF is inside this hunk
9922 var oldEOFNewline = /\n$/.test(oldStr);
9923 var newEOFNewline = /\n$/.test(newStr);
9924 if (lines.length == 0 && !oldEOFNewline) {
9925 // special case: old has no eol and no trailing context; no-nl can end up before adds
9926 curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file');
9927 } else if (!oldEOFNewline || !newEOFNewline) {
9928 curRange.push('\\ No newline at end of file');
9929 }
9930 }
9931 hunks.push(hunk);
9932
9933 oldRangeStart = 0;
9934 newRangeStart = 0;
9935 curRange = [];
9936 }
9937 }
9938 oldLine += lines.length;
9939 newLine += lines.length;
9940 }
9941 };
9942
9943 for (var i = 0; i < diff.length; i++) {
9944 /*istanbul ignore start*/
9945 _loop( /*istanbul ignore end*/i);
9946 }
9947
9948 return {
9949 oldFileName: oldFileName, newFileName: newFileName,
9950 oldHeader: oldHeader, newHeader: newHeader,
9951 hunks: hunks
9952 };
9953 }
9954
9955 function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader , newHeader, options) {
9956 var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader , newHeader, options);
9957
9958 var ret = [];
9959 if (oldFileName == newFileName) {
9960 ret.push('Index: ' + oldFileName);
9961 }
9962 ret.push('===================================================================' );
9963 ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader));
9964 ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader));
9965
9966 for (var i = 0; i < diff.hunks.length; i++) {
9967 var hunk = diff.hunks[i];
9968 ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');
9969 ret.push.apply(ret, hunk.lines);
9970 }
9971
9972 return ret.join('\n') + '\n';
9973 }
9974
9975 function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
9976 return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newH eader, options);
9977 }
9978
9979
9980 },{"../diff/line":53}],59:[function(require,module,exports){
9981 /*istanbul ignore start*/'use strict';
9982
9983 exports.__esModule = true;
9984 exports. /*istanbul ignore end*/parsePatch = parsePatch;
9985 function parsePatch(uniDiff) {
9986 /*istanbul ignore start*/var /*istanbul ignore end*/options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
9987
9988 var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
9989 delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
9990 list = [],
9991 i = 0;
9992
9993 function parseIndex() {
9994 var index = {};
9995 list.push(index);
9996
9997 // Parse diff metadata
9998 while (i < diffstr.length) {
9999 var line = diffstr[i];
10000
10001 // File header found, end parsing diff metadata
10002 if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) {
10003 break;
10004 }
10005
10006 // Diff index
10007 var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
10008 if (header) {
10009 index.index = header[1];
10010 }
10011
10012 i++;
10013 }
10014
10015 // Parse file headers if they are defined. Unified diff requires them, but
10016 // there's no technical issues to have an isolated hunk without file header
10017 parseFileHeader(index);
10018 parseFileHeader(index);
10019
10020 // Parse hunks
10021 index.hunks = [];
10022
10023 while (i < diffstr.length) {
10024 var _line = diffstr[i];
10025
10026 if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) {
10027 break;
10028 } else if (/^@@/.test(_line)) {
10029 index.hunks.push(parseHunk());
10030 } else if (_line && options.strict) {
10031 // Ignore unexpected content unless in strict mode
10032 throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)) ;
10033 } else {
10034 i++;
10035 }
10036 }
10037 }
10038
10039 // Parses the --- and +++ headers, if none are found, no lines
10040 // are consumed.
10041 function parseFileHeader(index) {
10042 var headerPattern = /^(---|\+\+\+)\s+([\S ]*)(?:\t(.*?)\s*)?$/;
10043 var fileHeader = headerPattern.exec(diffstr[i]);
10044 if (fileHeader) {
10045 var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';
10046 index[keyPrefix + 'FileName'] = fileHeader[2];
10047 index[keyPrefix + 'Header'] = fileHeader[3];
10048
10049 i++;
10050 }
10051 }
10052
10053 // Parses a hunk
10054 // This assumes that we are at the start of a hunk.
10055 function parseHunk() {
10056 var chunkHeaderIndex = i,
10057 chunkHeaderLine = diffstr[i++],
10058 chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d +))? @@/);
10059
10060 var hunk = {
10061 oldStart: +chunkHeader[1],
10062 oldLines: +chunkHeader[2] || 1,
10063 newStart: +chunkHeader[3],
10064 newLines: +chunkHeader[4] || 1,
10065 lines: [],
10066 linedelimiters: []
10067 };
10068
10069 var addCount = 0,
10070 removeCount = 0;
10071 for (; i < diffstr.length; i++) {
10072 // Lines starting with '---' could be mistaken for the "remove line" opera tion
10073 // But they could be the header for the next file. Therefore prune such ca ses out.
10074 if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[ i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {
10075 break;
10076 }
10077 var operation = diffstr[i][0];
10078
10079 if (operation === '+' || operation === '-' || operation === ' ' || operati on === '\\') {
10080 hunk.lines.push(diffstr[i]);
10081 hunk.linedelimiters.push(delimiters[i] || '\n');
10082
10083 if (operation === '+') {
10084 addCount++;
10085 } else if (operation === '-') {
10086 removeCount++;
10087 } else if (operation === ' ') {
10088 addCount++;
10089 removeCount++;
10090 }
10091 } else {
10092 break;
10093 }
10094 }
10095
10096 // Handle the empty block count case
10097 if (!addCount && hunk.newLines === 1) {
10098 hunk.newLines = 0;
10099 }
10100 if (!removeCount && hunk.oldLines === 1) {
10101 hunk.oldLines = 0;
10102 }
10103
10104 // Perform optional sanity checking
10105 if (options.strict) {
10106 if (addCount !== hunk.newLines) {
10107 throw new Error('Added line count did not match for hunk at line ' + (ch unkHeaderIndex + 1));
10108 }
10109 if (removeCount !== hunk.oldLines) {
10110 throw new Error('Removed line count did not match for hunk at line ' + ( chunkHeaderIndex + 1));
10111 }
10112 }
10113
10114 return hunk;
10115 }
10116
10117 while (i < diffstr.length) {
10118 parseIndex();
10119 }
10120
10121 return list;
10122 }
10123
10124
10125 },{}],60:[function(require,module,exports){
10126 /*istanbul ignore start*/"use strict";
10127
10128 exports.__esModule = true;
10129
10130 exports["default"] = /*istanbul ignore end*/function (start, minLine, maxLine) {
10131 var wantForward = true,
10132 backwardExhausted = false,
10133 forwardExhausted = false,
10134 localOffset = 1;
10135
10136 return function iterator() {
10137 if (wantForward && !forwardExhausted) {
10138 if (backwardExhausted) {
10139 localOffset++;
10140 } else {
10141 wantForward = false;
10142 }
10143
10144 // Check if trying to fit beyond text length, and if not, check it fits
10145 // after offset location (or desired location on first iteration)
10146 if (start + localOffset <= maxLine) {
10147 return localOffset;
10148 }
10149
10150 forwardExhausted = true;
10151 }
10152
10153 if (!backwardExhausted) {
10154 if (!forwardExhausted) {
10155 wantForward = true;
10156 }
10157
10158 // Check if trying to fit before text beginning, and if not, check it fits
10159 // before offset location
10160 if (minLine <= start - localOffset) {
10161 return -localOffset++;
10162 }
10163
10164 backwardExhausted = true;
10165 return iterator();
10166 }
10167
10168 // We tried to fit hunk before text beginning and beyond text lenght, then
10169 // hunk can't fit on the text. Return undefined
10170 };
10171 };
10172
10173
10174 },{}],61:[function(require,module,exports){
10175 /*istanbul ignore start*/'use strict';
10176
10177 exports.__esModule = true;
10178 exports. /*istanbul ignore end*/generateOptions = generateOptions;
10179 function generateOptions(options, defaults) {
10180 if (typeof options === 'function') {
10181 defaults.callback = options;
10182 } else if (options) {
10183 for (var name in options) {
10184 /* istanbul ignore else */
10185 if (options.hasOwnProperty(name)) {
10186 defaults[name] = options[name];
10187 }
10188 }
10189 }
10190 return defaults;
10191 }
10192
10193
10194 },{}],62:[function(require,module,exports){
10195 'use strict';
10196
10197 var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
10198
10199 module.exports = function (str) {
10200 if (typeof str !== 'string') {
10201 throw new TypeError('Expected a string');
10202 }
10203
10204 return str.replace(matchOperatorsRe, '\\$&');
10205 };
10206
10207 },{}],63:[function(require,module,exports){
10208 // Copyright Joyent, Inc. and other Node contributors.
10209 //
10210 // Permission is hereby granted, free of charge, to any person obtaining a
10211 // copy of this software and associated documentation files (the
10212 // "Software"), to deal in the Software without restriction, including
10213 // without limitation the rights to use, copy, modify, merge, publish,
10214 // distribute, sublicense, and/or sell copies of the Software, and to permit
10215 // persons to whom the Software is furnished to do so, subject to the
10216 // following conditions:
10217 //
10218 // The above copyright notice and this permission notice shall be included
10219 // in all copies or substantial portions of the Software.
10220 //
10221 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
10222 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
10223 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
10224 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
10225 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
10226 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
10227 // USE OR OTHER DEALINGS IN THE SOFTWARE.
10228
10229 function EventEmitter() {
10230 this._events = this._events || {};
10231 this._maxListeners = this._maxListeners || undefined;
10232 }
10233 module.exports = EventEmitter;
10234
10235 // Backwards-compat with node 0.10.x
10236 EventEmitter.EventEmitter = EventEmitter;
10237
10238 EventEmitter.prototype._events = undefined;
10239 EventEmitter.prototype._maxListeners = undefined;
10240
10241 // By default EventEmitters will print a warning if more than 10 listeners are
10242 // added to it. This is a useful default which helps finding memory leaks.
10243 EventEmitter.defaultMaxListeners = 10;
10244
10245 // Obviously not all Emitters should be limited to 10. This function allows
10246 // that to be increased. Set to zero for unlimited.
10247 EventEmitter.prototype.setMaxListeners = function(n) {
10248 if (!isNumber(n) || n < 0 || isNaN(n))
10249 throw TypeError('n must be a positive number');
10250 this._maxListeners = n;
10251 return this;
10252 };
10253
10254 EventEmitter.prototype.emit = function(type) {
10255 var er, handler, len, args, i, listeners;
10256
10257 if (!this._events)
10258 this._events = {};
10259
10260 // If there is no 'error' event listener then throw.
10261 if (type === 'error') {
10262 if (!this._events.error ||
10263 (isObject(this._events.error) && !this._events.error.length)) {
10264 er = arguments[1];
10265 if (er instanceof Error) {
10266 throw er; // Unhandled 'error' event
10267 } else {
10268 // At least give some kind of context to the user
10269 var err = new Error('Uncaught, unspecified "error" event. (' + er + ')') ;
10270 err.context = er;
10271 throw err;
10272 }
10273 }
10274 }
10275
10276 handler = this._events[type];
10277
10278 if (isUndefined(handler))
10279 return false;
10280
10281 if (isFunction(handler)) {
10282 switch (arguments.length) {
10283 // fast cases
10284 case 1:
10285 handler.call(this);
10286 break;
10287 case 2:
10288 handler.call(this, arguments[1]);
10289 break;
10290 case 3:
10291 handler.call(this, arguments[1], arguments[2]);
10292 break;
10293 // slower
10294 default:
10295 args = Array.prototype.slice.call(arguments, 1);
10296 handler.apply(this, args);
10297 }
10298 } else if (isObject(handler)) {
10299 args = Array.prototype.slice.call(arguments, 1);
10300 listeners = handler.slice();
10301 len = listeners.length;
10302 for (i = 0; i < len; i++)
10303 listeners[i].apply(this, args);
10304 }
10305
10306 return true;
10307 };
10308
10309 EventEmitter.prototype.addListener = function(type, listener) {
10310 var m;
10311
10312 if (!isFunction(listener))
10313 throw TypeError('listener must be a function');
10314
10315 if (!this._events)
10316 this._events = {};
10317
10318 // To avoid recursion in the case that type === "newListener"! Before
10319 // adding it to the listeners, first emit "newListener".
10320 if (this._events.newListener)
10321 this.emit('newListener', type,
10322 isFunction(listener.listener) ?
10323 listener.listener : listener);
10324
10325 if (!this._events[type])
10326 // Optimize the case of one listener. Don't need the extra array object.
10327 this._events[type] = listener;
10328 else if (isObject(this._events[type]))
10329 // If we've already got an array, just append.
10330 this._events[type].push(listener);
10331 else
10332 // Adding the second element, need to change to array.
10333 this._events[type] = [this._events[type], listener];
10334
10335 // Check for listener leak
10336 if (isObject(this._events[type]) && !this._events[type].warned) {
10337 if (!isUndefined(this._maxListeners)) {
10338 m = this._maxListeners;
10339 } else {
10340 m = EventEmitter.defaultMaxListeners;
10341 }
10342
10343 if (m && m > 0 && this._events[type].length > m) {
10344 this._events[type].warned = true;
10345 console.error('(node) warning: possible EventEmitter memory ' +
10346 'leak detected. %d listeners added. ' +
10347 'Use emitter.setMaxListeners() to increase limit.',
10348 this._events[type].length);
10349 if (typeof console.trace === 'function') {
10350 // not supported in IE 10
10351 console.trace();
10352 }
10353 }
10354 }
10355
10356 return this;
10357 };
10358
10359 EventEmitter.prototype.on = EventEmitter.prototype.addListener;
10360
10361 EventEmitter.prototype.once = function(type, listener) {
10362 if (!isFunction(listener))
10363 throw TypeError('listener must be a function');
10364
10365 var fired = false;
10366
10367 function g() {
10368 this.removeListener(type, g);
10369
10370 if (!fired) {
10371 fired = true;
10372 listener.apply(this, arguments);
10373 }
10374 }
10375
10376 g.listener = listener;
10377 this.on(type, g);
10378
10379 return this;
10380 };
10381
10382 // emits a 'removeListener' event iff the listener was removed
10383 EventEmitter.prototype.removeListener = function(type, listener) {
10384 var list, position, length, i;
10385
10386 if (!isFunction(listener))
10387 throw TypeError('listener must be a function');
10388
10389 if (!this._events || !this._events[type])
10390 return this;
10391
10392 list = this._events[type];
10393 length = list.length;
10394 position = -1;
10395
10396 if (list === listener ||
10397 (isFunction(list.listener) && list.listener === listener)) {
10398 delete this._events[type];
10399 if (this._events.removeListener)
10400 this.emit('removeListener', type, listener);
10401
10402 } else if (isObject(list)) {
10403 for (i = length; i-- > 0;) {
10404 if (list[i] === listener ||
10405 (list[i].listener && list[i].listener === listener)) {
10406 position = i;
10407 break;
10408 }
10409 }
10410
10411 if (position < 0)
10412 return this;
10413
10414 if (list.length === 1) {
10415 list.length = 0;
10416 delete this._events[type];
10417 } else {
10418 list.splice(position, 1);
10419 }
10420
10421 if (this._events.removeListener)
10422 this.emit('removeListener', type, listener);
10423 }
10424
10425 return this;
10426 };
10427
10428 EventEmitter.prototype.removeAllListeners = function(type) {
10429 var key, listeners;
10430
10431 if (!this._events)
10432 return this;
10433
10434 // not listening for removeListener, no need to emit
10435 if (!this._events.removeListener) {
10436 if (arguments.length === 0)
10437 this._events = {};
10438 else if (this._events[type])
10439 delete this._events[type];
10440 return this;
10441 }
10442
10443 // emit removeListener for all listeners on all events
10444 if (arguments.length === 0) {
10445 for (key in this._events) {
10446 if (key === 'removeListener') continue;
10447 this.removeAllListeners(key);
10448 }
10449 this.removeAllListeners('removeListener');
10450 this._events = {};
10451 return this;
10452 }
10453
10454 listeners = this._events[type];
10455
10456 if (isFunction(listeners)) {
10457 this.removeListener(type, listeners);
10458 } else if (listeners) {
10459 // LIFO order
10460 while (listeners.length)
10461 this.removeListener(type, listeners[listeners.length - 1]);
10462 }
10463 delete this._events[type];
10464
10465 return this;
10466 };
10467
10468 EventEmitter.prototype.listeners = function(type) {
10469 var ret;
10470 if (!this._events || !this._events[type])
10471 ret = [];
10472 else if (isFunction(this._events[type]))
10473 ret = [this._events[type]];
10474 else
10475 ret = this._events[type].slice();
10476 return ret;
10477 };
10478
10479 EventEmitter.prototype.listenerCount = function(type) {
10480 if (this._events) {
10481 var evlistener = this._events[type];
10482
10483 if (isFunction(evlistener))
10484 return 1;
10485 else if (evlistener)
10486 return evlistener.length;
10487 }
10488 return 0;
10489 };
10490
10491 EventEmitter.listenerCount = function(emitter, type) {
10492 return emitter.listenerCount(type);
10493 };
10494
10495 function isFunction(arg) {
10496 return typeof arg === 'function';
10497 }
10498
10499 function isNumber(arg) {
10500 return typeof arg === 'number';
10501 }
10502
10503 function isObject(arg) {
10504 return typeof arg === 'object' && arg !== null;
10505 }
10506
10507 function isUndefined(arg) {
10508 return arg === void 0;
10509 }
10510
10511 },{}],64:[function(require,module,exports){
10512 (function (process){
10513 // Growl - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)
10514
10515 /**
10516 * Module dependencies.
10517 */
10518
10519 var exec = require('child_process').exec
10520 , fs = require('fs')
10521 , path = require('path')
10522 , exists = fs.existsSync || path.existsSync
10523 , os = require('os')
10524 , quote = JSON.stringify
10525 , cmd;
10526
10527 function which(name) {
10528 var paths = process.env.PATH.split(':');
10529 var loc;
10530
10531 for (var i = 0, len = paths.length; i < len; ++i) {
10532 loc = path.join(paths[i], name);
10533 if (exists(loc)) return loc;
10534 }
10535 }
10536
10537 switch(os.type()) {
10538 case 'Darwin':
10539 if (which('terminal-notifier')) {
10540 cmd = {
10541 type: "Darwin-NotificationCenter"
10542 , pkg: "terminal-notifier"
10543 , msg: '-message'
10544 , title: '-title'
10545 , subtitle: '-subtitle'
10546 , icon: '-appIcon'
10547 , sound: '-sound'
10548 , url: '-open'
10549 , priority: {
10550 cmd: '-execute'
10551 , range: []
10552 }
10553 };
10554 } else {
10555 cmd = {
10556 type: "Darwin-Growl"
10557 , pkg: "growlnotify"
10558 , msg: '-m'
10559 , sticky: '--sticky'
10560 , priority: {
10561 cmd: '--priority'
10562 , range: [
10563 -2
10564 , -1
10565 , 0
10566 , 1
10567 , 2
10568 , "Very Low"
10569 , "Moderate"
10570 , "Normal"
10571 , "High"
10572 , "Emergency"
10573 ]
10574 }
10575 };
10576 }
10577 break;
10578 case 'Linux':
10579 if (which('growl')) {
10580 cmd = {
10581 type: "Linux-Growl"
10582 , pkg: "growl"
10583 , msg: '-m'
10584 , title: '-title'
10585 , subtitle: '-subtitle'
10586 , host: {
10587 cmd: '-H'
10588 , hostname: '192.168.33.1'
10589 }
10590 };
10591 } else {
10592 cmd = {
10593 type: "Linux"
10594 , pkg: "notify-send"
10595 , msg: ''
10596 , sticky: '-t 0'
10597 , icon: '-i'
10598 , priority: {
10599 cmd: '-u'
10600 , range: [
10601 "low"
10602 , "normal"
10603 , "critical"
10604 ]
10605 }
10606 };
10607 }
10608 break;
10609 case 'Windows_NT':
10610 cmd = {
10611 type: "Windows"
10612 , pkg: "growlnotify"
10613 , msg: ''
10614 , sticky: '/s:true'
10615 , title: '/t:'
10616 , icon: '/i:'
10617 , url: '/cu:'
10618 , priority: {
10619 cmd: '/p:'
10620 , range: [
10621 -2
10622 , -1
10623 , 0
10624 , 1
10625 , 2
10626 ]
10627 }
10628 };
10629 break;
10630 }
10631
10632 /**
10633 * Expose `growl`.
10634 */
10635
10636 exports = module.exports = growl;
10637
10638 /**
10639 * Node-growl version.
10640 */
10641
10642 exports.version = '1.4.1'
10643
10644 /**
10645 * Send growl notification _msg_ with _options_.
10646 *
10647 * Options:
10648 *
10649 * - title Notification title
10650 * - sticky Make the notification stick (defaults to false)
10651 * - priority Specify an int or named key (default is 0)
10652 * - name Application name (defaults to growlnotify)
10653 * - sound Sound efect ( in OSx defined in preferences -> sound -> effects) * works only in OSX > 10.8x
10654 * - image
10655 * - path to an icon sets --iconpath
10656 * - path to an image sets --image
10657 * - capitalized word sets --appIcon
10658 * - filename uses extname as --icon
10659 * - otherwise treated as --icon
10660 *
10661 * Examples:
10662 *
10663 * growl('New email')
10664 * growl('5 new emails', { title: 'Thunderbird' })
10665 * growl('5 new emails', { title: 'Thunderbird', sound: 'Purr' })
10666 * growl('Email sent', function(){
10667 * // ... notification sent
10668 * })
10669 *
10670 * @param {string} msg
10671 * @param {object} options
10672 * @param {function} fn
10673 * @api public
10674 */
10675
10676 function growl(msg, options, fn) {
10677 var image
10678 , args
10679 , options = options || {}
10680 , fn = fn || function(){};
10681
10682 if (options.exec) {
10683 cmd = {
10684 type: "Custom"
10685 , pkg: options.exec
10686 , range: []
10687 };
10688 }
10689
10690 // noop
10691 if (!cmd) return fn(new Error('growl not supported on this platform'));
10692 args = [cmd.pkg];
10693
10694 // image
10695 if (image = options.image) {
10696 switch(cmd.type) {
10697 case 'Darwin-Growl':
10698 var flag, ext = path.extname(image).substr(1)
10699 flag = flag || ext == 'icns' && 'iconpath'
10700 flag = flag || /^[A-Z]/.test(image) && 'appIcon'
10701 flag = flag || /^png|gif|jpe?g$/.test(ext) && 'image'
10702 flag = flag || ext && (image = ext) && 'icon'
10703 flag = flag || 'icon'
10704 args.push('--' + flag, quote(image))
10705 break;
10706 case 'Darwin-NotificationCenter':
10707 args.push(cmd.icon, quote(image));
10708 break;
10709 case 'Linux':
10710 args.push(cmd.icon, quote(image));
10711 // libnotify defaults to sticky, set a hint for transient notifications
10712 if (!options.sticky) args.push('--hint=int:transient:1');
10713 break;
10714 case 'Windows':
10715 args.push(cmd.icon + quote(image));
10716 break;
10717 }
10718 }
10719
10720 // sticky
10721 if (options.sticky) args.push(cmd.sticky);
10722
10723 // priority
10724 if (options.priority) {
10725 var priority = options.priority + '';
10726 var checkindexOf = cmd.priority.range.indexOf(priority);
10727 if (~cmd.priority.range.indexOf(priority)) {
10728 args.push(cmd.priority, options.priority);
10729 }
10730 }
10731
10732 //sound
10733 if(options.sound && cmd.type === 'Darwin-NotificationCenter'){
10734 args.push(cmd.sound, options.sound)
10735 }
10736
10737 // name
10738 if (options.name && cmd.type === "Darwin-Growl") {
10739 args.push('--name', options.name);
10740 }
10741
10742 switch(cmd.type) {
10743 case 'Darwin-Growl':
10744 args.push(cmd.msg);
10745 args.push(quote(msg).replace(/\\n/g, '\n'));
10746 if (options.title) args.push(quote(options.title));
10747 break;
10748 case 'Darwin-NotificationCenter':
10749 args.push(cmd.msg);
10750 var stringifiedMsg = quote(msg);
10751 var escapedMsg = stringifiedMsg.replace(/\\n/g, '\n');
10752 args.push(escapedMsg);
10753 if (options.title) {
10754 args.push(cmd.title);
10755 args.push(quote(options.title));
10756 }
10757 if (options.subtitle) {
10758 args.push(cmd.subtitle);
10759 args.push(quote(options.subtitle));
10760 }
10761 if (options.url) {
10762 args.push(cmd.url);
10763 args.push(quote(options.url));
10764 }
10765 break;
10766 case 'Linux-Growl':
10767 args.push(cmd.msg);
10768 args.push(quote(msg).replace(/\\n/g, '\n'));
10769 if (options.title) args.push(quote(options.title));
10770 if (cmd.host) {
10771 args.push(cmd.host.cmd, cmd.host.hostname)
10772 }
10773 break;
10774 case 'Linux':
10775 if (options.title) {
10776 args.push(quote(options.title));
10777 args.push(cmd.msg);
10778 args.push(quote(msg).replace(/\\n/g, '\n'));
10779 } else {
10780 args.push(quote(msg).replace(/\\n/g, '\n'));
10781 }
10782 break;
10783 case 'Windows':
10784 args.push(quote(msg).replace(/\\n/g, '\n'));
10785 if (options.title) args.push(cmd.title + quote(options.title));
10786 if (options.url) args.push(cmd.url + quote(options.url));
10787 break;
10788 case 'Custom':
10789 args[0] = (function(origCommand) {
10790 var message = options.title
10791 ? options.title + ': ' + msg
10792 : msg;
10793 var command = origCommand.replace(/(^|[^%])%s/g, '$1' + quote(message));
10794 if (command === origCommand) args.push(quote(message));
10795 return command;
10796 })(args[0]);
10797 break;
10798 }
10799
10800 // execute
10801 exec(args.join(' '), fn);
10802 };
10803
10804 }).call(this,require('_process'))
10805 },{"_process":82,"child_process":42,"fs":42,"os":80,"path":42}],65:[function(req uire,module,exports){
10806 exports.read = function (buffer, offset, isLE, mLen, nBytes) {
10807 var e, m
10808 var eLen = nBytes * 8 - mLen - 1
10809 var eMax = (1 << eLen) - 1
10810 var eBias = eMax >> 1
10811 var nBits = -7
10812 var i = isLE ? (nBytes - 1) : 0
10813 var d = isLE ? -1 : 1
10814 var s = buffer[offset + i]
10815
10816 i += d
10817
10818 e = s & ((1 << (-nBits)) - 1)
10819 s >>= (-nBits)
10820 nBits += eLen
10821 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
10822
10823 m = e & ((1 << (-nBits)) - 1)
10824 e >>= (-nBits)
10825 nBits += mLen
10826 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
10827
10828 if (e === 0) {
10829 e = 1 - eBias
10830 } else if (e === eMax) {
10831 return m ? NaN : ((s ? -1 : 1) * Infinity)
10832 } else {
10833 m = m + Math.pow(2, mLen)
10834 e = e - eBias
10835 }
10836 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
10837 }
10838
10839 exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
10840 var e, m, c
10841 var eLen = nBytes * 8 - mLen - 1
10842 var eMax = (1 << eLen) - 1
10843 var eBias = eMax >> 1
10844 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
10845 var i = isLE ? 0 : (nBytes - 1)
10846 var d = isLE ? 1 : -1
10847 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
10848
10849 value = Math.abs(value)
10850
10851 if (isNaN(value) || value === Infinity) {
10852 m = isNaN(value) ? 1 : 0
10853 e = eMax
10854 } else {
10855 e = Math.floor(Math.log(value) / Math.LN2)
10856 if (value * (c = Math.pow(2, -e)) < 1) {
10857 e--
10858 c *= 2
10859 }
10860 if (e + eBias >= 1) {
10861 value += rt / c
10862 } else {
10863 value += rt * Math.pow(2, 1 - eBias)
10864 }
10865 if (value * c >= 2) {
10866 e++
10867 c /= 2
10868 }
10869
10870 if (e + eBias >= eMax) {
10871 m = 0
10872 e = eMax
10873 } else if (e + eBias >= 1) {
10874 m = (value * c - 1) * Math.pow(2, mLen)
10875 e = e + eBias
10876 } else {
10877 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
10878 e = 0
10879 }
10880 }
10881
10882 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
10883
10884 e = (e << mLen) | m
10885 eLen += mLen
10886 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) { }
10887
10888 buffer[offset + i - d] |= s * 128
10889 }
10890
10891 },{}],66:[function(require,module,exports){
10892 if (typeof Object.create === 'function') {
10893 // implementation from standard node.js 'util' module
10894 module.exports = function inherits(ctor, superCtor) {
10895 ctor.super_ = superCtor
10896 ctor.prototype = Object.create(superCtor.prototype, {
10897 constructor: {
10898 value: ctor,
10899 enumerable: false,
10900 writable: true,
10901 configurable: true
10902 }
10903 });
10904 };
10905 } else {
10906 // old school shim for old browsers
10907 module.exports = function inherits(ctor, superCtor) {
10908 ctor.super_ = superCtor
10909 var TempCtor = function () {}
10910 TempCtor.prototype = superCtor.prototype
10911 ctor.prototype = new TempCtor()
10912 ctor.prototype.constructor = ctor
10913 }
10914 }
10915
10916 },{}],67:[function(require,module,exports){
10917 /*!
10918 * Determine if an object is a Buffer
10919 *
10920 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
10921 * @license MIT
10922 */
10923
10924 // The _isBuffer check is for Safari 5-7 support, because it's missing
10925 // Object.prototype.constructor. Remove this eventually
10926 module.exports = function (obj) {
10927 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
10928 }
10929
10930 function isBuffer (obj) {
10931 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
10932 }
10933
10934 // For Node v0.10 support. Remove this eventually.
10935 function isSlowBuffer (obj) {
10936 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function ' && isBuffer(obj.slice(0, 0))
10937 }
10938
10939 },{}],68:[function(require,module,exports){
10940 var toString = {}.toString;
10941
10942 module.exports = Array.isArray || function (arr) {
10943 return toString.call(arr) == '[object Array]';
10944 };
10945
10946 },{}],69:[function(require,module,exports){
10947 (function (global){
10948 /*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cam bridge | http://kit.mit-license.org */
10949 ;(function () {
10950 // Detect the `define` function exposed by asynchronous module loaders. The
10951 // strict `define` check is necessary for compatibility with `r.js`.
10952 var isLoader = false;
10953
10954 // A set of types used to distinguish objects from primitives.
10955 var objectTypes = {
10956 "function": true,
10957 "object": true
10958 };
10959
10960 // Detect the `exports` object exposed by CommonJS implementations.
10961 var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
10962
10963 // Use the `global` object exposed by Node (including Browserify via
10964 // `insert-module-globals`), Narwhal, and Ringo as the default context,
10965 // and the `window` object in browsers. Rhino exports a `global` function
10966 // instead.
10967 var root = objectTypes[typeof window] && window || this,
10968 freeGlobal = freeExports && objectTypes[typeof module] && module && !modul e.nodeType && typeof global == "object" && global;
10969
10970 if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) {
10971 root = freeGlobal;
10972 }
10973
10974 // Public: Initializes JSON 3 using the given `context` object, attaching the
10975 // `stringify` and `parse` functions to the specified `exports` object.
10976 function runInContext(context, exports) {
10977 context || (context = root["Object"]());
10978 exports || (exports = root["Object"]());
10979
10980 // Native constructor aliases.
10981 var Number = context["Number"] || root["Number"],
10982 String = context["String"] || root["String"],
10983 Object = context["Object"] || root["Object"],
10984 Date = context["Date"] || root["Date"],
10985 SyntaxError = context["SyntaxError"] || root["SyntaxError"],
10986 TypeError = context["TypeError"] || root["TypeError"],
10987 Math = context["Math"] || root["Math"],
10988 nativeJSON = context["JSON"] || root["JSON"];
10989
10990 // Delegate to the native `stringify` and `parse` implementations.
10991 if (typeof nativeJSON == "object" && nativeJSON) {
10992 exports.stringify = nativeJSON.stringify;
10993 exports.parse = nativeJSON.parse;
10994 }
10995
10996 // Convenience aliases.
10997 var objectProto = Object.prototype,
10998 getClass = objectProto.toString,
10999 isProperty, forEach, undef;
11000
11001 // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
11002 var isExtended = new Date(-3509827334573292);
11003 try {
11004 // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
11005 // results for certain dates in Opera >= 10.53.
11006 isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMo nth() === 0 && isExtended.getUTCDate() === 1 &&
11007 // Safari < 2.0.2 stores the internal millisecond time value correctly,
11008 // but clips the values returned by the date methods to the range of
11009 // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
11010 isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && is Extended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
11011 } catch (exception) {}
11012
11013 // Internal: Determines whether the native `JSON.stringify` and `parse`
11014 // implementations are spec-compliant. Based on work by Ken Snyder.
11015 function has(name) {
11016 if (has[name] !== undef) {
11017 // Return cached feature test result.
11018 return has[name];
11019 }
11020 var isSupported;
11021 if (name == "bug-string-char-index") {
11022 // IE <= 7 doesn't support accessing string characters using square
11023 // bracket notation. IE 8 only supports this for primitives.
11024 isSupported = "a"[0] != "a";
11025 } else if (name == "json") {
11026 // Indicates whether both `JSON.stringify` and `JSON.parse` are
11027 // supported.
11028 isSupported = has("json-stringify") && has("json-parse");
11029 } else {
11030 var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t "]}';
11031 // Test `JSON.stringify`.
11032 if (name == "json-stringify") {
11033 var stringify = exports.stringify, stringifySupported = typeof stringi fy == "function" && isExtended;
11034 if (stringifySupported) {
11035 // A test function object with a custom `toJSON` method.
11036 (value = function () {
11037 return 1;
11038 }).toJSON = value;
11039 try {
11040 stringifySupported =
11041 // Firefox 3.1b1 and b2 serialize string, number, and boolean
11042 // primitives as object literals.
11043 stringify(0) === "0" &&
11044 // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as obje ct
11045 // literals.
11046 stringify(new Number()) === "0" &&
11047 stringify(new String()) == '""' &&
11048 // FF 3.1b1, 2 throw an error if the value is `null`, `undefined `, or
11049 // does not define a canonical JSON representation (this applies to
11050 // objects with `toJSON` properties as well, *unless* they are n ested
11051 // within an object or array).
11052 stringify(getClass) === undef &&
11053 // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
11054 // FF 3.1b3 pass this test.
11055 stringify(undef) === undef &&
11056 // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
11057 // respectively, if the value is omitted entirely.
11058 stringify() === undef &&
11059 // FF 3.1b1, 2 throw an error if the given value is not a number ,
11060 // string, array, object, Boolean, or `null` literal. This appli es to
11061 // objects with custom `toJSON` methods as well, unless they are nested
11062 // inside object or array literals. YUI 3.0.0b1 ignores custom ` toJSON`
11063 // methods entirely.
11064 stringify(value) === "1" &&
11065 stringify([value]) == "[1]" &&
11066 // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
11067 // `"[null]"`.
11068 stringify([undef]) == "[null]" &&
11069 // YUI 3.0.0b1 fails to serialize `null` literals.
11070 stringify(null) == "null" &&
11071 // FF 3.1b1, 2 halts serialization if an array contains a functi on:
11072 // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
11073 // elides non-JSON values from objects and arrays, unless they
11074 // define custom `toJSON` methods.
11075 stringify([undef, getClass, null]) == "[null,null,null]" &&
11076 // Simple serialization test. FF 3.1b1 uses Unicode escape seque nces
11077 // where character escape codes are expected (e.g., `\b` => `\u0 008`).
11078 stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
11079 // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
11080 stringify(null, value) === "1" &&
11081 stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
11082 // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
11083 // serialize extended years.
11084 stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
11085 // The milliseconds are optional in ES 5, but required in 5.1.
11086 stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
11087 // Firefox <= 11.0 incorrectly serializes years prior to 0 as ne gative
11088 // four-digit years instead of six-digit years. Credits: @Yaffle .
11089 stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.00 0Z"' &&
11090 // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize mill isecond
11091 // values less than 1000. Credits: @Yaffle.
11092 stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
11093 } catch (exception) {
11094 stringifySupported = false;
11095 }
11096 }
11097 isSupported = stringifySupported;
11098 }
11099 // Test `JSON.parse`.
11100 if (name == "json-parse") {
11101 var parse = exports.parse;
11102 if (typeof parse == "function") {
11103 try {
11104 // FF 3.1b1, b2 will throw an exception if a bare literal is provi ded.
11105 // Conforming implementations should also coerce the initial argum ent to
11106 // a string prior to parsing.
11107 if (parse("0") === 0 && !parse(false)) {
11108 // Simple parsing test.
11109 value = parse(serialized);
11110 var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
11111 if (parseSupported) {
11112 try {
11113 // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in stri ngs.
11114 parseSupported = !parse('"\t"');
11115 } catch (exception) {}
11116 if (parseSupported) {
11117 try {
11118 // FF 4.0 and 4.0.1 allow leading `+` signs and leading
11119 // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
11120 // certain octal literals.
11121 parseSupported = parse("01") !== 1;
11122 } catch (exception) {}
11123 }
11124 if (parseSupported) {
11125 try {
11126 // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decima l
11127 // points. These environments, along with FF 3.1b1 and 2,
11128 // also allow trailing commas in JSON objects and arrays.
11129 parseSupported = parse("1.") !== 1;
11130 } catch (exception) {}
11131 }
11132 }
11133 }
11134 } catch (exception) {
11135 parseSupported = false;
11136 }
11137 }
11138 isSupported = parseSupported;
11139 }
11140 }
11141 return has[name] = !!isSupported;
11142 }
11143
11144 if (!has("json")) {
11145 // Common `[[Class]]` name aliases.
11146 var functionClass = "[object Function]",
11147 dateClass = "[object Date]",
11148 numberClass = "[object Number]",
11149 stringClass = "[object String]",
11150 arrayClass = "[object Array]",
11151 booleanClass = "[object Boolean]";
11152
11153 // Detect incomplete support for accessing string characters by index.
11154 var charIndexBuggy = has("bug-string-char-index");
11155
11156 // Define additional utility methods if the `Date` methods are buggy.
11157 if (!isExtended) {
11158 var floor = Math.floor;
11159 // A mapping between the months of the year and the number of days betwe en
11160 // January 1st and the first of the respective month.
11161 var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
11162 // Internal: Calculates the number of days between the Unix epoch and th e
11163 // first day of the given month.
11164 var getDay = function (year, month) {
11165 return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (mon th = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 16 01 + month) / 400);
11166 };
11167 }
11168
11169 // Internal: Determines if a property is a direct property of the given
11170 // object. Delegates to the native `Object#hasOwnProperty` method.
11171 if (!(isProperty = objectProto.hasOwnProperty)) {
11172 isProperty = function (property) {
11173 var members = {}, constructor;
11174 if ((members.__proto__ = null, members.__proto__ = {
11175 // The *proto* property cannot be set multiple times in recent
11176 // versions of Firefox and SeaMonkey.
11177 "toString": 1
11178 }, members).toString != getClass) {
11179 // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
11180 // supports the mutable *proto* property.
11181 isProperty = function (property) {
11182 // Capture and break the object's prototype chain (see section 8.6 .2
11183 // of the ES 5.1 spec). The parenthesized expression prevents an
11184 // unsafe transformation by the Closure Compiler.
11185 var original = this.__proto__, result = property in (this.__proto_ _ = null, this);
11186 // Restore the original prototype chain.
11187 this.__proto__ = original;
11188 return result;
11189 };
11190 } else {
11191 // Capture a reference to the top-level `Object` constructor.
11192 constructor = members.constructor;
11193 // Use the `constructor` property to simulate `Object#hasOwnProperty ` in
11194 // other environments.
11195 isProperty = function (property) {
11196 var parent = (this.constructor || constructor).prototype;
11197 return property in this && !(property in parent && this[property] === parent[property]);
11198 };
11199 }
11200 members = null;
11201 return isProperty.call(this, property);
11202 };
11203 }
11204
11205 // Internal: Normalizes the `for...in` iteration algorithm across
11206 // environments. Each enumerated key is yielded to a `callback` function.
11207 forEach = function (object, callback) {
11208 var size = 0, Properties, members, property;
11209
11210 // Tests for bugs in the current environment's `for...in` algorithm. The
11211 // `valueOf` property inherits the non-enumerable flag from
11212 // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
11213 (Properties = function () {
11214 this.valueOf = 0;
11215 }).prototype.valueOf = 0;
11216
11217 // Iterate over a new instance of the `Properties` class.
11218 members = new Properties();
11219 for (property in members) {
11220 // Ignore all properties inherited from `Object.prototype`.
11221 if (isProperty.call(members, property)) {
11222 size++;
11223 }
11224 }
11225 Properties = members = null;
11226
11227 // Normalize the iteration algorithm.
11228 if (!size) {
11229 // A list of non-enumerable properties inherited from `Object.prototyp e`.
11230 members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumera ble", "isPrototypeOf", "hasOwnProperty", "constructor"];
11231 // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerab le
11232 // properties.
11233 forEach = function (object, callback) {
11234 var isFunction = getClass.call(object) == functionClass, property, l ength;
11235 var hasProperty = !isFunction && typeof object.constructor != "funct ion" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || is Property;
11236 for (property in object) {
11237 // Gecko <= 1.0 enumerates the `prototype` property of functions u nder
11238 // certain conditions; IE does not.
11239 if (!(isFunction && property == "prototype") && hasProperty.call(o bject, property)) {
11240 callback(property);
11241 }
11242 }
11243 // Manually invoke the callback for each non-enumerable property.
11244 for (length = members.length; property = members[--length]; hasPrope rty.call(object, property) && callback(property));
11245 };
11246 } else if (size == 2) {
11247 // Safari <= 2.0.4 enumerates shadowed properties twice.
11248 forEach = function (object, callback) {
11249 // Create a set of iterated properties.
11250 var members = {}, isFunction = getClass.call(object) == functionClas s, property;
11251 for (property in object) {
11252 // Store each property name to prevent double enumeration. The
11253 // `prototype` property of functions is not enumerated due to cros s-
11254 // environment inconsistencies.
11255 if (!(isFunction && property == "prototype") && !isProperty.call(m embers, property) && (members[property] = 1) && isProperty.call(object, property )) {
11256 callback(property);
11257 }
11258 }
11259 };
11260 } else {
11261 // No bugs detected; use the standard `for...in` algorithm.
11262 forEach = function (object, callback) {
11263 var isFunction = getClass.call(object) == functionClass, property, i sConstructor;
11264 for (property in object) {
11265 if (!(isFunction && property == "prototype") && isProperty.call(ob ject, property) && !(isConstructor = property === "constructor")) {
11266 callback(property);
11267 }
11268 }
11269 // Manually invoke the callback for the `constructor` property due t o
11270 // cross-environment inconsistencies.
11271 if (isConstructor || isProperty.call(object, (property = "constructo r"))) {
11272 callback(property);
11273 }
11274 };
11275 }
11276 return forEach(object, callback);
11277 };
11278
11279 // Public: Serializes a JavaScript `value` as a JSON string. The optional
11280 // `filter` argument may specify either a function that alters how object and
11281 // array members are serialized, or an array of strings and numbers that
11282 // indicates which properties should be serialized. The optional `width`
11283 // argument may be either a string or number that specifies the indentatio n
11284 // level of the output.
11285 if (!has("json-stringify")) {
11286 // Internal: A map of control characters and their escaped equivalents.
11287 var Escapes = {
11288 92: "\\\\",
11289 34: '\\"',
11290 8: "\\b",
11291 12: "\\f",
11292 10: "\\n",
11293 13: "\\r",
11294 9: "\\t"
11295 };
11296
11297 // Internal: Converts `value` into a zero-padded string such that its
11298 // length is at least equal to `width`. The `width` must be <= 6.
11299 var leadingZeroes = "000000";
11300 var toPaddedString = function (width, value) {
11301 // The `|| 0` expression is necessary to work around a bug in
11302 // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
11303 return (leadingZeroes + (value || 0)).slice(-width);
11304 };
11305
11306 // Internal: Double-quotes a string `value`, replacing all ASCII control
11307 // characters (characters with code unit values between 0 and 31) with
11308 // their escaped equivalents. This is an implementation of the
11309 // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
11310 var unicodePrefix = "\\u00";
11311 var quote = function (value) {
11312 var result = '"', index = 0, length = value.length, useCharIndex = !ch arIndexBuggy || length > 10;
11313 var symbols = useCharIndex && (charIndexBuggy ? value.split("") : valu e);
11314 for (; index < length; index++) {
11315 var charCode = value.charCodeAt(index);
11316 // If the character is a control character, append its Unicode or
11317 // shorthand escape sequence; otherwise, append the character as-is.
11318 switch (charCode) {
11319 case 8: case 9: case 10: case 12: case 13: case 34: case 92:
11320 result += Escapes[charCode];
11321 break;
11322 default:
11323 if (charCode < 32) {
11324 result += unicodePrefix + toPaddedString(2, charCode.toString( 16));
11325 break;
11326 }
11327 result += useCharIndex ? symbols[index] : value.charAt(index);
11328 }
11329 }
11330 return result + '"';
11331 };
11332
11333 // Internal: Recursively serializes an object. Implements the
11334 // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
11335 var serialize = function (property, object, callback, properties, whites pace, indentation, stack) {
11336 var value, className, year, month, date, time, hours, minutes, seconds , milliseconds, results, element, index, length, prefix, result;
11337 try {
11338 // Necessary for host object support.
11339 value = object[property];
11340 } catch (exception) {}
11341 if (typeof value == "object" && value) {
11342 className = getClass.call(value);
11343 if (className == dateClass && !isProperty.call(value, "toJSON")) {
11344 if (value > -1 / 0 && value < 1 / 0) {
11345 // Dates are serialized according to the `Date#toJSON` method
11346 // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
11347 // for the ISO 8601 date time string format.
11348 if (getDay) {
11349 // Manually compute the year, month, date, hours, minutes,
11350 // seconds, and milliseconds if the `getUTC*` methods are
11351 // buggy. Adapted from @Yaffle's `date-shim` project.
11352 date = floor(value / 864e5);
11353 for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1 , 0) <= date; year++);
11354 for (month = floor((date - getDay(year, 0)) / 30.42); getDay(y ear, month + 1) <= date; month++);
11355 date = 1 + date - getDay(year, month);
11356 // The `time` value specifies the time within the day (see ES
11357 // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is use d
11358 // to compute `A modulo B`, as the `%` operator does not
11359 // correspond to the `modulo` operation for negative numbers.
11360 time = (value % 864e5 + 864e5) % 864e5;
11361 // The hours, minutes, seconds, and milliseconds are obtained by
11362 // decomposing the time within the day. See section 15.9.1.10.
11363 hours = floor(time / 36e5) % 24;
11364 minutes = floor(time / 6e4) % 60;
11365 seconds = floor(time / 1e3) % 60;
11366 milliseconds = time % 1e3;
11367 } else {
11368 year = value.getUTCFullYear();
11369 month = value.getUTCMonth();
11370 date = value.getUTCDate();
11371 hours = value.getUTCHours();
11372 minutes = value.getUTCMinutes();
11373 seconds = value.getUTCSeconds();
11374 milliseconds = value.getUTCMilliseconds();
11375 }
11376 // Serialize extended years correctly.
11377 value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toP addedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
11378 "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, d ate) +
11379 // Months, dates, hours, minutes, and seconds should have two
11380 // digits; milliseconds should have three.
11381 "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minut es) + ":" + toPaddedString(2, seconds) +
11382 // Milliseconds are optional in ES 5.0, but required in 5.1.
11383 "." + toPaddedString(3, milliseconds) + "Z";
11384 } else {
11385 value = null;
11386 }
11387 } else if (typeof value.toJSON == "function" && ((className != numbe rClass && className != stringClass && className != arrayClass) || isProperty.cal l(value, "toJSON"))) {
11388 // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
11389 // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
11390 // ignores all `toJSON` methods on these objects unless they are
11391 // defined directly on an instance.
11392 value = value.toJSON(property);
11393 }
11394 }
11395 if (callback) {
11396 // If a replacement function was provided, call it to obtain the val ue
11397 // for serialization.
11398 value = callback.call(object, property, value);
11399 }
11400 if (value === null) {
11401 return "null";
11402 }
11403 className = getClass.call(value);
11404 if (className == booleanClass) {
11405 // Booleans are represented literally.
11406 return "" + value;
11407 } else if (className == numberClass) {
11408 // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
11409 // `"null"`.
11410 return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
11411 } else if (className == stringClass) {
11412 // Strings are double-quoted and escaped.
11413 return quote("" + value);
11414 }
11415 // Recursively serialize objects and arrays.
11416 if (typeof value == "object") {
11417 // Check for cyclic structures. This is a linear search; performance
11418 // is inversely proportional to the number of unique nested objects.
11419 for (length = stack.length; length--;) {
11420 if (stack[length] === value) {
11421 // Cyclic structures cannot be serialized by `JSON.stringify`.
11422 throw TypeError();
11423 }
11424 }
11425 // Add the object to the stack of traversed objects.
11426 stack.push(value);
11427 results = [];
11428 // Save the current indentation level and indent one additional leve l.
11429 prefix = indentation;
11430 indentation += whitespace;
11431 if (className == arrayClass) {
11432 // Recursively serialize array elements.
11433 for (index = 0, length = value.length; index < length; index++) {
11434 element = serialize(index, value, callback, properties, whitespa ce, indentation, stack);
11435 results.push(element === undef ? "null" : element);
11436 }
11437 result = results.length ? (whitespace ? "[\n" + indentation + resu lts.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
11438 } else {
11439 // Recursively serialize object members. Members are selected from
11440 // either a user-specified list of property names, or the object
11441 // itself.
11442 forEach(properties || value, function (property) {
11443 var element = serialize(property, value, callback, properties, w hitespace, indentation, stack);
11444 if (element !== undef) {
11445 // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
11446 // is not the empty string, let `member` {quote(property) + ": "}
11447 // be the concatenation of `member` and the `space` character. "
11448 // The "`space` character" refers to the literal space
11449 // character, not the `space` {width} argument provided to
11450 // `JSON.stringify`.
11451 results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
11452 }
11453 });
11454 result = results.length ? (whitespace ? "{\n" + indentation + resu lts.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
11455 }
11456 // Remove the object from the traversed object stack.
11457 stack.pop();
11458 return result;
11459 }
11460 };
11461
11462 // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
11463 exports.stringify = function (source, filter, width) {
11464 var whitespace, callback, properties, className;
11465 if (objectTypes[typeof filter] && filter) {
11466 if ((className = getClass.call(filter)) == functionClass) {
11467 callback = filter;
11468 } else if (className == arrayClass) {
11469 // Convert the property names array into a makeshift set.
11470 properties = {};
11471 for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stri ngClass || className == numberClass) && (properties[value] = 1));
11472 }
11473 }
11474 if (width) {
11475 if ((className = getClass.call(width)) == numberClass) {
11476 // Convert the `width` to an integer and create a string containin g
11477 // `width` number of space characters.
11478 if ((width -= width % 1) > 0) {
11479 for (whitespace = "", width > 10 && (width = 10); whitespace.len gth < width; whitespace += " ");
11480 }
11481 } else if (className == stringClass) {
11482 whitespace = width.length <= 10 ? width : width.slice(0, 10);
11483 }
11484 }
11485 // Opera <= 7.54u2 discards the values associated with empty string ke ys
11486 // (`""`) only if they are used directly within an object member list
11487 // (e.g., `!("" in { "": 1})`).
11488 return serialize("", (value = {}, value[""] = source, value), callback , properties, whitespace, "", []);
11489 };
11490 }
11491
11492 // Public: Parses a JSON source string.
11493 if (!has("json-parse")) {
11494 var fromCharCode = String.fromCharCode;
11495
11496 // Internal: A map of escaped control characters and their unescaped
11497 // equivalents.
11498 var Unescapes = {
11499 92: "\\",
11500 34: '"',
11501 47: "/",
11502 98: "\b",
11503 116: "\t",
11504 110: "\n",
11505 102: "\f",
11506 114: "\r"
11507 };
11508
11509 // Internal: Stores the parser state.
11510 var Index, Source;
11511
11512 // Internal: Resets the parser state and throws a `SyntaxError`.
11513 var abort = function () {
11514 Index = Source = null;
11515 throw SyntaxError();
11516 };
11517
11518 // Internal: Returns the next token, or `"$"` if the parser has reached
11519 // the end of the source string. A token may be a string, number, `null`
11520 // literal, or Boolean literal.
11521 var lex = function () {
11522 var source = Source, length = source.length, value, begin, position, i sSigned, charCode;
11523 while (Index < length) {
11524 charCode = source.charCodeAt(Index);
11525 switch (charCode) {
11526 case 9: case 10: case 13: case 32:
11527 // Skip whitespace tokens, including tabs, carriage returns, lin e
11528 // feeds, and space characters.
11529 Index++;
11530 break;
11531 case 123: case 125: case 91: case 93: case 58: case 44:
11532 // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
11533 // the current position.
11534 value = charIndexBuggy ? source.charAt(Index) : source[Index];
11535 Index++;
11536 return value;
11537 case 34:
11538 // `"` delimits a JSON string; advance to the next character and
11539 // begin parsing the string. String tokens are prefixed with the
11540 // sentinel `@` character to distinguish them from punctuators a nd
11541 // end-of-string tokens.
11542 for (value = "@", Index++; Index < length;) {
11543 charCode = source.charCodeAt(Index);
11544 if (charCode < 32) {
11545 // Unescaped ASCII control characters (those with a code uni t
11546 // less than the space character) are not permitted.
11547 abort();
11548 } else if (charCode == 92) {
11549 // A reverse solidus (`\`) marks the beginning of an escaped
11550 // control character (including `"`, `\`, and `/`) or Unicod e
11551 // escape sequence.
11552 charCode = source.charCodeAt(++Index);
11553 switch (charCode) {
11554 case 92: case 34: case 47: case 98: case 116: case 110: ca se 102: case 114:
11555 // Revive escaped control characters.
11556 value += Unescapes[charCode];
11557 Index++;
11558 break;
11559 case 117:
11560 // `\u` marks the beginning of a Unicode escape sequence .
11561 // Advance to the first character and validate the
11562 // four-digit code point.
11563 begin = ++Index;
11564 for (position = Index + 4; Index < position; Index++) {
11565 charCode = source.charCodeAt(Index);
11566 // A valid sequence comprises four hexdigits (case-
11567 // insensitive) that form a single hexadecimal value.
11568 if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
11569 // Invalid Unicode escape sequence.
11570 abort();
11571 }
11572 }
11573 // Revive the escaped character.
11574 value += fromCharCode("0x" + source.slice(begin, Index)) ;
11575 break;
11576 default:
11577 // Invalid escape sequence.
11578 abort();
11579 }
11580 } else {
11581 if (charCode == 34) {
11582 // An unescaped double-quote character marks the end of th e
11583 // string.
11584 break;
11585 }
11586 charCode = source.charCodeAt(Index);
11587 begin = Index;
11588 // Optimize for the common case where a string is valid.
11589 while (charCode >= 32 && charCode != 92 && charCode != 34) {
11590 charCode = source.charCodeAt(++Index);
11591 }
11592 // Append the string as-is.
11593 value += source.slice(begin, Index);
11594 }
11595 }
11596 if (source.charCodeAt(Index) == 34) {
11597 // Advance to the next character and return the revived string .
11598 Index++;
11599 return value;
11600 }
11601 // Unterminated string.
11602 abort();
11603 default:
11604 // Parse numbers and literals.
11605 begin = Index;
11606 // Advance past the negative sign, if one is specified.
11607 if (charCode == 45) {
11608 isSigned = true;
11609 charCode = source.charCodeAt(++Index);
11610 }
11611 // Parse an integer or floating-point value.
11612 if (charCode >= 48 && charCode <= 57) {
11613 // Leading zeroes are interpreted as octal literals.
11614 if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1 )), charCode >= 48 && charCode <= 57)) {
11615 // Illegal octal literal.
11616 abort();
11617 }
11618 isSigned = false;
11619 // Parse the integer component.
11620 for (; Index < length && ((charCode = source.charCodeAt(Index) ), charCode >= 48 && charCode <= 57); Index++);
11621 // Floats cannot contain a leading decimal point; however, thi s
11622 // case is already accounted for by the parser.
11623 if (source.charCodeAt(Index) == 46) {
11624 position = ++Index;
11625 // Parse the decimal component.
11626 for (; position < length && ((charCode = source.charCodeAt(p osition)), charCode >= 48 && charCode <= 57); position++);
11627 if (position == Index) {
11628 // Illegal trailing decimal.
11629 abort();
11630 }
11631 Index = position;
11632 }
11633 // Parse exponents. The `e` denoting the exponent is
11634 // case-insensitive.
11635 charCode = source.charCodeAt(Index);
11636 if (charCode == 101 || charCode == 69) {
11637 charCode = source.charCodeAt(++Index);
11638 // Skip past the sign following the exponent, if one is
11639 // specified.
11640 if (charCode == 43 || charCode == 45) {
11641 Index++;
11642 }
11643 // Parse the exponential component.
11644 for (position = Index; position < length && ((charCode = sou rce.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
11645 if (position == Index) {
11646 // Illegal empty exponent.
11647 abort();
11648 }
11649 Index = position;
11650 }
11651 // Coerce the parsed value to a JavaScript number.
11652 return +source.slice(begin, Index);
11653 }
11654 // A negative sign may only precede numbers.
11655 if (isSigned) {
11656 abort();
11657 }
11658 // `true`, `false`, and `null` literals.
11659 if (source.slice(Index, Index + 4) == "true") {
11660 Index += 4;
11661 return true;
11662 } else if (source.slice(Index, Index + 5) == "false") {
11663 Index += 5;
11664 return false;
11665 } else if (source.slice(Index, Index + 4) == "null") {
11666 Index += 4;
11667 return null;
11668 }
11669 // Unrecognized token.
11670 abort();
11671 }
11672 }
11673 // Return the sentinel `$` character if the parser has reached the end
11674 // of the source string.
11675 return "$";
11676 };
11677
11678 // Internal: Parses a JSON `value` token.
11679 var get = function (value) {
11680 var results, hasMembers;
11681 if (value == "$") {
11682 // Unexpected end of input.
11683 abort();
11684 }
11685 if (typeof value == "string") {
11686 if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
11687 // Remove the sentinel `@` character.
11688 return value.slice(1);
11689 }
11690 // Parse object and array literals.
11691 if (value == "[") {
11692 // Parses a JSON array, returning a new JavaScript array.
11693 results = [];
11694 for (;; hasMembers || (hasMembers = true)) {
11695 value = lex();
11696 // A closing square bracket marks the end of the array literal.
11697 if (value == "]") {
11698 break;
11699 }
11700 // If the array literal contains elements, the current token
11701 // should be a comma separating the previous element from the
11702 // next.
11703 if (hasMembers) {
11704 if (value == ",") {
11705 value = lex();
11706 if (value == "]") {
11707 // Unexpected trailing `,` in array literal.
11708 abort();
11709 }
11710 } else {
11711 // A `,` must separate each array element.
11712 abort();
11713 }
11714 }
11715 // Elisions and leading commas are not permitted.
11716 if (value == ",") {
11717 abort();
11718 }
11719 results.push(get(value));
11720 }
11721 return results;
11722 } else if (value == "{") {
11723 // Parses a JSON object, returning a new JavaScript object.
11724 results = {};
11725 for (;; hasMembers || (hasMembers = true)) {
11726 value = lex();
11727 // A closing curly brace marks the end of the object literal.
11728 if (value == "}") {
11729 break;
11730 }
11731 // If the object literal contains members, the current token
11732 // should be a comma separator.
11733 if (hasMembers) {
11734 if (value == ",") {
11735 value = lex();
11736 if (value == "}") {
11737 // Unexpected trailing `,` in object literal.
11738 abort();
11739 }
11740 } else {
11741 // A `,` must separate each object member.
11742 abort();
11743 }
11744 }
11745 // Leading commas are not permitted, object property names must be
11746 // double-quoted strings, and a `:` must separate each property
11747 // name and value.
11748 if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
11749 abort();
11750 }
11751 results[value.slice(1)] = get(lex());
11752 }
11753 return results;
11754 }
11755 // Unexpected token encountered.
11756 abort();
11757 }
11758 return value;
11759 };
11760
11761 // Internal: Updates a traversed object member.
11762 var update = function (source, property, callback) {
11763 var element = walk(source, property, callback);
11764 if (element === undef) {
11765 delete source[property];
11766 } else {
11767 source[property] = element;
11768 }
11769 };
11770
11771 // Internal: Recursively traverses a parsed JSON object, invoking the
11772 // `callback` function for each value. This is an implementation of the
11773 // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
11774 var walk = function (source, property, callback) {
11775 var value = source[property], length;
11776 if (typeof value == "object" && value) {
11777 // `forEach` can't be used to traverse an array in Opera <= 8.54
11778 // because its `Object#hasOwnProperty` implementation returns `false `
11779 // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
11780 if (getClass.call(value) == arrayClass) {
11781 for (length = value.length; length--;) {
11782 update(value, length, callback);
11783 }
11784 } else {
11785 forEach(value, function (property) {
11786 update(value, property, callback);
11787 });
11788 }
11789 }
11790 return callback.call(source, property, value);
11791 };
11792
11793 // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
11794 exports.parse = function (source, callback) {
11795 var result, value;
11796 Index = 0;
11797 Source = "" + source;
11798 result = get(lex());
11799 // If a JSON string contains multiple tokens, it is invalid.
11800 if (lex() != "$") {
11801 abort();
11802 }
11803 // Reset the parser state.
11804 Index = Source = null;
11805 return callback && getClass.call(callback) == functionClass ? walk((va lue = {}, value[""] = result, value), "", callback) : result;
11806 };
11807 }
11808 }
11809
11810 exports["runInContext"] = runInContext;
11811 return exports;
11812 }
11813
11814 if (freeExports && !isLoader) {
11815 // Export for CommonJS environments.
11816 runInContext(root, freeExports);
11817 } else {
11818 // Export for web browsers and JavaScript engines.
11819 var nativeJSON = root.JSON,
11820 previousJSON = root["JSON3"],
11821 isRestored = false;
11822
11823 var JSON3 = runInContext(root, (root["JSON3"] = {
11824 // Public: Restores the original value of the global `JSON` object and
11825 // returns a reference to the `JSON3` object.
11826 "noConflict": function () {
11827 if (!isRestored) {
11828 isRestored = true;
11829 root.JSON = nativeJSON;
11830 root["JSON3"] = previousJSON;
11831 nativeJSON = previousJSON = null;
11832 }
11833 return JSON3;
11834 }
11835 }));
11836
11837 root.JSON = {
11838 "parse": JSON3.parse,
11839 "stringify": JSON3.stringify
11840 };
11841 }
11842
11843 // Export for asynchronous module loaders.
11844 if (isLoader) {
11845 define(function () {
11846 return JSON3;
11847 });
11848 }
11849 }).call(this);
11850
11851 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined " ? self : typeof window !== "undefined" ? window : {})
11852 },{}],70:[function(require,module,exports){
11853 /**
11854 * lodash 3.2.0 (Custom Build) <https://lodash.com/>
11855 * Build: `lodash modern modularize exports="npm" -o ./`
11856 * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
11857 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
11858 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporter s & Editors
11859 * Available under MIT license <https://lodash.com/license>
11860 */
11861 var baseCopy = require('lodash._basecopy'),
11862 keys = require('lodash.keys');
11863
11864 /**
11865 * The base implementation of `_.assign` without support for argument juggling,
11866 * multiple sources, and `customizer` functions.
11867 *
11868 * @private
11869 * @param {Object} object The destination object.
11870 * @param {Object} source The source object.
11871 * @returns {Object} Returns `object`.
11872 */
11873 function baseAssign(object, source) {
11874 return source == null
11875 ? object
11876 : baseCopy(source, keys(source), object);
11877 }
11878
11879 module.exports = baseAssign;
11880
11881 },{"lodash._basecopy":71,"lodash.keys":78}],71:[function(require,module,exports) {
11882 /**
11883 * lodash 3.0.1 (Custom Build) <https://lodash.com/>
11884 * Build: `lodash modern modularize exports="npm" -o ./`
11885 * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
11886 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
11887 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporter s & Editors
11888 * Available under MIT license <https://lodash.com/license>
11889 */
11890
11891 /**
11892 * Copies properties of `source` to `object`.
11893 *
11894 * @private
11895 * @param {Object} source The object to copy properties from.
11896 * @param {Array} props The property names to copy.
11897 * @param {Object} [object={}] The object to copy properties to.
11898 * @returns {Object} Returns `object`.
11899 */
11900 function baseCopy(source, props, object) {
11901 object || (object = {});
11902
11903 var index = -1,
11904 length = props.length;
11905
11906 while (++index < length) {
11907 var key = props[index];
11908 object[key] = source[key];
11909 }
11910 return object;
11911 }
11912
11913 module.exports = baseCopy;
11914
11915 },{}],72:[function(require,module,exports){
11916 /**
11917 * lodash 3.0.3 (Custom Build) <https://lodash.com/>
11918 * Build: `lodash modern modularize exports="npm" -o ./`
11919 * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
11920 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
11921 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporter s & Editors
11922 * Available under MIT license <https://lodash.com/license>
11923 */
11924
11925 /**
11926 * The base implementation of `_.create` without support for assigning
11927 * properties to the created object.
11928 *
11929 * @private
11930 * @param {Object} prototype The object to inherit from.
11931 * @returns {Object} Returns the new object.
11932 */
11933 var baseCreate = (function() {
11934 function object() {}
11935 return function(prototype) {
11936 if (isObject(prototype)) {
11937 object.prototype = prototype;
11938 var result = new object;
11939 object.prototype = undefined;
11940 }
11941 return result || {};
11942 };
11943 }());
11944
11945 /**
11946 * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Objec t`.
11947 * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String(' ')`)
11948 *
11949 * @static
11950 * @memberOf _
11951 * @category Lang
11952 * @param {*} value The value to check.
11953 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
11954 * @example
11955 *
11956 * _.isObject({});
11957 * // => true
11958 *
11959 * _.isObject([1, 2, 3]);
11960 * // => true
11961 *
11962 * _.isObject(1);
11963 * // => false
11964 */
11965 function isObject(value) {
11966 // Avoid a V8 JIT bug in Chrome 19-20.
11967 // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
11968 var type = typeof value;
11969 return !!value && (type == 'object' || type == 'function');
11970 }
11971
11972 module.exports = baseCreate;
11973
11974 },{}],73:[function(require,module,exports){
11975 /**
11976 * lodash 3.9.1 (Custom Build) <https://lodash.com/>
11977 * Build: `lodash modern modularize exports="npm" -o ./`
11978 * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
11979 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
11980 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporter s & Editors
11981 * Available under MIT license <https://lodash.com/license>
11982 */
11983
11984 /** `Object#toString` result references. */
11985 var funcTag = '[object Function]';
11986
11987 /** Used to detect host constructors (Safari > 5). */
11988 var reIsHostCtor = /^\[object .+?Constructor\]$/;
11989
11990 /**
11991 * Checks if `value` is object-like.
11992 *
11993 * @private
11994 * @param {*} value The value to check.
11995 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
11996 */
11997 function isObjectLike(value) {
11998 return !!value && typeof value == 'object';
11999 }
12000
12001 /** Used for native method references. */
12002 var objectProto = Object.prototype;
12003
12004 /** Used to resolve the decompiled source of functions. */
12005 var fnToString = Function.prototype.toString;
12006
12007 /** Used to check objects for own properties. */
12008 var hasOwnProperty = objectProto.hasOwnProperty;
12009
12010 /**
12011 * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6. 0/#sec-object.prototype.tostring)
12012 * of values.
12013 */
12014 var objToString = objectProto.toString;
12015
12016 /** Used to detect if a method is native. */
12017 var reIsNative = RegExp('^' +
12018 fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
12019 .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
12020 );
12021
12022 /**
12023 * Gets the native function at `key` of `object`.
12024 *
12025 * @private
12026 * @param {Object} object The object to query.
12027 * @param {string} key The key of the method to get.
12028 * @returns {*} Returns the function if it's native, else `undefined`.
12029 */
12030 function getNative(object, key) {
12031 var value = object == null ? undefined : object[key];
12032 return isNative(value) ? value : undefined;
12033 }
12034
12035 /**
12036 * Checks if `value` is classified as a `Function` object.
12037 *
12038 * @static
12039 * @memberOf _
12040 * @category Lang
12041 * @param {*} value The value to check.
12042 * @returns {boolean} Returns `true` if `value` is correctly classified, else `f alse`.
12043 * @example
12044 *
12045 * _.isFunction(_);
12046 * // => true
12047 *
12048 * _.isFunction(/abc/);
12049 * // => false
12050 */
12051 function isFunction(value) {
12052 // The use of `Object#toString` avoids issues with the `typeof` operator
12053 // in older versions of Chrome and Safari which return 'function' for regexes
12054 // and Safari 8 equivalents which return 'object' for typed array constructors .
12055 return isObject(value) && objToString.call(value) == funcTag;
12056 }
12057
12058 /**
12059 * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Objec t`.
12060 * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String(' ')`)
12061 *
12062 * @static
12063 * @memberOf _
12064 * @category Lang
12065 * @param {*} value The value to check.
12066 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
12067 * @example
12068 *
12069 * _.isObject({});
12070 * // => true
12071 *
12072 * _.isObject([1, 2, 3]);
12073 * // => true
12074 *
12075 * _.isObject(1);
12076 * // => false
12077 */
12078 function isObject(value) {
12079 // Avoid a V8 JIT bug in Chrome 19-20.
12080 // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
12081 var type = typeof value;
12082 return !!value && (type == 'object' || type == 'function');
12083 }
12084
12085 /**
12086 * Checks if `value` is a native function.
12087 *
12088 * @static
12089 * @memberOf _
12090 * @category Lang
12091 * @param {*} value The value to check.
12092 * @returns {boolean} Returns `true` if `value` is a native function, else `fals e`.
12093 * @example
12094 *
12095 * _.isNative(Array.prototype.push);
12096 * // => true
12097 *
12098 * _.isNative(_);
12099 * // => false
12100 */
12101 function isNative(value) {
12102 if (value == null) {
12103 return false;
12104 }
12105 if (isFunction(value)) {
12106 return reIsNative.test(fnToString.call(value));
12107 }
12108 return isObjectLike(value) && reIsHostCtor.test(value);
12109 }
12110
12111 module.exports = getNative;
12112
12113 },{}],74:[function(require,module,exports){
12114 /**
12115 * lodash 3.0.9 (Custom Build) <https://lodash.com/>
12116 * Build: `lodash modern modularize exports="npm" -o ./`
12117 * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
12118 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
12119 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporter s & Editors
12120 * Available under MIT license <https://lodash.com/license>
12121 */
12122
12123 /** Used to detect unsigned integer values. */
12124 var reIsUint = /^\d+$/;
12125
12126 /**
12127 * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft .html#sec-number.max_safe_integer)
12128 * of an array-like value.
12129 */
12130 var MAX_SAFE_INTEGER = 9007199254740991;
12131
12132 /**
12133 * The base implementation of `_.property` without support for deep paths.
12134 *
12135 * @private
12136 * @param {string} key The key of the property to get.
12137 * @returns {Function} Returns the new function.
12138 */
12139 function baseProperty(key) {
12140 return function(object) {
12141 return object == null ? undefined : object[key];
12142 };
12143 }
12144
12145 /**
12146 * Gets the "length" property value of `object`.
12147 *
12148 * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/ show_bug.cgi?id=142792)
12149 * that affects Safari on at least iOS 8.1-8.3 ARM64.
12150 *
12151 * @private
12152 * @param {Object} object The object to query.
12153 * @returns {*} Returns the "length" value.
12154 */
12155 var getLength = baseProperty('length');
12156
12157 /**
12158 * Checks if `value` is array-like.
12159 *
12160 * @private
12161 * @param {*} value The value to check.
12162 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
12163 */
12164 function isArrayLike(value) {
12165 return value != null && isLength(getLength(value));
12166 }
12167
12168 /**
12169 * Checks if `value` is a valid array-like index.
12170 *
12171 * @private
12172 * @param {*} value The value to check.
12173 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
12174 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
12175 */
12176 function isIndex(value, length) {
12177 value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
12178 length = length == null ? MAX_SAFE_INTEGER : length;
12179 return value > -1 && value % 1 == 0 && value < length;
12180 }
12181
12182 /**
12183 * Checks if the provided arguments are from an iteratee call.
12184 *
12185 * @private
12186 * @param {*} value The potential iteratee value argument.
12187 * @param {*} index The potential iteratee index or key argument.
12188 * @param {*} object The potential iteratee object argument.
12189 * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
12190 */
12191 function isIterateeCall(value, index, object) {
12192 if (!isObject(object)) {
12193 return false;
12194 }
12195 var type = typeof index;
12196 if (type == 'number'
12197 ? (isArrayLike(object) && isIndex(index, object.length))
12198 : (type == 'string' && index in object)) {
12199 var other = object[index];
12200 return value === value ? (value === other) : (other !== other);
12201 }
12202 return false;
12203 }
12204
12205 /**
12206 * Checks if `value` is a valid array-like length.
12207 *
12208 * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~ jorendorff/es6-draft.html#sec-tolength).
12209 *
12210 * @private
12211 * @param {*} value The value to check.
12212 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
12213 */
12214 function isLength(value) {
12215 return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MA X_SAFE_INTEGER;
12216 }
12217
12218 /**
12219 * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Objec t`.
12220 * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String(' ')`)
12221 *
12222 * @static
12223 * @memberOf _
12224 * @category Lang
12225 * @param {*} value The value to check.
12226 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
12227 * @example
12228 *
12229 * _.isObject({});
12230 * // => true
12231 *
12232 * _.isObject([1, 2, 3]);
12233 * // => true
12234 *
12235 * _.isObject(1);
12236 * // => false
12237 */
12238 function isObject(value) {
12239 // Avoid a V8 JIT bug in Chrome 19-20.
12240 // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
12241 var type = typeof value;
12242 return !!value && (type == 'object' || type == 'function');
12243 }
12244
12245 module.exports = isIterateeCall;
12246
12247 },{}],75:[function(require,module,exports){
12248 /**
12249 * lodash 3.1.1 (Custom Build) <https://lodash.com/>
12250 * Build: `lodash modern modularize exports="npm" -o ./`
12251 * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
12252 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
12253 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporter s & Editors
12254 * Available under MIT license <https://lodash.com/license>
12255 */
12256 var baseAssign = require('lodash._baseassign'),
12257 baseCreate = require('lodash._basecreate'),
12258 isIterateeCall = require('lodash._isiterateecall');
12259
12260 /**
12261 * Creates an object that inherits from the given `prototype` object. If a
12262 * `properties` object is provided its own enumerable properties are assigned
12263 * to the created object.
12264 *
12265 * @static
12266 * @memberOf _
12267 * @category Object
12268 * @param {Object} prototype The object to inherit from.
12269 * @param {Object} [properties] The properties to assign to the object.
12270 * @param- {Object} [guard] Enables use as a callback for functions like `_.map` .
12271 * @returns {Object} Returns the new object.
12272 * @example
12273 *
12274 * function Shape() {
12275 * this.x = 0;
12276 * this.y = 0;
12277 * }
12278 *
12279 * function Circle() {
12280 * Shape.call(this);
12281 * }
12282 *
12283 * Circle.prototype = _.create(Shape.prototype, {
12284 * 'constructor': Circle
12285 * });
12286 *
12287 * var circle = new Circle;
12288 * circle instanceof Circle;
12289 * // => true
12290 *
12291 * circle instanceof Shape;
12292 * // => true
12293 */
12294 function create(prototype, properties, guard) {
12295 var result = baseCreate(prototype);
12296 if (guard && isIterateeCall(prototype, properties, guard)) {
12297 properties = undefined;
12298 }
12299 return properties ? baseAssign(result, properties) : result;
12300 }
12301
12302 module.exports = create;
12303
12304 },{"lodash._baseassign":70,"lodash._basecreate":72,"lodash._isiterateecall":74}] ,76:[function(require,module,exports){
12305 /**
12306 * lodash (Custom Build) <https://lodash.com/>
12307 * Build: `lodash modularize exports="npm" -o ./`
12308 * Copyright jQuery Foundation and other contributors <https://jquery.org/>
12309 * Released under MIT license <https://lodash.com/license>
12310 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
12311 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editor s
12312 */
12313
12314 /** Used as references for various `Number` constants. */
12315 var MAX_SAFE_INTEGER = 9007199254740991;
12316
12317 /** `Object#toString` result references. */
12318 var argsTag = '[object Arguments]',
12319 funcTag = '[object Function]',
12320 genTag = '[object GeneratorFunction]';
12321
12322 /** Used for built-in method references. */
12323 var objectProto = Object.prototype;
12324
12325 /** Used to check objects for own properties. */
12326 var hasOwnProperty = objectProto.hasOwnProperty;
12327
12328 /**
12329 * Used to resolve the
12330 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.protot ype.tostring)
12331 * of values.
12332 */
12333 var objectToString = objectProto.toString;
12334
12335 /** Built-in value references. */
12336 var propertyIsEnumerable = objectProto.propertyIsEnumerable;
12337
12338 /**
12339 * Checks if `value` is likely an `arguments` object.
12340 *
12341 * @static
12342 * @memberOf _
12343 * @since 0.1.0
12344 * @category Lang
12345 * @param {*} value The value to check.
12346 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
12347 * else `false`.
12348 * @example
12349 *
12350 * _.isArguments(function() { return arguments; }());
12351 * // => true
12352 *
12353 * _.isArguments([1, 2, 3]);
12354 * // => false
12355 */
12356 function isArguments(value) {
12357 // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
12358 return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
12359 (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) = = argsTag);
12360 }
12361
12362 /**
12363 * Checks if `value` is array-like. A value is considered array-like if it's
12364 * not a function and has a `value.length` that's an integer greater than or
12365 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
12366 *
12367 * @static
12368 * @memberOf _
12369 * @since 4.0.0
12370 * @category Lang
12371 * @param {*} value The value to check.
12372 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
12373 * @example
12374 *
12375 * _.isArrayLike([1, 2, 3]);
12376 * // => true
12377 *
12378 * _.isArrayLike(document.body.children);
12379 * // => true
12380 *
12381 * _.isArrayLike('abc');
12382 * // => true
12383 *
12384 * _.isArrayLike(_.noop);
12385 * // => false
12386 */
12387 function isArrayLike(value) {
12388 return value != null && isLength(value.length) && !isFunction(value);
12389 }
12390
12391 /**
12392 * This method is like `_.isArrayLike` except that it also checks if `value`
12393 * is an object.
12394 *
12395 * @static
12396 * @memberOf _
12397 * @since 4.0.0
12398 * @category Lang
12399 * @param {*} value The value to check.
12400 * @returns {boolean} Returns `true` if `value` is an array-like object,
12401 * else `false`.
12402 * @example
12403 *
12404 * _.isArrayLikeObject([1, 2, 3]);
12405 * // => true
12406 *
12407 * _.isArrayLikeObject(document.body.children);
12408 * // => true
12409 *
12410 * _.isArrayLikeObject('abc');
12411 * // => false
12412 *
12413 * _.isArrayLikeObject(_.noop);
12414 * // => false
12415 */
12416 function isArrayLikeObject(value) {
12417 return isObjectLike(value) && isArrayLike(value);
12418 }
12419
12420 /**
12421 * Checks if `value` is classified as a `Function` object.
12422 *
12423 * @static
12424 * @memberOf _
12425 * @since 0.1.0
12426 * @category Lang
12427 * @param {*} value The value to check.
12428 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
12429 * @example
12430 *
12431 * _.isFunction(_);
12432 * // => true
12433 *
12434 * _.isFunction(/abc/);
12435 * // => false
12436 */
12437 function isFunction(value) {
12438 // The use of `Object#toString` avoids issues with the `typeof` operator
12439 // in Safari 8-9 which returns 'object' for typed array and other constructors .
12440 var tag = isObject(value) ? objectToString.call(value) : '';
12441 return tag == funcTag || tag == genTag;
12442 }
12443
12444 /**
12445 * Checks if `value` is a valid array-like length.
12446 *
12447 * **Note:** This method is loosely based on
12448 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
12449 *
12450 * @static
12451 * @memberOf _
12452 * @since 4.0.0
12453 * @category Lang
12454 * @param {*} value The value to check.
12455 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
12456 * @example
12457 *
12458 * _.isLength(3);
12459 * // => true
12460 *
12461 * _.isLength(Number.MIN_VALUE);
12462 * // => false
12463 *
12464 * _.isLength(Infinity);
12465 * // => false
12466 *
12467 * _.isLength('3');
12468 * // => false
12469 */
12470 function isLength(value) {
12471 return typeof value == 'number' &&
12472 value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
12473 }
12474
12475 /**
12476 * Checks if `value` is the
12477 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascrip t-language-types)
12478 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
12479 *
12480 * @static
12481 * @memberOf _
12482 * @since 0.1.0
12483 * @category Lang
12484 * @param {*} value The value to check.
12485 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
12486 * @example
12487 *
12488 * _.isObject({});
12489 * // => true
12490 *
12491 * _.isObject([1, 2, 3]);
12492 * // => true
12493 *
12494 * _.isObject(_.noop);
12495 * // => true
12496 *
12497 * _.isObject(null);
12498 * // => false
12499 */
12500 function isObject(value) {
12501 var type = typeof value;
12502 return !!value && (type == 'object' || type == 'function');
12503 }
12504
12505 /**
12506 * Checks if `value` is object-like. A value is object-like if it's not `null`
12507 * and has a `typeof` result of "object".
12508 *
12509 * @static
12510 * @memberOf _
12511 * @since 4.0.0
12512 * @category Lang
12513 * @param {*} value The value to check.
12514 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
12515 * @example
12516 *
12517 * _.isObjectLike({});
12518 * // => true
12519 *
12520 * _.isObjectLike([1, 2, 3]);
12521 * // => true
12522 *
12523 * _.isObjectLike(_.noop);
12524 * // => false
12525 *
12526 * _.isObjectLike(null);
12527 * // => false
12528 */
12529 function isObjectLike(value) {
12530 return !!value && typeof value == 'object';
12531 }
12532
12533 module.exports = isArguments;
12534
12535 },{}],77:[function(require,module,exports){
12536 /**
12537 * lodash 3.0.4 (Custom Build) <https://lodash.com/>
12538 * Build: `lodash modern modularize exports="npm" -o ./`
12539 * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
12540 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
12541 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporter s & Editors
12542 * Available under MIT license <https://lodash.com/license>
12543 */
12544
12545 /** `Object#toString` result references. */
12546 var arrayTag = '[object Array]',
12547 funcTag = '[object Function]';
12548
12549 /** Used to detect host constructors (Safari > 5). */
12550 var reIsHostCtor = /^\[object .+?Constructor\]$/;
12551
12552 /**
12553 * Checks if `value` is object-like.
12554 *
12555 * @private
12556 * @param {*} value The value to check.
12557 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
12558 */
12559 function isObjectLike(value) {
12560 return !!value && typeof value == 'object';
12561 }
12562
12563 /** Used for native method references. */
12564 var objectProto = Object.prototype;
12565
12566 /** Used to resolve the decompiled source of functions. */
12567 var fnToString = Function.prototype.toString;
12568
12569 /** Used to check objects for own properties. */
12570 var hasOwnProperty = objectProto.hasOwnProperty;
12571
12572 /**
12573 * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6. 0/#sec-object.prototype.tostring)
12574 * of values.
12575 */
12576 var objToString = objectProto.toString;
12577
12578 /** Used to detect if a method is native. */
12579 var reIsNative = RegExp('^' +
12580 fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
12581 .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
12582 );
12583
12584 /* Native method references for those with the same name as other `lodash` metho ds. */
12585 var nativeIsArray = getNative(Array, 'isArray');
12586
12587 /**
12588 * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec- number.max_safe_integer)
12589 * of an array-like value.
12590 */
12591 var MAX_SAFE_INTEGER = 9007199254740991;
12592
12593 /**
12594 * Gets the native function at `key` of `object`.
12595 *
12596 * @private
12597 * @param {Object} object The object to query.
12598 * @param {string} key The key of the method to get.
12599 * @returns {*} Returns the function if it's native, else `undefined`.
12600 */
12601 function getNative(object, key) {
12602 var value = object == null ? undefined : object[key];
12603 return isNative(value) ? value : undefined;
12604 }
12605
12606 /**
12607 * Checks if `value` is a valid array-like length.
12608 *
12609 * **Note:** This function is based on [`ToLength`](http://ecma-international.or g/ecma-262/6.0/#sec-tolength).
12610 *
12611 * @private
12612 * @param {*} value The value to check.
12613 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
12614 */
12615 function isLength(value) {
12616 return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MA X_SAFE_INTEGER;
12617 }
12618
12619 /**
12620 * Checks if `value` is classified as an `Array` object.
12621 *
12622 * @static
12623 * @memberOf _
12624 * @category Lang
12625 * @param {*} value The value to check.
12626 * @returns {boolean} Returns `true` if `value` is correctly classified, else `f alse`.
12627 * @example
12628 *
12629 * _.isArray([1, 2, 3]);
12630 * // => true
12631 *
12632 * _.isArray(function() { return arguments; }());
12633 * // => false
12634 */
12635 var isArray = nativeIsArray || function(value) {
12636 return isObjectLike(value) && isLength(value.length) && objToString.call(value ) == arrayTag;
12637 };
12638
12639 /**
12640 * Checks if `value` is classified as a `Function` object.
12641 *
12642 * @static
12643 * @memberOf _
12644 * @category Lang
12645 * @param {*} value The value to check.
12646 * @returns {boolean} Returns `true` if `value` is correctly classified, else `f alse`.
12647 * @example
12648 *
12649 * _.isFunction(_);
12650 * // => true
12651 *
12652 * _.isFunction(/abc/);
12653 * // => false
12654 */
12655 function isFunction(value) {
12656 // The use of `Object#toString` avoids issues with the `typeof` operator
12657 // in older versions of Chrome and Safari which return 'function' for regexes
12658 // and Safari 8 equivalents which return 'object' for typed array constructors .
12659 return isObject(value) && objToString.call(value) == funcTag;
12660 }
12661
12662 /**
12663 * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Objec t`.
12664 * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String(' ')`)
12665 *
12666 * @static
12667 * @memberOf _
12668 * @category Lang
12669 * @param {*} value The value to check.
12670 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
12671 * @example
12672 *
12673 * _.isObject({});
12674 * // => true
12675 *
12676 * _.isObject([1, 2, 3]);
12677 * // => true
12678 *
12679 * _.isObject(1);
12680 * // => false
12681 */
12682 function isObject(value) {
12683 // Avoid a V8 JIT bug in Chrome 19-20.
12684 // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
12685 var type = typeof value;
12686 return !!value && (type == 'object' || type == 'function');
12687 }
12688
12689 /**
12690 * Checks if `value` is a native function.
12691 *
12692 * @static
12693 * @memberOf _
12694 * @category Lang
12695 * @param {*} value The value to check.
12696 * @returns {boolean} Returns `true` if `value` is a native function, else `fals e`.
12697 * @example
12698 *
12699 * _.isNative(Array.prototype.push);
12700 * // => true
12701 *
12702 * _.isNative(_);
12703 * // => false
12704 */
12705 function isNative(value) {
12706 if (value == null) {
12707 return false;
12708 }
12709 if (isFunction(value)) {
12710 return reIsNative.test(fnToString.call(value));
12711 }
12712 return isObjectLike(value) && reIsHostCtor.test(value);
12713 }
12714
12715 module.exports = isArray;
12716
12717 },{}],78:[function(require,module,exports){
12718 /**
12719 * lodash 3.1.2 (Custom Build) <https://lodash.com/>
12720 * Build: `lodash modern modularize exports="npm" -o ./`
12721 * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
12722 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
12723 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporter s & Editors
12724 * Available under MIT license <https://lodash.com/license>
12725 */
12726 var getNative = require('lodash._getnative'),
12727 isArguments = require('lodash.isarguments'),
12728 isArray = require('lodash.isarray');
12729
12730 /** Used to detect unsigned integer values. */
12731 var reIsUint = /^\d+$/;
12732
12733 /** Used for native method references. */
12734 var objectProto = Object.prototype;
12735
12736 /** Used to check objects for own properties. */
12737 var hasOwnProperty = objectProto.hasOwnProperty;
12738
12739 /* Native method references for those with the same name as other `lodash` metho ds. */
12740 var nativeKeys = getNative(Object, 'keys');
12741
12742 /**
12743 * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec- number.max_safe_integer)
12744 * of an array-like value.
12745 */
12746 var MAX_SAFE_INTEGER = 9007199254740991;
12747
12748 /**
12749 * The base implementation of `_.property` without support for deep paths.
12750 *
12751 * @private
12752 * @param {string} key The key of the property to get.
12753 * @returns {Function} Returns the new function.
12754 */
12755 function baseProperty(key) {
12756 return function(object) {
12757 return object == null ? undefined : object[key];
12758 };
12759 }
12760
12761 /**
12762 * Gets the "length" property value of `object`.
12763 *
12764 * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/ show_bug.cgi?id=142792)
12765 * that affects Safari on at least iOS 8.1-8.3 ARM64.
12766 *
12767 * @private
12768 * @param {Object} object The object to query.
12769 * @returns {*} Returns the "length" value.
12770 */
12771 var getLength = baseProperty('length');
12772
12773 /**
12774 * Checks if `value` is array-like.
12775 *
12776 * @private
12777 * @param {*} value The value to check.
12778 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
12779 */
12780 function isArrayLike(value) {
12781 return value != null && isLength(getLength(value));
12782 }
12783
12784 /**
12785 * Checks if `value` is a valid array-like index.
12786 *
12787 * @private
12788 * @param {*} value The value to check.
12789 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
12790 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
12791 */
12792 function isIndex(value, length) {
12793 value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
12794 length = length == null ? MAX_SAFE_INTEGER : length;
12795 return value > -1 && value % 1 == 0 && value < length;
12796 }
12797
12798 /**
12799 * Checks if `value` is a valid array-like length.
12800 *
12801 * **Note:** This function is based on [`ToLength`](http://ecma-international.or g/ecma-262/6.0/#sec-tolength).
12802 *
12803 * @private
12804 * @param {*} value The value to check.
12805 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
12806 */
12807 function isLength(value) {
12808 return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MA X_SAFE_INTEGER;
12809 }
12810
12811 /**
12812 * A fallback implementation of `Object.keys` which creates an array of the
12813 * own enumerable property names of `object`.
12814 *
12815 * @private
12816 * @param {Object} object The object to query.
12817 * @returns {Array} Returns the array of property names.
12818 */
12819 function shimKeys(object) {
12820 var props = keysIn(object),
12821 propsLength = props.length,
12822 length = propsLength && object.length;
12823
12824 var allowIndexes = !!length && isLength(length) &&
12825 (isArray(object) || isArguments(object));
12826
12827 var index = -1,
12828 result = [];
12829
12830 while (++index < propsLength) {
12831 var key = props[index];
12832 if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, ke y)) {
12833 result.push(key);
12834 }
12835 }
12836 return result;
12837 }
12838
12839 /**
12840 * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Objec t`.
12841 * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String(' ')`)
12842 *
12843 * @static
12844 * @memberOf _
12845 * @category Lang
12846 * @param {*} value The value to check.
12847 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
12848 * @example
12849 *
12850 * _.isObject({});
12851 * // => true
12852 *
12853 * _.isObject([1, 2, 3]);
12854 * // => true
12855 *
12856 * _.isObject(1);
12857 * // => false
12858 */
12859 function isObject(value) {
12860 // Avoid a V8 JIT bug in Chrome 19-20.
12861 // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
12862 var type = typeof value;
12863 return !!value && (type == 'object' || type == 'function');
12864 }
12865
12866 /**
12867 * Creates an array of the own enumerable property names of `object`.
12868 *
12869 * **Note:** Non-object values are coerced to objects. See the
12870 * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
12871 * for more details.
12872 *
12873 * @static
12874 * @memberOf _
12875 * @category Object
12876 * @param {Object} object The object to query.
12877 * @returns {Array} Returns the array of property names.
12878 * @example
12879 *
12880 * function Foo() {
12881 * this.a = 1;
12882 * this.b = 2;
12883 * }
12884 *
12885 * Foo.prototype.c = 3;
12886 *
12887 * _.keys(new Foo);
12888 * // => ['a', 'b'] (iteration order is not guaranteed)
12889 *
12890 * _.keys('hi');
12891 * // => ['0', '1']
12892 */
12893 var keys = !nativeKeys ? shimKeys : function(object) {
12894 var Ctor = object == null ? undefined : object.constructor;
12895 if ((typeof Ctor == 'function' && Ctor.prototype === object) ||
12896 (typeof object != 'function' && isArrayLike(object))) {
12897 return shimKeys(object);
12898 }
12899 return isObject(object) ? nativeKeys(object) : [];
12900 };
12901
12902 /**
12903 * Creates an array of the own and inherited enumerable property names of `objec t`.
12904 *
12905 * **Note:** Non-object values are coerced to objects.
12906 *
12907 * @static
12908 * @memberOf _
12909 * @category Object
12910 * @param {Object} object The object to query.
12911 * @returns {Array} Returns the array of property names.
12912 * @example
12913 *
12914 * function Foo() {
12915 * this.a = 1;
12916 * this.b = 2;
12917 * }
12918 *
12919 * Foo.prototype.c = 3;
12920 *
12921 * _.keysIn(new Foo);
12922 * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
12923 */
12924 function keysIn(object) {
12925 if (object == null) {
12926 return [];
12927 }
12928 if (!isObject(object)) {
12929 object = Object(object);
12930 }
12931 var length = object.length;
12932 length = (length && isLength(length) &&
12933 (isArray(object) || isArguments(object)) && length) || 0;
12934
12935 var Ctor = object.constructor,
12936 index = -1,
12937 isProto = typeof Ctor == 'function' && Ctor.prototype === object,
12938 result = Array(length),
12939 skipIndexes = length > 0;
12940
12941 while (++index < length) {
12942 result[index] = (index + '');
12943 }
12944 for (var key in object) {
12945 if (!(skipIndexes && isIndex(key, length)) &&
12946 !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)) )) {
12947 result.push(key);
12948 }
12949 }
12950 return result;
12951 }
12952
12953 module.exports = keys;
12954
12955 },{"lodash._getnative":73,"lodash.isarguments":76,"lodash.isarray":77}],79:[func tion(require,module,exports){
12956 (function (process){
12957 var path = require('path');
12958 var fs = require('fs');
12959 var _0777 = parseInt('0777', 8);
12960
12961 module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;
12962
12963 function mkdirP (p, opts, f, made) {
12964 if (typeof opts === 'function') {
12965 f = opts;
12966 opts = {};
12967 }
12968 else if (!opts || typeof opts !== 'object') {
12969 opts = { mode: opts };
12970 }
12971
12972 var mode = opts.mode;
12973 var xfs = opts.fs || fs;
12974
12975 if (mode === undefined) {
12976 mode = _0777 & (~process.umask());
12977 }
12978 if (!made) made = null;
12979
12980 var cb = f || function () {};
12981 p = path.resolve(p);
12982
12983 xfs.mkdir(p, mode, function (er) {
12984 if (!er) {
12985 made = made || p;
12986 return cb(null, made);
12987 }
12988 switch (er.code) {
12989 case 'ENOENT':
12990 mkdirP(path.dirname(p), opts, function (er, made) {
12991 if (er) cb(er, made);
12992 else mkdirP(p, opts, cb, made);
12993 });
12994 break;
12995
12996 // In the case of any other error, just see if there's a dir
12997 // there already. If so, then hooray! If not, then something
12998 // is borked.
12999 default:
13000 xfs.stat(p, function (er2, stat) {
13001 // if the stat fails, then that's super weird.
13002 // let the original error be the failure reason.
13003 if (er2 || !stat.isDirectory()) cb(er, made)
13004 else cb(null, made);
13005 });
13006 break;
13007 }
13008 });
13009 }
13010
13011 mkdirP.sync = function sync (p, opts, made) {
13012 if (!opts || typeof opts !== 'object') {
13013 opts = { mode: opts };
13014 }
13015
13016 var mode = opts.mode;
13017 var xfs = opts.fs || fs;
13018
13019 if (mode === undefined) {
13020 mode = _0777 & (~process.umask());
13021 }
13022 if (!made) made = null;
13023
13024 p = path.resolve(p);
13025
13026 try {
13027 xfs.mkdirSync(p, mode);
13028 made = made || p;
13029 }
13030 catch (err0) {
13031 switch (err0.code) {
13032 case 'ENOENT' :
13033 made = sync(path.dirname(p), opts, made);
13034 sync(p, opts, made);
13035 break;
13036
13037 // In the case of any other error, just see if there's a dir
13038 // there already. If so, then hooray! If not, then something
13039 // is borked.
13040 default:
13041 var stat;
13042 try {
13043 stat = xfs.statSync(p);
13044 }
13045 catch (err1) {
13046 throw err0;
13047 }
13048 if (!stat.isDirectory()) throw err0;
13049 break;
13050 }
13051 }
13052
13053 return made;
13054 };
13055
13056 }).call(this,require('_process'))
13057 },{"_process":82,"fs":42,"path":42}],80:[function(require,module,exports){
13058 exports.endianness = function () { return 'LE' };
13059
13060 exports.hostname = function () {
13061 if (typeof location !== 'undefined') {
13062 return location.hostname
13063 }
13064 else return '';
13065 };
13066
13067 exports.loadavg = function () { return [] };
13068
13069 exports.uptime = function () { return 0 };
13070
13071 exports.freemem = function () {
13072 return Number.MAX_VALUE;
13073 };
13074
13075 exports.totalmem = function () {
13076 return Number.MAX_VALUE;
13077 };
13078
13079 exports.cpus = function () { return [] };
13080
13081 exports.type = function () { return 'Browser' };
13082
13083 exports.release = function () {
13084 if (typeof navigator !== 'undefined') {
13085 return navigator.appVersion;
13086 }
13087 return '';
13088 };
13089
13090 exports.networkInterfaces
13091 = exports.getNetworkInterfaces
13092 = function () { return {} };
13093
13094 exports.arch = function () { return 'javascript' };
13095
13096 exports.platform = function () { return 'browser' };
13097
13098 exports.tmpdir = exports.tmpDir = function () {
13099 return '/tmp';
13100 };
13101
13102 exports.EOL = '\n';
13103
13104 },{}],81:[function(require,module,exports){
13105 (function (process){
13106 'use strict';
13107
13108 if (!process.version ||
13109 process.version.indexOf('v0.') === 0 ||
13110 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
13111 module.exports = nextTick;
13112 } else {
13113 module.exports = process.nextTick;
13114 }
13115
13116 function nextTick(fn, arg1, arg2, arg3) {
13117 if (typeof fn !== 'function') {
13118 throw new TypeError('"callback" argument must be a function');
13119 }
13120 var len = arguments.length;
13121 var args, i;
13122 switch (len) {
13123 case 0:
13124 case 1:
13125 return process.nextTick(fn);
13126 case 2:
13127 return process.nextTick(function afterTickOne() {
13128 fn.call(null, arg1);
13129 });
13130 case 3:
13131 return process.nextTick(function afterTickTwo() {
13132 fn.call(null, arg1, arg2);
13133 });
13134 case 4:
13135 return process.nextTick(function afterTickThree() {
13136 fn.call(null, arg1, arg2, arg3);
13137 });
13138 default:
13139 args = new Array(len - 1);
13140 i = 0;
13141 while (i < args.length) {
13142 args[i++] = arguments[i];
13143 }
13144 return process.nextTick(function afterTick() {
13145 fn.apply(null, args);
13146 });
13147 }
13148 }
13149
13150 }).call(this,require('_process'))
13151 },{"_process":82}],82:[function(require,module,exports){
13152 // shim for using process in browser
13153 var process = module.exports = {};
13154
13155 // cached from whatever global is present so that test runners that stub it
13156 // don't break things. But we need to wrap it in a try catch in case it is
13157 // wrapped in strict mode code which doesn't define any globals. It's inside a
13158 // function because try/catches deoptimize in certain engines.
13159
13160 var cachedSetTimeout;
13161 var cachedClearTimeout;
13162
13163 function defaultSetTimout() {
13164 throw new Error('setTimeout has not been defined');
13165 }
13166 function defaultClearTimeout () {
13167 throw new Error('clearTimeout has not been defined');
13168 }
13169 (function () {
13170 try {
13171 if (typeof setTimeout === 'function') {
13172 cachedSetTimeout = setTimeout;
13173 } else {
13174 cachedSetTimeout = defaultSetTimout;
13175 }
13176 } catch (e) {
13177 cachedSetTimeout = defaultSetTimout;
13178 }
13179 try {
13180 if (typeof clearTimeout === 'function') {
13181 cachedClearTimeout = clearTimeout;
13182 } else {
13183 cachedClearTimeout = defaultClearTimeout;
13184 }
13185 } catch (e) {
13186 cachedClearTimeout = defaultClearTimeout;
13187 }
13188 } ())
13189 function runTimeout(fun) {
13190 if (cachedSetTimeout === setTimeout) {
13191 //normal enviroments in sane situations
13192 return setTimeout(fun, 0);
13193 }
13194 // if setTimeout wasn't available but was latter defined
13195 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeo ut) {
13196 cachedSetTimeout = setTimeout;
13197 return setTimeout(fun, 0);
13198 }
13199 try {
13200 // when when somebody has screwed with setTimeout but no I.E. maddness
13201 return cachedSetTimeout(fun, 0);
13202 } catch(e){
13203 try {
13204 // When we are in I.E. but the script has been evaled so I.E. doesn' t trust the global object when called normally
13205 return cachedSetTimeout.call(null, fun, 0);
13206 } catch(e){
13207 // 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
13208 return cachedSetTimeout.call(this, fun, 0);
13209 }
13210 }
13211
13212
13213 }
13214 function runClearTimeout(marker) {
13215 if (cachedClearTimeout === clearTimeout) {
13216 //normal enviroments in sane situations
13217 return clearTimeout(marker);
13218 }
13219 // if clearTimeout wasn't available but was latter defined
13220 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && c learTimeout) {
13221 cachedClearTimeout = clearTimeout;
13222 return clearTimeout(marker);
13223 }
13224 try {
13225 // when when somebody has screwed with setTimeout but no I.E. maddness
13226 return cachedClearTimeout(marker);
13227 } catch (e){
13228 try {
13229 // When we are in I.E. but the script has been evaled so I.E. doesn' t trust the global object when called normally
13230 return cachedClearTimeout.call(null, marker);
13231 } catch (e){
13232 // 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.
13233 // Some versions of I.E. have different rules for clearTimeout vs se tTimeout
13234 return cachedClearTimeout.call(this, marker);
13235 }
13236 }
13237
13238
13239
13240 }
13241 var queue = [];
13242 var draining = false;
13243 var currentQueue;
13244 var queueIndex = -1;
13245
13246 function cleanUpNextTick() {
13247 if (!draining || !currentQueue) {
13248 return;
13249 }
13250 draining = false;
13251 if (currentQueue.length) {
13252 queue = currentQueue.concat(queue);
13253 } else {
13254 queueIndex = -1;
13255 }
13256 if (queue.length) {
13257 drainQueue();
13258 }
13259 }
13260
13261 function drainQueue() {
13262 if (draining) {
13263 return;
13264 }
13265 var timeout = runTimeout(cleanUpNextTick);
13266 draining = true;
13267
13268 var len = queue.length;
13269 while(len) {
13270 currentQueue = queue;
13271 queue = [];
13272 while (++queueIndex < len) {
13273 if (currentQueue) {
13274 currentQueue[queueIndex].run();
13275 }
13276 }
13277 queueIndex = -1;
13278 len = queue.length;
13279 }
13280 currentQueue = null;
13281 draining = false;
13282 runClearTimeout(timeout);
13283 }
13284
13285 process.nextTick = function (fun) {
13286 var args = new Array(arguments.length - 1);
13287 if (arguments.length > 1) {
13288 for (var i = 1; i < arguments.length; i++) {
13289 args[i - 1] = arguments[i];
13290 }
13291 }
13292 queue.push(new Item(fun, args));
13293 if (queue.length === 1 && !draining) {
13294 runTimeout(drainQueue);
13295 }
13296 };
13297
13298 // v8 likes predictible objects
13299 function Item(fun, array) {
13300 this.fun = fun;
13301 this.array = array;
13302 }
13303 Item.prototype.run = function () {
13304 this.fun.apply(null, this.array);
13305 };
13306 process.title = 'browser';
13307 process.browser = true;
13308 process.env = {};
13309 process.argv = [];
13310 process.version = ''; // empty string to avoid regexp issues
13311 process.versions = {};
13312
13313 function noop() {}
13314
13315 process.on = noop;
13316 process.addListener = noop;
13317 process.once = noop;
13318 process.off = noop;
13319 process.removeListener = noop;
13320 process.removeAllListeners = noop;
13321 process.emit = noop;
13322
13323 process.binding = function (name) {
13324 throw new Error('process.binding is not supported');
13325 };
13326
13327 process.cwd = function () { return '/' };
13328 process.chdir = function (dir) {
13329 throw new Error('process.chdir is not supported');
13330 };
13331 process.umask = function() { return 0; };
13332
13333 },{}],83:[function(require,module,exports){
13334 module.exports = require("./lib/_stream_duplex.js")
13335
13336 },{"./lib/_stream_duplex.js":84}],84:[function(require,module,exports){
13337 // a duplex stream is just a stream that is both readable and writable.
13338 // Since JS doesn't have multiple prototypal inheritance, this class
13339 // prototypally inherits from Readable, and then parasitically from
13340 // Writable.
13341
13342 'use strict';
13343
13344 /*<replacement>*/
13345
13346 var objectKeys = Object.keys || function (obj) {
13347 var keys = [];
13348 for (var key in obj) {
13349 keys.push(key);
13350 }return keys;
13351 };
13352 /*</replacement>*/
13353
13354 module.exports = Duplex;
13355
13356 /*<replacement>*/
13357 var processNextTick = require('process-nextick-args');
13358 /*</replacement>*/
13359
13360 /*<replacement>*/
13361 var util = require('core-util-is');
13362 util.inherits = require('inherits');
13363 /*</replacement>*/
13364
13365 var Readable = require('./_stream_readable');
13366 var Writable = require('./_stream_writable');
13367
13368 util.inherits(Duplex, Readable);
13369
13370 var keys = objectKeys(Writable.prototype);
13371 for (var v = 0; v < keys.length; v++) {
13372 var method = keys[v];
13373 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[m ethod];
13374 }
13375
13376 function Duplex(options) {
13377 if (!(this instanceof Duplex)) return new Duplex(options);
13378
13379 Readable.call(this, options);
13380 Writable.call(this, options);
13381
13382 if (options && options.readable === false) this.readable = false;
13383
13384 if (options && options.writable === false) this.writable = false;
13385
13386 this.allowHalfOpen = true;
13387 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
13388
13389 this.once('end', onend);
13390 }
13391
13392 // the no-half-open enforcer
13393 function onend() {
13394 // if we allow half-open state, or if the writable side ended,
13395 // then we're ok.
13396 if (this.allowHalfOpen || this._writableState.ended) return;
13397
13398 // no more data can be written.
13399 // But allow more writes to happen in this tick.
13400 processNextTick(onEndNT, this);
13401 }
13402
13403 function onEndNT(self) {
13404 self.end();
13405 }
13406
13407 function forEach(xs, f) {
13408 for (var i = 0, l = xs.length; i < l; i++) {
13409 f(xs[i], i);
13410 }
13411 }
13412 },{"./_stream_readable":86,"./_stream_writable":88,"core-util-is":45,"inherits": 66,"process-nextick-args":81}],85:[function(require,module,exports){
13413 // a passthrough stream.
13414 // basically just the most minimal sort of Transform stream.
13415 // Every written chunk gets output as-is.
13416
13417 'use strict';
13418
13419 module.exports = PassThrough;
13420
13421 var Transform = require('./_stream_transform');
13422
13423 /*<replacement>*/
13424 var util = require('core-util-is');
13425 util.inherits = require('inherits');
13426 /*</replacement>*/
13427
13428 util.inherits(PassThrough, Transform);
13429
13430 function PassThrough(options) {
13431 if (!(this instanceof PassThrough)) return new PassThrough(options);
13432
13433 Transform.call(this, options);
13434 }
13435
13436 PassThrough.prototype._transform = function (chunk, encoding, cb) {
13437 cb(null, chunk);
13438 };
13439 },{"./_stream_transform":87,"core-util-is":45,"inherits":66}],86:[function(requi re,module,exports){
13440 (function (process){
13441 'use strict';
13442
13443 module.exports = Readable;
13444
13445 /*<replacement>*/
13446 var processNextTick = require('process-nextick-args');
13447 /*</replacement>*/
13448
13449 /*<replacement>*/
13450 var isArray = require('isarray');
13451 /*</replacement>*/
13452
13453 Readable.ReadableState = ReadableState;
13454
13455 /*<replacement>*/
13456 var EE = require('events').EventEmitter;
13457
13458 var EElistenerCount = function (emitter, type) {
13459 return emitter.listeners(type).length;
13460 };
13461 /*</replacement>*/
13462
13463 /*<replacement>*/
13464 var Stream;
13465 (function () {
13466 try {
13467 Stream = require('st' + 'ream');
13468 } catch (_) {} finally {
13469 if (!Stream) Stream = require('events').EventEmitter;
13470 }
13471 })();
13472 /*</replacement>*/
13473
13474 var Buffer = require('buffer').Buffer;
13475 /*<replacement>*/
13476 var bufferShim = require('buffer-shims');
13477 /*</replacement>*/
13478
13479 /*<replacement>*/
13480 var util = require('core-util-is');
13481 util.inherits = require('inherits');
13482 /*</replacement>*/
13483
13484 /*<replacement>*/
13485 var debugUtil = require('util');
13486 var debug = void 0;
13487 if (debugUtil && debugUtil.debuglog) {
13488 debug = debugUtil.debuglog('stream');
13489 } else {
13490 debug = function () {};
13491 }
13492 /*</replacement>*/
13493
13494 var BufferList = require('./internal/streams/BufferList');
13495 var StringDecoder;
13496
13497 util.inherits(Readable, Stream);
13498
13499 function prependListener(emitter, event, fn) {
13500 if (typeof emitter.prependListener === 'function') {
13501 return emitter.prependListener(event, fn);
13502 } else {
13503 // This is a hack to make sure that our error handler is attached before any
13504 // userland ones. NEVER DO THIS. This is here only because this code needs
13505 // to continue to work with older versions of Node.js that do not include
13506 // the prependListener() method. The goal is to eventually remove this hack.
13507 if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emi tter._events[event] = [fn, emitter._events[event]];
13508 }
13509 }
13510
13511 var Duplex;
13512 function ReadableState(options, stream) {
13513 Duplex = Duplex || require('./_stream_duplex');
13514
13515 options = options || {};
13516
13517 // object stream flag. Used to make read(n) ignore n and to
13518 // make all the buffer merging and length checks go away
13519 this.objectMode = !!options.objectMode;
13520
13521 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.r eadableObjectMode;
13522
13523 // the point at which it stops calling _read() to fill the buffer
13524 // Note: 0 is a valid value, means "don't call _read preemptively ever"
13525 var hwm = options.highWaterMark;
13526 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
13527 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
13528
13529 // cast to ints.
13530 this.highWaterMark = ~ ~this.highWaterMark;
13531
13532 // A linked list is used to store data chunks instead of an array because the
13533 // linked list can remove elements from the beginning faster than
13534 // array.shift()
13535 this.buffer = new BufferList();
13536 this.length = 0;
13537 this.pipes = null;
13538 this.pipesCount = 0;
13539 this.flowing = null;
13540 this.ended = false;
13541 this.endEmitted = false;
13542 this.reading = false;
13543
13544 // a flag to be able to tell if the onwrite cb is called immediately,
13545 // or on a later tick. We set this to true at first, because any
13546 // actions that shouldn't happen until "later" should generally also
13547 // not happen before the first write call.
13548 this.sync = true;
13549
13550 // whenever we return null, then we set a flag to say
13551 // that we're awaiting a 'readable' event emission.
13552 this.needReadable = false;
13553 this.emittedReadable = false;
13554 this.readableListening = false;
13555 this.resumeScheduled = false;
13556
13557 // Crypto is kind of old and crusty. Historically, its default string
13558 // encoding is 'binary' so we have to make this configurable.
13559 // Everything else in the universe uses 'utf8', though.
13560 this.defaultEncoding = options.defaultEncoding || 'utf8';
13561
13562 // when piping, we only care about 'readable' events that happen
13563 // after read()ing all the bytes and not getting any pushback.
13564 this.ranOut = false;
13565
13566 // the number of writers that are awaiting a drain event in .pipe()s
13567 this.awaitDrain = 0;
13568
13569 // if true, a maybeReadMore has been scheduled
13570 this.readingMore = false;
13571
13572 this.decoder = null;
13573 this.encoding = null;
13574 if (options.encoding) {
13575 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder ;
13576 this.decoder = new StringDecoder(options.encoding);
13577 this.encoding = options.encoding;
13578 }
13579 }
13580
13581 var Duplex;
13582 function Readable(options) {
13583 Duplex = Duplex || require('./_stream_duplex');
13584
13585 if (!(this instanceof Readable)) return new Readable(options);
13586
13587 this._readableState = new ReadableState(options, this);
13588
13589 // legacy
13590 this.readable = true;
13591
13592 if (options && typeof options.read === 'function') this._read = options.read;
13593
13594 Stream.call(this);
13595 }
13596
13597 // Manually shove something into the read() buffer.
13598 // This returns true if the highWaterMark has not been hit yet,
13599 // similar to how Writable.write() returns true if you should
13600 // write() some more.
13601 Readable.prototype.push = function (chunk, encoding) {
13602 var state = this._readableState;
13603
13604 if (!state.objectMode && typeof chunk === 'string') {
13605 encoding = encoding || state.defaultEncoding;
13606 if (encoding !== state.encoding) {
13607 chunk = bufferShim.from(chunk, encoding);
13608 encoding = '';
13609 }
13610 }
13611
13612 return readableAddChunk(this, state, chunk, encoding, false);
13613 };
13614
13615 // Unshift should *always* be something directly out of read()
13616 Readable.prototype.unshift = function (chunk) {
13617 var state = this._readableState;
13618 return readableAddChunk(this, state, chunk, '', true);
13619 };
13620
13621 Readable.prototype.isPaused = function () {
13622 return this._readableState.flowing === false;
13623 };
13624
13625 function readableAddChunk(stream, state, chunk, encoding, addToFront) {
13626 var er = chunkInvalid(state, chunk);
13627 if (er) {
13628 stream.emit('error', er);
13629 } else if (chunk === null) {
13630 state.reading = false;
13631 onEofChunk(stream, state);
13632 } else if (state.objectMode || chunk && chunk.length > 0) {
13633 if (state.ended && !addToFront) {
13634 var e = new Error('stream.push() after EOF');
13635 stream.emit('error', e);
13636 } else if (state.endEmitted && addToFront) {
13637 var _e = new Error('stream.unshift() after end event');
13638 stream.emit('error', _e);
13639 } else {
13640 var skipAdd;
13641 if (state.decoder && !addToFront && !encoding) {
13642 chunk = state.decoder.write(chunk);
13643 skipAdd = !state.objectMode && chunk.length === 0;
13644 }
13645
13646 if (!addToFront) state.reading = false;
13647
13648 // Don't add to the buffer if we've decoded to an empty string chunk and
13649 // we're not in object mode
13650 if (!skipAdd) {
13651 // if we want the data now, just emit it.
13652 if (state.flowing && state.length === 0 && !state.sync) {
13653 stream.emit('data', chunk);
13654 stream.read(0);
13655 } else {
13656 // update the buffer info.
13657 state.length += state.objectMode ? 1 : chunk.length;
13658 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chu nk);
13659
13660 if (state.needReadable) emitReadable(stream);
13661 }
13662 }
13663
13664 maybeReadMore(stream, state);
13665 }
13666 } else if (!addToFront) {
13667 state.reading = false;
13668 }
13669
13670 return needMoreData(state);
13671 }
13672
13673 // if it's past the high water mark, we can push in some more.
13674 // Also, if we have no data yet, we can stand some
13675 // more bytes. This is to work around cases where hwm=0,
13676 // such as the repl. Also, if the push() triggered a
13677 // readable event, and the user called read(largeNumber) such that
13678 // needReadable was set, then we ought to push more, so that another
13679 // 'readable' event will be triggered.
13680 function needMoreData(state) {
13681 return !state.ended && (state.needReadable || state.length < state.highWaterMa rk || state.length === 0);
13682 }
13683
13684 // backwards compatibility.
13685 Readable.prototype.setEncoding = function (enc) {
13686 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
13687 this._readableState.decoder = new StringDecoder(enc);
13688 this._readableState.encoding = enc;
13689 return this;
13690 };
13691
13692 // Don't raise the hwm > 8MB
13693 var MAX_HWM = 0x800000;
13694 function computeNewHighWaterMark(n) {
13695 if (n >= MAX_HWM) {
13696 n = MAX_HWM;
13697 } else {
13698 // Get the next highest power of 2 to prevent increasing hwm excessively in
13699 // tiny amounts
13700 n--;
13701 n |= n >>> 1;
13702 n |= n >>> 2;
13703 n |= n >>> 4;
13704 n |= n >>> 8;
13705 n |= n >>> 16;
13706 n++;
13707 }
13708 return n;
13709 }
13710
13711 // This function is designed to be inlinable, so please take care when making
13712 // changes to the function body.
13713 function howMuchToRead(n, state) {
13714 if (n <= 0 || state.length === 0 && state.ended) return 0;
13715 if (state.objectMode) return 1;
13716 if (n !== n) {
13717 // Only flow one buffer at a time
13718 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
13719 }
13720 // If we're asking for more than the current hwm, then raise the hwm.
13721 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
13722 if (n <= state.length) return n;
13723 // Don't have enough
13724 if (!state.ended) {
13725 state.needReadable = true;
13726 return 0;
13727 }
13728 return state.length;
13729 }
13730
13731 // you can override either this method, or the async _read(n) below.
13732 Readable.prototype.read = function (n) {
13733 debug('read', n);
13734 n = parseInt(n, 10);
13735 var state = this._readableState;
13736 var nOrig = n;
13737
13738 if (n !== 0) state.emittedReadable = false;
13739
13740 // if we're doing read(0) to trigger a readable event, but we
13741 // already have a bunch of data in the buffer, then just trigger
13742 // the 'readable' event and move on.
13743 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || s tate.ended)) {
13744 debug('read: emitReadable', state.length, state.ended);
13745 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(t his);
13746 return null;
13747 }
13748
13749 n = howMuchToRead(n, state);
13750
13751 // if we've ended, and we're now clear, then finish it up.
13752 if (n === 0 && state.ended) {
13753 if (state.length === 0) endReadable(this);
13754 return null;
13755 }
13756
13757 // All the actual chunk generation logic needs to be
13758 // *below* the call to _read. The reason is that in certain
13759 // synthetic stream cases, such as passthrough streams, _read
13760 // may be a completely synchronous operation which may change
13761 // the state of the read buffer, providing enough data when
13762 // before there was *not* enough.
13763 //
13764 // So, the steps are:
13765 // 1. Figure out what the state of things will be after we do
13766 // a read from the buffer.
13767 //
13768 // 2. If that resulting state will trigger a _read, then call _read.
13769 // Note that this may be asynchronous, or synchronous. Yes, it is
13770 // deeply ugly to write APIs this way, but that still doesn't mean
13771 // that the Readable class should behave improperly, as streams are
13772 // designed to be sync/async agnostic.
13773 // Take note if the _read call is sync or async (ie, if the read call
13774 // has returned yet), so that we know whether or not it's safe to emit
13775 // 'readable' etc.
13776 //
13777 // 3. Actually pull the requested chunks out of the buffer and return.
13778
13779 // if we need a readable event, then we need to do some reading.
13780 var doRead = state.needReadable;
13781 debug('need readable', doRead);
13782
13783 // if we currently have less than the highWaterMark, then also read some
13784 if (state.length === 0 || state.length - n < state.highWaterMark) {
13785 doRead = true;
13786 debug('length less than watermark', doRead);
13787 }
13788
13789 // however, if we've ended, then there's no point, and if we're already
13790 // reading, then it's unnecessary.
13791 if (state.ended || state.reading) {
13792 doRead = false;
13793 debug('reading or ended', doRead);
13794 } else if (doRead) {
13795 debug('do read');
13796 state.reading = true;
13797 state.sync = true;
13798 // if the length is currently zero, then we *need* a readable event.
13799 if (state.length === 0) state.needReadable = true;
13800 // call internal read method
13801 this._read(state.highWaterMark);
13802 state.sync = false;
13803 // If _read pushed data synchronously, then `reading` will be false,
13804 // and we need to re-evaluate how much data we can return to the user.
13805 if (!state.reading) n = howMuchToRead(nOrig, state);
13806 }
13807
13808 var ret;
13809 if (n > 0) ret = fromList(n, state);else ret = null;
13810
13811 if (ret === null) {
13812 state.needReadable = true;
13813 n = 0;
13814 } else {
13815 state.length -= n;
13816 }
13817
13818 if (state.length === 0) {
13819 // If we have nothing in the buffer, then we want to know
13820 // as soon as we *do* get something into the buffer.
13821 if (!state.ended) state.needReadable = true;
13822
13823 // If we tried to read() past the EOF, then emit end on the next tick.
13824 if (nOrig !== n && state.ended) endReadable(this);
13825 }
13826
13827 if (ret !== null) this.emit('data', ret);
13828
13829 return ret;
13830 };
13831
13832 function chunkInvalid(state, chunk) {
13833 var er = null;
13834 if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
13835 er = new TypeError('Invalid non-string/buffer chunk');
13836 }
13837 return er;
13838 }
13839
13840 function onEofChunk(stream, state) {
13841 if (state.ended) return;
13842 if (state.decoder) {
13843 var chunk = state.decoder.end();
13844 if (chunk && chunk.length) {
13845 state.buffer.push(chunk);
13846 state.length += state.objectMode ? 1 : chunk.length;
13847 }
13848 }
13849 state.ended = true;
13850
13851 // emit 'readable' now to make sure it gets picked up.
13852 emitReadable(stream);
13853 }
13854
13855 // Don't emit readable right away in sync mode, because this can trigger
13856 // another read() call => stack overflow. This way, it might trigger
13857 // a nextTick recursion warning, but that's not so bad.
13858 function emitReadable(stream) {
13859 var state = stream._readableState;
13860 state.needReadable = false;
13861 if (!state.emittedReadable) {
13862 debug('emitReadable', state.flowing);
13863 state.emittedReadable = true;
13864 if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(st ream);
13865 }
13866 }
13867
13868 function emitReadable_(stream) {
13869 debug('emit readable');
13870 stream.emit('readable');
13871 flow(stream);
13872 }
13873
13874 // at this point, the user has presumably seen the 'readable' event,
13875 // and called read() to consume some data. that may have triggered
13876 // in turn another _read(n) call, in which case reading = true if
13877 // it's in progress.
13878 // However, if we're not ended, or reading, and the length < hwm,
13879 // then go ahead and try to read some more preemptively.
13880 function maybeReadMore(stream, state) {
13881 if (!state.readingMore) {
13882 state.readingMore = true;
13883 processNextTick(maybeReadMore_, stream, state);
13884 }
13885 }
13886
13887 function maybeReadMore_(stream, state) {
13888 var len = state.length;
13889 while (!state.reading && !state.flowing && !state.ended && state.length < stat e.highWaterMark) {
13890 debug('maybeReadMore read 0');
13891 stream.read(0);
13892 if (len === state.length)
13893 // didn't get any data, stop spinning.
13894 break;else len = state.length;
13895 }
13896 state.readingMore = false;
13897 }
13898
13899 // abstract method. to be overridden in specific implementation classes.
13900 // call cb(er, data) where data is <= n in length.
13901 // for virtual (non-string, non-buffer) streams, "length" is somewhat
13902 // arbitrary, and perhaps not very meaningful.
13903 Readable.prototype._read = function (n) {
13904 this.emit('error', new Error('not implemented'));
13905 };
13906
13907 Readable.prototype.pipe = function (dest, pipeOpts) {
13908 var src = this;
13909 var state = this._readableState;
13910
13911 switch (state.pipesCount) {
13912 case 0:
13913 state.pipes = dest;
13914 break;
13915 case 1:
13916 state.pipes = [state.pipes, dest];
13917 break;
13918 default:
13919 state.pipes.push(dest);
13920 break;
13921 }
13922 state.pipesCount += 1;
13923 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
13924
13925 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout & & dest !== process.stderr;
13926
13927 var endFn = doEnd ? onend : cleanup;
13928 if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
13929
13930 dest.on('unpipe', onunpipe);
13931 function onunpipe(readable) {
13932 debug('onunpipe');
13933 if (readable === src) {
13934 cleanup();
13935 }
13936 }
13937
13938 function onend() {
13939 debug('onend');
13940 dest.end();
13941 }
13942
13943 // when the dest drains, it reduces the awaitDrain counter
13944 // on the source. This would be more elegant with a .once()
13945 // handler in flow(), but adding and removing repeatedly is
13946 // too slow.
13947 var ondrain = pipeOnDrain(src);
13948 dest.on('drain', ondrain);
13949
13950 var cleanedUp = false;
13951 function cleanup() {
13952 debug('cleanup');
13953 // cleanup event handlers once the pipe is broken
13954 dest.removeListener('close', onclose);
13955 dest.removeListener('finish', onfinish);
13956 dest.removeListener('drain', ondrain);
13957 dest.removeListener('error', onerror);
13958 dest.removeListener('unpipe', onunpipe);
13959 src.removeListener('end', onend);
13960 src.removeListener('end', cleanup);
13961 src.removeListener('data', ondata);
13962
13963 cleanedUp = true;
13964
13965 // if the reader is waiting for a drain event from this
13966 // specific writer, then it would cause it to never start
13967 // flowing again.
13968 // So, if this is awaiting a drain, then we just call it now.
13969 // If we don't know, then assume that we are waiting for one.
13970 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDra in)) ondrain();
13971 }
13972
13973 // If the user pushes more data while we're writing to dest then we'll end up
13974 // in ondata again. However, we only want to increase awaitDrain once because
13975 // dest will only emit one 'drain' event for the multiple writes.
13976 // => Introduce a guard on increasing awaitDrain.
13977 var increasedAwaitDrain = false;
13978 src.on('data', ondata);
13979 function ondata(chunk) {
13980 debug('ondata');
13981 increasedAwaitDrain = false;
13982 var ret = dest.write(chunk);
13983 if (false === ret && !increasedAwaitDrain) {
13984 // If the user unpiped during `dest.write()`, it is possible
13985 // to get stuck in a permanently paused state if that write
13986 // also returned false.
13987 // => Check whether `dest` is still a piping destination.
13988 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
13989 debug('false write response, pause', src._readableState.awaitDrain);
13990 src._readableState.awaitDrain++;
13991 increasedAwaitDrain = true;
13992 }
13993 src.pause();
13994 }
13995 }
13996
13997 // if the dest has an error, then stop piping into it.
13998 // however, don't suppress the throwing behavior for this.
13999 function onerror(er) {
14000 debug('onerror', er);
14001 unpipe();
14002 dest.removeListener('error', onerror);
14003 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
14004 }
14005
14006 // Make sure our error handler is attached before userland ones.
14007 prependListener(dest, 'error', onerror);
14008
14009 // Both close and finish should trigger unpipe, but only once.
14010 function onclose() {
14011 dest.removeListener('finish', onfinish);
14012 unpipe();
14013 }
14014 dest.once('close', onclose);
14015 function onfinish() {
14016 debug('onfinish');
14017 dest.removeListener('close', onclose);
14018 unpipe();
14019 }
14020 dest.once('finish', onfinish);
14021
14022 function unpipe() {
14023 debug('unpipe');
14024 src.unpipe(dest);
14025 }
14026
14027 // tell the dest that it's being piped to
14028 dest.emit('pipe', src);
14029
14030 // start the flow if it hasn't been started already.
14031 if (!state.flowing) {
14032 debug('pipe resume');
14033 src.resume();
14034 }
14035
14036 return dest;
14037 };
14038
14039 function pipeOnDrain(src) {
14040 return function () {
14041 var state = src._readableState;
14042 debug('pipeOnDrain', state.awaitDrain);
14043 if (state.awaitDrain) state.awaitDrain--;
14044 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
14045 state.flowing = true;
14046 flow(src);
14047 }
14048 };
14049 }
14050
14051 Readable.prototype.unpipe = function (dest) {
14052 var state = this._readableState;
14053
14054 // if we're not piping anywhere, then do nothing.
14055 if (state.pipesCount === 0) return this;
14056
14057 // just one destination. most common case.
14058 if (state.pipesCount === 1) {
14059 // passed in one, but it's not the right one.
14060 if (dest && dest !== state.pipes) return this;
14061
14062 if (!dest) dest = state.pipes;
14063
14064 // got a match.
14065 state.pipes = null;
14066 state.pipesCount = 0;
14067 state.flowing = false;
14068 if (dest) dest.emit('unpipe', this);
14069 return this;
14070 }
14071
14072 // slow case. multiple pipe destinations.
14073
14074 if (!dest) {
14075 // remove all.
14076 var dests = state.pipes;
14077 var len = state.pipesCount;
14078 state.pipes = null;
14079 state.pipesCount = 0;
14080 state.flowing = false;
14081
14082 for (var _i = 0; _i < len; _i++) {
14083 dests[_i].emit('unpipe', this);
14084 }return this;
14085 }
14086
14087 // try to find the right one.
14088 var i = indexOf(state.pipes, dest);
14089 if (i === -1) return this;
14090
14091 state.pipes.splice(i, 1);
14092 state.pipesCount -= 1;
14093 if (state.pipesCount === 1) state.pipes = state.pipes[0];
14094
14095 dest.emit('unpipe', this);
14096
14097 return this;
14098 };
14099
14100 // set up data events if they are asked for
14101 // Ensure readable listeners eventually get something
14102 Readable.prototype.on = function (ev, fn) {
14103 var res = Stream.prototype.on.call(this, ev, fn);
14104
14105 if (ev === 'data') {
14106 // Start flowing on next tick if stream isn't explicitly paused
14107 if (this._readableState.flowing !== false) this.resume();
14108 } else if (ev === 'readable') {
14109 var state = this._readableState;
14110 if (!state.endEmitted && !state.readableListening) {
14111 state.readableListening = state.needReadable = true;
14112 state.emittedReadable = false;
14113 if (!state.reading) {
14114 processNextTick(nReadingNextTick, this);
14115 } else if (state.length) {
14116 emitReadable(this, state);
14117 }
14118 }
14119 }
14120
14121 return res;
14122 };
14123 Readable.prototype.addListener = Readable.prototype.on;
14124
14125 function nReadingNextTick(self) {
14126 debug('readable nexttick read 0');
14127 self.read(0);
14128 }
14129
14130 // pause() and resume() are remnants of the legacy readable stream API
14131 // If the user uses them, then switch into old mode.
14132 Readable.prototype.resume = function () {
14133 var state = this._readableState;
14134 if (!state.flowing) {
14135 debug('resume');
14136 state.flowing = true;
14137 resume(this, state);
14138 }
14139 return this;
14140 };
14141
14142 function resume(stream, state) {
14143 if (!state.resumeScheduled) {
14144 state.resumeScheduled = true;
14145 processNextTick(resume_, stream, state);
14146 }
14147 }
14148
14149 function resume_(stream, state) {
14150 if (!state.reading) {
14151 debug('resume read 0');
14152 stream.read(0);
14153 }
14154
14155 state.resumeScheduled = false;
14156 state.awaitDrain = 0;
14157 stream.emit('resume');
14158 flow(stream);
14159 if (state.flowing && !state.reading) stream.read(0);
14160 }
14161
14162 Readable.prototype.pause = function () {
14163 debug('call pause flowing=%j', this._readableState.flowing);
14164 if (false !== this._readableState.flowing) {
14165 debug('pause');
14166 this._readableState.flowing = false;
14167 this.emit('pause');
14168 }
14169 return this;
14170 };
14171
14172 function flow(stream) {
14173 var state = stream._readableState;
14174 debug('flow', state.flowing);
14175 while (state.flowing && stream.read() !== null) {}
14176 }
14177
14178 // wrap an old-style stream as the async data source.
14179 // This is *not* part of the readable stream interface.
14180 // It is an ugly unfortunate mess of history.
14181 Readable.prototype.wrap = function (stream) {
14182 var state = this._readableState;
14183 var paused = false;
14184
14185 var self = this;
14186 stream.on('end', function () {
14187 debug('wrapped end');
14188 if (state.decoder && !state.ended) {
14189 var chunk = state.decoder.end();
14190 if (chunk && chunk.length) self.push(chunk);
14191 }
14192
14193 self.push(null);
14194 });
14195
14196 stream.on('data', function (chunk) {
14197 debug('wrapped data');
14198 if (state.decoder) chunk = state.decoder.write(chunk);
14199
14200 // don't skip over falsy values in objectMode
14201 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
14202
14203 var ret = self.push(chunk);
14204 if (!ret) {
14205 paused = true;
14206 stream.pause();
14207 }
14208 });
14209
14210 // proxy all the other methods.
14211 // important when wrapping filters and duplexes.
14212 for (var i in stream) {
14213 if (this[i] === undefined && typeof stream[i] === 'function') {
14214 this[i] = function (method) {
14215 return function () {
14216 return stream[method].apply(stream, arguments);
14217 };
14218 }(i);
14219 }
14220 }
14221
14222 // proxy certain important events.
14223 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
14224 forEach(events, function (ev) {
14225 stream.on(ev, self.emit.bind(self, ev));
14226 });
14227
14228 // when we try to consume some more bytes, simply unpause the
14229 // underlying stream.
14230 self._read = function (n) {
14231 debug('wrapped _read', n);
14232 if (paused) {
14233 paused = false;
14234 stream.resume();
14235 }
14236 };
14237
14238 return self;
14239 };
14240
14241 // exposed for testing purposes only.
14242 Readable._fromList = fromList;
14243
14244 // Pluck off n bytes from an array of buffers.
14245 // Length is the combined lengths of all the buffers in the list.
14246 // This function is designed to be inlinable, so please take care when making
14247 // changes to the function body.
14248 function fromList(n, state) {
14249 // nothing buffered
14250 if (state.length === 0) return null;
14251
14252 var ret;
14253 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.len gth) {
14254 // read it all, truncate the list
14255 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) ;
14256 state.buffer.clear();
14257 } else {
14258 // read part of list
14259 ret = fromListPartial(n, state.buffer, state.decoder);
14260 }
14261
14262 return ret;
14263 }
14264
14265 // Extracts only enough buffered data to satisfy the amount requested.
14266 // This function is designed to be inlinable, so please take care when making
14267 // changes to the function body.
14268 function fromListPartial(n, list, hasStrings) {
14269 var ret;
14270 if (n < list.head.data.length) {
14271 // slice is the same for buffers and strings
14272 ret = list.head.data.slice(0, n);
14273 list.head.data = list.head.data.slice(n);
14274 } else if (n === list.head.data.length) {
14275 // first chunk is a perfect match
14276 ret = list.shift();
14277 } else {
14278 // result spans more than one buffer
14279 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
14280 }
14281 return ret;
14282 }
14283
14284 // Copies a specified amount of characters from the list of buffered data
14285 // chunks.
14286 // This function is designed to be inlinable, so please take care when making
14287 // changes to the function body.
14288 function copyFromBufferString(n, list) {
14289 var p = list.head;
14290 var c = 1;
14291 var ret = p.data;
14292 n -= ret.length;
14293 while (p = p.next) {
14294 var str = p.data;
14295 var nb = n > str.length ? str.length : n;
14296 if (nb === str.length) ret += str;else ret += str.slice(0, n);
14297 n -= nb;
14298 if (n === 0) {
14299 if (nb === str.length) {
14300 ++c;
14301 if (p.next) list.head = p.next;else list.head = list.tail = null;
14302 } else {
14303 list.head = p;
14304 p.data = str.slice(nb);
14305 }
14306 break;
14307 }
14308 ++c;
14309 }
14310 list.length -= c;
14311 return ret;
14312 }
14313
14314 // Copies a specified amount of bytes from the list of buffered data chunks.
14315 // This function is designed to be inlinable, so please take care when making
14316 // changes to the function body.
14317 function copyFromBuffer(n, list) {
14318 var ret = bufferShim.allocUnsafe(n);
14319 var p = list.head;
14320 var c = 1;
14321 p.data.copy(ret);
14322 n -= p.data.length;
14323 while (p = p.next) {
14324 var buf = p.data;
14325 var nb = n > buf.length ? buf.length : n;
14326 buf.copy(ret, ret.length - n, 0, nb);
14327 n -= nb;
14328 if (n === 0) {
14329 if (nb === buf.length) {
14330 ++c;
14331 if (p.next) list.head = p.next;else list.head = list.tail = null;
14332 } else {
14333 list.head = p;
14334 p.data = buf.slice(nb);
14335 }
14336 break;
14337 }
14338 ++c;
14339 }
14340 list.length -= c;
14341 return ret;
14342 }
14343
14344 function endReadable(stream) {
14345 var state = stream._readableState;
14346
14347 // If we get here before consuming all the bytes, then that is a
14348 // bug in node. Should never happen.
14349 if (state.length > 0) throw new Error('"endReadable()" called on non-empty str eam');
14350
14351 if (!state.endEmitted) {
14352 state.ended = true;
14353 processNextTick(endReadableNT, state, stream);
14354 }
14355 }
14356
14357 function endReadableNT(state, stream) {
14358 // Check that we didn't get one last unshift.
14359 if (!state.endEmitted && state.length === 0) {
14360 state.endEmitted = true;
14361 stream.readable = false;
14362 stream.emit('end');
14363 }
14364 }
14365
14366 function forEach(xs, f) {
14367 for (var i = 0, l = xs.length; i < l; i++) {
14368 f(xs[i], i);
14369 }
14370 }
14371
14372 function indexOf(xs, x) {
14373 for (var i = 0, l = xs.length; i < l; i++) {
14374 if (xs[i] === x) return i;
14375 }
14376 return -1;
14377 }
14378 }).call(this,require('_process'))
14379 },{"./_stream_duplex":84,"./internal/streams/BufferList":89,"_process":82,"buffe r":44,"buffer-shims":43,"core-util-is":45,"events":63,"inherits":66,"isarray":68 ,"process-nextick-args":81,"string_decoder/":95,"util":40}],87:[function(require ,module,exports){
14380 // a transform stream is a readable/writable stream where you do
14381 // something with the data. Sometimes it's called a "filter",
14382 // but that's not a great name for it, since that implies a thing where
14383 // some bits pass through, and others are simply ignored. (That would
14384 // be a valid example of a transform, of course.)
14385 //
14386 // While the output is causally related to the input, it's not a
14387 // necessarily symmetric or synchronous transformation. For example,
14388 // a zlib stream might take multiple plain-text writes(), and then
14389 // emit a single compressed chunk some time in the future.
14390 //
14391 // Here's how this works:
14392 //
14393 // The Transform stream has all the aspects of the readable and writable
14394 // stream classes. When you write(chunk), that calls _write(chunk,cb)
14395 // internally, and returns false if there's a lot of pending writes
14396 // buffered up. When you call read(), that calls _read(n) until
14397 // there's enough pending readable data buffered up.
14398 //
14399 // In a transform stream, the written data is placed in a buffer. When
14400 // _read(n) is called, it transforms the queued up data, calling the
14401 // buffered _write cb's as it consumes chunks. If consuming a single
14402 // written chunk would result in multiple output chunks, then the first
14403 // outputted bit calls the readcb, and subsequent chunks just go into
14404 // the read buffer, and will cause it to emit 'readable' if necessary.
14405 //
14406 // This way, back-pressure is actually determined by the reading side,
14407 // since _read has to be called to start processing a new chunk. However,
14408 // a pathological inflate type of transform can cause excessive buffering
14409 // here. For example, imagine a stream where every byte of input is
14410 // interpreted as an integer from 0-255, and then results in that many
14411 // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
14412 // 1kb of data being output. In this case, you could write a very small
14413 // amount of input, and end up with a very large amount of output. In
14414 // such a pathological inflating mechanism, there'd be no way to tell
14415 // the system to stop doing the transform. A single 4MB write could
14416 // cause the system to run out of memory.
14417 //
14418 // However, even in such a pathological case, only a single written chunk
14419 // would be consumed, and then the rest would wait (un-transformed) until
14420 // the results of the previous transformed chunk were consumed.
14421
14422 'use strict';
14423
14424 module.exports = Transform;
14425
14426 var Duplex = require('./_stream_duplex');
14427
14428 /*<replacement>*/
14429 var util = require('core-util-is');
14430 util.inherits = require('inherits');
14431 /*</replacement>*/
14432
14433 util.inherits(Transform, Duplex);
14434
14435 function TransformState(stream) {
14436 this.afterTransform = function (er, data) {
14437 return afterTransform(stream, er, data);
14438 };
14439
14440 this.needTransform = false;
14441 this.transforming = false;
14442 this.writecb = null;
14443 this.writechunk = null;
14444 this.writeencoding = null;
14445 }
14446
14447 function afterTransform(stream, er, data) {
14448 var ts = stream._transformState;
14449 ts.transforming = false;
14450
14451 var cb = ts.writecb;
14452
14453 if (!cb) return stream.emit('error', new Error('no writecb in Transform class' ));
14454
14455 ts.writechunk = null;
14456 ts.writecb = null;
14457
14458 if (data !== null && data !== undefined) stream.push(data);
14459
14460 cb(er);
14461
14462 var rs = stream._readableState;
14463 rs.reading = false;
14464 if (rs.needReadable || rs.length < rs.highWaterMark) {
14465 stream._read(rs.highWaterMark);
14466 }
14467 }
14468
14469 function Transform(options) {
14470 if (!(this instanceof Transform)) return new Transform(options);
14471
14472 Duplex.call(this, options);
14473
14474 this._transformState = new TransformState(this);
14475
14476 // when the writable side finishes, then flush out anything remaining.
14477 var stream = this;
14478
14479 // start out asking for a readable event once data is transformed.
14480 this._readableState.needReadable = true;
14481
14482 // we have implemented the _read method, and done the other things
14483 // that Readable wants before the first _read call, so unset the
14484 // sync guard flag.
14485 this._readableState.sync = false;
14486
14487 if (options) {
14488 if (typeof options.transform === 'function') this._transform = options.trans form;
14489
14490 if (typeof options.flush === 'function') this._flush = options.flush;
14491 }
14492
14493 this.once('prefinish', function () {
14494 if (typeof this._flush === 'function') this._flush(function (er) {
14495 done(stream, er);
14496 });else done(stream);
14497 });
14498 }
14499
14500 Transform.prototype.push = function (chunk, encoding) {
14501 this._transformState.needTransform = false;
14502 return Duplex.prototype.push.call(this, chunk, encoding);
14503 };
14504
14505 // This is the part where you do stuff!
14506 // override this function in implementation classes.
14507 // 'chunk' is an input chunk.
14508 //
14509 // Call `push(newChunk)` to pass along transformed output
14510 // to the readable side. You may call 'push' zero or more times.
14511 //
14512 // Call `cb(err)` when you are done with this chunk. If you pass
14513 // an error, then that'll put the hurt on the whole operation. If you
14514 // never call cb(), then you'll never get another chunk.
14515 Transform.prototype._transform = function (chunk, encoding, cb) {
14516 throw new Error('Not implemented');
14517 };
14518
14519 Transform.prototype._write = function (chunk, encoding, cb) {
14520 var ts = this._transformState;
14521 ts.writecb = cb;
14522 ts.writechunk = chunk;
14523 ts.writeencoding = encoding;
14524 if (!ts.transforming) {
14525 var rs = this._readableState;
14526 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) thi s._read(rs.highWaterMark);
14527 }
14528 };
14529
14530 // Doesn't matter what the args are here.
14531 // _transform does all the work.
14532 // That we got here means that the readable side wants more data.
14533 Transform.prototype._read = function (n) {
14534 var ts = this._transformState;
14535
14536 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
14537 ts.transforming = true;
14538 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
14539 } else {
14540 // mark that we need a transform, so that any data that comes in
14541 // will get processed, now that we've asked for it.
14542 ts.needTransform = true;
14543 }
14544 };
14545
14546 function done(stream, er) {
14547 if (er) return stream.emit('error', er);
14548
14549 // if there's nothing in the write buffer, then that means
14550 // that nothing more will ever be provided
14551 var ws = stream._writableState;
14552 var ts = stream._transformState;
14553
14554 if (ws.length) throw new Error('Calling transform done when ws.length != 0');
14555
14556 if (ts.transforming) throw new Error('Calling transform done when still transf orming');
14557
14558 return stream.push(null);
14559 }
14560 },{"./_stream_duplex":84,"core-util-is":45,"inherits":66}],88:[function(require, module,exports){
14561 (function (process){
14562 // A bit simpler than readable streams.
14563 // Implement an async ._write(chunk, encoding, cb), and it'll handle all
14564 // the drain event emission and buffering.
14565
14566 'use strict';
14567
14568 module.exports = Writable;
14569
14570 /*<replacement>*/
14571 var processNextTick = require('process-nextick-args');
14572 /*</replacement>*/
14573
14574 /*<replacement>*/
14575 var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version. slice(0, 5)) > -1 ? setImmediate : processNextTick;
14576 /*</replacement>*/
14577
14578 Writable.WritableState = WritableState;
14579
14580 /*<replacement>*/
14581 var util = require('core-util-is');
14582 util.inherits = require('inherits');
14583 /*</replacement>*/
14584
14585 /*<replacement>*/
14586 var internalUtil = {
14587 deprecate: require('util-deprecate')
14588 };
14589 /*</replacement>*/
14590
14591 /*<replacement>*/
14592 var Stream;
14593 (function () {
14594 try {
14595 Stream = require('st' + 'ream');
14596 } catch (_) {} finally {
14597 if (!Stream) Stream = require('events').EventEmitter;
14598 }
14599 })();
14600 /*</replacement>*/
14601
14602 var Buffer = require('buffer').Buffer;
14603 /*<replacement>*/
14604 var bufferShim = require('buffer-shims');
14605 /*</replacement>*/
14606
14607 util.inherits(Writable, Stream);
14608
14609 function nop() {}
14610
14611 function WriteReq(chunk, encoding, cb) {
14612 this.chunk = chunk;
14613 this.encoding = encoding;
14614 this.callback = cb;
14615 this.next = null;
14616 }
14617
14618 var Duplex;
14619 function WritableState(options, stream) {
14620 Duplex = Duplex || require('./_stream_duplex');
14621
14622 options = options || {};
14623
14624 // object stream flag to indicate whether or not this stream
14625 // contains buffers or objects.
14626 this.objectMode = !!options.objectMode;
14627
14628 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.w ritableObjectMode;
14629
14630 // the point at which write() starts returning false
14631 // Note: 0 is a valid value, means that we always return false if
14632 // the entire buffer is not flushed immediately on write()
14633 var hwm = options.highWaterMark;
14634 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
14635 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
14636
14637 // cast to ints.
14638 this.highWaterMark = ~ ~this.highWaterMark;
14639
14640 this.needDrain = false;
14641 // at the start of calling end()
14642 this.ending = false;
14643 // when end() has been called, and returned
14644 this.ended = false;
14645 // when 'finish' is emitted
14646 this.finished = false;
14647
14648 // should we decode strings into buffers before passing to _write?
14649 // this is here so that some node-core streams can optimize string
14650 // handling at a lower level.
14651 var noDecode = options.decodeStrings === false;
14652 this.decodeStrings = !noDecode;
14653
14654 // Crypto is kind of old and crusty. Historically, its default string
14655 // encoding is 'binary' so we have to make this configurable.
14656 // Everything else in the universe uses 'utf8', though.
14657 this.defaultEncoding = options.defaultEncoding || 'utf8';
14658
14659 // not an actual buffer we keep track of, but a measurement
14660 // of how much we're waiting to get pushed to some underlying
14661 // socket or file.
14662 this.length = 0;
14663
14664 // a flag to see when we're in the middle of a write.
14665 this.writing = false;
14666
14667 // when true all writes will be buffered until .uncork() call
14668 this.corked = 0;
14669
14670 // a flag to be able to tell if the onwrite cb is called immediately,
14671 // or on a later tick. We set this to true at first, because any
14672 // actions that shouldn't happen until "later" should generally also
14673 // not happen before the first write call.
14674 this.sync = true;
14675
14676 // a flag to know if we're processing previously buffered items, which
14677 // may call the _write() callback in the same tick, so that we don't
14678 // end up in an overlapped onwrite situation.
14679 this.bufferProcessing = false;
14680
14681 // the callback that's passed to _write(chunk,cb)
14682 this.onwrite = function (er) {
14683 onwrite(stream, er);
14684 };
14685
14686 // the callback that the user supplies to write(chunk,encoding,cb)
14687 this.writecb = null;
14688
14689 // the amount that is being written when _write is called.
14690 this.writelen = 0;
14691
14692 this.bufferedRequest = null;
14693 this.lastBufferedRequest = null;
14694
14695 // number of pending user-supplied write callbacks
14696 // this must be 0 before 'finish' can be emitted
14697 this.pendingcb = 0;
14698
14699 // emit prefinish if the only thing we're waiting for is _write cbs
14700 // This is relevant for synchronous Transform streams
14701 this.prefinished = false;
14702
14703 // True if the error was already emitted and should not be thrown again
14704 this.errorEmitted = false;
14705
14706 // count buffered requests
14707 this.bufferedRequestCount = 0;
14708
14709 // allocate the first CorkedRequest, there is always
14710 // one allocated and free to use, and we maintain at most two
14711 this.corkedRequestsFree = new CorkedRequest(this);
14712 }
14713
14714 WritableState.prototype.getBuffer = function writableStateGetBuffer() {
14715 var current = this.bufferedRequest;
14716 var out = [];
14717 while (current) {
14718 out.push(current);
14719 current = current.next;
14720 }
14721 return out;
14722 };
14723
14724 (function () {
14725 try {
14726 Object.defineProperty(WritableState.prototype, 'buffer', {
14727 get: internalUtil.deprecate(function () {
14728 return this.getBuffer();
14729 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
14730 });
14731 } catch (_) {}
14732 })();
14733
14734 var Duplex;
14735 function Writable(options) {
14736 Duplex = Duplex || require('./_stream_duplex');
14737
14738 // Writable ctor is applied to Duplexes, though they're not
14739 // instanceof Writable, they're instanceof Readable.
14740 if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writa ble(options);
14741
14742 this._writableState = new WritableState(options, this);
14743
14744 // legacy.
14745 this.writable = true;
14746
14747 if (options) {
14748 if (typeof options.write === 'function') this._write = options.write;
14749
14750 if (typeof options.writev === 'function') this._writev = options.writev;
14751 }
14752
14753 Stream.call(this);
14754 }
14755
14756 // Otherwise people can pipe Writable streams, which is just wrong.
14757 Writable.prototype.pipe = function () {
14758 this.emit('error', new Error('Cannot pipe, not readable'));
14759 };
14760
14761 function writeAfterEnd(stream, cb) {
14762 var er = new Error('write after end');
14763 // TODO: defer error events consistently everywhere, not just the cb
14764 stream.emit('error', er);
14765 processNextTick(cb, er);
14766 }
14767
14768 // If we get something that is not a buffer, string, null, or undefined,
14769 // and we're not in objectMode, then that's an error.
14770 // Otherwise stream chunks are all considered to be of length=1, and the
14771 // watermarks determine how many objects to keep in the buffer, rather than
14772 // how many bytes or characters.
14773 function validChunk(stream, state, chunk, cb) {
14774 var valid = true;
14775 var er = false;
14776 // Always throw error if a null is written
14777 // if we are not in object mode then throw
14778 // if it is not a buffer, string, or undefined.
14779 if (chunk === null) {
14780 er = new TypeError('May not write null values to stream');
14781 } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== u ndefined && !state.objectMode) {
14782 er = new TypeError('Invalid non-string/buffer chunk');
14783 }
14784 if (er) {
14785 stream.emit('error', er);
14786 processNextTick(cb, er);
14787 valid = false;
14788 }
14789 return valid;
14790 }
14791
14792 Writable.prototype.write = function (chunk, encoding, cb) {
14793 var state = this._writableState;
14794 var ret = false;
14795
14796 if (typeof encoding === 'function') {
14797 cb = encoding;
14798 encoding = null;
14799 }
14800
14801 if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
14802
14803 if (typeof cb !== 'function') cb = nop;
14804
14805 if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chun k, cb)) {
14806 state.pendingcb++;
14807 ret = writeOrBuffer(this, state, chunk, encoding, cb);
14808 }
14809
14810 return ret;
14811 };
14812
14813 Writable.prototype.cork = function () {
14814 var state = this._writableState;
14815
14816 state.corked++;
14817 };
14818
14819 Writable.prototype.uncork = function () {
14820 var state = this._writableState;
14821
14822 if (state.corked) {
14823 state.corked--;
14824
14825 if (!state.writing && !state.corked && !state.finished && !state.bufferProce ssing && state.bufferedRequest) clearBuffer(this, state);
14826 }
14827 };
14828
14829 Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
14830 // node::ParseEncoding() requires lower case.
14831 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
14832 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);
14833 this._writableState.defaultEncoding = encoding;
14834 return this;
14835 };
14836
14837 function decodeChunk(state, chunk, encoding) {
14838 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'st ring') {
14839 chunk = bufferShim.from(chunk, encoding);
14840 }
14841 return chunk;
14842 }
14843
14844 // if we're already writing something, then just put this
14845 // in the queue, and wait our turn. Otherwise, call _write
14846 // If we return false, then we need a drain event, so set that flag.
14847 function writeOrBuffer(stream, state, chunk, encoding, cb) {
14848 chunk = decodeChunk(state, chunk, encoding);
14849
14850 if (Buffer.isBuffer(chunk)) encoding = 'buffer';
14851 var len = state.objectMode ? 1 : chunk.length;
14852
14853 state.length += len;
14854
14855 var ret = state.length < state.highWaterMark;
14856 // we must ensure that previous needDrain will not be reset to false.
14857 if (!ret) state.needDrain = true;
14858
14859 if (state.writing || state.corked) {
14860 var last = state.lastBufferedRequest;
14861 state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
14862 if (last) {
14863 last.next = state.lastBufferedRequest;
14864 } else {
14865 state.bufferedRequest = state.lastBufferedRequest;
14866 }
14867 state.bufferedRequestCount += 1;
14868 } else {
14869 doWrite(stream, state, false, len, chunk, encoding, cb);
14870 }
14871
14872 return ret;
14873 }
14874
14875 function doWrite(stream, state, writev, len, chunk, encoding, cb) {
14876 state.writelen = len;
14877 state.writecb = cb;
14878 state.writing = true;
14879 state.sync = true;
14880 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, enc oding, state.onwrite);
14881 state.sync = false;
14882 }
14883
14884 function onwriteError(stream, state, sync, er, cb) {
14885 --state.pendingcb;
14886 if (sync) processNextTick(cb, er);else cb(er);
14887
14888 stream._writableState.errorEmitted = true;
14889 stream.emit('error', er);
14890 }
14891
14892 function onwriteStateUpdate(state) {
14893 state.writing = false;
14894 state.writecb = null;
14895 state.length -= state.writelen;
14896 state.writelen = 0;
14897 }
14898
14899 function onwrite(stream, er) {
14900 var state = stream._writableState;
14901 var sync = state.sync;
14902 var cb = state.writecb;
14903
14904 onwriteStateUpdate(state);
14905
14906 if (er) onwriteError(stream, state, sync, er, cb);else {
14907 // Check if we're actually ready to finish, but don't emit yet
14908 var finished = needFinish(state);
14909
14910 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedR equest) {
14911 clearBuffer(stream, state);
14912 }
14913
14914 if (sync) {
14915 /*<replacement>*/
14916 asyncWrite(afterWrite, stream, state, finished, cb);
14917 /*</replacement>*/
14918 } else {
14919 afterWrite(stream, state, finished, cb);
14920 }
14921 }
14922 }
14923
14924 function afterWrite(stream, state, finished, cb) {
14925 if (!finished) onwriteDrain(stream, state);
14926 state.pendingcb--;
14927 cb();
14928 finishMaybe(stream, state);
14929 }
14930
14931 // Must force callback to be called on nextTick, so that we don't
14932 // emit 'drain' before the write() consumer gets the 'false' return
14933 // value, and has a chance to attach a 'drain' listener.
14934 function onwriteDrain(stream, state) {
14935 if (state.length === 0 && state.needDrain) {
14936 state.needDrain = false;
14937 stream.emit('drain');
14938 }
14939 }
14940
14941 // if there's something in the buffer waiting, then process it
14942 function clearBuffer(stream, state) {
14943 state.bufferProcessing = true;
14944 var entry = state.bufferedRequest;
14945
14946 if (stream._writev && entry && entry.next) {
14947 // Fast case, write everything using _writev()
14948 var l = state.bufferedRequestCount;
14949 var buffer = new Array(l);
14950 var holder = state.corkedRequestsFree;
14951 holder.entry = entry;
14952
14953 var count = 0;
14954 while (entry) {
14955 buffer[count] = entry;
14956 entry = entry.next;
14957 count += 1;
14958 }
14959
14960 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
14961
14962 // doWrite is almost always async, defer these to save a bit of time
14963 // as the hot path ends with doWrite
14964 state.pendingcb++;
14965 state.lastBufferedRequest = null;
14966 if (holder.next) {
14967 state.corkedRequestsFree = holder.next;
14968 holder.next = null;
14969 } else {
14970 state.corkedRequestsFree = new CorkedRequest(state);
14971 }
14972 } else {
14973 // Slow case, write chunks one-by-one
14974 while (entry) {
14975 var chunk = entry.chunk;
14976 var encoding = entry.encoding;
14977 var cb = entry.callback;
14978 var len = state.objectMode ? 1 : chunk.length;
14979
14980 doWrite(stream, state, false, len, chunk, encoding, cb);
14981 entry = entry.next;
14982 // if we didn't call the onwrite immediately, then
14983 // it means that we need to wait until it does.
14984 // also, that means that the chunk and cb are currently
14985 // being processed, so move the buffer counter past them.
14986 if (state.writing) {
14987 break;
14988 }
14989 }
14990
14991 if (entry === null) state.lastBufferedRequest = null;
14992 }
14993
14994 state.bufferedRequestCount = 0;
14995 state.bufferedRequest = entry;
14996 state.bufferProcessing = false;
14997 }
14998
14999 Writable.prototype._write = function (chunk, encoding, cb) {
15000 cb(new Error('not implemented'));
15001 };
15002
15003 Writable.prototype._writev = null;
15004
15005 Writable.prototype.end = function (chunk, encoding, cb) {
15006 var state = this._writableState;
15007
15008 if (typeof chunk === 'function') {
15009 cb = chunk;
15010 chunk = null;
15011 encoding = null;
15012 } else if (typeof encoding === 'function') {
15013 cb = encoding;
15014 encoding = null;
15015 }
15016
15017 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
15018
15019 // .end() fully uncorks
15020 if (state.corked) {
15021 state.corked = 1;
15022 this.uncork();
15023 }
15024
15025 // ignore unnecessary end() calls.
15026 if (!state.ending && !state.finished) endWritable(this, state, cb);
15027 };
15028
15029 function needFinish(state) {
15030 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
15031 }
15032
15033 function prefinish(stream, state) {
15034 if (!state.prefinished) {
15035 state.prefinished = true;
15036 stream.emit('prefinish');
15037 }
15038 }
15039
15040 function finishMaybe(stream, state) {
15041 var need = needFinish(state);
15042 if (need) {
15043 if (state.pendingcb === 0) {
15044 prefinish(stream, state);
15045 state.finished = true;
15046 stream.emit('finish');
15047 } else {
15048 prefinish(stream, state);
15049 }
15050 }
15051 return need;
15052 }
15053
15054 function endWritable(stream, state, cb) {
15055 state.ending = true;
15056 finishMaybe(stream, state);
15057 if (cb) {
15058 if (state.finished) processNextTick(cb);else stream.once('finish', cb);
15059 }
15060 state.ended = true;
15061 stream.writable = false;
15062 }
15063
15064 // It seems a linked list but it is not
15065 // there will be only 2 of these for each stream
15066 function CorkedRequest(state) {
15067 var _this = this;
15068
15069 this.next = null;
15070 this.entry = null;
15071
15072 this.finish = function (err) {
15073 var entry = _this.entry;
15074 _this.entry = null;
15075 while (entry) {
15076 var cb = entry.callback;
15077 state.pendingcb--;
15078 cb(err);
15079 entry = entry.next;
15080 }
15081 if (state.corkedRequestsFree) {
15082 state.corkedRequestsFree.next = _this;
15083 } else {
15084 state.corkedRequestsFree = _this;
15085 }
15086 };
15087 }
15088 }).call(this,require('_process'))
15089 },{"./_stream_duplex":84,"_process":82,"buffer":44,"buffer-shims":43,"core-util- is":45,"events":63,"inherits":66,"process-nextick-args":81,"util-deprecate":96}] ,89:[function(require,module,exports){
15090 'use strict';
15091
15092 var Buffer = require('buffer').Buffer;
15093 /*<replacement>*/
15094 var bufferShim = require('buffer-shims');
15095 /*</replacement>*/
15096
15097 module.exports = BufferList;
15098
15099 function BufferList() {
15100 this.head = null;
15101 this.tail = null;
15102 this.length = 0;
15103 }
15104
15105 BufferList.prototype.push = function (v) {
15106 var entry = { data: v, next: null };
15107 if (this.length > 0) this.tail.next = entry;else this.head = entry;
15108 this.tail = entry;
15109 ++this.length;
15110 };
15111
15112 BufferList.prototype.unshift = function (v) {
15113 var entry = { data: v, next: this.head };
15114 if (this.length === 0) this.tail = entry;
15115 this.head = entry;
15116 ++this.length;
15117 };
15118
15119 BufferList.prototype.shift = function () {
15120 if (this.length === 0) return;
15121 var ret = this.head.data;
15122 if (this.length === 1) this.head = this.tail = null;else this.head = this.head .next;
15123 --this.length;
15124 return ret;
15125 };
15126
15127 BufferList.prototype.clear = function () {
15128 this.head = this.tail = null;
15129 this.length = 0;
15130 };
15131
15132 BufferList.prototype.join = function (s) {
15133 if (this.length === 0) return '';
15134 var p = this.head;
15135 var ret = '' + p.data;
15136 while (p = p.next) {
15137 ret += s + p.data;
15138 }return ret;
15139 };
15140
15141 BufferList.prototype.concat = function (n) {
15142 if (this.length === 0) return bufferShim.alloc(0);
15143 if (this.length === 1) return this.head.data;
15144 var ret = bufferShim.allocUnsafe(n >>> 0);
15145 var p = this.head;
15146 var i = 0;
15147 while (p) {
15148 p.data.copy(ret, i);
15149 i += p.data.length;
15150 p = p.next;
15151 }
15152 return ret;
15153 };
15154 },{"buffer":44,"buffer-shims":43}],90:[function(require,module,exports){
15155 module.exports = require("./lib/_stream_passthrough.js")
15156
15157 },{"./lib/_stream_passthrough.js":85}],91:[function(require,module,exports){
15158 (function (process){
15159 var Stream = (function (){
15160 try {
15161 return require('st' + 'ream'); // hack to fix a circular dependency issue wh en used with browserify
15162 } catch(_){}
15163 }());
15164 exports = module.exports = require('./lib/_stream_readable.js');
15165 exports.Stream = Stream || exports;
15166 exports.Readable = exports;
15167 exports.Writable = require('./lib/_stream_writable.js');
15168 exports.Duplex = require('./lib/_stream_duplex.js');
15169 exports.Transform = require('./lib/_stream_transform.js');
15170 exports.PassThrough = require('./lib/_stream_passthrough.js');
15171
15172 if (!process.browser && process.env.READABLE_STREAM === 'disable' && Stream) {
15173 module.exports = Stream;
15174 }
15175
15176 }).call(this,require('_process'))
15177 },{"./lib/_stream_duplex.js":84,"./lib/_stream_passthrough.js":85,"./lib/_stream _readable.js":86,"./lib/_stream_transform.js":87,"./lib/_stream_writable.js":88, "_process":82}],92:[function(require,module,exports){
15178 module.exports = require("./lib/_stream_transform.js")
15179
15180 },{"./lib/_stream_transform.js":87}],93:[function(require,module,exports){
15181 module.exports = require("./lib/_stream_writable.js")
15182
15183 },{"./lib/_stream_writable.js":88}],94:[function(require,module,exports){
15184 // Copyright Joyent, Inc. and other Node contributors.
15185 //
15186 // Permission is hereby granted, free of charge, to any person obtaining a
15187 // copy of this software and associated documentation files (the
15188 // "Software"), to deal in the Software without restriction, including
15189 // without limitation the rights to use, copy, modify, merge, publish,
15190 // distribute, sublicense, and/or sell copies of the Software, and to permit
15191 // persons to whom the Software is furnished to do so, subject to the
15192 // following conditions:
15193 //
15194 // The above copyright notice and this permission notice shall be included
15195 // in all copies or substantial portions of the Software.
15196 //
15197 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15198 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15199 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15200 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15201 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15202 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15203 // USE OR OTHER DEALINGS IN THE SOFTWARE.
15204
15205 module.exports = Stream;
15206
15207 var EE = require('events').EventEmitter;
15208 var inherits = require('inherits');
15209
15210 inherits(Stream, EE);
15211 Stream.Readable = require('readable-stream/readable.js');
15212 Stream.Writable = require('readable-stream/writable.js');
15213 Stream.Duplex = require('readable-stream/duplex.js');
15214 Stream.Transform = require('readable-stream/transform.js');
15215 Stream.PassThrough = require('readable-stream/passthrough.js');
15216
15217 // Backwards-compat with node 0.4.x
15218 Stream.Stream = Stream;
15219
15220
15221
15222 // old-style streams. Note that the pipe method (the only relevant
15223 // part of this class) is overridden in the Readable class.
15224
15225 function Stream() {
15226 EE.call(this);
15227 }
15228
15229 Stream.prototype.pipe = function(dest, options) {
15230 var source = this;
15231
15232 function ondata(chunk) {
15233 if (dest.writable) {
15234 if (false === dest.write(chunk) && source.pause) {
15235 source.pause();
15236 }
15237 }
15238 }
15239
15240 source.on('data', ondata);
15241
15242 function ondrain() {
15243 if (source.readable && source.resume) {
15244 source.resume();
15245 }
15246 }
15247
15248 dest.on('drain', ondrain);
15249
15250 // If the 'end' option is not supplied, dest.end() will be called when
15251 // source gets the 'end' or 'close' events. Only dest.end() once.
15252 if (!dest._isStdio && (!options || options.end !== false)) {
15253 source.on('end', onend);
15254 source.on('close', onclose);
15255 }
15256
15257 var didOnEnd = false;
15258 function onend() {
15259 if (didOnEnd) return;
15260 didOnEnd = true;
15261
15262 dest.end();
15263 }
15264
15265
15266 function onclose() {
15267 if (didOnEnd) return;
15268 didOnEnd = true;
15269
15270 if (typeof dest.destroy === 'function') dest.destroy();
15271 }
15272
15273 // don't leave dangling pipes when there are errors.
15274 function onerror(er) {
15275 cleanup();
15276 if (EE.listenerCount(this, 'error') === 0) {
15277 throw er; // Unhandled stream error in pipe.
15278 }
15279 }
15280
15281 source.on('error', onerror);
15282 dest.on('error', onerror);
15283
15284 // remove all the event listeners that were added.
15285 function cleanup() {
15286 source.removeListener('data', ondata);
15287 dest.removeListener('drain', ondrain);
15288
15289 source.removeListener('end', onend);
15290 source.removeListener('close', onclose);
15291
15292 source.removeListener('error', onerror);
15293 dest.removeListener('error', onerror);
15294
15295 source.removeListener('end', cleanup);
15296 source.removeListener('close', cleanup);
15297
15298 dest.removeListener('close', cleanup);
15299 }
15300
15301 source.on('end', cleanup);
15302 source.on('close', cleanup);
15303
15304 dest.on('close', cleanup);
15305
15306 dest.emit('pipe', source);
15307
15308 // Allow for unix-like usage: A.pipe(B).pipe(C)
15309 return dest;
15310 };
15311
15312 },{"events":63,"inherits":66,"readable-stream/duplex.js":83,"readable-stream/pas sthrough.js":90,"readable-stream/readable.js":91,"readable-stream/transform.js": 92,"readable-stream/writable.js":93}],95:[function(require,module,exports){
15313 // Copyright Joyent, Inc. and other Node contributors.
15314 //
15315 // Permission is hereby granted, free of charge, to any person obtaining a
15316 // copy of this software and associated documentation files (the
15317 // "Software"), to deal in the Software without restriction, including
15318 // without limitation the rights to use, copy, modify, merge, publish,
15319 // distribute, sublicense, and/or sell copies of the Software, and to permit
15320 // persons to whom the Software is furnished to do so, subject to the
15321 // following conditions:
15322 //
15323 // The above copyright notice and this permission notice shall be included
15324 // in all copies or substantial portions of the Software.
15325 //
15326 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15327 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15328 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15329 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15330 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15331 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15332 // USE OR OTHER DEALINGS IN THE SOFTWARE.
15333
15334 var Buffer = require('buffer').Buffer;
15335
15336 var isBufferEncoding = Buffer.isEncoding
15337 || function(encoding) {
15338 switch (encoding && encoding.toLowerCase()) {
15339 case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': cas e 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'ra w': return true;
15340 default: return false;
15341 }
15342 }
15343
15344
15345 function assertEncoding(encoding) {
15346 if (encoding && !isBufferEncoding(encoding)) {
15347 throw new Error('Unknown encoding: ' + encoding);
15348 }
15349 }
15350
15351 // StringDecoder provides an interface for efficiently splitting a series of
15352 // buffers into a series of JS strings without breaking apart multi-byte
15353 // characters. CESU-8 is handled as part of the UTF-8 encoding.
15354 //
15355 // @TODO Handling all encodings inside a single object makes it very difficult
15356 // to reason about this code, so it should be split up in the future.
15357 // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
15358 // points as used by CESU-8.
15359 var StringDecoder = exports.StringDecoder = function(encoding) {
15360 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
15361 assertEncoding(encoding);
15362 switch (this.encoding) {
15363 case 'utf8':
15364 // CESU-8 represents each of Surrogate Pair by 3-bytes
15365 this.surrogateSize = 3;
15366 break;
15367 case 'ucs2':
15368 case 'utf16le':
15369 // UTF-16 represents each of Surrogate Pair by 2-bytes
15370 this.surrogateSize = 2;
15371 this.detectIncompleteChar = utf16DetectIncompleteChar;
15372 break;
15373 case 'base64':
15374 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
15375 this.surrogateSize = 3;
15376 this.detectIncompleteChar = base64DetectIncompleteChar;
15377 break;
15378 default:
15379 this.write = passThroughWrite;
15380 return;
15381 }
15382
15383 // Enough space to store all bytes of a single character. UTF-8 needs 4
15384 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
15385 this.charBuffer = new Buffer(6);
15386 // Number of bytes received for the current incomplete multi-byte character.
15387 this.charReceived = 0;
15388 // Number of bytes expected for the current incomplete multi-byte character.
15389 this.charLength = 0;
15390 };
15391
15392
15393 // write decodes the given buffer and returns it as JS string that is
15394 // guaranteed to not contain any partial multi-byte characters. Any partial
15395 // character found at the end of the buffer is buffered up, and will be
15396 // returned when calling write again with the remaining bytes.
15397 //
15398 // Note: Converting a Buffer containing an orphan surrogate to a String
15399 // currently works, but converting a String to a Buffer (via `new Buffer`, or
15400 // Buffer#write) will replace incomplete surrogates with the unicode
15401 // replacement character. See https://codereview.chromium.org/121173009/ .
15402 StringDecoder.prototype.write = function(buffer) {
15403 var charStr = '';
15404 // if our last write ended with an incomplete multibyte character
15405 while (this.charLength) {
15406 // determine how many remaining bytes this buffer has to offer for this char
15407 var available = (buffer.length >= this.charLength - this.charReceived) ?
15408 this.charLength - this.charReceived :
15409 buffer.length;
15410
15411 // add the new bytes to the char buffer
15412 buffer.copy(this.charBuffer, this.charReceived, 0, available);
15413 this.charReceived += available;
15414
15415 if (this.charReceived < this.charLength) {
15416 // still not enough chars in this buffer? wait for more ...
15417 return '';
15418 }
15419
15420 // remove bytes belonging to the current character from the buffer
15421 buffer = buffer.slice(available, buffer.length);
15422
15423 // get the character that was split
15424 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
15425
15426 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
15427 var charCode = charStr.charCodeAt(charStr.length - 1);
15428 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
15429 this.charLength += this.surrogateSize;
15430 charStr = '';
15431 continue;
15432 }
15433 this.charReceived = this.charLength = 0;
15434
15435 // if there are no more bytes in this buffer, just emit our char
15436 if (buffer.length === 0) {
15437 return charStr;
15438 }
15439 break;
15440 }
15441
15442 // determine and set charLength / charReceived
15443 this.detectIncompleteChar(buffer);
15444
15445 var end = buffer.length;
15446 if (this.charLength) {
15447 // buffer the incomplete character bytes we got
15448 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
15449 end -= this.charReceived;
15450 }
15451
15452 charStr += buffer.toString(this.encoding, 0, end);
15453
15454 var end = charStr.length - 1;
15455 var charCode = charStr.charCodeAt(end);
15456 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
15457 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
15458 var size = this.surrogateSize;
15459 this.charLength += size;
15460 this.charReceived += size;
15461 this.charBuffer.copy(this.charBuffer, size, 0, size);
15462 buffer.copy(this.charBuffer, 0, 0, size);
15463 return charStr.substring(0, end);
15464 }
15465
15466 // or just emit the charStr
15467 return charStr;
15468 };
15469
15470 // detectIncompleteChar determines if there is an incomplete UTF-8 character at
15471 // the end of the given buffer. If so, it sets this.charLength to the byte
15472 // length that character, and sets this.charReceived to the number of bytes
15473 // that are available for this character.
15474 StringDecoder.prototype.detectIncompleteChar = function(buffer) {
15475 // determine how many bytes we have to check at the end of this buffer
15476 var i = (buffer.length >= 3) ? 3 : buffer.length;
15477
15478 // Figure out if one of the last i bytes of our buffer announces an
15479 // incomplete char.
15480 for (; i > 0; i--) {
15481 var c = buffer[buffer.length - i];
15482
15483 // See http://en.wikipedia.org/wiki/UTF-8#Description
15484
15485 // 110XXXXX
15486 if (i == 1 && c >> 5 == 0x06) {
15487 this.charLength = 2;
15488 break;
15489 }
15490
15491 // 1110XXXX
15492 if (i <= 2 && c >> 4 == 0x0E) {
15493 this.charLength = 3;
15494 break;
15495 }
15496
15497 // 11110XXX
15498 if (i <= 3 && c >> 3 == 0x1E) {
15499 this.charLength = 4;
15500 break;
15501 }
15502 }
15503 this.charReceived = i;
15504 };
15505
15506 StringDecoder.prototype.end = function(buffer) {
15507 var res = '';
15508 if (buffer && buffer.length)
15509 res = this.write(buffer);
15510
15511 if (this.charReceived) {
15512 var cr = this.charReceived;
15513 var buf = this.charBuffer;
15514 var enc = this.encoding;
15515 res += buf.slice(0, cr).toString(enc);
15516 }
15517
15518 return res;
15519 };
15520
15521 function passThroughWrite(buffer) {
15522 return buffer.toString(this.encoding);
15523 }
15524
15525 function utf16DetectIncompleteChar(buffer) {
15526 this.charReceived = buffer.length % 2;
15527 this.charLength = this.charReceived ? 2 : 0;
15528 }
15529
15530 function base64DetectIncompleteChar(buffer) {
15531 this.charReceived = buffer.length % 3;
15532 this.charLength = this.charReceived ? 3 : 0;
15533 }
15534
15535 },{"buffer":44}],96:[function(require,module,exports){
15536 (function (global){
15537
15538 /**
15539 * Module exports.
15540 */
15541
15542 module.exports = deprecate;
15543
15544 /**
15545 * Mark that a method should not be used.
15546 * Returns a modified function which warns once by default.
15547 *
15548 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
15549 *
15550 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
15551 * will throw an Error when invoked.
15552 *
15553 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
15554 * will invoke `console.trace()` instead of `console.error()`.
15555 *
15556 * @param {Function} fn - the function to deprecate
15557 * @param {String} msg - the string to print to the console when `fn` is invoked
15558 * @returns {Function} a new "deprecated" version of `fn`
15559 * @api public
15560 */
15561
15562 function deprecate (fn, msg) {
15563 if (config('noDeprecation')) {
15564 return fn;
15565 }
15566
15567 var warned = false;
15568 function deprecated() {
15569 if (!warned) {
15570 if (config('throwDeprecation')) {
15571 throw new Error(msg);
15572 } else if (config('traceDeprecation')) {
15573 console.trace(msg);
15574 } else {
15575 console.warn(msg);
15576 }
15577 warned = true;
15578 }
15579 return fn.apply(this, arguments);
15580 }
15581
15582 return deprecated;
15583 }
15584
15585 /**
15586 * Checks `localStorage` for boolean values for the given `name`.
15587 *
15588 * @param {String} name
15589 * @returns {Boolean}
15590 * @api private
15591 */
15592
15593 function config (name) {
15594 // accessing global.localStorage can trigger a DOMException in sandboxed ifram es
15595 try {
15596 if (!global.localStorage) return false;
15597 } catch (_) {
15598 return false;
15599 }
15600 var val = global.localStorage[name];
15601 if (null == val) return false;
15602 return String(val).toLowerCase() === 'true';
15603 }
15604
15605 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined " ? self : typeof window !== "undefined" ? window : {})
15606 },{}],97:[function(require,module,exports){
15607 arguments[4][66][0].apply(exports,arguments)
15608 },{"dup":66}],98:[function(require,module,exports){
15609 module.exports = function isBuffer(arg) {
15610 return arg && typeof arg === 'object'
15611 && typeof arg.copy === 'function'
15612 && typeof arg.fill === 'function'
15613 && typeof arg.readUInt8 === 'function';
15614 }
15615 },{}],99:[function(require,module,exports){
15616 (function (process,global){
15617 // Copyright Joyent, Inc. and other Node contributors.
15618 //
15619 // Permission is hereby granted, free of charge, to any person obtaining a
15620 // copy of this software and associated documentation files (the
15621 // "Software"), to deal in the Software without restriction, including
15622 // without limitation the rights to use, copy, modify, merge, publish,
15623 // distribute, sublicense, and/or sell copies of the Software, and to permit
15624 // persons to whom the Software is furnished to do so, subject to the
15625 // following conditions:
15626 //
15627 // The above copyright notice and this permission notice shall be included
15628 // in all copies or substantial portions of the Software.
15629 //
15630 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15631 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15632 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15633 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15634 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15635 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15636 // USE OR OTHER DEALINGS IN THE SOFTWARE.
15637
15638 var formatRegExp = /%[sdj%]/g;
15639 exports.format = function(f) {
15640 if (!isString(f)) {
15641 var objects = [];
15642 for (var i = 0; i < arguments.length; i++) {
15643 objects.push(inspect(arguments[i]));
15644 }
15645 return objects.join(' ');
15646 }
15647
15648 var i = 1;
15649 var args = arguments;
15650 var len = args.length;
15651 var str = String(f).replace(formatRegExp, function(x) {
15652 if (x === '%%') return '%';
15653 if (i >= len) return x;
15654 switch (x) {
15655 case '%s': return String(args[i++]);
15656 case '%d': return Number(args[i++]);
15657 case '%j':
15658 try {
15659 return JSON.stringify(args[i++]);
15660 } catch (_) {
15661 return '[Circular]';
15662 }
15663 default:
15664 return x;
15665 }
15666 });
15667 for (var x = args[i]; i < len; x = args[++i]) {
15668 if (isNull(x) || !isObject(x)) {
15669 str += ' ' + x;
15670 } else {
15671 str += ' ' + inspect(x);
15672 }
15673 }
15674 return str;
15675 };
15676
15677
15678 // Mark that a method should not be used.
15679 // Returns a modified function which warns once by default.
15680 // If --no-deprecation is set, then it is a no-op.
15681 exports.deprecate = function(fn, msg) {
15682 // Allow for deprecating things in the process of starting up.
15683 if (isUndefined(global.process)) {
15684 return function() {
15685 return exports.deprecate(fn, msg).apply(this, arguments);
15686 };
15687 }
15688
15689 if (process.noDeprecation === true) {
15690 return fn;
15691 }
15692
15693 var warned = false;
15694 function deprecated() {
15695 if (!warned) {
15696 if (process.throwDeprecation) {
15697 throw new Error(msg);
15698 } else if (process.traceDeprecation) {
15699 console.trace(msg);
15700 } else {
15701 console.error(msg);
15702 }
15703 warned = true;
15704 }
15705 return fn.apply(this, arguments);
15706 }
15707
15708 return deprecated;
15709 };
15710
15711
15712 var debugs = {};
15713 var debugEnviron;
15714 exports.debuglog = function(set) {
15715 if (isUndefined(debugEnviron))
15716 debugEnviron = process.env.NODE_DEBUG || '';
15717 set = set.toUpperCase();
15718 if (!debugs[set]) {
15719 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
15720 var pid = process.pid;
15721 debugs[set] = function() {
15722 var msg = exports.format.apply(exports, arguments);
15723 console.error('%s %d: %s', set, pid, msg);
15724 };
15725 } else {
15726 debugs[set] = function() {};
15727 }
15728 }
15729 return debugs[set];
15730 };
15731
15732
15733 /**
15734 * Echos the value of a value. Trys to print the value out
15735 * in the best way possible given the different types.
15736 *
15737 * @param {Object} obj The object to print out.
15738 * @param {Object} opts Optional options object that alters the output.
15739 */
15740 /* legacy: obj, showHidden, depth, colors*/
15741 function inspect(obj, opts) {
15742 // default options
15743 var ctx = {
15744 seen: [],
15745 stylize: stylizeNoColor
15746 };
15747 // legacy...
15748 if (arguments.length >= 3) ctx.depth = arguments[2];
15749 if (arguments.length >= 4) ctx.colors = arguments[3];
15750 if (isBoolean(opts)) {
15751 // legacy...
15752 ctx.showHidden = opts;
15753 } else if (opts) {
15754 // got an "options" object
15755 exports._extend(ctx, opts);
15756 }
15757 // set default options
15758 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
15759 if (isUndefined(ctx.depth)) ctx.depth = 2;
15760 if (isUndefined(ctx.colors)) ctx.colors = false;
15761 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
15762 if (ctx.colors) ctx.stylize = stylizeWithColor;
15763 return formatValue(ctx, obj, ctx.depth);
15764 }
15765 exports.inspect = inspect;
15766
15767
15768 // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
15769 inspect.colors = {
15770 'bold' : [1, 22],
15771 'italic' : [3, 23],
15772 'underline' : [4, 24],
15773 'inverse' : [7, 27],
15774 'white' : [37, 39],
15775 'grey' : [90, 39],
15776 'black' : [30, 39],
15777 'blue' : [34, 39],
15778 'cyan' : [36, 39],
15779 'green' : [32, 39],
15780 'magenta' : [35, 39],
15781 'red' : [31, 39],
15782 'yellow' : [33, 39]
15783 };
15784
15785 // Don't use 'blue' not visible on cmd.exe
15786 inspect.styles = {
15787 'special': 'cyan',
15788 'number': 'yellow',
15789 'boolean': 'yellow',
15790 'undefined': 'grey',
15791 'null': 'bold',
15792 'string': 'green',
15793 'date': 'magenta',
15794 // "name": intentionally not styling
15795 'regexp': 'red'
15796 };
15797
15798
15799 function stylizeWithColor(str, styleType) {
15800 var style = inspect.styles[styleType];
15801
15802 if (style) {
15803 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
15804 '\u001b[' + inspect.colors[style][1] + 'm';
15805 } else {
15806 return str;
15807 }
15808 }
15809
15810
15811 function stylizeNoColor(str, styleType) {
15812 return str;
15813 }
15814
15815
15816 function arrayToHash(array) {
15817 var hash = {};
15818
15819 array.forEach(function(val, idx) {
15820 hash[val] = true;
15821 });
15822
15823 return hash;
15824 }
15825
15826
15827 function formatValue(ctx, value, recurseTimes) {
15828 // Provide a hook for user-specified inspect functions.
15829 // Check that value is an object with an inspect function on it
15830 if (ctx.customInspect &&
15831 value &&
15832 isFunction(value.inspect) &&
15833 // Filter out the util module, it's inspect function is special
15834 value.inspect !== exports.inspect &&
15835 // Also filter out any prototype objects using the circular check.
15836 !(value.constructor && value.constructor.prototype === value)) {
15837 var ret = value.inspect(recurseTimes, ctx);
15838 if (!isString(ret)) {
15839 ret = formatValue(ctx, ret, recurseTimes);
15840 }
15841 return ret;
15842 }
15843
15844 // Primitive types cannot have properties
15845 var primitive = formatPrimitive(ctx, value);
15846 if (primitive) {
15847 return primitive;
15848 }
15849
15850 // Look up the keys of the object.
15851 var keys = Object.keys(value);
15852 var visibleKeys = arrayToHash(keys);
15853
15854 if (ctx.showHidden) {
15855 keys = Object.getOwnPropertyNames(value);
15856 }
15857
15858 // IE doesn't make error fields non-enumerable
15859 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
15860 if (isError(value)
15861 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
15862 return formatError(value);
15863 }
15864
15865 // Some type of object without properties can be shortcutted.
15866 if (keys.length === 0) {
15867 if (isFunction(value)) {
15868 var name = value.name ? ': ' + value.name : '';
15869 return ctx.stylize('[Function' + name + ']', 'special');
15870 }
15871 if (isRegExp(value)) {
15872 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
15873 }
15874 if (isDate(value)) {
15875 return ctx.stylize(Date.prototype.toString.call(value), 'date');
15876 }
15877 if (isError(value)) {
15878 return formatError(value);
15879 }
15880 }
15881
15882 var base = '', array = false, braces = ['{', '}'];
15883
15884 // Make Array say that they are Array
15885 if (isArray(value)) {
15886 array = true;
15887 braces = ['[', ']'];
15888 }
15889
15890 // Make functions say that they are functions
15891 if (isFunction(value)) {
15892 var n = value.name ? ': ' + value.name : '';
15893 base = ' [Function' + n + ']';
15894 }
15895
15896 // Make RegExps say that they are RegExps
15897 if (isRegExp(value)) {
15898 base = ' ' + RegExp.prototype.toString.call(value);
15899 }
15900
15901 // Make dates with properties first say the date
15902 if (isDate(value)) {
15903 base = ' ' + Date.prototype.toUTCString.call(value);
15904 }
15905
15906 // Make error with message first say the error
15907 if (isError(value)) {
15908 base = ' ' + formatError(value);
15909 }
15910
15911 if (keys.length === 0 && (!array || value.length == 0)) {
15912 return braces[0] + base + braces[1];
15913 }
15914
15915 if (recurseTimes < 0) {
15916 if (isRegExp(value)) {
15917 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
15918 } else {
15919 return ctx.stylize('[Object]', 'special');
15920 }
15921 }
15922
15923 ctx.seen.push(value);
15924
15925 var output;
15926 if (array) {
15927 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
15928 } else {
15929 output = keys.map(function(key) {
15930 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
15931 });
15932 }
15933
15934 ctx.seen.pop();
15935
15936 return reduceToSingleString(output, base, braces);
15937 }
15938
15939
15940 function formatPrimitive(ctx, value) {
15941 if (isUndefined(value))
15942 return ctx.stylize('undefined', 'undefined');
15943 if (isString(value)) {
15944 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
15945 .replace(/'/g, "\\'")
15946 .replace(/\\"/g, '"') + '\'';
15947 return ctx.stylize(simple, 'string');
15948 }
15949 if (isNumber(value))
15950 return ctx.stylize('' + value, 'number');
15951 if (isBoolean(value))
15952 return ctx.stylize('' + value, 'boolean');
15953 // For some reason typeof null is "object", so special case here.
15954 if (isNull(value))
15955 return ctx.stylize('null', 'null');
15956 }
15957
15958
15959 function formatError(value) {
15960 return '[' + Error.prototype.toString.call(value) + ']';
15961 }
15962
15963
15964 function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
15965 var output = [];
15966 for (var i = 0, l = value.length; i < l; ++i) {
15967 if (hasOwnProperty(value, String(i))) {
15968 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
15969 String(i), true));
15970 } else {
15971 output.push('');
15972 }
15973 }
15974 keys.forEach(function(key) {
15975 if (!key.match(/^\d+$/)) {
15976 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
15977 key, true));
15978 }
15979 });
15980 return output;
15981 }
15982
15983
15984 function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
15985 var name, str, desc;
15986 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
15987 if (desc.get) {
15988 if (desc.set) {
15989 str = ctx.stylize('[Getter/Setter]', 'special');
15990 } else {
15991 str = ctx.stylize('[Getter]', 'special');
15992 }
15993 } else {
15994 if (desc.set) {
15995 str = ctx.stylize('[Setter]', 'special');
15996 }
15997 }
15998 if (!hasOwnProperty(visibleKeys, key)) {
15999 name = '[' + key + ']';
16000 }
16001 if (!str) {
16002 if (ctx.seen.indexOf(desc.value) < 0) {
16003 if (isNull(recurseTimes)) {
16004 str = formatValue(ctx, desc.value, null);
16005 } else {
16006 str = formatValue(ctx, desc.value, recurseTimes - 1);
16007 }
16008 if (str.indexOf('\n') > -1) {
16009 if (array) {
16010 str = str.split('\n').map(function(line) {
16011 return ' ' + line;
16012 }).join('\n').substr(2);
16013 } else {
16014 str = '\n' + str.split('\n').map(function(line) {
16015 return ' ' + line;
16016 }).join('\n');
16017 }
16018 }
16019 } else {
16020 str = ctx.stylize('[Circular]', 'special');
16021 }
16022 }
16023 if (isUndefined(name)) {
16024 if (array && key.match(/^\d+$/)) {
16025 return str;
16026 }
16027 name = JSON.stringify('' + key);
16028 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
16029 name = name.substr(1, name.length - 2);
16030 name = ctx.stylize(name, 'name');
16031 } else {
16032 name = name.replace(/'/g, "\\'")
16033 .replace(/\\"/g, '"')
16034 .replace(/(^"|"$)/g, "'");
16035 name = ctx.stylize(name, 'string');
16036 }
16037 }
16038
16039 return name + ': ' + str;
16040 }
16041
16042
16043 function reduceToSingleString(output, base, braces) {
16044 var numLinesEst = 0;
16045 var length = output.reduce(function(prev, cur) {
16046 numLinesEst++;
16047 if (cur.indexOf('\n') >= 0) numLinesEst++;
16048 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
16049 }, 0);
16050
16051 if (length > 60) {
16052 return braces[0] +
16053 (base === '' ? '' : base + '\n ') +
16054 ' ' +
16055 output.join(',\n ') +
16056 ' ' +
16057 braces[1];
16058 }
16059
16060 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
16061 }
16062
16063
16064 // NOTE: These type checking functions intentionally don't use `instanceof`
16065 // because it is fragile and can be easily faked with `Object.create()`.
16066 function isArray(ar) {
16067 return Array.isArray(ar);
16068 }
16069 exports.isArray = isArray;
16070
16071 function isBoolean(arg) {
16072 return typeof arg === 'boolean';
16073 }
16074 exports.isBoolean = isBoolean;
16075
16076 function isNull(arg) {
16077 return arg === null;
16078 }
16079 exports.isNull = isNull;
16080
16081 function isNullOrUndefined(arg) {
16082 return arg == null;
16083 }
16084 exports.isNullOrUndefined = isNullOrUndefined;
16085
16086 function isNumber(arg) {
16087 return typeof arg === 'number';
16088 }
16089 exports.isNumber = isNumber;
16090
16091 function isString(arg) {
16092 return typeof arg === 'string';
16093 }
16094 exports.isString = isString;
16095
16096 function isSymbol(arg) {
16097 return typeof arg === 'symbol';
16098 }
16099 exports.isSymbol = isSymbol;
16100
16101 function isUndefined(arg) {
16102 return arg === void 0;
16103 }
16104 exports.isUndefined = isUndefined;
16105
16106 function isRegExp(re) {
16107 return isObject(re) && objectToString(re) === '[object RegExp]';
16108 }
16109 exports.isRegExp = isRegExp;
16110
16111 function isObject(arg) {
16112 return typeof arg === 'object' && arg !== null;
16113 }
16114 exports.isObject = isObject;
16115
16116 function isDate(d) {
16117 return isObject(d) && objectToString(d) === '[object Date]';
16118 }
16119 exports.isDate = isDate;
16120
16121 function isError(e) {
16122 return isObject(e) &&
16123 (objectToString(e) === '[object Error]' || e instanceof Error);
16124 }
16125 exports.isError = isError;
16126
16127 function isFunction(arg) {
16128 return typeof arg === 'function';
16129 }
16130 exports.isFunction = isFunction;
16131
16132 function isPrimitive(arg) {
16133 return arg === null ||
16134 typeof arg === 'boolean' ||
16135 typeof arg === 'number' ||
16136 typeof arg === 'string' ||
16137 typeof arg === 'symbol' || // ES6 symbol
16138 typeof arg === 'undefined';
16139 }
16140 exports.isPrimitive = isPrimitive;
16141
16142 exports.isBuffer = require('./support/isBuffer');
16143
16144 function objectToString(o) {
16145 return Object.prototype.toString.call(o);
16146 }
16147
16148
16149 function pad(n) {
16150 return n < 10 ? '0' + n.toString(10) : n.toString(10);
16151 }
16152
16153
16154 var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
16155 'Oct', 'Nov', 'Dec'];
16156
16157 // 26 Feb 16:19:34
16158 function timestamp() {
16159 var d = new Date();
16160 var time = [pad(d.getHours()),
16161 pad(d.getMinutes()),
16162 pad(d.getSeconds())].join(':');
16163 return [d.getDate(), months[d.getMonth()], time].join(' ');
16164 }
16165
16166
16167 // log is just a thin wrapper to console.log that prepends a timestamp
16168 exports.log = function() {
16169 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
16170 };
16171
16172
16173 /**
16174 * Inherit the prototype methods from one constructor into another.
16175 *
16176 * The Function.prototype.inherits from lang.js rewritten as a standalone
16177 * function (not on Function.prototype). NOTE: If this file is to be loaded
16178 * during bootstrapping this function needs to be rewritten using some native
16179 * functions as prototype setup using normal JavaScript does not work as
16180 * expected during bootstrapping (see mirror.js in r114903).
16181 *
16182 * @param {function} ctor Constructor function which needs to inherit the
16183 * prototype.
16184 * @param {function} superCtor Constructor function to inherit prototype from.
16185 */
16186 exports.inherits = require('inherits');
16187
16188 exports._extend = function(origin, add) {
16189 // Don't do anything if add isn't an object
16190 if (!add || !isObject(add)) return origin;
16191
16192 var keys = Object.keys(add);
16193 var i = keys.length;
16194 while (i--) {
16195 origin[keys[i]] = add[keys[i]];
16196 }
16197 return origin;
16198 };
16199
16200 function hasOwnProperty(obj, prop) {
16201 return Object.prototype.hasOwnProperty.call(obj, prop);
16202 }
16203
16204 }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
16205 },{"./support/isBuffer":98,"_process":82,"inherits":97}]},{},[1]);
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698