UNPKG

139 kBJavaScriptView Raw
1/*!
2 * QUnit 2.2.1
3 * https://qunitjs.com/
4 *
5 * Copyright jQuery Foundation and other contributors
6 * Released under the MIT license
7 * https://jquery.org/license
8 *
9 * Date: 2017-03-20T00:27Z
10 */
11(function (global$1) {
12 'use strict';
13
14 global$1 = 'default' in global$1 ? global$1['default'] : global$1;
15
16 var window = global$1.window;
17 var console = global$1.console;
18 var setTimeout = global$1.setTimeout;
19 var clearTimeout = global$1.clearTimeout;
20
21 var document = window && window.document;
22 var navigator = window && window.navigator;
23
24 var localSessionStorage = function () {
25 var x = "qunit-test-string";
26 try {
27 global$1.sessionStorage.setItem(x, x);
28 global$1.sessionStorage.removeItem(x);
29 return global$1.sessionStorage;
30 } catch (e) {
31 return undefined;
32 }
33 }();
34
35 var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
36 return typeof obj;
37 } : function (obj) {
38 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
39 };
40
41
42
43
44
45
46
47
48
49
50
51 var classCallCheck = function (instance, Constructor) {
52 if (!(instance instanceof Constructor)) {
53 throw new TypeError("Cannot call a class as a function");
54 }
55 };
56
57 var createClass = function () {
58 function defineProperties(target, props) {
59 for (var i = 0; i < props.length; i++) {
60 var descriptor = props[i];
61 descriptor.enumerable = descriptor.enumerable || false;
62 descriptor.configurable = true;
63 if ("value" in descriptor) descriptor.writable = true;
64 Object.defineProperty(target, descriptor.key, descriptor);
65 }
66 }
67
68 return function (Constructor, protoProps, staticProps) {
69 if (protoProps) defineProperties(Constructor.prototype, protoProps);
70 if (staticProps) defineProperties(Constructor, staticProps);
71 return Constructor;
72 };
73 }();
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115 var toConsumableArray = function (arr) {
116 if (Array.isArray(arr)) {
117 for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
118
119 return arr2;
120 } else {
121 return Array.from(arr);
122 }
123 };
124
125 var toString = Object.prototype.toString;
126 var hasOwn = Object.prototype.hasOwnProperty;
127 var now = Date.now || function () {
128 return new Date().getTime();
129 };
130
131 var defined = {
132 document: window && window.document !== undefined,
133 setTimeout: setTimeout !== undefined
134 };
135
136 // Returns a new Array with the elements that are in a but not in b
137 function diff(a, b) {
138 var i,
139 j,
140 result = a.slice();
141
142 for (i = 0; i < result.length; i++) {
143 for (j = 0; j < b.length; j++) {
144 if (result[i] === b[j]) {
145 result.splice(i, 1);
146 i--;
147 break;
148 }
149 }
150 }
151 return result;
152 }
153
154 /**
155 * Determines whether an element exists in a given array or not.
156 *
157 * @method inArray
158 * @param {Any} elem
159 * @param {Array} array
160 * @return {Boolean}
161 */
162 function inArray(elem, array) {
163 return array.indexOf(elem) !== -1;
164 }
165
166 /**
167 * Makes a clone of an object using only Array or Object as base,
168 * and copies over the own enumerable properties.
169 *
170 * @param {Object} obj
171 * @return {Object} New object with only the own properties (recursively).
172 */
173 function objectValues(obj) {
174 var key,
175 val,
176 vals = is("array", obj) ? [] : {};
177 for (key in obj) {
178 if (hasOwn.call(obj, key)) {
179 val = obj[key];
180 vals[key] = val === Object(val) ? objectValues(val) : val;
181 }
182 }
183 return vals;
184 }
185
186 function extend(a, b, undefOnly) {
187 for (var prop in b) {
188 if (hasOwn.call(b, prop)) {
189 if (b[prop] === undefined) {
190 delete a[prop];
191 } else if (!(undefOnly && typeof a[prop] !== "undefined")) {
192 a[prop] = b[prop];
193 }
194 }
195 }
196
197 return a;
198 }
199
200 function objectType(obj) {
201 if (typeof obj === "undefined") {
202 return "undefined";
203 }
204
205 // Consider: typeof null === object
206 if (obj === null) {
207 return "null";
208 }
209
210 var match = toString.call(obj).match(/^\[object\s(.*)\]$/),
211 type = match && match[1];
212
213 switch (type) {
214 case "Number":
215 if (isNaN(obj)) {
216 return "nan";
217 }
218 return "number";
219 case "String":
220 case "Boolean":
221 case "Array":
222 case "Set":
223 case "Map":
224 case "Date":
225 case "RegExp":
226 case "Function":
227 case "Symbol":
228 return type.toLowerCase();
229 }
230
231 if ((typeof obj === "undefined" ? "undefined" : _typeof(obj)) === "object") {
232 return "object";
233 }
234 }
235
236 // Safe object type checking
237 function is(type, obj) {
238 return objectType(obj) === type;
239 }
240
241 // Test for equality any JavaScript type.
242 // Authors: Philippe Rathé <prathe@gmail.com>, David Chan <david@troi.org>
243 var equiv = (function () {
244
245 // Value pairs queued for comparison. Used for breadth-first processing order, recursion
246 // detection and avoiding repeated comparison (see below for details).
247 // Elements are { a: val, b: val }.
248 var pairs = [];
249
250 var getProto = Object.getPrototypeOf || function (obj) {
251 return obj.__proto__;
252 };
253
254 function useStrictEquality(a, b) {
255
256 // This only gets called if a and b are not strict equal, and is used to compare on
257 // the primitive values inside object wrappers. For example:
258 // `var i = 1;`
259 // `var j = new Number(1);`
260 // Neither a nor b can be null, as a !== b and they have the same type.
261 if ((typeof a === "undefined" ? "undefined" : _typeof(a)) === "object") {
262 a = a.valueOf();
263 }
264 if ((typeof b === "undefined" ? "undefined" : _typeof(b)) === "object") {
265 b = b.valueOf();
266 }
267
268 return a === b;
269 }
270
271 function compareConstructors(a, b) {
272 var protoA = getProto(a);
273 var protoB = getProto(b);
274
275 // Comparing constructors is more strict than using `instanceof`
276 if (a.constructor === b.constructor) {
277 return true;
278 }
279
280 // Ref #851
281 // If the obj prototype descends from a null constructor, treat it
282 // as a null prototype.
283 if (protoA && protoA.constructor === null) {
284 protoA = null;
285 }
286 if (protoB && protoB.constructor === null) {
287 protoB = null;
288 }
289
290 // Allow objects with no prototype to be equivalent to
291 // objects with Object as their constructor.
292 if (protoA === null && protoB === Object.prototype || protoB === null && protoA === Object.prototype) {
293 return true;
294 }
295
296 return false;
297 }
298
299 function getRegExpFlags(regexp) {
300 return "flags" in regexp ? regexp.flags : regexp.toString().match(/[gimuy]*$/)[0];
301 }
302
303 function isContainer(val) {
304 return ["object", "array", "map", "set"].indexOf(objectType(val)) !== -1;
305 }
306
307 function breadthFirstCompareChild(a, b) {
308
309 // If a is a container not reference-equal to b, postpone the comparison to the
310 // end of the pairs queue -- unless (a, b) has been seen before, in which case skip
311 // over the pair.
312 if (a === b) {
313 return true;
314 }
315 if (!isContainer(a)) {
316 return typeEquiv(a, b);
317 }
318 if (pairs.every(function (pair) {
319 return pair.a !== a || pair.b !== b;
320 })) {
321
322 // Not yet started comparing this pair
323 pairs.push({ a: a, b: b });
324 }
325 return true;
326 }
327
328 var callbacks = {
329 "string": useStrictEquality,
330 "boolean": useStrictEquality,
331 "number": useStrictEquality,
332 "null": useStrictEquality,
333 "undefined": useStrictEquality,
334 "symbol": useStrictEquality,
335 "date": useStrictEquality,
336
337 "nan": function nan() {
338 return true;
339 },
340
341 "regexp": function regexp(a, b) {
342 return a.source === b.source &&
343
344 // Include flags in the comparison
345 getRegExpFlags(a) === getRegExpFlags(b);
346 },
347
348 // abort (identical references / instance methods were skipped earlier)
349 "function": function _function() {
350 return false;
351 },
352
353 "array": function array(a, b) {
354 var i, len;
355
356 len = a.length;
357 if (len !== b.length) {
358
359 // Safe and faster
360 return false;
361 }
362
363 for (i = 0; i < len; i++) {
364
365 // Compare non-containers; queue non-reference-equal containers
366 if (!breadthFirstCompareChild(a[i], b[i])) {
367 return false;
368 }
369 }
370 return true;
371 },
372
373 // Define sets a and b to be equivalent if for each element aVal in a, there
374 // is some element bVal in b such that aVal and bVal are equivalent. Element
375 // repetitions are not counted, so these are equivalent:
376 // a = new Set( [ {}, [], [] ] );
377 // b = new Set( [ {}, {}, [] ] );
378 "set": function set$$1(a, b) {
379 var innerEq,
380 outerEq = true;
381
382 if (a.size !== b.size) {
383
384 // This optimization has certain quirks because of the lack of
385 // repetition counting. For instance, adding the same
386 // (reference-identical) element to two equivalent sets can
387 // make them non-equivalent.
388 return false;
389 }
390
391 a.forEach(function (aVal) {
392
393 // Short-circuit if the result is already known. (Using for...of
394 // with a break clause would be cleaner here, but it would cause
395 // a syntax error on older Javascript implementations even if
396 // Set is unused)
397 if (!outerEq) {
398 return;
399 }
400
401 innerEq = false;
402
403 b.forEach(function (bVal) {
404 var parentPairs;
405
406 // Likewise, short-circuit if the result is already known
407 if (innerEq) {
408 return;
409 }
410
411 // Swap out the global pairs list, as the nested call to
412 // innerEquiv will clobber its contents
413 parentPairs = pairs;
414 if (innerEquiv(bVal, aVal)) {
415 innerEq = true;
416 }
417
418 // Replace the global pairs list
419 pairs = parentPairs;
420 });
421
422 if (!innerEq) {
423 outerEq = false;
424 }
425 });
426
427 return outerEq;
428 },
429
430 // Define maps a and b to be equivalent if for each key-value pair (aKey, aVal)
431 // in a, there is some key-value pair (bKey, bVal) in b such that
432 // [ aKey, aVal ] and [ bKey, bVal ] are equivalent. Key repetitions are not
433 // counted, so these are equivalent:
434 // a = new Map( [ [ {}, 1 ], [ {}, 1 ], [ [], 1 ] ] );
435 // b = new Map( [ [ {}, 1 ], [ [], 1 ], [ [], 1 ] ] );
436 "map": function map(a, b) {
437 var innerEq,
438 outerEq = true;
439
440 if (a.size !== b.size) {
441
442 // This optimization has certain quirks because of the lack of
443 // repetition counting. For instance, adding the same
444 // (reference-identical) key-value pair to two equivalent maps
445 // can make them non-equivalent.
446 return false;
447 }
448
449 a.forEach(function (aVal, aKey) {
450
451 // Short-circuit if the result is already known. (Using for...of
452 // with a break clause would be cleaner here, but it would cause
453 // a syntax error on older Javascript implementations even if
454 // Map is unused)
455 if (!outerEq) {
456 return;
457 }
458
459 innerEq = false;
460
461 b.forEach(function (bVal, bKey) {
462 var parentPairs;
463
464 // Likewise, short-circuit if the result is already known
465 if (innerEq) {
466 return;
467 }
468
469 // Swap out the global pairs list, as the nested call to
470 // innerEquiv will clobber its contents
471 parentPairs = pairs;
472 if (innerEquiv([bVal, bKey], [aVal, aKey])) {
473 innerEq = true;
474 }
475
476 // Replace the global pairs list
477 pairs = parentPairs;
478 });
479
480 if (!innerEq) {
481 outerEq = false;
482 }
483 });
484
485 return outerEq;
486 },
487
488 "object": function object(a, b) {
489 var i,
490 aProperties = [],
491 bProperties = [];
492
493 if (compareConstructors(a, b) === false) {
494 return false;
495 }
496
497 // Be strict: don't ensure hasOwnProperty and go deep
498 for (i in a) {
499
500 // Collect a's properties
501 aProperties.push(i);
502
503 // Skip OOP methods that look the same
504 if (a.constructor !== Object && typeof a.constructor !== "undefined" && typeof a[i] === "function" && typeof b[i] === "function" && a[i].toString() === b[i].toString()) {
505 continue;
506 }
507
508 // Compare non-containers; queue non-reference-equal containers
509 if (!breadthFirstCompareChild(a[i], b[i])) {
510 return false;
511 }
512 }
513
514 for (i in b) {
515
516 // Collect b's properties
517 bProperties.push(i);
518 }
519
520 // Ensures identical properties name
521 return typeEquiv(aProperties.sort(), bProperties.sort());
522 }
523 };
524
525 function typeEquiv(a, b) {
526 var type = objectType(a);
527
528 // Callbacks for containers will append to the pairs queue to achieve breadth-first
529 // search order. The pairs queue is also used to avoid reprocessing any pair of
530 // containers that are reference-equal to a previously visited pair (a special case
531 // this being recursion detection).
532 //
533 // Because of this approach, once typeEquiv returns a false value, it should not be
534 // called again without clearing the pair queue else it may wrongly report a visited
535 // pair as being equivalent.
536 return objectType(b) === type && callbacks[type](a, b);
537 }
538
539 function innerEquiv(a, b) {
540 var i, pair;
541
542 // We're done when there's nothing more to compare
543 if (arguments.length < 2) {
544 return true;
545 }
546
547 // Clear the global pair queue and add the top-level values being compared
548 pairs = [{ a: a, b: b }];
549
550 for (i = 0; i < pairs.length; i++) {
551 pair = pairs[i];
552
553 // Perform type-specific comparison on any pairs that are not strictly
554 // equal. For container types, that comparison will postpone comparison
555 // of any sub-container pair to the end of the pair queue. This gives
556 // breadth-first search order. It also avoids the reprocessing of
557 // reference-equal siblings, cousins etc, which can have a significant speed
558 // impact when comparing a container of small objects each of which has a
559 // reference to the same (singleton) large object.
560 if (pair.a !== pair.b && !typeEquiv(pair.a, pair.b)) {
561 return false;
562 }
563 }
564
565 // ...across all consecutive argument pairs
566 return arguments.length === 2 || innerEquiv.apply(this, [].slice.call(arguments, 1));
567 }
568
569 return innerEquiv;
570 })();
571
572 /**
573 * Config object: Maintain internal state
574 * Later exposed as QUnit.config
575 * `config` initialized at top of scope
576 */
577 var config = {
578
579 // The queue of tests to run
580 queue: [],
581
582 // Block until document ready
583 blocking: true,
584
585 // By default, run previously failed tests first
586 // very useful in combination with "Hide passed tests" checked
587 reorder: true,
588
589 // By default, modify document.title when suite is done
590 altertitle: true,
591
592 // HTML Reporter: collapse every test except the first failing test
593 // If false, all failing tests will be expanded
594 collapse: true,
595
596 // By default, scroll to top of the page when suite is done
597 scrolltop: true,
598
599 // Depth up-to which object will be dumped
600 maxDepth: 5,
601
602 // When enabled, all tests must call expect()
603 requireExpects: false,
604
605 // Placeholder for user-configurable form-exposed URL parameters
606 urlConfig: [],
607
608 // Set of all modules.
609 modules: [],
610
611 // Stack of nested modules
612 moduleStack: [],
613
614 // The first unnamed module
615 currentModule: {
616 name: "",
617 tests: [],
618 childModules: [],
619 testsRun: 0
620 },
621
622 callbacks: {},
623
624 // The storage module to use for reordering tests
625 storage: localSessionStorage
626 };
627
628 // take a predefined QUnit.config and extend the defaults
629 var globalConfig = window && window.QUnit && window.QUnit.config;
630
631 // only extend the global config if there is no QUnit overload
632 if (window && window.QUnit && !window.QUnit.version) {
633 extend(config, globalConfig);
634 }
635
636 // Push a loose unnamed module to the modules collection
637 config.modules.push(config.currentModule);
638
639 // Based on jsDump by Ariel Flesler
640 // http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html
641 var dump = (function () {
642 function quote(str) {
643 return "\"" + str.toString().replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\"";
644 }
645 function literal(o) {
646 return o + "";
647 }
648 function join(pre, arr, post) {
649 var s = dump.separator(),
650 base = dump.indent(),
651 inner = dump.indent(1);
652 if (arr.join) {
653 arr = arr.join("," + s + inner);
654 }
655 if (!arr) {
656 return pre + post;
657 }
658 return [pre, inner + arr, base + post].join(s);
659 }
660 function array(arr, stack) {
661 var i = arr.length,
662 ret = new Array(i);
663
664 if (dump.maxDepth && dump.depth > dump.maxDepth) {
665 return "[object Array]";
666 }
667
668 this.up();
669 while (i--) {
670 ret[i] = this.parse(arr[i], undefined, stack);
671 }
672 this.down();
673 return join("[", ret, "]");
674 }
675
676 function isArray(obj) {
677 return (
678
679 //Native Arrays
680 toString.call(obj) === "[object Array]" ||
681
682 // NodeList objects
683 typeof obj.length === "number" && obj.item !== undefined && (obj.length ? obj.item(0) === obj[0] : obj.item(0) === null && obj[0] === undefined)
684 );
685 }
686
687 var reName = /^function (\w+)/,
688 dump = {
689
690 // The objType is used mostly internally, you can fix a (custom) type in advance
691 parse: function parse(obj, objType, stack) {
692 stack = stack || [];
693 var res,
694 parser,
695 parserType,
696 objIndex = stack.indexOf(obj);
697
698 if (objIndex !== -1) {
699 return "recursion(" + (objIndex - stack.length) + ")";
700 }
701
702 objType = objType || this.typeOf(obj);
703 parser = this.parsers[objType];
704 parserType = typeof parser === "undefined" ? "undefined" : _typeof(parser);
705
706 if (parserType === "function") {
707 stack.push(obj);
708 res = parser.call(this, obj, stack);
709 stack.pop();
710 return res;
711 }
712 return parserType === "string" ? parser : this.parsers.error;
713 },
714 typeOf: function typeOf(obj) {
715 var type;
716
717 if (obj === null) {
718 type = "null";
719 } else if (typeof obj === "undefined") {
720 type = "undefined";
721 } else if (is("regexp", obj)) {
722 type = "regexp";
723 } else if (is("date", obj)) {
724 type = "date";
725 } else if (is("function", obj)) {
726 type = "function";
727 } else if (obj.setInterval !== undefined && obj.document !== undefined && obj.nodeType === undefined) {
728 type = "window";
729 } else if (obj.nodeType === 9) {
730 type = "document";
731 } else if (obj.nodeType) {
732 type = "node";
733 } else if (isArray(obj)) {
734 type = "array";
735 } else if (obj.constructor === Error.prototype.constructor) {
736 type = "error";
737 } else {
738 type = typeof obj === "undefined" ? "undefined" : _typeof(obj);
739 }
740 return type;
741 },
742
743 separator: function separator() {
744 if (this.multiline) {
745 return this.HTML ? "<br />" : "\n";
746 } else {
747 return this.HTML ? "&#160;" : " ";
748 }
749 },
750
751 // Extra can be a number, shortcut for increasing-calling-decreasing
752 indent: function indent(extra) {
753 if (!this.multiline) {
754 return "";
755 }
756 var chr = this.indentChar;
757 if (this.HTML) {
758 chr = chr.replace(/\t/g, " ").replace(/ /g, "&#160;");
759 }
760 return new Array(this.depth + (extra || 0)).join(chr);
761 },
762 up: function up(a) {
763 this.depth += a || 1;
764 },
765 down: function down(a) {
766 this.depth -= a || 1;
767 },
768 setParser: function setParser(name, parser) {
769 this.parsers[name] = parser;
770 },
771
772 // The next 3 are exposed so you can use them
773 quote: quote,
774 literal: literal,
775 join: join,
776 depth: 1,
777 maxDepth: config.maxDepth,
778
779 // This is the list of parsers, to modify them, use dump.setParser
780 parsers: {
781 window: "[Window]",
782 document: "[Document]",
783 error: function error(_error) {
784 return "Error(\"" + _error.message + "\")";
785 },
786 unknown: "[Unknown]",
787 "null": "null",
788 "undefined": "undefined",
789 "function": function _function(fn) {
790 var ret = "function",
791
792
793 // Functions never have name in IE
794 name = "name" in fn ? fn.name : (reName.exec(fn) || [])[1];
795
796 if (name) {
797 ret += " " + name;
798 }
799 ret += "(";
800
801 ret = [ret, dump.parse(fn, "functionArgs"), "){"].join("");
802 return join(ret, dump.parse(fn, "functionCode"), "}");
803 },
804 array: array,
805 nodelist: array,
806 "arguments": array,
807 object: function object(map, stack) {
808 var keys,
809 key,
810 val,
811 i,
812 nonEnumerableProperties,
813 ret = [];
814
815 if (dump.maxDepth && dump.depth > dump.maxDepth) {
816 return "[object Object]";
817 }
818
819 dump.up();
820 keys = [];
821 for (key in map) {
822 keys.push(key);
823 }
824
825 // Some properties are not always enumerable on Error objects.
826 nonEnumerableProperties = ["message", "name"];
827 for (i in nonEnumerableProperties) {
828 key = nonEnumerableProperties[i];
829 if (key in map && !inArray(key, keys)) {
830 keys.push(key);
831 }
832 }
833 keys.sort();
834 for (i = 0; i < keys.length; i++) {
835 key = keys[i];
836 val = map[key];
837 ret.push(dump.parse(key, "key") + ": " + dump.parse(val, undefined, stack));
838 }
839 dump.down();
840 return join("{", ret, "}");
841 },
842 node: function node(_node) {
843 var len,
844 i,
845 val,
846 open = dump.HTML ? "&lt;" : "<",
847 close = dump.HTML ? "&gt;" : ">",
848 tag = _node.nodeName.toLowerCase(),
849 ret = open + tag,
850 attrs = _node.attributes;
851
852 if (attrs) {
853 for (i = 0, len = attrs.length; i < len; i++) {
854 val = attrs[i].nodeValue;
855
856 // IE6 includes all attributes in .attributes, even ones not explicitly
857 // set. Those have values like undefined, null, 0, false, "" or
858 // "inherit".
859 if (val && val !== "inherit") {
860 ret += " " + attrs[i].nodeName + "=" + dump.parse(val, "attribute");
861 }
862 }
863 }
864 ret += close;
865
866 // Show content of TextNode or CDATASection
867 if (_node.nodeType === 3 || _node.nodeType === 4) {
868 ret += _node.nodeValue;
869 }
870
871 return ret + open + "/" + tag + close;
872 },
873
874 // Function calls it internally, it's the arguments part of the function
875 functionArgs: function functionArgs(fn) {
876 var args,
877 l = fn.length;
878
879 if (!l) {
880 return "";
881 }
882
883 args = new Array(l);
884 while (l--) {
885
886 // 97 is 'a'
887 args[l] = String.fromCharCode(97 + l);
888 }
889 return " " + args.join(", ") + " ";
890 },
891
892 // Object calls it internally, the key part of an item in a map
893 key: quote,
894
895 // Function calls it internally, it's the content of the function
896 functionCode: "[code]",
897
898 // Node calls it internally, it's a html attribute value
899 attribute: quote,
900 string: quote,
901 date: quote,
902 regexp: literal,
903 number: literal,
904 "boolean": literal,
905 symbol: function symbol(sym) {
906 return sym.toString();
907 }
908 },
909
910 // If true, entities are escaped ( <, >, \t, space and \n )
911 HTML: false,
912
913 // Indentation unit
914 indentChar: " ",
915
916 // If true, items in a collection, are separated by a \n, else just a space.
917 multiline: true
918 };
919
920 return dump;
921 })();
922
923 var LISTENERS = Object.create(null);
924 var SUPPORTED_EVENTS = ["runStart", "suiteStart", "testStart", "assertion", "testEnd", "suiteEnd", "runEnd"];
925
926 /**
927 * Emits an event with the specified data to all currently registered listeners.
928 * Callbacks will fire in the order in which they are registered (FIFO). This
929 * function is not exposed publicly; it is used by QUnit internals to emit
930 * logging events.
931 *
932 * @private
933 * @method emit
934 * @param {String} eventName
935 * @param {Object} data
936 * @return {Void}
937 */
938 function emit(eventName, data) {
939 if (objectType(eventName) !== "string") {
940 throw new TypeError("eventName must be a string when emitting an event");
941 }
942
943 // Clone the callbacks in case one of them registers a new callback
944 var originalCallbacks = LISTENERS[eventName];
945 var callbacks = originalCallbacks ? [].concat(toConsumableArray(originalCallbacks)) : [];
946
947 for (var i = 0; i < callbacks.length; i++) {
948 callbacks[i](data);
949 }
950 }
951
952 /**
953 * Registers a callback as a listener to the specified event.
954 *
955 * @public
956 * @method on
957 * @param {String} eventName
958 * @param {Function} callback
959 * @return {Void}
960 */
961 function on(eventName, callback) {
962 if (objectType(eventName) !== "string") {
963 throw new TypeError("eventName must be a string when registering a listener");
964 } else if (!inArray(eventName, SUPPORTED_EVENTS)) {
965 var events = SUPPORTED_EVENTS.join(", ");
966 throw new Error("\"" + eventName + "\" is not a valid event; must be one of: " + events + ".");
967 } else if (objectType(callback) !== "function") {
968 throw new TypeError("callback must be a function when registering a listener");
969 }
970
971 if (!LISTENERS[eventName]) {
972 LISTENERS[eventName] = [];
973 }
974
975 // Don't register the same callback more than once
976 if (!inArray(callback, LISTENERS[eventName])) {
977 LISTENERS[eventName].push(callback);
978 }
979 }
980
981 // Register logging callbacks
982 function registerLoggingCallbacks(obj) {
983 var i,
984 l,
985 key,
986 callbackNames = ["begin", "done", "log", "testStart", "testDone", "moduleStart", "moduleDone"];
987
988 function registerLoggingCallback(key) {
989 var loggingCallback = function loggingCallback(callback) {
990 if (objectType(callback) !== "function") {
991 throw new Error("QUnit logging methods require a callback function as their first parameters.");
992 }
993
994 config.callbacks[key].push(callback);
995 };
996
997 return loggingCallback;
998 }
999
1000 for (i = 0, l = callbackNames.length; i < l; i++) {
1001 key = callbackNames[i];
1002
1003 // Initialize key collection of logging callback
1004 if (objectType(config.callbacks[key]) === "undefined") {
1005 config.callbacks[key] = [];
1006 }
1007
1008 obj[key] = registerLoggingCallback(key);
1009 }
1010 }
1011
1012 function runLoggingCallbacks(key, args) {
1013 var i, l, callbacks;
1014
1015 callbacks = config.callbacks[key];
1016 for (i = 0, l = callbacks.length; i < l; i++) {
1017 callbacks[i](args);
1018 }
1019 }
1020
1021 // Doesn't support IE9, it will return undefined on these browsers
1022 // See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack
1023 var fileName = (sourceFromStacktrace(0) || "").replace(/(:\d+)+\)?/, "").replace(/.+\//, "");
1024
1025 function extractStacktrace(e, offset) {
1026 offset = offset === undefined ? 4 : offset;
1027
1028 var stack, include, i;
1029
1030 if (e && e.stack) {
1031 stack = e.stack.split("\n");
1032 if (/^error$/i.test(stack[0])) {
1033 stack.shift();
1034 }
1035 if (fileName) {
1036 include = [];
1037 for (i = offset; i < stack.length; i++) {
1038 if (stack[i].indexOf(fileName) !== -1) {
1039 break;
1040 }
1041 include.push(stack[i]);
1042 }
1043 if (include.length) {
1044 return include.join("\n");
1045 }
1046 }
1047 return stack[offset];
1048 }
1049 }
1050
1051 function sourceFromStacktrace(offset) {
1052 var error = new Error();
1053
1054 // Support: Safari <=7 only, IE <=10 - 11 only
1055 // Not all browsers generate the `stack` property for `new Error()`, see also #636
1056 if (!error.stack) {
1057 try {
1058 throw error;
1059 } catch (err) {
1060 error = err;
1061 }
1062 }
1063
1064 return extractStacktrace(error, offset);
1065 }
1066
1067 var TestReport = function () {
1068 function TestReport(name, suite, options) {
1069 classCallCheck(this, TestReport);
1070
1071 this.name = name;
1072 this.suiteName = suite.name;
1073 this.fullName = suite.fullName.concat(name);
1074 this.runtime = 0;
1075 this.assertions = [];
1076
1077 this.skipped = !!options.skip;
1078 this.todo = !!options.todo;
1079
1080 this._startTime = 0;
1081 this._endTime = 0;
1082
1083 suite.pushTest(this);
1084 }
1085
1086 createClass(TestReport, [{
1087 key: "start",
1088 value: function start(recordTime) {
1089 if (recordTime) {
1090 this._startTime = Date.now();
1091 }
1092
1093 return {
1094 name: this.name,
1095 suiteName: this.suiteName,
1096 fullName: this.fullName.slice()
1097 };
1098 }
1099 }, {
1100 key: "end",
1101 value: function end(recordTime) {
1102 if (recordTime) {
1103 this._endTime = Date.now();
1104 }
1105
1106 return extend(this.start(), {
1107 runtime: this.getRuntime(),
1108 status: this.getStatus(),
1109 errors: this.getFailedAssertions(),
1110 assertions: this.getAssertions()
1111 });
1112 }
1113 }, {
1114 key: "pushAssertion",
1115 value: function pushAssertion(assertion) {
1116 this.assertions.push(assertion);
1117 }
1118 }, {
1119 key: "getRuntime",
1120 value: function getRuntime() {
1121 return this._endTime - this._startTime;
1122 }
1123 }, {
1124 key: "getStatus",
1125 value: function getStatus() {
1126 if (this.skipped) {
1127 return "skipped";
1128 }
1129
1130 var testPassed = this.getFailedAssertions().length > 0 ? this.todo : !this.todo;
1131
1132 if (!testPassed) {
1133 return "failed";
1134 } else if (this.todo) {
1135 return "todo";
1136 } else {
1137 return "passed";
1138 }
1139 }
1140 }, {
1141 key: "getFailedAssertions",
1142 value: function getFailedAssertions() {
1143 return this.assertions.filter(function (assertion) {
1144 return !assertion.passed;
1145 });
1146 }
1147 }, {
1148 key: "getAssertions",
1149 value: function getAssertions() {
1150 return this.assertions.slice();
1151 }
1152 }]);
1153 return TestReport;
1154 }();
1155
1156 var unitSampler;
1157 var focused = false;
1158 var priorityCount = 0;
1159
1160 function Test(settings) {
1161 var i, l;
1162
1163 ++Test.count;
1164
1165 this.expected = null;
1166 extend(this, settings);
1167 this.assertions = [];
1168 this.semaphore = 0;
1169 this.usedAsync = false;
1170 this.module = config.currentModule;
1171 this.stack = sourceFromStacktrace(3);
1172 this.steps = [];
1173
1174 this.testReport = new TestReport(settings.testName, this.module.suiteReport, {
1175 todo: settings.todo,
1176 skip: settings.skip
1177 });
1178
1179 // Register unique strings
1180 for (i = 0, l = this.module.tests; i < l.length; i++) {
1181 if (this.module.tests[i].name === this.testName) {
1182 this.testName += " ";
1183 }
1184 }
1185
1186 this.testId = generateHash(this.module.name, this.testName);
1187
1188 this.module.tests.push({
1189 name: this.testName,
1190 testId: this.testId
1191 });
1192
1193 if (settings.skip) {
1194
1195 // Skipped tests will fully ignore any sent callback
1196 this.callback = function () {};
1197 this.async = false;
1198 this.expected = 0;
1199 } else {
1200 this.assert = new Assert(this);
1201 }
1202 }
1203
1204 Test.count = 0;
1205
1206 function getNotStartedModules(startModule) {
1207 var module = startModule,
1208 modules = [];
1209
1210 while (module && module.testsRun === 0) {
1211 modules.push(module);
1212 module = module.parentModule;
1213 }
1214
1215 return modules;
1216 }
1217
1218 Test.prototype = {
1219 before: function before() {
1220 var i,
1221 startModule,
1222 module = this.module,
1223 notStartedModules = getNotStartedModules(module);
1224
1225 for (i = notStartedModules.length - 1; i >= 0; i--) {
1226 startModule = notStartedModules[i];
1227 startModule.stats = { all: 0, bad: 0, started: now() };
1228 emit("suiteStart", startModule.suiteReport.start(true));
1229 runLoggingCallbacks("moduleStart", {
1230 name: startModule.name,
1231 tests: startModule.tests
1232 });
1233 }
1234
1235 config.current = this;
1236
1237 if (module.testEnvironment) {
1238 delete module.testEnvironment.before;
1239 delete module.testEnvironment.beforeEach;
1240 delete module.testEnvironment.afterEach;
1241 delete module.testEnvironment.after;
1242 }
1243 this.testEnvironment = extend({}, module.testEnvironment);
1244
1245 this.started = now();
1246 emit("testStart", this.testReport.start(true));
1247 runLoggingCallbacks("testStart", {
1248 name: this.testName,
1249 module: module.name,
1250 testId: this.testId,
1251 previousFailure: this.previousFailure
1252 });
1253
1254 if (!config.pollution) {
1255 saveGlobal();
1256 }
1257 },
1258
1259 run: function run() {
1260 var promise;
1261
1262 config.current = this;
1263
1264 this.callbackStarted = now();
1265
1266 if (config.notrycatch) {
1267 runTest(this);
1268 return;
1269 }
1270
1271 try {
1272 runTest(this);
1273 } catch (e) {
1274 this.pushFailure("Died on test #" + (this.assertions.length + 1) + " " + this.stack + ": " + (e.message || e), extractStacktrace(e, 0));
1275
1276 // Else next test will carry the responsibility
1277 saveGlobal();
1278
1279 // Restart the tests if they're blocking
1280 if (config.blocking) {
1281 internalRecover(this);
1282 }
1283 }
1284
1285 function runTest(test) {
1286 promise = test.callback.call(test.testEnvironment, test.assert);
1287 test.resolvePromise(promise);
1288 }
1289 },
1290
1291 after: function after() {
1292 checkPollution();
1293 },
1294
1295 queueHook: function queueHook(hook, hookName, hookOwner) {
1296 var promise,
1297 test = this;
1298 return function runHook() {
1299 if (hookName === "before") {
1300 if (hookOwner.testsRun !== 0) {
1301 return;
1302 }
1303
1304 test.preserveEnvironment = true;
1305 }
1306
1307 if (hookName === "after" && hookOwner.testsRun !== numberOfTests(hookOwner) - 1) {
1308 return;
1309 }
1310
1311 config.current = test;
1312 if (config.notrycatch) {
1313 callHook();
1314 return;
1315 }
1316 try {
1317 callHook();
1318 } catch (error) {
1319 test.pushFailure(hookName + " failed on " + test.testName + ": " + (error.message || error), extractStacktrace(error, 0));
1320 }
1321
1322 function callHook() {
1323 promise = hook.call(test.testEnvironment, test.assert);
1324 test.resolvePromise(promise, hookName);
1325 }
1326 };
1327 },
1328
1329 // Currently only used for module level hooks, can be used to add global level ones
1330 hooks: function hooks(handler) {
1331 var hooks = [];
1332
1333 function processHooks(test, module) {
1334 if (module.parentModule) {
1335 processHooks(test, module.parentModule);
1336 }
1337 if (module.testEnvironment && objectType(module.testEnvironment[handler]) === "function") {
1338 hooks.push(test.queueHook(module.testEnvironment[handler], handler, module));
1339 }
1340 }
1341
1342 // Hooks are ignored on skipped tests
1343 if (!this.skip) {
1344 processHooks(this, this.module);
1345 }
1346 return hooks;
1347 },
1348
1349 finish: function finish() {
1350 config.current = this;
1351 if (config.requireExpects && this.expected === null) {
1352 this.pushFailure("Expected number of assertions to be defined, but expect() was " + "not called.", this.stack);
1353 } else if (this.expected !== null && this.expected !== this.assertions.length) {
1354 this.pushFailure("Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack);
1355 } else if (this.expected === null && !this.assertions.length) {
1356 this.pushFailure("Expected at least one assertion, but none were run - call " + "expect(0) to accept zero assertions.", this.stack);
1357 }
1358
1359 var i,
1360 module = this.module,
1361 moduleName = module.name,
1362 testName = this.testName,
1363 skipped = !!this.skip,
1364 todo = !!this.todo,
1365 bad = 0,
1366 storage = config.storage;
1367
1368 this.runtime = now() - this.started;
1369
1370 config.stats.all += this.assertions.length;
1371 module.stats.all += this.assertions.length;
1372
1373 for (i = 0; i < this.assertions.length; i++) {
1374 if (!this.assertions[i].result) {
1375 bad++;
1376 config.stats.bad++;
1377 module.stats.bad++;
1378 }
1379 }
1380
1381 notifyTestsRan(module);
1382
1383 // Store result when possible
1384 if (storage) {
1385 if (bad) {
1386 storage.setItem("qunit-test-" + moduleName + "-" + testName, bad);
1387 } else {
1388 storage.removeItem("qunit-test-" + moduleName + "-" + testName);
1389 }
1390 }
1391
1392 emit("testEnd", this.testReport.end(true));
1393 runLoggingCallbacks("testDone", {
1394 name: testName,
1395 module: moduleName,
1396 skipped: skipped,
1397 todo: todo,
1398 failed: bad,
1399 passed: this.assertions.length - bad,
1400 total: this.assertions.length,
1401 runtime: skipped ? 0 : this.runtime,
1402
1403 // HTML Reporter use
1404 assertions: this.assertions,
1405 testId: this.testId,
1406
1407 // Source of Test
1408 source: this.stack
1409 });
1410
1411 if (module.testsRun === numberOfTests(module)) {
1412 emit("suiteEnd", module.suiteReport.end(true));
1413 runLoggingCallbacks("moduleDone", {
1414 name: module.name,
1415 tests: module.tests,
1416 failed: module.stats.bad,
1417 passed: module.stats.all - module.stats.bad,
1418 total: module.stats.all,
1419 runtime: now() - module.stats.started
1420 });
1421 }
1422
1423 config.current = undefined;
1424 },
1425
1426 preserveTestEnvironment: function preserveTestEnvironment() {
1427 if (this.preserveEnvironment) {
1428 this.module.testEnvironment = this.testEnvironment;
1429 this.testEnvironment = extend({}, this.module.testEnvironment);
1430 }
1431 },
1432
1433 queue: function queue() {
1434 var priority,
1435 previousFailCount,
1436 test = this;
1437
1438 if (!this.valid()) {
1439 return;
1440 }
1441
1442 function run() {
1443
1444 // Each of these can by async
1445 synchronize([function () {
1446 test.before();
1447 }, test.hooks("before"), function () {
1448 test.preserveTestEnvironment();
1449 }, test.hooks("beforeEach"), function () {
1450 test.run();
1451 }, test.hooks("afterEach").reverse(), test.hooks("after").reverse(), function () {
1452 test.after();
1453 }, function () {
1454 test.finish();
1455 }]);
1456 }
1457
1458 previousFailCount = config.storage && +config.storage.getItem("qunit-test-" + this.module.name + "-" + this.testName);
1459
1460 // Prioritize previously failed tests, detected from storage
1461 priority = config.reorder && previousFailCount;
1462
1463 this.previousFailure = !!previousFailCount;
1464
1465 return synchronize(run, priority, config.seed);
1466 },
1467
1468 pushResult: function pushResult(resultInfo) {
1469
1470 // Destructure of resultInfo = { result, actual, expected, message, negative }
1471 var source,
1472 details = {
1473 module: this.module.name,
1474 name: this.testName,
1475 result: resultInfo.result,
1476 message: resultInfo.message,
1477 actual: resultInfo.actual,
1478 expected: resultInfo.expected,
1479 testId: this.testId,
1480 negative: resultInfo.negative || false,
1481 runtime: now() - this.started,
1482 todo: !!this.todo
1483 };
1484
1485 if (!resultInfo.result) {
1486 source = resultInfo.source || sourceFromStacktrace();
1487
1488 if (source) {
1489 details.source = source;
1490 }
1491 }
1492
1493 this.logAssertion(details);
1494
1495 this.assertions.push({
1496 result: !!resultInfo.result,
1497 message: resultInfo.message
1498 });
1499 },
1500
1501 pushFailure: function pushFailure(message, source, actual) {
1502 if (!(this instanceof Test)) {
1503 throw new Error("pushFailure() assertion outside test context, was " + sourceFromStacktrace(2));
1504 }
1505
1506 this.assert.pushResult({
1507 result: false,
1508 message: message || "error",
1509 actual: actual || null,
1510 expected: null,
1511 source: source
1512 });
1513 },
1514
1515 /**
1516 * Log assertion details using both the old QUnit.log interface and
1517 * QUnit.on( "assertion" ) interface.
1518 *
1519 * @private
1520 */
1521 logAssertion: function logAssertion(details) {
1522 runLoggingCallbacks("log", details);
1523
1524 var assertion = {
1525 passed: details.result,
1526 actual: details.actual,
1527 expected: details.expected,
1528 message: details.message,
1529 stack: details.source,
1530 todo: details.todo
1531 };
1532 this.testReport.pushAssertion(assertion);
1533 emit("assertion", assertion);
1534 },
1535
1536
1537 resolvePromise: function resolvePromise(promise, phase) {
1538 var then,
1539 resume,
1540 message,
1541 test = this;
1542 if (promise != null) {
1543 then = promise.then;
1544 if (objectType(then) === "function") {
1545 resume = internalStop(test);
1546 then.call(promise, function () {
1547 resume();
1548 }, function (error) {
1549 message = "Promise rejected " + (!phase ? "during" : phase.replace(/Each$/, "")) + " \"" + test.testName + "\": " + (error && error.message || error);
1550 test.pushFailure(message, extractStacktrace(error, 0));
1551
1552 // Else next test will carry the responsibility
1553 saveGlobal();
1554
1555 // Unblock
1556 resume();
1557 });
1558 }
1559 }
1560 },
1561
1562 valid: function valid() {
1563 var filter = config.filter,
1564 regexFilter = /^(!?)\/([\w\W]*)\/(i?$)/.exec(filter),
1565 module = config.module && config.module.toLowerCase(),
1566 fullName = this.module.name + ": " + this.testName;
1567
1568 function moduleChainNameMatch(testModule) {
1569 var testModuleName = testModule.name ? testModule.name.toLowerCase() : null;
1570 if (testModuleName === module) {
1571 return true;
1572 } else if (testModule.parentModule) {
1573 return moduleChainNameMatch(testModule.parentModule);
1574 } else {
1575 return false;
1576 }
1577 }
1578
1579 function moduleChainIdMatch(testModule) {
1580 return inArray(testModule.moduleId, config.moduleId) || testModule.parentModule && moduleChainIdMatch(testModule.parentModule);
1581 }
1582
1583 // Internally-generated tests are always valid
1584 if (this.callback && this.callback.validTest) {
1585 return true;
1586 }
1587
1588 if (config.moduleId && config.moduleId.length > 0 && !moduleChainIdMatch(this.module)) {
1589
1590 return false;
1591 }
1592
1593 if (config.testId && config.testId.length > 0 && !inArray(this.testId, config.testId)) {
1594
1595 return false;
1596 }
1597
1598 if (module && !moduleChainNameMatch(this.module)) {
1599 return false;
1600 }
1601
1602 if (!filter) {
1603 return true;
1604 }
1605
1606 return regexFilter ? this.regexFilter(!!regexFilter[1], regexFilter[2], regexFilter[3], fullName) : this.stringFilter(filter, fullName);
1607 },
1608
1609 regexFilter: function regexFilter(exclude, pattern, flags, fullName) {
1610 var regex = new RegExp(pattern, flags);
1611 var match = regex.test(fullName);
1612
1613 return match !== exclude;
1614 },
1615
1616 stringFilter: function stringFilter(filter, fullName) {
1617 filter = filter.toLowerCase();
1618 fullName = fullName.toLowerCase();
1619
1620 var include = filter.charAt(0) !== "!";
1621 if (!include) {
1622 filter = filter.slice(1);
1623 }
1624
1625 // If the filter matches, we need to honour include
1626 if (fullName.indexOf(filter) !== -1) {
1627 return include;
1628 }
1629
1630 // Otherwise, do the opposite
1631 return !include;
1632 }
1633 };
1634
1635 function pushFailure() {
1636 if (!config.current) {
1637 throw new Error("pushFailure() assertion outside test context, in " + sourceFromStacktrace(2));
1638 }
1639
1640 // Gets current test obj
1641 var currentTest = config.current;
1642
1643 return currentTest.pushFailure.apply(currentTest, arguments);
1644 }
1645
1646 // Based on Java's String.hashCode, a simple but not
1647 // rigorously collision resistant hashing function
1648 function generateHash(module, testName) {
1649 var hex,
1650 i = 0,
1651 hash = 0,
1652 str = module + "\x1C" + testName,
1653 len = str.length;
1654
1655 for (; i < len; i++) {
1656 hash = (hash << 5) - hash + str.charCodeAt(i);
1657 hash |= 0;
1658 }
1659
1660 // Convert the possibly negative integer hash code into an 8 character hex string, which isn't
1661 // strictly necessary but increases user understanding that the id is a SHA-like hash
1662 hex = (0x100000000 + hash).toString(16);
1663 if (hex.length < 8) {
1664 hex = "0000000" + hex;
1665 }
1666
1667 return hex.slice(-8);
1668 }
1669
1670 function synchronize(callback, priority, seed) {
1671 var last = !priority,
1672 index;
1673
1674 if (objectType(callback) === "array") {
1675 while (callback.length) {
1676 synchronize(callback.shift());
1677 }
1678 return;
1679 }
1680
1681 if (priority) {
1682 config.queue.splice(priorityCount++, 0, callback);
1683 } else if (seed) {
1684 if (!unitSampler) {
1685 unitSampler = unitSamplerGenerator(seed);
1686 }
1687
1688 // Insert into a random position after all priority items
1689 index = Math.floor(unitSampler() * (config.queue.length - priorityCount + 1));
1690 config.queue.splice(priorityCount + index, 0, callback);
1691 } else {
1692 config.queue.push(callback);
1693 }
1694
1695 if (internalState.autorun && !config.blocking) {
1696 process(last);
1697 }
1698 }
1699
1700 function unitSamplerGenerator(seed) {
1701
1702 // 32-bit xorshift, requires only a nonzero seed
1703 // http://excamera.com/sphinx/article-xorshift.html
1704 var sample = parseInt(generateHash(seed), 16) || -1;
1705 return function () {
1706 sample ^= sample << 13;
1707 sample ^= sample >>> 17;
1708 sample ^= sample << 5;
1709
1710 // ECMAScript has no unsigned number type
1711 if (sample < 0) {
1712 sample += 0x100000000;
1713 }
1714
1715 return sample / 0x100000000;
1716 };
1717 }
1718
1719 function saveGlobal() {
1720 config.pollution = [];
1721
1722 if (config.noglobals) {
1723 for (var key in global$1) {
1724 if (hasOwn.call(global$1, key)) {
1725
1726 // In Opera sometimes DOM element ids show up here, ignore them
1727 if (/^qunit-test-output/.test(key)) {
1728 continue;
1729 }
1730 config.pollution.push(key);
1731 }
1732 }
1733 }
1734 }
1735
1736 function checkPollution() {
1737 var newGlobals,
1738 deletedGlobals,
1739 old = config.pollution;
1740
1741 saveGlobal();
1742
1743 newGlobals = diff(config.pollution, old);
1744 if (newGlobals.length > 0) {
1745 pushFailure("Introduced global variable(s): " + newGlobals.join(", "));
1746 }
1747
1748 deletedGlobals = diff(old, config.pollution);
1749 if (deletedGlobals.length > 0) {
1750 pushFailure("Deleted global variable(s): " + deletedGlobals.join(", "));
1751 }
1752 }
1753
1754 // Will be exposed as QUnit.test
1755 function test(testName, callback) {
1756 if (focused) {
1757 return;
1758 }
1759
1760 var newTest = new Test({
1761 testName: testName,
1762 callback: callback
1763 });
1764
1765 newTest.queue();
1766 }
1767
1768 function todo(testName, callback) {
1769 if (focused) {
1770 return;
1771 }
1772
1773 var newTest = new Test({
1774 testName: testName,
1775 callback: callback,
1776 todo: true
1777 });
1778
1779 newTest.queue();
1780 }
1781
1782 // Will be exposed as QUnit.skip
1783 function skip(testName) {
1784 if (focused) {
1785 return;
1786 }
1787
1788 var test = new Test({
1789 testName: testName,
1790 skip: true
1791 });
1792
1793 test.queue();
1794 }
1795
1796 // Will be exposed as QUnit.only
1797 function only(testName, callback) {
1798 if (focused) {
1799 return;
1800 }
1801
1802 config.queue.length = 0;
1803 focused = true;
1804
1805 var newTest = new Test({
1806 testName: testName,
1807 callback: callback
1808 });
1809
1810 newTest.queue();
1811 }
1812
1813 // Put a hold on processing and return a function that will release it.
1814 function internalStop(test) {
1815 var released = false;
1816
1817 test.semaphore += 1;
1818 config.blocking = true;
1819
1820 // Set a recovery timeout, if so configured.
1821 if (config.testTimeout && defined.setTimeout) {
1822 clearTimeout(config.timeout);
1823 config.timeout = setTimeout(function () {
1824 pushFailure("Test timed out", sourceFromStacktrace(2));
1825 internalRecover(test);
1826 }, config.testTimeout);
1827 }
1828
1829 return function resume() {
1830 if (released) {
1831 return;
1832 }
1833
1834 released = true;
1835 test.semaphore -= 1;
1836 internalStart(test);
1837 };
1838 }
1839
1840 // Forcefully release all processing holds.
1841 function internalRecover(test) {
1842 test.semaphore = 0;
1843 internalStart(test);
1844 }
1845
1846 // Release a processing hold, scheduling a resumption attempt if no holds remain.
1847 function internalStart(test) {
1848
1849 // If semaphore is non-numeric, throw error
1850 if (isNaN(test.semaphore)) {
1851 test.semaphore = 0;
1852
1853 pushFailure("Invalid value on test.semaphore", sourceFromStacktrace(2));
1854 return;
1855 }
1856
1857 // Don't start until equal number of stop-calls
1858 if (test.semaphore > 0) {
1859 return;
1860 }
1861
1862 // Throw an Error if start is called more often than stop
1863 if (test.semaphore < 0) {
1864 test.semaphore = 0;
1865
1866 pushFailure("Tried to restart test while already started (test's semaphore was 0 already)", sourceFromStacktrace(2));
1867 return;
1868 }
1869
1870 // Add a slight delay to allow more assertions etc.
1871 if (defined.setTimeout) {
1872 if (config.timeout) {
1873 clearTimeout(config.timeout);
1874 }
1875 config.timeout = setTimeout(function () {
1876 if (test.semaphore > 0) {
1877 return;
1878 }
1879
1880 if (config.timeout) {
1881 clearTimeout(config.timeout);
1882 }
1883
1884 begin();
1885 }, 13);
1886 } else {
1887 begin();
1888 }
1889 }
1890
1891 function numberOfTests(module) {
1892 var count = module.tests.length,
1893 modules = [].concat(toConsumableArray(module.childModules));
1894
1895 // Do a breadth-first traversal of the child modules
1896 while (modules.length) {
1897 var nextModule = modules.shift();
1898 count += nextModule.tests.length;
1899 modules.push.apply(modules, toConsumableArray(nextModule.childModules));
1900 }
1901
1902 return count;
1903 }
1904
1905 function notifyTestsRan(module) {
1906 module.testsRun++;
1907 while (module = module.parentModule) {
1908 module.testsRun++;
1909 }
1910 }
1911
1912 /**
1913 * Returns a function that proxies to the given method name on the globals
1914 * console object. The proxy will also detect if the console doesn't exist and
1915 * will appropriately no-op. This allows support for IE9, which doesn't have a
1916 * console if the developer tools are not open.
1917 */
1918 function consoleProxy(method) {
1919 return function () {
1920 if (console) {
1921 console[method].apply(console, arguments);
1922 }
1923 };
1924 }
1925
1926 var Logger = {
1927 warn: consoleProxy("warn")
1928 };
1929
1930 var Assert = function () {
1931 function Assert(testContext) {
1932 classCallCheck(this, Assert);
1933
1934 this.test = testContext;
1935 }
1936
1937 // Assert helpers
1938
1939 // Documents a "step", which is a string value, in a test as a passing assertion
1940
1941
1942 createClass(Assert, [{
1943 key: "step",
1944 value: function step(message) {
1945 var result = !!message;
1946
1947 this.test.steps.push(message);
1948
1949 return this.pushResult({
1950 result: result,
1951 message: message || "You must provide a message to assert.step"
1952 });
1953 }
1954
1955 // Verifies the steps in a test match a given array of string values
1956
1957 }, {
1958 key: "verifySteps",
1959 value: function verifySteps(steps, message) {
1960 this.deepEqual(this.test.steps, steps, message);
1961 }
1962
1963 // Specify the number of expected assertions to guarantee that failed test
1964 // (no assertions are run at all) don't slip through.
1965
1966 }, {
1967 key: "expect",
1968 value: function expect(asserts) {
1969 if (arguments.length === 1) {
1970 this.test.expected = asserts;
1971 } else {
1972 return this.test.expected;
1973 }
1974 }
1975
1976 // Put a hold on processing and return a function that will release it a maximum of once.
1977
1978 }, {
1979 key: "async",
1980 value: function async(count) {
1981 var test$$1 = this.test,
1982 popped = false,
1983 acceptCallCount = count;
1984
1985 if (typeof acceptCallCount === "undefined") {
1986 acceptCallCount = 1;
1987 }
1988
1989 test$$1.usedAsync = true;
1990 var resume = internalStop(test$$1);
1991
1992 return function done() {
1993 if (popped) {
1994 test$$1.pushFailure("Too many calls to the `assert.async` callback", sourceFromStacktrace(2));
1995 return;
1996 }
1997
1998 acceptCallCount -= 1;
1999 if (acceptCallCount > 0) {
2000 return;
2001 }
2002
2003 popped = true;
2004 resume();
2005 };
2006 }
2007
2008 // Exports test.push() to the user API
2009 // Alias of pushResult.
2010
2011 }, {
2012 key: "push",
2013 value: function push(result, actual, expected, message, negative) {
2014 Logger.warn("assert.push is deprecated and will be removed in QUnit 3.0." + " Please use assert.pushResult instead (http://api.qunitjs.com/pushResult/).");
2015
2016 var currentAssert = this instanceof Assert ? this : config.current.assert;
2017 return currentAssert.pushResult({
2018 result: result,
2019 actual: actual,
2020 expected: expected,
2021 message: message,
2022 negative: negative
2023 });
2024 }
2025 }, {
2026 key: "pushResult",
2027 value: function pushResult(resultInfo) {
2028
2029 // Destructure of resultInfo = { result, actual, expected, message, negative }
2030 var assert = this,
2031 currentTest = assert instanceof Assert && assert.test || config.current;
2032
2033 // Backwards compatibility fix.
2034 // Allows the direct use of global exported assertions and QUnit.assert.*
2035 // Although, it's use is not recommended as it can leak assertions
2036 // to other tests from async tests, because we only get a reference to the current test,
2037 // not exactly the test where assertion were intended to be called.
2038 if (!currentTest) {
2039 throw new Error("assertion outside test context, in " + sourceFromStacktrace(2));
2040 }
2041
2042 if (currentTest.usedAsync === true && currentTest.semaphore === 0) {
2043 currentTest.pushFailure("Assertion after the final `assert.async` was resolved", sourceFromStacktrace(2));
2044
2045 // Allow this assertion to continue running anyway...
2046 }
2047
2048 if (!(assert instanceof Assert)) {
2049 assert = currentTest.assert;
2050 }
2051
2052 return assert.test.pushResult(resultInfo);
2053 }
2054 }, {
2055 key: "ok",
2056 value: function ok(result, message) {
2057 if (!message) {
2058 message = result ? "okay" : "failed, expected argument to be truthy, was: " + dump.parse(result);
2059 }
2060
2061 this.pushResult({
2062 result: !!result,
2063 actual: result,
2064 expected: true,
2065 message: message
2066 });
2067 }
2068 }, {
2069 key: "notOk",
2070 value: function notOk(result, message) {
2071 if (!message) {
2072 message = !result ? "okay" : "failed, expected argument to be falsy, was: " + dump.parse(result);
2073 }
2074
2075 this.pushResult({
2076 result: !result,
2077 actual: result,
2078 expected: false,
2079 message: message
2080 });
2081 }
2082 }, {
2083 key: "equal",
2084 value: function equal(actual, expected, message) {
2085
2086 // eslint-disable-next-line eqeqeq
2087 var result = expected == actual;
2088
2089 this.pushResult({
2090 result: result,
2091 actual: actual,
2092 expected: expected,
2093 message: message
2094 });
2095 }
2096 }, {
2097 key: "notEqual",
2098 value: function notEqual(actual, expected, message) {
2099
2100 // eslint-disable-next-line eqeqeq
2101 var result = expected != actual;
2102
2103 this.pushResult({
2104 result: result,
2105 actual: actual,
2106 expected: expected,
2107 message: message,
2108 negative: true
2109 });
2110 }
2111 }, {
2112 key: "propEqual",
2113 value: function propEqual(actual, expected, message) {
2114 actual = objectValues(actual);
2115 expected = objectValues(expected);
2116
2117 this.pushResult({
2118 result: equiv(actual, expected),
2119 actual: actual,
2120 expected: expected,
2121 message: message
2122 });
2123 }
2124 }, {
2125 key: "notPropEqual",
2126 value: function notPropEqual(actual, expected, message) {
2127 actual = objectValues(actual);
2128 expected = objectValues(expected);
2129
2130 this.pushResult({
2131 result: !equiv(actual, expected),
2132 actual: actual,
2133 expected: expected,
2134 message: message,
2135 negative: true
2136 });
2137 }
2138 }, {
2139 key: "deepEqual",
2140 value: function deepEqual(actual, expected, message) {
2141 this.pushResult({
2142 result: equiv(actual, expected),
2143 actual: actual,
2144 expected: expected,
2145 message: message
2146 });
2147 }
2148 }, {
2149 key: "notDeepEqual",
2150 value: function notDeepEqual(actual, expected, message) {
2151 this.pushResult({
2152 result: !equiv(actual, expected),
2153 actual: actual,
2154 expected: expected,
2155 message: message,
2156 negative: true
2157 });
2158 }
2159 }, {
2160 key: "strictEqual",
2161 value: function strictEqual(actual, expected, message) {
2162 this.pushResult({
2163 result: expected === actual,
2164 actual: actual,
2165 expected: expected,
2166 message: message
2167 });
2168 }
2169 }, {
2170 key: "notStrictEqual",
2171 value: function notStrictEqual(actual, expected, message) {
2172 this.pushResult({
2173 result: expected !== actual,
2174 actual: actual,
2175 expected: expected,
2176 message: message,
2177 negative: true
2178 });
2179 }
2180 }, {
2181 key: "throws",
2182 value: function throws(block, expected, message) {
2183 var actual = void 0,
2184 result = false,
2185 currentTest = this instanceof Assert && this.test || config.current;
2186
2187 // 'expected' is optional unless doing string comparison
2188 if (objectType(expected) === "string") {
2189 if (message == null) {
2190 message = expected;
2191 expected = null;
2192 } else {
2193 throw new Error("throws/raises does not accept a string value for the expected argument.\n" + "Use a non-string object value (e.g. regExp) instead if it's necessary.");
2194 }
2195 }
2196
2197 currentTest.ignoreGlobalErrors = true;
2198 try {
2199 block.call(currentTest.testEnvironment);
2200 } catch (e) {
2201 actual = e;
2202 }
2203 currentTest.ignoreGlobalErrors = false;
2204
2205 if (actual) {
2206 var expectedType = objectType(expected);
2207
2208 // We don't want to validate thrown error
2209 if (!expected) {
2210 result = true;
2211 expected = null;
2212
2213 // Expected is a regexp
2214 } else if (expectedType === "regexp") {
2215 result = expected.test(errorString(actual));
2216
2217 // Expected is a constructor, maybe an Error constructor
2218 } else if (expectedType === "function" && actual instanceof expected) {
2219 result = true;
2220
2221 // Expected is an Error object
2222 } else if (expectedType === "object") {
2223 result = actual instanceof expected.constructor && actual.name === expected.name && actual.message === expected.message;
2224
2225 // Expected is a validation function which returns true if validation passed
2226 } else if (expectedType === "function" && expected.call({}, actual) === true) {
2227 expected = null;
2228 result = true;
2229 }
2230 }
2231
2232 currentTest.assert.pushResult({
2233 result: result,
2234 actual: actual,
2235 expected: expected,
2236 message: message
2237 });
2238 }
2239 }]);
2240 return Assert;
2241 }();
2242
2243 // Provide an alternative to assert.throws(), for environments that consider throws a reserved word
2244 // Known to us are: Closure Compiler, Narwhal
2245 // eslint-disable-next-line dot-notation
2246
2247
2248 Assert.prototype.raises = Assert.prototype["throws"];
2249
2250 /**
2251 * Converts an error into a simple string for comparisons.
2252 *
2253 * @param {Error} error
2254 * @return {String}
2255 */
2256 function errorString(error) {
2257 var resultErrorString = error.toString();
2258
2259 if (resultErrorString.substring(0, 7) === "[object") {
2260 var name = error.name ? error.name.toString() : "Error";
2261 var message = error.message ? error.message.toString() : "";
2262
2263 if (name && message) {
2264 return name + ": " + message;
2265 } else if (name) {
2266 return name;
2267 } else if (message) {
2268 return message;
2269 } else {
2270 return "Error";
2271 }
2272 } else {
2273 return resultErrorString;
2274 }
2275 }
2276
2277 /* global module, exports, define */
2278 function exportQUnit(QUnit) {
2279
2280 if (defined.document) {
2281
2282 // QUnit may be defined when it is preconfigured but then only QUnit and QUnit.config may be defined.
2283 if (window.QUnit && window.QUnit.version) {
2284 throw new Error("QUnit has already been defined.");
2285 }
2286
2287 window.QUnit = QUnit;
2288 }
2289
2290 // For nodejs
2291 if (typeof module !== "undefined" && module && module.exports) {
2292 module.exports = QUnit;
2293
2294 // For consistency with CommonJS environments' exports
2295 module.exports.QUnit = QUnit;
2296 }
2297
2298 // For CommonJS with exports, but without module.exports, like Rhino
2299 if (typeof exports !== "undefined" && exports) {
2300 exports.QUnit = QUnit;
2301 }
2302
2303 if (typeof define === "function" && define.amd) {
2304 define(function () {
2305 return QUnit;
2306 });
2307 QUnit.config.autostart = false;
2308 }
2309 }
2310
2311 var SuiteReport = function () {
2312 function SuiteReport(name, parentSuite) {
2313 classCallCheck(this, SuiteReport);
2314
2315 this.name = name;
2316 this.fullName = parentSuite ? parentSuite.fullName.concat(name) : [];
2317
2318 this.tests = [];
2319 this.childSuites = [];
2320
2321 if (parentSuite) {
2322 parentSuite.pushChildSuite(this);
2323 }
2324 }
2325
2326 createClass(SuiteReport, [{
2327 key: "start",
2328 value: function start(recordTime) {
2329 if (recordTime) {
2330 this._startTime = Date.now();
2331 }
2332
2333 return {
2334 name: this.name,
2335 fullName: this.fullName.slice(),
2336 tests: this.tests.map(function (test) {
2337 return test.start();
2338 }),
2339 childSuites: this.childSuites.map(function (suite) {
2340 return suite.start();
2341 }),
2342 testCounts: {
2343 total: this.getTestCounts().total
2344 }
2345 };
2346 }
2347 }, {
2348 key: "end",
2349 value: function end(recordTime) {
2350 if (recordTime) {
2351 this._endTime = Date.now();
2352 }
2353
2354 return {
2355 name: this.name,
2356 fullName: this.fullName.slice(),
2357 tests: this.tests.map(function (test) {
2358 return test.end();
2359 }),
2360 childSuites: this.childSuites.map(function (suite) {
2361 return suite.end();
2362 }),
2363 testCounts: this.getTestCounts(),
2364 runtime: this.getRuntime(),
2365 status: this.getStatus()
2366 };
2367 }
2368 }, {
2369 key: "pushChildSuite",
2370 value: function pushChildSuite(suite) {
2371 this.childSuites.push(suite);
2372 }
2373 }, {
2374 key: "pushTest",
2375 value: function pushTest(test) {
2376 this.tests.push(test);
2377 }
2378 }, {
2379 key: "getRuntime",
2380 value: function getRuntime() {
2381 return this._endTime - this._startTime;
2382 }
2383 }, {
2384 key: "getTestCounts",
2385 value: function getTestCounts() {
2386 var counts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { passed: 0, failed: 0, skipped: 0, todo: 0, total: 0 };
2387
2388 counts = this.tests.reduce(function (counts, test) {
2389 counts[test.getStatus()]++;
2390 counts.total++;
2391 return counts;
2392 }, counts);
2393
2394 return this.childSuites.reduce(function (counts, suite) {
2395 return suite.getTestCounts(counts);
2396 }, counts);
2397 }
2398 }, {
2399 key: "getStatus",
2400 value: function getStatus() {
2401 var _getTestCounts = this.getTestCounts(),
2402 total = _getTestCounts.total,
2403 failed = _getTestCounts.failed,
2404 skipped = _getTestCounts.skipped,
2405 todo = _getTestCounts.todo;
2406
2407 if (failed) {
2408 return "failed";
2409 } else {
2410 if (skipped === total) {
2411 return "skipped";
2412 } else if (todo === total) {
2413 return "todo";
2414 } else {
2415 return "passed";
2416 }
2417 }
2418 }
2419 }]);
2420 return SuiteReport;
2421 }();
2422
2423 // Handle an unhandled exception. By convention, returns true if further
2424 // error handling should be suppressed and false otherwise.
2425 // In this case, we will only suppress further error handling if the
2426 // "ignoreGlobalErrors" configuration option is enabled.
2427 function onError(error) {
2428 for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
2429 args[_key - 1] = arguments[_key];
2430 }
2431
2432 if (config.current) {
2433 if (config.current.ignoreGlobalErrors) {
2434 return true;
2435 }
2436 pushFailure.apply(undefined, [error.message, error.fileName + ":" + error.lineNumber].concat(args));
2437 } else {
2438 test("global failure", extend(function () {
2439 pushFailure.apply(undefined, [error.message, error.fileName + ":" + error.lineNumber].concat(args));
2440 }, { validTest: true }));
2441 }
2442
2443 return false;
2444 }
2445
2446 var QUnit = {};
2447 var globalSuite = new SuiteReport();
2448
2449 // The initial "currentModule" represents the global (or top-level) module that
2450 // is not explicitly defined by the user, therefore we add the "globalSuite" to
2451 // it since each module has a suiteReport associated with it.
2452 config.currentModule.suiteReport = globalSuite;
2453
2454 var globalStartCalled = false;
2455 var runStarted = false;
2456
2457 var internalState = {
2458 autorun: false
2459 };
2460
2461 // Figure out if we're running the tests from a server or not
2462 QUnit.isLocal = !(defined.document && window.location.protocol !== "file:");
2463
2464 // Expose the current QUnit version
2465 QUnit.version = "2.2.1";
2466
2467 extend(QUnit, {
2468 on: on,
2469
2470 // Call on start of module test to prepend name to all tests
2471 module: function module(name, testEnvironment, executeNow) {
2472 var module, moduleFns;
2473 var currentModule = config.currentModule;
2474
2475 if (arguments.length === 2) {
2476 if (objectType(testEnvironment) === "function") {
2477 executeNow = testEnvironment;
2478 testEnvironment = undefined;
2479 }
2480 }
2481
2482 module = createModule();
2483
2484 moduleFns = {
2485 before: setHook(module, "before"),
2486 beforeEach: setHook(module, "beforeEach"),
2487 afterEach: setHook(module, "afterEach"),
2488 after: setHook(module, "after")
2489 };
2490
2491 if (objectType(executeNow) === "function") {
2492 config.moduleStack.push(module);
2493 setCurrentModule(module);
2494 executeNow.call(module.testEnvironment, moduleFns);
2495 config.moduleStack.pop();
2496 module = module.parentModule || currentModule;
2497 }
2498
2499 setCurrentModule(module);
2500
2501 function createModule() {
2502 var parentModule = config.moduleStack.length ? config.moduleStack.slice(-1)[0] : null;
2503 var moduleName = parentModule !== null ? [parentModule.name, name].join(" > ") : name;
2504 var parentSuite = parentModule ? parentModule.suiteReport : globalSuite;
2505
2506 var module = {
2507 name: moduleName,
2508 parentModule: parentModule,
2509 tests: [],
2510 moduleId: generateHash(moduleName),
2511 testsRun: 0,
2512 childModules: [],
2513 suiteReport: new SuiteReport(name, parentSuite)
2514 };
2515
2516 var env = {};
2517 if (parentModule) {
2518 parentModule.childModules.push(module);
2519 extend(env, parentModule.testEnvironment);
2520 delete env.beforeEach;
2521 delete env.afterEach;
2522 }
2523 extend(env, testEnvironment);
2524 module.testEnvironment = env;
2525
2526 config.modules.push(module);
2527 return module;
2528 }
2529
2530 function setCurrentModule(module) {
2531 config.currentModule = module;
2532 }
2533 },
2534
2535 test: test,
2536
2537 todo: todo,
2538
2539 skip: skip,
2540
2541 only: only,
2542
2543 start: function start(count) {
2544 var globalStartAlreadyCalled = globalStartCalled;
2545
2546 if (!config.current) {
2547 globalStartCalled = true;
2548
2549 if (runStarted) {
2550 throw new Error("Called start() while test already started running");
2551 } else if (globalStartAlreadyCalled || count > 1) {
2552 throw new Error("Called start() outside of a test context too many times");
2553 } else if (config.autostart) {
2554 throw new Error("Called start() outside of a test context when " + "QUnit.config.autostart was true");
2555 } else if (!config.pageLoaded) {
2556
2557 // The page isn't completely loaded yet, so we set autostart and then
2558 // load if we're in Node or wait for the browser's load event.
2559 config.autostart = true;
2560
2561 // Starts from Node even if .load was not previously called. We still return
2562 // early otherwise we'll wind up "beginning" twice.
2563 if (!defined.document) {
2564 QUnit.load();
2565 }
2566
2567 return;
2568 }
2569 } else {
2570 throw new Error("QUnit.start cannot be called inside a test context.");
2571 }
2572
2573 scheduleBegin();
2574 },
2575
2576 config: config,
2577
2578 is: is,
2579
2580 objectType: objectType,
2581
2582 extend: extend,
2583
2584 load: function load() {
2585 config.pageLoaded = true;
2586
2587 // Initialize the configuration options
2588 extend(config, {
2589 stats: { all: 0, bad: 0 },
2590 started: 0,
2591 updateRate: 1000,
2592 autostart: true,
2593 filter: ""
2594 }, true);
2595
2596 if (!runStarted) {
2597 config.blocking = false;
2598
2599 if (config.autostart) {
2600 scheduleBegin();
2601 }
2602 }
2603 },
2604
2605 stack: function stack(offset) {
2606 offset = (offset || 0) + 2;
2607 return sourceFromStacktrace(offset);
2608 },
2609
2610 onError: onError
2611 });
2612
2613 QUnit.pushFailure = pushFailure;
2614 QUnit.assert = Assert.prototype;
2615 QUnit.equiv = equiv;
2616 QUnit.dump = dump;
2617
2618 registerLoggingCallbacks(QUnit);
2619
2620 function scheduleBegin() {
2621
2622 runStarted = true;
2623
2624 // Add a slight delay to allow definition of more modules and tests.
2625 if (defined.setTimeout) {
2626 setTimeout(function () {
2627 begin();
2628 }, 13);
2629 } else {
2630 begin();
2631 }
2632 }
2633
2634 function begin() {
2635 var i,
2636 l,
2637 modulesLog = [];
2638
2639 // If the test run hasn't officially begun yet
2640 if (!config.started) {
2641
2642 // Record the time of the test run's beginning
2643 config.started = now();
2644
2645 // Delete the loose unnamed module if unused.
2646 if (config.modules[0].name === "" && config.modules[0].tests.length === 0) {
2647 config.modules.shift();
2648 }
2649
2650 // Avoid unnecessary information by not logging modules' test environments
2651 for (i = 0, l = config.modules.length; i < l; i++) {
2652 modulesLog.push({
2653 name: config.modules[i].name,
2654 tests: config.modules[i].tests
2655 });
2656 }
2657
2658 // The test run is officially beginning now
2659 emit("runStart", globalSuite.start(true));
2660 runLoggingCallbacks("begin", {
2661 totalTests: Test.count,
2662 modules: modulesLog
2663 });
2664 }
2665
2666 config.blocking = false;
2667 process(true);
2668 }
2669
2670 function process(last) {
2671 function next() {
2672 process(last);
2673 }
2674 var start = now();
2675 config.depth = (config.depth || 0) + 1;
2676
2677 while (config.queue.length && !config.blocking) {
2678 if (!defined.setTimeout || config.updateRate <= 0 || now() - start < config.updateRate) {
2679 if (config.current) {
2680
2681 // Reset async tracking for each phase of the Test lifecycle
2682 config.current.usedAsync = false;
2683 }
2684 config.queue.shift()();
2685 } else {
2686 setTimeout(next, 13);
2687 break;
2688 }
2689 }
2690 config.depth--;
2691 if (last && !config.blocking && !config.queue.length && config.depth === 0) {
2692 done();
2693 }
2694 }
2695
2696 function done() {
2697 var runtime,
2698 passed,
2699 i,
2700 key,
2701 storage = config.storage;
2702
2703 internalState.autorun = true;
2704
2705 runtime = now() - config.started;
2706 passed = config.stats.all - config.stats.bad;
2707
2708 emit("runEnd", globalSuite.end(true));
2709 runLoggingCallbacks("done", {
2710 failed: config.stats.bad,
2711 passed: passed,
2712 total: config.stats.all,
2713 runtime: runtime
2714 });
2715
2716 // Clear own storage items if all tests passed
2717 if (storage && config.stats.bad === 0) {
2718 for (i = storage.length - 1; i >= 0; i--) {
2719 key = storage.key(i);
2720 if (key.indexOf("qunit-test-") === 0) {
2721 storage.removeItem(key);
2722 }
2723 }
2724 }
2725 }
2726
2727 function setHook(module, hookName) {
2728 if (module.testEnvironment === undefined) {
2729 module.testEnvironment = {};
2730 }
2731
2732 return function (callback) {
2733 module.testEnvironment[hookName] = callback;
2734 };
2735 }
2736
2737 exportQUnit(QUnit);
2738
2739 (function () {
2740
2741 if (typeof window === "undefined" || typeof document === "undefined") {
2742 return;
2743 }
2744
2745 var config = QUnit.config,
2746 hasOwn = Object.prototype.hasOwnProperty;
2747
2748 // Stores fixture HTML for resetting later
2749 function storeFixture() {
2750
2751 // Avoid overwriting user-defined values
2752 if (hasOwn.call(config, "fixture")) {
2753 return;
2754 }
2755
2756 var fixture = document.getElementById("qunit-fixture");
2757 if (fixture) {
2758 config.fixture = fixture.innerHTML;
2759 }
2760 }
2761
2762 QUnit.begin(storeFixture);
2763
2764 // Resets the fixture DOM element if available.
2765 function resetFixture() {
2766 if (config.fixture == null) {
2767 return;
2768 }
2769
2770 var fixture = document.getElementById("qunit-fixture");
2771 if (fixture) {
2772 fixture.innerHTML = config.fixture;
2773 }
2774 }
2775
2776 QUnit.testStart(resetFixture);
2777 })();
2778
2779 (function () {
2780
2781 // Only interact with URLs via window.location
2782 var location = typeof window !== "undefined" && window.location;
2783 if (!location) {
2784 return;
2785 }
2786
2787 var urlParams = getUrlParams();
2788
2789 QUnit.urlParams = urlParams;
2790
2791 // Match module/test by inclusion in an array
2792 QUnit.config.moduleId = [].concat(urlParams.moduleId || []);
2793 QUnit.config.testId = [].concat(urlParams.testId || []);
2794
2795 // Exact case-insensitive match of the module name
2796 QUnit.config.module = urlParams.module;
2797
2798 // Regular expression or case-insenstive substring match against "moduleName: testName"
2799 QUnit.config.filter = urlParams.filter;
2800
2801 // Test order randomization
2802 if (urlParams.seed === true) {
2803
2804 // Generate a random seed if the option is specified without a value
2805 QUnit.config.seed = Math.random().toString(36).slice(2);
2806 } else if (urlParams.seed) {
2807 QUnit.config.seed = urlParams.seed;
2808 }
2809
2810 // Add URL-parameter-mapped config values with UI form rendering data
2811 QUnit.config.urlConfig.push({
2812 id: "hidepassed",
2813 label: "Hide passed tests",
2814 tooltip: "Only show tests and assertions that fail. Stored as query-strings."
2815 }, {
2816 id: "noglobals",
2817 label: "Check for Globals",
2818 tooltip: "Enabling this will test if any test introduces new properties on the " + "global object (`window` in Browsers). Stored as query-strings."
2819 }, {
2820 id: "notrycatch",
2821 label: "No try-catch",
2822 tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging " + "exceptions in IE reasonable. Stored as query-strings."
2823 });
2824
2825 QUnit.begin(function () {
2826 var i,
2827 option,
2828 urlConfig = QUnit.config.urlConfig;
2829
2830 for (i = 0; i < urlConfig.length; i++) {
2831
2832 // Options can be either strings or objects with nonempty "id" properties
2833 option = QUnit.config.urlConfig[i];
2834 if (typeof option !== "string") {
2835 option = option.id;
2836 }
2837
2838 if (QUnit.config[option] === undefined) {
2839 QUnit.config[option] = urlParams[option];
2840 }
2841 }
2842 });
2843
2844 function getUrlParams() {
2845 var i, param, name, value;
2846 var urlParams = Object.create(null);
2847 var params = location.search.slice(1).split("&");
2848 var length = params.length;
2849
2850 for (i = 0; i < length; i++) {
2851 if (params[i]) {
2852 param = params[i].split("=");
2853 name = decodeQueryParam(param[0]);
2854
2855 // Allow just a key to turn on a flag, e.g., test.html?noglobals
2856 value = param.length === 1 || decodeQueryParam(param.slice(1).join("="));
2857 if (name in urlParams) {
2858 urlParams[name] = [].concat(urlParams[name], value);
2859 } else {
2860 urlParams[name] = value;
2861 }
2862 }
2863 }
2864
2865 return urlParams;
2866 }
2867
2868 function decodeQueryParam(param) {
2869 return decodeURIComponent(param.replace(/\+/g, "%20"));
2870 }
2871 })();
2872
2873 var stats = {
2874 passedTests: 0,
2875 failedTests: 0,
2876 skippedTests: 0,
2877 todoTests: 0
2878 };
2879
2880 // Escape text for attribute or text content.
2881 function escapeText(s) {
2882 if (!s) {
2883 return "";
2884 }
2885 s = s + "";
2886
2887 // Both single quotes and double quotes (for attributes)
2888 return s.replace(/['"<>&]/g, function (s) {
2889 switch (s) {
2890 case "'":
2891 return "&#039;";
2892 case "\"":
2893 return "&quot;";
2894 case "<":
2895 return "&lt;";
2896 case ">":
2897 return "&gt;";
2898 case "&":
2899 return "&amp;";
2900 }
2901 });
2902 }
2903
2904 (function () {
2905
2906 // Don't load the HTML Reporter on non-browser environments
2907 if (typeof window === "undefined" || !window.document) {
2908 return;
2909 }
2910
2911 var config = QUnit.config,
2912 document$$1 = window.document,
2913 collapseNext = false,
2914 hasOwn = Object.prototype.hasOwnProperty,
2915 unfilteredUrl = setUrl({ filter: undefined, module: undefined,
2916 moduleId: undefined, testId: undefined }),
2917 modulesList = [];
2918
2919 function addEvent(elem, type, fn) {
2920 elem.addEventListener(type, fn, false);
2921 }
2922
2923 function removeEvent(elem, type, fn) {
2924 elem.removeEventListener(type, fn, false);
2925 }
2926
2927 function addEvents(elems, type, fn) {
2928 var i = elems.length;
2929 while (i--) {
2930 addEvent(elems[i], type, fn);
2931 }
2932 }
2933
2934 function hasClass(elem, name) {
2935 return (" " + elem.className + " ").indexOf(" " + name + " ") >= 0;
2936 }
2937
2938 function addClass(elem, name) {
2939 if (!hasClass(elem, name)) {
2940 elem.className += (elem.className ? " " : "") + name;
2941 }
2942 }
2943
2944 function toggleClass(elem, name, force) {
2945 if (force || typeof force === "undefined" && !hasClass(elem, name)) {
2946 addClass(elem, name);
2947 } else {
2948 removeClass(elem, name);
2949 }
2950 }
2951
2952 function removeClass(elem, name) {
2953 var set = " " + elem.className + " ";
2954
2955 // Class name may appear multiple times
2956 while (set.indexOf(" " + name + " ") >= 0) {
2957 set = set.replace(" " + name + " ", " ");
2958 }
2959
2960 // Trim for prettiness
2961 elem.className = typeof set.trim === "function" ? set.trim() : set.replace(/^\s+|\s+$/g, "");
2962 }
2963
2964 function id(name) {
2965 return document$$1.getElementById && document$$1.getElementById(name);
2966 }
2967
2968 function abortTests() {
2969 var abortButton = id("qunit-abort-tests-button");
2970 if (abortButton) {
2971 abortButton.disabled = true;
2972 abortButton.innerHTML = "Aborting...";
2973 }
2974 QUnit.config.queue.length = 0;
2975 return false;
2976 }
2977
2978 function interceptNavigation(ev) {
2979 applyUrlParams();
2980
2981 if (ev && ev.preventDefault) {
2982 ev.preventDefault();
2983 }
2984
2985 return false;
2986 }
2987
2988 function getUrlConfigHtml() {
2989 var i,
2990 j,
2991 val,
2992 escaped,
2993 escapedTooltip,
2994 selection = false,
2995 urlConfig = config.urlConfig,
2996 urlConfigHtml = "";
2997
2998 for (i = 0; i < urlConfig.length; i++) {
2999
3000 // Options can be either strings or objects with nonempty "id" properties
3001 val = config.urlConfig[i];
3002 if (typeof val === "string") {
3003 val = {
3004 id: val,
3005 label: val
3006 };
3007 }
3008
3009 escaped = escapeText(val.id);
3010 escapedTooltip = escapeText(val.tooltip);
3011
3012 if (!val.value || typeof val.value === "string") {
3013 urlConfigHtml += "<label for='qunit-urlconfig-" + escaped + "' title='" + escapedTooltip + "'><input id='qunit-urlconfig-" + escaped + "' name='" + escaped + "' type='checkbox'" + (val.value ? " value='" + escapeText(val.value) + "'" : "") + (config[val.id] ? " checked='checked'" : "") + " title='" + escapedTooltip + "' />" + escapeText(val.label) + "</label>";
3014 } else {
3015 urlConfigHtml += "<label for='qunit-urlconfig-" + escaped + "' title='" + escapedTooltip + "'>" + val.label + ": </label><select id='qunit-urlconfig-" + escaped + "' name='" + escaped + "' title='" + escapedTooltip + "'><option></option>";
3016
3017 if (QUnit.is("array", val.value)) {
3018 for (j = 0; j < val.value.length; j++) {
3019 escaped = escapeText(val.value[j]);
3020 urlConfigHtml += "<option value='" + escaped + "'" + (config[val.id] === val.value[j] ? (selection = true) && " selected='selected'" : "") + ">" + escaped + "</option>";
3021 }
3022 } else {
3023 for (j in val.value) {
3024 if (hasOwn.call(val.value, j)) {
3025 urlConfigHtml += "<option value='" + escapeText(j) + "'" + (config[val.id] === j ? (selection = true) && " selected='selected'" : "") + ">" + escapeText(val.value[j]) + "</option>";
3026 }
3027 }
3028 }
3029 if (config[val.id] && !selection) {
3030 escaped = escapeText(config[val.id]);
3031 urlConfigHtml += "<option value='" + escaped + "' selected='selected' disabled='disabled'>" + escaped + "</option>";
3032 }
3033 urlConfigHtml += "</select>";
3034 }
3035 }
3036
3037 return urlConfigHtml;
3038 }
3039
3040 // Handle "click" events on toolbar checkboxes and "change" for select menus.
3041 // Updates the URL with the new state of `config.urlConfig` values.
3042 function toolbarChanged() {
3043 var updatedUrl,
3044 value,
3045 tests,
3046 field = this,
3047 params = {};
3048
3049 // Detect if field is a select menu or a checkbox
3050 if ("selectedIndex" in field) {
3051 value = field.options[field.selectedIndex].value || undefined;
3052 } else {
3053 value = field.checked ? field.defaultValue || true : undefined;
3054 }
3055
3056 params[field.name] = value;
3057 updatedUrl = setUrl(params);
3058
3059 // Check if we can apply the change without a page refresh
3060 if ("hidepassed" === field.name && "replaceState" in window.history) {
3061 QUnit.urlParams[field.name] = value;
3062 config[field.name] = value || false;
3063 tests = id("qunit-tests");
3064 if (tests) {
3065 toggleClass(tests, "hidepass", value || false);
3066 }
3067 window.history.replaceState(null, "", updatedUrl);
3068 } else {
3069 window.location = updatedUrl;
3070 }
3071 }
3072
3073 function setUrl(params) {
3074 var key,
3075 arrValue,
3076 i,
3077 querystring = "?",
3078 location = window.location;
3079
3080 params = QUnit.extend(QUnit.extend({}, QUnit.urlParams), params);
3081
3082 for (key in params) {
3083
3084 // Skip inherited or undefined properties
3085 if (hasOwn.call(params, key) && params[key] !== undefined) {
3086
3087 // Output a parameter for each value of this key (but usually just one)
3088 arrValue = [].concat(params[key]);
3089 for (i = 0; i < arrValue.length; i++) {
3090 querystring += encodeURIComponent(key);
3091 if (arrValue[i] !== true) {
3092 querystring += "=" + encodeURIComponent(arrValue[i]);
3093 }
3094 querystring += "&";
3095 }
3096 }
3097 }
3098 return location.protocol + "//" + location.host + location.pathname + querystring.slice(0, -1);
3099 }
3100
3101 function applyUrlParams() {
3102 var i,
3103 selectedModules = [],
3104 modulesList = id("qunit-modulefilter-dropdown-list").getElementsByTagName("input"),
3105 filter = id("qunit-filter-input").value;
3106
3107 for (i = 0; i < modulesList.length; i++) {
3108 if (modulesList[i].checked) {
3109 selectedModules.push(modulesList[i].value);
3110 }
3111 }
3112
3113 window.location = setUrl({
3114 filter: filter === "" ? undefined : filter,
3115 moduleId: selectedModules.length === 0 ? undefined : selectedModules,
3116
3117 // Remove module and testId filter
3118 module: undefined,
3119 testId: undefined
3120 });
3121 }
3122
3123 function toolbarUrlConfigContainer() {
3124 var urlConfigContainer = document$$1.createElement("span");
3125
3126 urlConfigContainer.innerHTML = getUrlConfigHtml();
3127 addClass(urlConfigContainer, "qunit-url-config");
3128
3129 addEvents(urlConfigContainer.getElementsByTagName("input"), "change", toolbarChanged);
3130 addEvents(urlConfigContainer.getElementsByTagName("select"), "change", toolbarChanged);
3131
3132 return urlConfigContainer;
3133 }
3134
3135 function abortTestsButton() {
3136 var button = document$$1.createElement("button");
3137 button.id = "qunit-abort-tests-button";
3138 button.innerHTML = "Abort";
3139 addEvent(button, "click", abortTests);
3140 return button;
3141 }
3142
3143 function toolbarLooseFilter() {
3144 var filter = document$$1.createElement("form"),
3145 label = document$$1.createElement("label"),
3146 input = document$$1.createElement("input"),
3147 button = document$$1.createElement("button");
3148
3149 addClass(filter, "qunit-filter");
3150
3151 label.innerHTML = "Filter: ";
3152
3153 input.type = "text";
3154 input.value = config.filter || "";
3155 input.name = "filter";
3156 input.id = "qunit-filter-input";
3157
3158 button.innerHTML = "Go";
3159
3160 label.appendChild(input);
3161
3162 filter.appendChild(label);
3163 filter.appendChild(document$$1.createTextNode(" "));
3164 filter.appendChild(button);
3165 addEvent(filter, "submit", interceptNavigation);
3166
3167 return filter;
3168 }
3169
3170 function moduleListHtml() {
3171 var i,
3172 checked,
3173 html = "";
3174
3175 for (i = 0; i < config.modules.length; i++) {
3176 if (config.modules[i].name !== "") {
3177 checked = config.moduleId.indexOf(config.modules[i].moduleId) > -1;
3178 html += "<li><label class='clickable" + (checked ? " checked" : "") + "'><input type='checkbox' " + "value='" + config.modules[i].moduleId + "'" + (checked ? " checked='checked'" : "") + " />" + escapeText(config.modules[i].name) + "</label></li>";
3179 }
3180 }
3181
3182 return html;
3183 }
3184
3185 function toolbarModuleFilter() {
3186 var allCheckbox,
3187 commit,
3188 reset,
3189 moduleFilter = document$$1.createElement("form"),
3190 label = document$$1.createElement("label"),
3191 moduleSearch = document$$1.createElement("input"),
3192 dropDown = document$$1.createElement("div"),
3193 actions = document$$1.createElement("span"),
3194 dropDownList = document$$1.createElement("ul"),
3195 dirty = false;
3196
3197 moduleSearch.id = "qunit-modulefilter-search";
3198 addEvent(moduleSearch, "input", searchInput);
3199 addEvent(moduleSearch, "input", searchFocus);
3200 addEvent(moduleSearch, "focus", searchFocus);
3201 addEvent(moduleSearch, "click", searchFocus);
3202
3203 label.id = "qunit-modulefilter-search-container";
3204 label.innerHTML = "Module: ";
3205 label.appendChild(moduleSearch);
3206
3207 actions.id = "qunit-modulefilter-actions";
3208 actions.innerHTML = "<button style='display:none'>Apply</button>" + "<button type='reset' style='display:none'>Reset</button>" + "<label class='clickable" + (config.moduleId.length ? "" : " checked") + "'><input type='checkbox'" + (config.moduleId.length ? "" : " checked='checked'") + ">All modules</label>";
3209 allCheckbox = actions.lastChild.firstChild;
3210 commit = actions.firstChild;
3211 reset = commit.nextSibling;
3212 addEvent(commit, "click", applyUrlParams);
3213
3214 dropDownList.id = "qunit-modulefilter-dropdown-list";
3215 dropDownList.innerHTML = moduleListHtml();
3216
3217 dropDown.id = "qunit-modulefilter-dropdown";
3218 dropDown.style.display = "none";
3219 dropDown.appendChild(actions);
3220 dropDown.appendChild(dropDownList);
3221 addEvent(dropDown, "change", selectionChange);
3222 selectionChange();
3223
3224 moduleFilter.id = "qunit-modulefilter";
3225 moduleFilter.appendChild(label);
3226 moduleFilter.appendChild(dropDown);
3227 addEvent(moduleFilter, "submit", interceptNavigation);
3228 addEvent(moduleFilter, "reset", function () {
3229
3230 // Let the reset happen, then update styles
3231 window.setTimeout(selectionChange);
3232 });
3233
3234 // Enables show/hide for the dropdown
3235 function searchFocus() {
3236 if (dropDown.style.display !== "none") {
3237 return;
3238 }
3239
3240 dropDown.style.display = "block";
3241 addEvent(document$$1, "click", hideHandler);
3242 addEvent(document$$1, "keydown", hideHandler);
3243
3244 // Hide on Escape keydown or outside-container click
3245 function hideHandler(e) {
3246 var inContainer = moduleFilter.contains(e.target);
3247
3248 if (e.keyCode === 27 || !inContainer) {
3249 if (e.keyCode === 27 && inContainer) {
3250 moduleSearch.focus();
3251 }
3252 dropDown.style.display = "none";
3253 removeEvent(document$$1, "click", hideHandler);
3254 removeEvent(document$$1, "keydown", hideHandler);
3255 moduleSearch.value = "";
3256 searchInput();
3257 }
3258 }
3259 }
3260
3261 // Processes module search box input
3262 function searchInput() {
3263 var i,
3264 item,
3265 searchText = moduleSearch.value.toLowerCase(),
3266 listItems = dropDownList.children;
3267
3268 for (i = 0; i < listItems.length; i++) {
3269 item = listItems[i];
3270 if (!searchText || item.textContent.toLowerCase().indexOf(searchText) > -1) {
3271 item.style.display = "";
3272 } else {
3273 item.style.display = "none";
3274 }
3275 }
3276 }
3277
3278 // Processes selection changes
3279 function selectionChange(evt) {
3280 var i,
3281 item,
3282 checkbox = evt && evt.target || allCheckbox,
3283 modulesList = dropDownList.getElementsByTagName("input"),
3284 selectedNames = [];
3285
3286 toggleClass(checkbox.parentNode, "checked", checkbox.checked);
3287
3288 dirty = false;
3289 if (checkbox.checked && checkbox !== allCheckbox) {
3290 allCheckbox.checked = false;
3291 removeClass(allCheckbox.parentNode, "checked");
3292 }
3293 for (i = 0; i < modulesList.length; i++) {
3294 item = modulesList[i];
3295 if (!evt) {
3296 toggleClass(item.parentNode, "checked", item.checked);
3297 } else if (checkbox === allCheckbox && checkbox.checked) {
3298 item.checked = false;
3299 removeClass(item.parentNode, "checked");
3300 }
3301 dirty = dirty || item.checked !== item.defaultChecked;
3302 if (item.checked) {
3303 selectedNames.push(item.parentNode.textContent);
3304 }
3305 }
3306
3307 commit.style.display = reset.style.display = dirty ? "" : "none";
3308 moduleSearch.placeholder = selectedNames.join(", ") || allCheckbox.parentNode.textContent;
3309 moduleSearch.title = "Type to filter list. Current selection:\n" + (selectedNames.join("\n") || allCheckbox.parentNode.textContent);
3310 }
3311
3312 return moduleFilter;
3313 }
3314
3315 function appendToolbar() {
3316 var toolbar = id("qunit-testrunner-toolbar");
3317
3318 if (toolbar) {
3319 toolbar.appendChild(toolbarUrlConfigContainer());
3320 toolbar.appendChild(toolbarModuleFilter());
3321 toolbar.appendChild(toolbarLooseFilter());
3322 toolbar.appendChild(document$$1.createElement("div")).className = "clearfix";
3323 }
3324 }
3325
3326 function appendHeader() {
3327 var header = id("qunit-header");
3328
3329 if (header) {
3330 header.innerHTML = "<a href='" + escapeText(unfilteredUrl) + "'>" + header.innerHTML + "</a> ";
3331 }
3332 }
3333
3334 function appendBanner() {
3335 var banner = id("qunit-banner");
3336
3337 if (banner) {
3338 banner.className = "";
3339 }
3340 }
3341
3342 function appendTestResults() {
3343 var tests = id("qunit-tests"),
3344 result = id("qunit-testresult"),
3345 controls;
3346
3347 if (result) {
3348 result.parentNode.removeChild(result);
3349 }
3350
3351 if (tests) {
3352 tests.innerHTML = "";
3353 result = document$$1.createElement("p");
3354 result.id = "qunit-testresult";
3355 result.className = "result";
3356 tests.parentNode.insertBefore(result, tests);
3357 result.innerHTML = "<div id=\"qunit-testresult-display\">Running...<br />&#160;</div>" + "<div id=\"qunit-testresult-controls\"></div>" + "<div class=\"clearfix\"></div>";
3358 controls = id("qunit-testresult-controls");
3359 }
3360
3361 if (controls) {
3362 controls.appendChild(abortTestsButton());
3363 }
3364 }
3365
3366 function appendFilteredTest() {
3367 var testId = QUnit.config.testId;
3368 if (!testId || testId.length <= 0) {
3369 return "";
3370 }
3371 return "<div id='qunit-filteredTest'>Rerunning selected tests: " + escapeText(testId.join(", ")) + " <a id='qunit-clearFilter' href='" + escapeText(unfilteredUrl) + "'>Run all tests</a></div>";
3372 }
3373
3374 function appendUserAgent() {
3375 var userAgent = id("qunit-userAgent");
3376
3377 if (userAgent) {
3378 userAgent.innerHTML = "";
3379 userAgent.appendChild(document$$1.createTextNode("QUnit " + QUnit.version + "; " + navigator.userAgent));
3380 }
3381 }
3382
3383 function appendInterface() {
3384 var qunit = id("qunit");
3385
3386 if (qunit) {
3387 qunit.innerHTML = "<h1 id='qunit-header'>" + escapeText(document$$1.title) + "</h1>" + "<h2 id='qunit-banner'></h2>" + "<div id='qunit-testrunner-toolbar'></div>" + appendFilteredTest() + "<h2 id='qunit-userAgent'></h2>" + "<ol id='qunit-tests'></ol>";
3388 }
3389
3390 appendHeader();
3391 appendBanner();
3392 appendTestResults();
3393 appendUserAgent();
3394 appendToolbar();
3395 }
3396
3397 function appendTestsList(modules) {
3398 var i, l, x, z, test, moduleObj;
3399
3400 for (i = 0, l = modules.length; i < l; i++) {
3401 moduleObj = modules[i];
3402
3403 for (x = 0, z = moduleObj.tests.length; x < z; x++) {
3404 test = moduleObj.tests[x];
3405
3406 appendTest(test.name, test.testId, moduleObj.name);
3407 }
3408 }
3409 }
3410
3411 function appendTest(name, testId, moduleName) {
3412 var title,
3413 rerunTrigger,
3414 testBlock,
3415 assertList,
3416 tests = id("qunit-tests");
3417
3418 if (!tests) {
3419 return;
3420 }
3421
3422 title = document$$1.createElement("strong");
3423 title.innerHTML = getNameHtml(name, moduleName);
3424
3425 rerunTrigger = document$$1.createElement("a");
3426 rerunTrigger.innerHTML = "Rerun";
3427 rerunTrigger.href = setUrl({ testId: testId });
3428
3429 testBlock = document$$1.createElement("li");
3430 testBlock.appendChild(title);
3431 testBlock.appendChild(rerunTrigger);
3432 testBlock.id = "qunit-test-output-" + testId;
3433
3434 assertList = document$$1.createElement("ol");
3435 assertList.className = "qunit-assert-list";
3436
3437 testBlock.appendChild(assertList);
3438
3439 tests.appendChild(testBlock);
3440 }
3441
3442 // HTML Reporter initialization and load
3443 QUnit.begin(function (details) {
3444 var i, moduleObj, tests;
3445
3446 // Sort modules by name for the picker
3447 for (i = 0; i < details.modules.length; i++) {
3448 moduleObj = details.modules[i];
3449 if (moduleObj.name) {
3450 modulesList.push(moduleObj.name);
3451 }
3452 }
3453 modulesList.sort(function (a, b) {
3454 return a.localeCompare(b);
3455 });
3456
3457 // Initialize QUnit elements
3458 appendInterface();
3459 appendTestsList(details.modules);
3460 tests = id("qunit-tests");
3461 if (tests && config.hidepassed) {
3462 addClass(tests, "hidepass");
3463 }
3464 });
3465
3466 QUnit.done(function (details) {
3467 var banner = id("qunit-banner"),
3468 tests = id("qunit-tests"),
3469 abortButton = id("qunit-abort-tests-button"),
3470 totalTests = stats.passedTests + stats.skippedTests + stats.todoTests + stats.failedTests,
3471 html = [totalTests, " tests completed in ", details.runtime, " milliseconds, with ", stats.failedTests, " failed, ", stats.skippedTests, " skipped, and ", stats.todoTests, " todo.<br />", "<span class='passed'>", details.passed, "</span> assertions of <span class='total'>", details.total, "</span> passed, <span class='failed'>", details.failed, "</span> failed."].join(""),
3472 test,
3473 assertLi,
3474 assertList;
3475
3476 // Update remaing tests to aborted
3477 if (abortButton && abortButton.disabled) {
3478 html = "Tests aborted after " + details.runtime + " milliseconds.";
3479
3480 for (var i = 0; i < tests.children.length; i++) {
3481 test = tests.children[i];
3482 if (test.className === "" || test.className === "running") {
3483 test.className = "aborted";
3484 assertList = test.getElementsByTagName("ol")[0];
3485 assertLi = document$$1.createElement("li");
3486 assertLi.className = "fail";
3487 assertLi.innerHTML = "Test aborted.";
3488 assertList.appendChild(assertLi);
3489 }
3490 }
3491 }
3492
3493 if (banner && (!abortButton || abortButton.disabled === false)) {
3494 banner.className = stats.failedTests ? "qunit-fail" : "qunit-pass";
3495 }
3496
3497 if (abortButton) {
3498 abortButton.parentNode.removeChild(abortButton);
3499 }
3500
3501 if (tests) {
3502 id("qunit-testresult-display").innerHTML = html;
3503 }
3504
3505 if (config.altertitle && document$$1.title) {
3506
3507 // Show ✖ for good, ✔ for bad suite result in title
3508 // use escape sequences in case file gets loaded with non-utf-8-charset
3509 document$$1.title = [stats.failedTests ? "\u2716" : "\u2714", document$$1.title.replace(/^[\u2714\u2716] /i, "")].join(" ");
3510 }
3511
3512 // Scroll back to top to show results
3513 if (config.scrolltop && window.scrollTo) {
3514 window.scrollTo(0, 0);
3515 }
3516 });
3517
3518 function getNameHtml(name, module) {
3519 var nameHtml = "";
3520
3521 if (module) {
3522 nameHtml = "<span class='module-name'>" + escapeText(module) + "</span>: ";
3523 }
3524
3525 nameHtml += "<span class='test-name'>" + escapeText(name) + "</span>";
3526
3527 return nameHtml;
3528 }
3529
3530 QUnit.testStart(function (details) {
3531 var running, testBlock, bad;
3532
3533 testBlock = id("qunit-test-output-" + details.testId);
3534 if (testBlock) {
3535 testBlock.className = "running";
3536 } else {
3537
3538 // Report later registered tests
3539 appendTest(details.name, details.testId, details.module);
3540 }
3541
3542 running = id("qunit-testresult-display");
3543 if (running) {
3544 bad = QUnit.config.reorder && details.previousFailure;
3545
3546 running.innerHTML = (bad ? "Rerunning previously failed test: <br />" : "Running: <br />") + getNameHtml(details.name, details.module);
3547 }
3548 });
3549
3550 function stripHtml(string) {
3551
3552 // Strip tags, html entity and whitespaces
3553 return string.replace(/<\/?[^>]+(>|$)/g, "").replace(/\&quot;/g, "").replace(/\s+/g, "");
3554 }
3555
3556 QUnit.log(function (details) {
3557 var assertList,
3558 assertLi,
3559 message,
3560 expected,
3561 actual,
3562 diff,
3563 showDiff = false,
3564 testItem = id("qunit-test-output-" + details.testId);
3565
3566 if (!testItem) {
3567 return;
3568 }
3569
3570 message = escapeText(details.message) || (details.result ? "okay" : "failed");
3571 message = "<span class='test-message'>" + message + "</span>";
3572 message += "<span class='runtime'>@ " + details.runtime + " ms</span>";
3573
3574 // The pushFailure doesn't provide details.expected
3575 // when it calls, it's implicit to also not show expected and diff stuff
3576 // Also, we need to check details.expected existence, as it can exist and be undefined
3577 if (!details.result && hasOwn.call(details, "expected")) {
3578 if (details.negative) {
3579 expected = "NOT " + QUnit.dump.parse(details.expected);
3580 } else {
3581 expected = QUnit.dump.parse(details.expected);
3582 }
3583
3584 actual = QUnit.dump.parse(details.actual);
3585 message += "<table><tr class='test-expected'><th>Expected: </th><td><pre>" + escapeText(expected) + "</pre></td></tr>";
3586
3587 if (actual !== expected) {
3588
3589 message += "<tr class='test-actual'><th>Result: </th><td><pre>" + escapeText(actual) + "</pre></td></tr>";
3590
3591 // Don't show diff if actual or expected are booleans
3592 if (!/^(true|false)$/.test(actual) && !/^(true|false)$/.test(expected)) {
3593 diff = QUnit.diff(expected, actual);
3594 showDiff = stripHtml(diff).length !== stripHtml(expected).length + stripHtml(actual).length;
3595 }
3596
3597 // Don't show diff if expected and actual are totally different
3598 if (showDiff) {
3599 message += "<tr class='test-diff'><th>Diff: </th><td><pre>" + diff + "</pre></td></tr>";
3600 }
3601 } else if (expected.indexOf("[object Array]") !== -1 || expected.indexOf("[object Object]") !== -1) {
3602 message += "<tr class='test-message'><th>Message: </th><td>" + "Diff suppressed as the depth of object is more than current max depth (" + QUnit.config.maxDepth + ").<p>Hint: Use <code>QUnit.dump.maxDepth</code> to " + " run with a higher max depth or <a href='" + escapeText(setUrl({ maxDepth: -1 })) + "'>" + "Rerun</a> without max depth.</p></td></tr>";
3603 } else {
3604 message += "<tr class='test-message'><th>Message: </th><td>" + "Diff suppressed as the expected and actual results have an equivalent" + " serialization</td></tr>";
3605 }
3606
3607 if (details.source) {
3608 message += "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText(details.source) + "</pre></td></tr>";
3609 }
3610
3611 message += "</table>";
3612
3613 // This occurs when pushFailure is set and we have an extracted stack trace
3614 } else if (!details.result && details.source) {
3615 message += "<table>" + "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText(details.source) + "</pre></td></tr>" + "</table>";
3616 }
3617
3618 assertList = testItem.getElementsByTagName("ol")[0];
3619
3620 assertLi = document$$1.createElement("li");
3621 assertLi.className = details.result ? "pass" : "fail";
3622 assertLi.innerHTML = message;
3623 assertList.appendChild(assertLi);
3624 });
3625
3626 QUnit.testDone(function (details) {
3627 var testTitle,
3628 time,
3629 testItem,
3630 assertList,
3631 good,
3632 bad,
3633 testCounts,
3634 skipped,
3635 sourceName,
3636 tests = id("qunit-tests");
3637
3638 if (!tests) {
3639 return;
3640 }
3641
3642 testItem = id("qunit-test-output-" + details.testId);
3643
3644 assertList = testItem.getElementsByTagName("ol")[0];
3645
3646 good = details.passed;
3647 bad = details.failed;
3648
3649 // This test passed if it has no unexpected failed assertions
3650 var testPassed = details.failed > 0 ? details.todo : !details.todo;
3651
3652 if (testPassed) {
3653
3654 // Collapse the passing tests
3655 addClass(assertList, "qunit-collapsed");
3656 } else if (config.collapse) {
3657 if (!collapseNext) {
3658
3659 // Skip collapsing the first failing test
3660 collapseNext = true;
3661 } else {
3662
3663 // Collapse remaining tests
3664 addClass(assertList, "qunit-collapsed");
3665 }
3666 }
3667
3668 // The testItem.firstChild is the test name
3669 testTitle = testItem.firstChild;
3670
3671 testCounts = bad ? "<b class='failed'>" + bad + "</b>, " + "<b class='passed'>" + good + "</b>, " : "";
3672
3673 testTitle.innerHTML += " <b class='counts'>(" + testCounts + details.assertions.length + ")</b>";
3674
3675 if (details.skipped) {
3676 stats.skippedTests++;
3677
3678 testItem.className = "skipped";
3679 skipped = document$$1.createElement("em");
3680 skipped.className = "qunit-skipped-label";
3681 skipped.innerHTML = "skipped";
3682 testItem.insertBefore(skipped, testTitle);
3683 } else {
3684 addEvent(testTitle, "click", function () {
3685 toggleClass(assertList, "qunit-collapsed");
3686 });
3687
3688 testItem.className = testPassed ? "pass" : "fail";
3689
3690 if (details.todo) {
3691 var todoLabel = document$$1.createElement("em");
3692 todoLabel.className = "qunit-todo-label";
3693 todoLabel.innerHTML = "todo";
3694 testItem.insertBefore(todoLabel, testTitle);
3695 }
3696
3697 time = document$$1.createElement("span");
3698 time.className = "runtime";
3699 time.innerHTML = details.runtime + " ms";
3700 testItem.insertBefore(time, assertList);
3701
3702 if (!testPassed) {
3703 stats.failedTests++;
3704 } else if (details.todo) {
3705 stats.todoTests++;
3706 } else {
3707 stats.passedTests++;
3708 }
3709 }
3710
3711 // Show the source of the test when showing assertions
3712 if (details.source) {
3713 sourceName = document$$1.createElement("p");
3714 sourceName.innerHTML = "<strong>Source: </strong>" + details.source;
3715 addClass(sourceName, "qunit-source");
3716 if (testPassed) {
3717 addClass(sourceName, "qunit-collapsed");
3718 }
3719 addEvent(testTitle, "click", function () {
3720 toggleClass(sourceName, "qunit-collapsed");
3721 });
3722 testItem.appendChild(sourceName);
3723 }
3724 });
3725
3726 // Avoid readyState issue with phantomjs
3727 // Ref: #818
3728 var notPhantom = function (p) {
3729 return !(p && p.version && p.version.major > 0);
3730 }(window.phantom);
3731
3732 if (notPhantom && document$$1.readyState === "complete") {
3733 QUnit.load();
3734 } else {
3735 addEvent(window, "load", QUnit.load);
3736 }
3737
3738 // Wrap window.onerror. We will call the original window.onerror to see if
3739 // the existing handler fully handles the error; if not, we will call the
3740 // QUnit.onError function.
3741 var originalWindowOnError = window.onerror;
3742
3743 // Cover uncaught exceptions
3744 // Returning true will suppress the default browser handler,
3745 // returning false will let it run.
3746 window.onerror = function (message, fileName, lineNumber) {
3747 var ret = false;
3748 if (originalWindowOnError) {
3749 for (var _len = arguments.length, args = Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
3750 args[_key - 3] = arguments[_key];
3751 }
3752
3753 ret = originalWindowOnError.call.apply(originalWindowOnError, [this, message, fileName, lineNumber].concat(args));
3754 }
3755
3756 // Treat return value as window.onerror itself does,
3757 // Only do our handling if not suppressed.
3758 if (ret !== true) {
3759 var error = {
3760 message: message,
3761 fileName: fileName,
3762 lineNumber: lineNumber
3763 };
3764
3765 ret = QUnit.onError(error);
3766 }
3767
3768 return ret;
3769 };
3770 })();
3771
3772 /*
3773 * This file is a modified version of google-diff-match-patch's JavaScript implementation
3774 * (https://code.google.com/p/google-diff-match-patch/source/browse/trunk/javascript/diff_match_patch_uncompressed.js),
3775 * modifications are licensed as more fully set forth in LICENSE.txt.
3776 *
3777 * The original source of google-diff-match-patch is attributable and licensed as follows:
3778 *
3779 * Copyright 2006 Google Inc.
3780 * https://code.google.com/p/google-diff-match-patch/
3781 *
3782 * Licensed under the Apache License, Version 2.0 (the "License");
3783 * you may not use this file except in compliance with the License.
3784 * You may obtain a copy of the License at
3785 *
3786 * https://www.apache.org/licenses/LICENSE-2.0
3787 *
3788 * Unless required by applicable law or agreed to in writing, software
3789 * distributed under the License is distributed on an "AS IS" BASIS,
3790 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3791 * See the License for the specific language governing permissions and
3792 * limitations under the License.
3793 *
3794 * More Info:
3795 * https://code.google.com/p/google-diff-match-patch/
3796 *
3797 * Usage: QUnit.diff(expected, actual)
3798 *
3799 */
3800 QUnit.diff = function () {
3801 function DiffMatchPatch() {}
3802
3803 // DIFF FUNCTIONS
3804
3805 /**
3806 * The data structure representing a diff is an array of tuples:
3807 * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
3808 * which means: delete 'Hello', add 'Goodbye' and keep ' world.'
3809 */
3810 var DIFF_DELETE = -1,
3811 DIFF_INSERT = 1,
3812 DIFF_EQUAL = 0;
3813
3814 /**
3815 * Find the differences between two texts. Simplifies the problem by stripping
3816 * any common prefix or suffix off the texts before diffing.
3817 * @param {string} text1 Old string to be diffed.
3818 * @param {string} text2 New string to be diffed.
3819 * @param {boolean=} optChecklines Optional speedup flag. If present and false,
3820 * then don't run a line-level diff first to identify the changed areas.
3821 * Defaults to true, which does a faster, slightly less optimal diff.
3822 * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
3823 */
3824 DiffMatchPatch.prototype.DiffMain = function (text1, text2, optChecklines) {
3825 var deadline, checklines, commonlength, commonprefix, commonsuffix, diffs;
3826
3827 // The diff must be complete in up to 1 second.
3828 deadline = new Date().getTime() + 1000;
3829
3830 // Check for null inputs.
3831 if (text1 === null || text2 === null) {
3832 throw new Error("Null input. (DiffMain)");
3833 }
3834
3835 // Check for equality (speedup).
3836 if (text1 === text2) {
3837 if (text1) {
3838 return [[DIFF_EQUAL, text1]];
3839 }
3840 return [];
3841 }
3842
3843 if (typeof optChecklines === "undefined") {
3844 optChecklines = true;
3845 }
3846
3847 checklines = optChecklines;
3848
3849 // Trim off common prefix (speedup).
3850 commonlength = this.diffCommonPrefix(text1, text2);
3851 commonprefix = text1.substring(0, commonlength);
3852 text1 = text1.substring(commonlength);
3853 text2 = text2.substring(commonlength);
3854
3855 // Trim off common suffix (speedup).
3856 commonlength = this.diffCommonSuffix(text1, text2);
3857 commonsuffix = text1.substring(text1.length - commonlength);
3858 text1 = text1.substring(0, text1.length - commonlength);
3859 text2 = text2.substring(0, text2.length - commonlength);
3860
3861 // Compute the diff on the middle block.
3862 diffs = this.diffCompute(text1, text2, checklines, deadline);
3863
3864 // Restore the prefix and suffix.
3865 if (commonprefix) {
3866 diffs.unshift([DIFF_EQUAL, commonprefix]);
3867 }
3868 if (commonsuffix) {
3869 diffs.push([DIFF_EQUAL, commonsuffix]);
3870 }
3871 this.diffCleanupMerge(diffs);
3872 return diffs;
3873 };
3874
3875 /**
3876 * Reduce the number of edits by eliminating operationally trivial equalities.
3877 * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
3878 */
3879 DiffMatchPatch.prototype.diffCleanupEfficiency = function (diffs) {
3880 var changes, equalities, equalitiesLength, lastequality, pointer, preIns, preDel, postIns, postDel;
3881 changes = false;
3882 equalities = []; // Stack of indices where equalities are found.
3883 equalitiesLength = 0; // Keeping our own length var is faster in JS.
3884 /** @type {?string} */
3885 lastequality = null;
3886
3887 // Always equal to diffs[equalities[equalitiesLength - 1]][1]
3888 pointer = 0; // Index of current position.
3889
3890 // Is there an insertion operation before the last equality.
3891 preIns = false;
3892
3893 // Is there a deletion operation before the last equality.
3894 preDel = false;
3895
3896 // Is there an insertion operation after the last equality.
3897 postIns = false;
3898
3899 // Is there a deletion operation after the last equality.
3900 postDel = false;
3901 while (pointer < diffs.length) {
3902
3903 // Equality found.
3904 if (diffs[pointer][0] === DIFF_EQUAL) {
3905 if (diffs[pointer][1].length < 4 && (postIns || postDel)) {
3906
3907 // Candidate found.
3908 equalities[equalitiesLength++] = pointer;
3909 preIns = postIns;
3910 preDel = postDel;
3911 lastequality = diffs[pointer][1];
3912 } else {
3913
3914 // Not a candidate, and can never become one.
3915 equalitiesLength = 0;
3916 lastequality = null;
3917 }
3918 postIns = postDel = false;
3919
3920 // An insertion or deletion.
3921 } else {
3922
3923 if (diffs[pointer][0] === DIFF_DELETE) {
3924 postDel = true;
3925 } else {
3926 postIns = true;
3927 }
3928
3929 /*
3930 * Five types to be split:
3931 * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
3932 * <ins>A</ins>X<ins>C</ins><del>D</del>
3933 * <ins>A</ins><del>B</del>X<ins>C</ins>
3934 * <ins>A</del>X<ins>C</ins><del>D</del>
3935 * <ins>A</ins><del>B</del>X<del>C</del>
3936 */
3937 if (lastequality && (preIns && preDel && postIns && postDel || lastequality.length < 2 && preIns + preDel + postIns + postDel === 3)) {
3938
3939 // Duplicate record.
3940 diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastequality]);
3941
3942 // Change second copy to insert.
3943 diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
3944 equalitiesLength--; // Throw away the equality we just deleted;
3945 lastequality = null;
3946 if (preIns && preDel) {
3947
3948 // No changes made which could affect previous entry, keep going.
3949 postIns = postDel = true;
3950 equalitiesLength = 0;
3951 } else {
3952 equalitiesLength--; // Throw away the previous equality.
3953 pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
3954 postIns = postDel = false;
3955 }
3956 changes = true;
3957 }
3958 }
3959 pointer++;
3960 }
3961
3962 if (changes) {
3963 this.diffCleanupMerge(diffs);
3964 }
3965 };
3966
3967 /**
3968 * Convert a diff array into a pretty HTML report.
3969 * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
3970 * @param {integer} string to be beautified.
3971 * @return {string} HTML representation.
3972 */
3973 DiffMatchPatch.prototype.diffPrettyHtml = function (diffs) {
3974 var op,
3975 data,
3976 x,
3977 html = [];
3978 for (x = 0; x < diffs.length; x++) {
3979 op = diffs[x][0]; // Operation (insert, delete, equal)
3980 data = diffs[x][1]; // Text of change.
3981 switch (op) {
3982 case DIFF_INSERT:
3983 html[x] = "<ins>" + escapeText(data) + "</ins>";
3984 break;
3985 case DIFF_DELETE:
3986 html[x] = "<del>" + escapeText(data) + "</del>";
3987 break;
3988 case DIFF_EQUAL:
3989 html[x] = "<span>" + escapeText(data) + "</span>";
3990 break;
3991 }
3992 }
3993 return html.join("");
3994 };
3995
3996 /**
3997 * Determine the common prefix of two strings.
3998 * @param {string} text1 First string.
3999 * @param {string} text2 Second string.
4000 * @return {number} The number of characters common to the start of each
4001 * string.
4002 */
4003 DiffMatchPatch.prototype.diffCommonPrefix = function (text1, text2) {
4004 var pointermid, pointermax, pointermin, pointerstart;
4005
4006 // Quick check for common null cases.
4007 if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) {
4008 return 0;
4009 }
4010
4011 // Binary search.
4012 // Performance analysis: https://neil.fraser.name/news/2007/10/09/
4013 pointermin = 0;
4014 pointermax = Math.min(text1.length, text2.length);
4015 pointermid = pointermax;
4016 pointerstart = 0;
4017 while (pointermin < pointermid) {
4018 if (text1.substring(pointerstart, pointermid) === text2.substring(pointerstart, pointermid)) {
4019 pointermin = pointermid;
4020 pointerstart = pointermin;
4021 } else {
4022 pointermax = pointermid;
4023 }
4024 pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
4025 }
4026 return pointermid;
4027 };
4028
4029 /**
4030 * Determine the common suffix of two strings.
4031 * @param {string} text1 First string.
4032 * @param {string} text2 Second string.
4033 * @return {number} The number of characters common to the end of each string.
4034 */
4035 DiffMatchPatch.prototype.diffCommonSuffix = function (text1, text2) {
4036 var pointermid, pointermax, pointermin, pointerend;
4037
4038 // Quick check for common null cases.
4039 if (!text1 || !text2 || text1.charAt(text1.length - 1) !== text2.charAt(text2.length - 1)) {
4040 return 0;
4041 }
4042
4043 // Binary search.
4044 // Performance analysis: https://neil.fraser.name/news/2007/10/09/
4045 pointermin = 0;
4046 pointermax = Math.min(text1.length, text2.length);
4047 pointermid = pointermax;
4048 pointerend = 0;
4049 while (pointermin < pointermid) {
4050 if (text1.substring(text1.length - pointermid, text1.length - pointerend) === text2.substring(text2.length - pointermid, text2.length - pointerend)) {
4051 pointermin = pointermid;
4052 pointerend = pointermin;
4053 } else {
4054 pointermax = pointermid;
4055 }
4056 pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
4057 }
4058 return pointermid;
4059 };
4060
4061 /**
4062 * Find the differences between two texts. Assumes that the texts do not
4063 * have any common prefix or suffix.
4064 * @param {string} text1 Old string to be diffed.
4065 * @param {string} text2 New string to be diffed.
4066 * @param {boolean} checklines Speedup flag. If false, then don't run a
4067 * line-level diff first to identify the changed areas.
4068 * If true, then run a faster, slightly less optimal diff.
4069 * @param {number} deadline Time when the diff should be complete by.
4070 * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
4071 * @private
4072 */
4073 DiffMatchPatch.prototype.diffCompute = function (text1, text2, checklines, deadline) {
4074 var diffs, longtext, shorttext, i, hm, text1A, text2A, text1B, text2B, midCommon, diffsA, diffsB;
4075
4076 if (!text1) {
4077
4078 // Just add some text (speedup).
4079 return [[DIFF_INSERT, text2]];
4080 }
4081
4082 if (!text2) {
4083
4084 // Just delete some text (speedup).
4085 return [[DIFF_DELETE, text1]];
4086 }
4087
4088 longtext = text1.length > text2.length ? text1 : text2;
4089 shorttext = text1.length > text2.length ? text2 : text1;
4090 i = longtext.indexOf(shorttext);
4091 if (i !== -1) {
4092
4093 // Shorter text is inside the longer text (speedup).
4094 diffs = [[DIFF_INSERT, longtext.substring(0, i)], [DIFF_EQUAL, shorttext], [DIFF_INSERT, longtext.substring(i + shorttext.length)]];
4095
4096 // Swap insertions for deletions if diff is reversed.
4097 if (text1.length > text2.length) {
4098 diffs[0][0] = diffs[2][0] = DIFF_DELETE;
4099 }
4100 return diffs;
4101 }
4102
4103 if (shorttext.length === 1) {
4104
4105 // Single character string.
4106 // After the previous speedup, the character can't be an equality.
4107 return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
4108 }
4109
4110 // Check to see if the problem can be split in two.
4111 hm = this.diffHalfMatch(text1, text2);
4112 if (hm) {
4113
4114 // A half-match was found, sort out the return data.
4115 text1A = hm[0];
4116 text1B = hm[1];
4117 text2A = hm[2];
4118 text2B = hm[3];
4119 midCommon = hm[4];
4120
4121 // Send both pairs off for separate processing.
4122 diffsA = this.DiffMain(text1A, text2A, checklines, deadline);
4123 diffsB = this.DiffMain(text1B, text2B, checklines, deadline);
4124
4125 // Merge the results.
4126 return diffsA.concat([[DIFF_EQUAL, midCommon]], diffsB);
4127 }
4128
4129 if (checklines && text1.length > 100 && text2.length > 100) {
4130 return this.diffLineMode(text1, text2, deadline);
4131 }
4132
4133 return this.diffBisect(text1, text2, deadline);
4134 };
4135
4136 /**
4137 * Do the two texts share a substring which is at least half the length of the
4138 * longer text?
4139 * This speedup can produce non-minimal diffs.
4140 * @param {string} text1 First string.
4141 * @param {string} text2 Second string.
4142 * @return {Array.<string>} Five element Array, containing the prefix of
4143 * text1, the suffix of text1, the prefix of text2, the suffix of
4144 * text2 and the common middle. Or null if there was no match.
4145 * @private
4146 */
4147 DiffMatchPatch.prototype.diffHalfMatch = function (text1, text2) {
4148 var longtext, shorttext, dmp, text1A, text2B, text2A, text1B, midCommon, hm1, hm2, hm;
4149
4150 longtext = text1.length > text2.length ? text1 : text2;
4151 shorttext = text1.length > text2.length ? text2 : text1;
4152 if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {
4153 return null; // Pointless.
4154 }
4155 dmp = this; // 'this' becomes 'window' in a closure.
4156
4157 /**
4158 * Does a substring of shorttext exist within longtext such that the substring
4159 * is at least half the length of longtext?
4160 * Closure, but does not reference any external variables.
4161 * @param {string} longtext Longer string.
4162 * @param {string} shorttext Shorter string.
4163 * @param {number} i Start index of quarter length substring within longtext.
4164 * @return {Array.<string>} Five element Array, containing the prefix of
4165 * longtext, the suffix of longtext, the prefix of shorttext, the suffix
4166 * of shorttext and the common middle. Or null if there was no match.
4167 * @private
4168 */
4169 function diffHalfMatchI(longtext, shorttext, i) {
4170 var seed, j, bestCommon, prefixLength, suffixLength, bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB;
4171
4172 // Start with a 1/4 length substring at position i as a seed.
4173 seed = longtext.substring(i, i + Math.floor(longtext.length / 4));
4174 j = -1;
4175 bestCommon = "";
4176 while ((j = shorttext.indexOf(seed, j + 1)) !== -1) {
4177 prefixLength = dmp.diffCommonPrefix(longtext.substring(i), shorttext.substring(j));
4178 suffixLength = dmp.diffCommonSuffix(longtext.substring(0, i), shorttext.substring(0, j));
4179 if (bestCommon.length < suffixLength + prefixLength) {
4180 bestCommon = shorttext.substring(j - suffixLength, j) + shorttext.substring(j, j + prefixLength);
4181 bestLongtextA = longtext.substring(0, i - suffixLength);
4182 bestLongtextB = longtext.substring(i + prefixLength);
4183 bestShorttextA = shorttext.substring(0, j - suffixLength);
4184 bestShorttextB = shorttext.substring(j + prefixLength);
4185 }
4186 }
4187 if (bestCommon.length * 2 >= longtext.length) {
4188 return [bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB, bestCommon];
4189 } else {
4190 return null;
4191 }
4192 }
4193
4194 // First check if the second quarter is the seed for a half-match.
4195 hm1 = diffHalfMatchI(longtext, shorttext, Math.ceil(longtext.length / 4));
4196
4197 // Check again based on the third quarter.
4198 hm2 = diffHalfMatchI(longtext, shorttext, Math.ceil(longtext.length / 2));
4199 if (!hm1 && !hm2) {
4200 return null;
4201 } else if (!hm2) {
4202 hm = hm1;
4203 } else if (!hm1) {
4204 hm = hm2;
4205 } else {
4206
4207 // Both matched. Select the longest.
4208 hm = hm1[4].length > hm2[4].length ? hm1 : hm2;
4209 }
4210
4211 // A half-match was found, sort out the return data.
4212 if (text1.length > text2.length) {
4213 text1A = hm[0];
4214 text1B = hm[1];
4215 text2A = hm[2];
4216 text2B = hm[3];
4217 } else {
4218 text2A = hm[0];
4219 text2B = hm[1];
4220 text1A = hm[2];
4221 text1B = hm[3];
4222 }
4223 midCommon = hm[4];
4224 return [text1A, text1B, text2A, text2B, midCommon];
4225 };
4226
4227 /**
4228 * Do a quick line-level diff on both strings, then rediff the parts for
4229 * greater accuracy.
4230 * This speedup can produce non-minimal diffs.
4231 * @param {string} text1 Old string to be diffed.
4232 * @param {string} text2 New string to be diffed.
4233 * @param {number} deadline Time when the diff should be complete by.
4234 * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
4235 * @private
4236 */
4237 DiffMatchPatch.prototype.diffLineMode = function (text1, text2, deadline) {
4238 var a, diffs, linearray, pointer, countInsert, countDelete, textInsert, textDelete, j;
4239
4240 // Scan the text on a line-by-line basis first.
4241 a = this.diffLinesToChars(text1, text2);
4242 text1 = a.chars1;
4243 text2 = a.chars2;
4244 linearray = a.lineArray;
4245
4246 diffs = this.DiffMain(text1, text2, false, deadline);
4247
4248 // Convert the diff back to original text.
4249 this.diffCharsToLines(diffs, linearray);
4250
4251 // Eliminate freak matches (e.g. blank lines)
4252 this.diffCleanupSemantic(diffs);
4253
4254 // Rediff any replacement blocks, this time character-by-character.
4255 // Add a dummy entry at the end.
4256 diffs.push([DIFF_EQUAL, ""]);
4257 pointer = 0;
4258 countDelete = 0;
4259 countInsert = 0;
4260 textDelete = "";
4261 textInsert = "";
4262 while (pointer < diffs.length) {
4263 switch (diffs[pointer][0]) {
4264 case DIFF_INSERT:
4265 countInsert++;
4266 textInsert += diffs[pointer][1];
4267 break;
4268 case DIFF_DELETE:
4269 countDelete++;
4270 textDelete += diffs[pointer][1];
4271 break;
4272 case DIFF_EQUAL:
4273
4274 // Upon reaching an equality, check for prior redundancies.
4275 if (countDelete >= 1 && countInsert >= 1) {
4276
4277 // Delete the offending records and add the merged ones.
4278 diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert);
4279 pointer = pointer - countDelete - countInsert;
4280 a = this.DiffMain(textDelete, textInsert, false, deadline);
4281 for (j = a.length - 1; j >= 0; j--) {
4282 diffs.splice(pointer, 0, a[j]);
4283 }
4284 pointer = pointer + a.length;
4285 }
4286 countInsert = 0;
4287 countDelete = 0;
4288 textDelete = "";
4289 textInsert = "";
4290 break;
4291 }
4292 pointer++;
4293 }
4294 diffs.pop(); // Remove the dummy entry at the end.
4295
4296 return diffs;
4297 };
4298
4299 /**
4300 * Find the 'middle snake' of a diff, split the problem in two
4301 * and return the recursively constructed diff.
4302 * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
4303 * @param {string} text1 Old string to be diffed.
4304 * @param {string} text2 New string to be diffed.
4305 * @param {number} deadline Time at which to bail if not yet complete.
4306 * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
4307 * @private
4308 */
4309 DiffMatchPatch.prototype.diffBisect = function (text1, text2, deadline) {
4310 var text1Length, text2Length, maxD, vOffset, vLength, v1, v2, x, delta, front, k1start, k1end, k2start, k2end, k2Offset, k1Offset, x1, x2, y1, y2, d, k1, k2;
4311
4312 // Cache the text lengths to prevent multiple calls.
4313 text1Length = text1.length;
4314 text2Length = text2.length;
4315 maxD = Math.ceil((text1Length + text2Length) / 2);
4316 vOffset = maxD;
4317 vLength = 2 * maxD;
4318 v1 = new Array(vLength);
4319 v2 = new Array(vLength);
4320
4321 // Setting all elements to -1 is faster in Chrome & Firefox than mixing
4322 // integers and undefined.
4323 for (x = 0; x < vLength; x++) {
4324 v1[x] = -1;
4325 v2[x] = -1;
4326 }
4327 v1[vOffset + 1] = 0;
4328 v2[vOffset + 1] = 0;
4329 delta = text1Length - text2Length;
4330
4331 // If the total number of characters is odd, then the front path will collide
4332 // with the reverse path.
4333 front = delta % 2 !== 0;
4334
4335 // Offsets for start and end of k loop.
4336 // Prevents mapping of space beyond the grid.
4337 k1start = 0;
4338 k1end = 0;
4339 k2start = 0;
4340 k2end = 0;
4341 for (d = 0; d < maxD; d++) {
4342
4343 // Bail out if deadline is reached.
4344 if (new Date().getTime() > deadline) {
4345 break;
4346 }
4347
4348 // Walk the front path one step.
4349 for (k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
4350 k1Offset = vOffset + k1;
4351 if (k1 === -d || k1 !== d && v1[k1Offset - 1] < v1[k1Offset + 1]) {
4352 x1 = v1[k1Offset + 1];
4353 } else {
4354 x1 = v1[k1Offset - 1] + 1;
4355 }
4356 y1 = x1 - k1;
4357 while (x1 < text1Length && y1 < text2Length && text1.charAt(x1) === text2.charAt(y1)) {
4358 x1++;
4359 y1++;
4360 }
4361 v1[k1Offset] = x1;
4362 if (x1 > text1Length) {
4363
4364 // Ran off the right of the graph.
4365 k1end += 2;
4366 } else if (y1 > text2Length) {
4367
4368 // Ran off the bottom of the graph.
4369 k1start += 2;
4370 } else if (front) {
4371 k2Offset = vOffset + delta - k1;
4372 if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] !== -1) {
4373
4374 // Mirror x2 onto top-left coordinate system.
4375 x2 = text1Length - v2[k2Offset];
4376 if (x1 >= x2) {
4377
4378 // Overlap detected.
4379 return this.diffBisectSplit(text1, text2, x1, y1, deadline);
4380 }
4381 }
4382 }
4383 }
4384
4385 // Walk the reverse path one step.
4386 for (k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
4387 k2Offset = vOffset + k2;
4388 if (k2 === -d || k2 !== d && v2[k2Offset - 1] < v2[k2Offset + 1]) {
4389 x2 = v2[k2Offset + 1];
4390 } else {
4391 x2 = v2[k2Offset - 1] + 1;
4392 }
4393 y2 = x2 - k2;
4394 while (x2 < text1Length && y2 < text2Length && text1.charAt(text1Length - x2 - 1) === text2.charAt(text2Length - y2 - 1)) {
4395 x2++;
4396 y2++;
4397 }
4398 v2[k2Offset] = x2;
4399 if (x2 > text1Length) {
4400
4401 // Ran off the left of the graph.
4402 k2end += 2;
4403 } else if (y2 > text2Length) {
4404
4405 // Ran off the top of the graph.
4406 k2start += 2;
4407 } else if (!front) {
4408 k1Offset = vOffset + delta - k2;
4409 if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] !== -1) {
4410 x1 = v1[k1Offset];
4411 y1 = vOffset + x1 - k1Offset;
4412
4413 // Mirror x2 onto top-left coordinate system.
4414 x2 = text1Length - x2;
4415 if (x1 >= x2) {
4416
4417 // Overlap detected.
4418 return this.diffBisectSplit(text1, text2, x1, y1, deadline);
4419 }
4420 }
4421 }
4422 }
4423 }
4424
4425 // Diff took too long and hit the deadline or
4426 // number of diffs equals number of characters, no commonality at all.
4427 return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
4428 };
4429
4430 /**
4431 * Given the location of the 'middle snake', split the diff in two parts
4432 * and recurse.
4433 * @param {string} text1 Old string to be diffed.
4434 * @param {string} text2 New string to be diffed.
4435 * @param {number} x Index of split point in text1.
4436 * @param {number} y Index of split point in text2.
4437 * @param {number} deadline Time at which to bail if not yet complete.
4438 * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
4439 * @private
4440 */
4441 DiffMatchPatch.prototype.diffBisectSplit = function (text1, text2, x, y, deadline) {
4442 var text1a, text1b, text2a, text2b, diffs, diffsb;
4443 text1a = text1.substring(0, x);
4444 text2a = text2.substring(0, y);
4445 text1b = text1.substring(x);
4446 text2b = text2.substring(y);
4447
4448 // Compute both diffs serially.
4449 diffs = this.DiffMain(text1a, text2a, false, deadline);
4450 diffsb = this.DiffMain(text1b, text2b, false, deadline);
4451
4452 return diffs.concat(diffsb);
4453 };
4454
4455 /**
4456 * Reduce the number of edits by eliminating semantically trivial equalities.
4457 * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
4458 */
4459 DiffMatchPatch.prototype.diffCleanupSemantic = function (diffs) {
4460 var changes, equalities, equalitiesLength, lastequality, pointer, lengthInsertions2, lengthDeletions2, lengthInsertions1, lengthDeletions1, deletion, insertion, overlapLength1, overlapLength2;
4461 changes = false;
4462 equalities = []; // Stack of indices where equalities are found.
4463 equalitiesLength = 0; // Keeping our own length var is faster in JS.
4464 /** @type {?string} */
4465 lastequality = null;
4466
4467 // Always equal to diffs[equalities[equalitiesLength - 1]][1]
4468 pointer = 0; // Index of current position.
4469
4470 // Number of characters that changed prior to the equality.
4471 lengthInsertions1 = 0;
4472 lengthDeletions1 = 0;
4473
4474 // Number of characters that changed after the equality.
4475 lengthInsertions2 = 0;
4476 lengthDeletions2 = 0;
4477 while (pointer < diffs.length) {
4478 if (diffs[pointer][0] === DIFF_EQUAL) {
4479 // Equality found.
4480 equalities[equalitiesLength++] = pointer;
4481 lengthInsertions1 = lengthInsertions2;
4482 lengthDeletions1 = lengthDeletions2;
4483 lengthInsertions2 = 0;
4484 lengthDeletions2 = 0;
4485 lastequality = diffs[pointer][1];
4486 } else {
4487 // An insertion or deletion.
4488 if (diffs[pointer][0] === DIFF_INSERT) {
4489 lengthInsertions2 += diffs[pointer][1].length;
4490 } else {
4491 lengthDeletions2 += diffs[pointer][1].length;
4492 }
4493
4494 // Eliminate an equality that is smaller or equal to the edits on both
4495 // sides of it.
4496 if (lastequality && lastequality.length <= Math.max(lengthInsertions1, lengthDeletions1) && lastequality.length <= Math.max(lengthInsertions2, lengthDeletions2)) {
4497
4498 // Duplicate record.
4499 diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastequality]);
4500
4501 // Change second copy to insert.
4502 diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
4503
4504 // Throw away the equality we just deleted.
4505 equalitiesLength--;
4506
4507 // Throw away the previous equality (it needs to be reevaluated).
4508 equalitiesLength--;
4509 pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
4510
4511 // Reset the counters.
4512 lengthInsertions1 = 0;
4513 lengthDeletions1 = 0;
4514 lengthInsertions2 = 0;
4515 lengthDeletions2 = 0;
4516 lastequality = null;
4517 changes = true;
4518 }
4519 }
4520 pointer++;
4521 }
4522
4523 // Normalize the diff.
4524 if (changes) {
4525 this.diffCleanupMerge(diffs);
4526 }
4527
4528 // Find any overlaps between deletions and insertions.
4529 // e.g: <del>abcxxx</del><ins>xxxdef</ins>
4530 // -> <del>abc</del>xxx<ins>def</ins>
4531 // e.g: <del>xxxabc</del><ins>defxxx</ins>
4532 // -> <ins>def</ins>xxx<del>abc</del>
4533 // Only extract an overlap if it is as big as the edit ahead or behind it.
4534 pointer = 1;
4535 while (pointer < diffs.length) {
4536 if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) {
4537 deletion = diffs[pointer - 1][1];
4538 insertion = diffs[pointer][1];
4539 overlapLength1 = this.diffCommonOverlap(deletion, insertion);
4540 overlapLength2 = this.diffCommonOverlap(insertion, deletion);
4541 if (overlapLength1 >= overlapLength2) {
4542 if (overlapLength1 >= deletion.length / 2 || overlapLength1 >= insertion.length / 2) {
4543
4544 // Overlap found. Insert an equality and trim the surrounding edits.
4545 diffs.splice(pointer, 0, [DIFF_EQUAL, insertion.substring(0, overlapLength1)]);
4546 diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlapLength1);
4547 diffs[pointer + 1][1] = insertion.substring(overlapLength1);
4548 pointer++;
4549 }
4550 } else {
4551 if (overlapLength2 >= deletion.length / 2 || overlapLength2 >= insertion.length / 2) {
4552
4553 // Reverse overlap found.
4554 // Insert an equality and swap and trim the surrounding edits.
4555 diffs.splice(pointer, 0, [DIFF_EQUAL, deletion.substring(0, overlapLength2)]);
4556
4557 diffs[pointer - 1][0] = DIFF_INSERT;
4558 diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlapLength2);
4559 diffs[pointer + 1][0] = DIFF_DELETE;
4560 diffs[pointer + 1][1] = deletion.substring(overlapLength2);
4561 pointer++;
4562 }
4563 }
4564 pointer++;
4565 }
4566 pointer++;
4567 }
4568 };
4569
4570 /**
4571 * Determine if the suffix of one string is the prefix of another.
4572 * @param {string} text1 First string.
4573 * @param {string} text2 Second string.
4574 * @return {number} The number of characters common to the end of the first
4575 * string and the start of the second string.
4576 * @private
4577 */
4578 DiffMatchPatch.prototype.diffCommonOverlap = function (text1, text2) {
4579 var text1Length, text2Length, textLength, best, length, pattern, found;
4580
4581 // Cache the text lengths to prevent multiple calls.
4582 text1Length = text1.length;
4583 text2Length = text2.length;
4584
4585 // Eliminate the null case.
4586 if (text1Length === 0 || text2Length === 0) {
4587 return 0;
4588 }
4589
4590 // Truncate the longer string.
4591 if (text1Length > text2Length) {
4592 text1 = text1.substring(text1Length - text2Length);
4593 } else if (text1Length < text2Length) {
4594 text2 = text2.substring(0, text1Length);
4595 }
4596 textLength = Math.min(text1Length, text2Length);
4597
4598 // Quick check for the worst case.
4599 if (text1 === text2) {
4600 return textLength;
4601 }
4602
4603 // Start by looking for a single character match
4604 // and increase length until no match is found.
4605 // Performance analysis: https://neil.fraser.name/news/2010/11/04/
4606 best = 0;
4607 length = 1;
4608 while (true) {
4609 pattern = text1.substring(textLength - length);
4610 found = text2.indexOf(pattern);
4611 if (found === -1) {
4612 return best;
4613 }
4614 length += found;
4615 if (found === 0 || text1.substring(textLength - length) === text2.substring(0, length)) {
4616 best = length;
4617 length++;
4618 }
4619 }
4620 };
4621
4622 /**
4623 * Split two texts into an array of strings. Reduce the texts to a string of
4624 * hashes where each Unicode character represents one line.
4625 * @param {string} text1 First string.
4626 * @param {string} text2 Second string.
4627 * @return {{chars1: string, chars2: string, lineArray: !Array.<string>}}
4628 * An object containing the encoded text1, the encoded text2 and
4629 * the array of unique strings.
4630 * The zeroth element of the array of unique strings is intentionally blank.
4631 * @private
4632 */
4633 DiffMatchPatch.prototype.diffLinesToChars = function (text1, text2) {
4634 var lineArray, lineHash, chars1, chars2;
4635 lineArray = []; // E.g. lineArray[4] === 'Hello\n'
4636 lineHash = {}; // E.g. lineHash['Hello\n'] === 4
4637
4638 // '\x00' is a valid character, but various debuggers don't like it.
4639 // So we'll insert a junk entry to avoid generating a null character.
4640 lineArray[0] = "";
4641
4642 /**
4643 * Split a text into an array of strings. Reduce the texts to a string of
4644 * hashes where each Unicode character represents one line.
4645 * Modifies linearray and linehash through being a closure.
4646 * @param {string} text String to encode.
4647 * @return {string} Encoded string.
4648 * @private
4649 */
4650 function diffLinesToCharsMunge(text) {
4651 var chars, lineStart, lineEnd, lineArrayLength, line;
4652 chars = "";
4653
4654 // Walk the text, pulling out a substring for each line.
4655 // text.split('\n') would would temporarily double our memory footprint.
4656 // Modifying text would create many large strings to garbage collect.
4657 lineStart = 0;
4658 lineEnd = -1;
4659
4660 // Keeping our own length variable is faster than looking it up.
4661 lineArrayLength = lineArray.length;
4662 while (lineEnd < text.length - 1) {
4663 lineEnd = text.indexOf("\n", lineStart);
4664 if (lineEnd === -1) {
4665 lineEnd = text.length - 1;
4666 }
4667 line = text.substring(lineStart, lineEnd + 1);
4668 lineStart = lineEnd + 1;
4669
4670 if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : lineHash[line] !== undefined) {
4671 chars += String.fromCharCode(lineHash[line]);
4672 } else {
4673 chars += String.fromCharCode(lineArrayLength);
4674 lineHash[line] = lineArrayLength;
4675 lineArray[lineArrayLength++] = line;
4676 }
4677 }
4678 return chars;
4679 }
4680
4681 chars1 = diffLinesToCharsMunge(text1);
4682 chars2 = diffLinesToCharsMunge(text2);
4683 return {
4684 chars1: chars1,
4685 chars2: chars2,
4686 lineArray: lineArray
4687 };
4688 };
4689
4690 /**
4691 * Rehydrate the text in a diff from a string of line hashes to real lines of
4692 * text.
4693 * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
4694 * @param {!Array.<string>} lineArray Array of unique strings.
4695 * @private
4696 */
4697 DiffMatchPatch.prototype.diffCharsToLines = function (diffs, lineArray) {
4698 var x, chars, text, y;
4699 for (x = 0; x < diffs.length; x++) {
4700 chars = diffs[x][1];
4701 text = [];
4702 for (y = 0; y < chars.length; y++) {
4703 text[y] = lineArray[chars.charCodeAt(y)];
4704 }
4705 diffs[x][1] = text.join("");
4706 }
4707 };
4708
4709 /**
4710 * Reorder and merge like edit sections. Merge equalities.
4711 * Any edit section can move as long as it doesn't cross an equality.
4712 * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
4713 */
4714 DiffMatchPatch.prototype.diffCleanupMerge = function (diffs) {
4715 var pointer, countDelete, countInsert, textInsert, textDelete, commonlength, changes, diffPointer, position;
4716 diffs.push([DIFF_EQUAL, ""]); // Add a dummy entry at the end.
4717 pointer = 0;
4718 countDelete = 0;
4719 countInsert = 0;
4720 textDelete = "";
4721 textInsert = "";
4722
4723 while (pointer < diffs.length) {
4724 switch (diffs[pointer][0]) {
4725 case DIFF_INSERT:
4726 countInsert++;
4727 textInsert += diffs[pointer][1];
4728 pointer++;
4729 break;
4730 case DIFF_DELETE:
4731 countDelete++;
4732 textDelete += diffs[pointer][1];
4733 pointer++;
4734 break;
4735 case DIFF_EQUAL:
4736
4737 // Upon reaching an equality, check for prior redundancies.
4738 if (countDelete + countInsert > 1) {
4739 if (countDelete !== 0 && countInsert !== 0) {
4740
4741 // Factor out any common prefixes.
4742 commonlength = this.diffCommonPrefix(textInsert, textDelete);
4743 if (commonlength !== 0) {
4744 if (pointer - countDelete - countInsert > 0 && diffs[pointer - countDelete - countInsert - 1][0] === DIFF_EQUAL) {
4745 diffs[pointer - countDelete - countInsert - 1][1] += textInsert.substring(0, commonlength);
4746 } else {
4747 diffs.splice(0, 0, [DIFF_EQUAL, textInsert.substring(0, commonlength)]);
4748 pointer++;
4749 }
4750 textInsert = textInsert.substring(commonlength);
4751 textDelete = textDelete.substring(commonlength);
4752 }
4753
4754 // Factor out any common suffixies.
4755 commonlength = this.diffCommonSuffix(textInsert, textDelete);
4756 if (commonlength !== 0) {
4757 diffs[pointer][1] = textInsert.substring(textInsert.length - commonlength) + diffs[pointer][1];
4758 textInsert = textInsert.substring(0, textInsert.length - commonlength);
4759 textDelete = textDelete.substring(0, textDelete.length - commonlength);
4760 }
4761 }
4762
4763 // Delete the offending records and add the merged ones.
4764 if (countDelete === 0) {
4765 diffs.splice(pointer - countInsert, countDelete + countInsert, [DIFF_INSERT, textInsert]);
4766 } else if (countInsert === 0) {
4767 diffs.splice(pointer - countDelete, countDelete + countInsert, [DIFF_DELETE, textDelete]);
4768 } else {
4769 diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert, [DIFF_DELETE, textDelete], [DIFF_INSERT, textInsert]);
4770 }
4771 pointer = pointer - countDelete - countInsert + (countDelete ? 1 : 0) + (countInsert ? 1 : 0) + 1;
4772 } else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) {
4773
4774 // Merge this equality with the previous one.
4775 diffs[pointer - 1][1] += diffs[pointer][1];
4776 diffs.splice(pointer, 1);
4777 } else {
4778 pointer++;
4779 }
4780 countInsert = 0;
4781 countDelete = 0;
4782 textDelete = "";
4783 textInsert = "";
4784 break;
4785 }
4786 }
4787 if (diffs[diffs.length - 1][1] === "") {
4788 diffs.pop(); // Remove the dummy entry at the end.
4789 }
4790
4791 // Second pass: look for single edits surrounded on both sides by equalities
4792 // which can be shifted sideways to eliminate an equality.
4793 // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
4794 changes = false;
4795 pointer = 1;
4796
4797 // Intentionally ignore the first and last element (don't need checking).
4798 while (pointer < diffs.length - 1) {
4799 if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) {
4800
4801 diffPointer = diffs[pointer][1];
4802 position = diffPointer.substring(diffPointer.length - diffs[pointer - 1][1].length);
4803
4804 // This is a single edit surrounded by equalities.
4805 if (position === diffs[pointer - 1][1]) {
4806
4807 // Shift the edit over the previous equality.
4808 diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length);
4809 diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];
4810 diffs.splice(pointer - 1, 1);
4811 changes = true;
4812 } else if (diffPointer.substring(0, diffs[pointer + 1][1].length) === diffs[pointer + 1][1]) {
4813
4814 // Shift the edit over the next equality.
4815 diffs[pointer - 1][1] += diffs[pointer + 1][1];
4816 diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1];
4817 diffs.splice(pointer + 1, 1);
4818 changes = true;
4819 }
4820 }
4821 pointer++;
4822 }
4823
4824 // If shifts were made, the diff needs reordering and another shift sweep.
4825 if (changes) {
4826 this.diffCleanupMerge(diffs);
4827 }
4828 };
4829
4830 return function (o, n) {
4831 var diff, output, text;
4832 diff = new DiffMatchPatch();
4833 output = diff.DiffMain(o, n);
4834 diff.diffCleanupEfficiency(output);
4835 text = diff.diffPrettyHtml(output);
4836
4837 return text;
4838 };
4839 }();
4840
4841}((function() { return this; }())));