5 * Copyright jQuery Foundation and other contributors
6 * Released under the MIT license
7 * https://jquery.org/license
9 * Date: 2017-07-08T15:20Z
11 (function (global
$1) {
14 global
$1 = global
$1 && 'default' in global
$1 ? global
$1['default'] : global
$1;
16 var window
= global
$1.window
;
17 var self
$1 = global
$1.self
;
18 var console
= global
$1.console
;
19 var setTimeout
= global
$1.setTimeout
;
20 var clearTimeout
= global
$1.clearTimeout
;
22 var document
= window
&& window
.document
;
23 var navigator
= window
&& window
.navigator
;
25 var localSessionStorage = function () {
26 var x
= "qunit-test-string";
28 global
$1.sessionStorage
.setItem(x
, x
);
29 global
$1.sessionStorage
.removeItem(x
);
30 return global
$1.sessionStorage
;
36 var _typeof
= typeof Symbol
=== "function" && typeof Symbol
.iterator
=== "symbol" ? function (obj
) {
39 return obj
&& typeof Symbol
=== "function" && obj
.constructor === Symbol
&& obj
!== Symbol
.prototype ? "symbol" : typeof obj
;
52 var classCallCheck = function (instance
, Constructor
) {
53 if (!(instance
instanceof Constructor
)) {
54 throw new TypeError("Cannot call a class as a function");
58 var createClass = function () {
59 function defineProperties(target
, props
) {
60 for (var i
= 0; i
< props
.length
; i
++) {
61 var descriptor
= props
[i
];
62 descriptor
.enumerable
= descriptor
.enumerable
|| false;
63 descriptor
.configurable
= true;
64 if ("value" in descriptor
) descriptor
.writable
= true;
65 Object
.defineProperty(target
, descriptor
.key
, descriptor
);
69 return function (Constructor
, protoProps
, staticProps
) {
70 if (protoProps
) defineProperties(Constructor
.prototype, protoProps
);
71 if (staticProps
) defineProperties(Constructor
, staticProps
);
116 var toConsumableArray = function (arr
) {
117 if (Array
.isArray(arr
)) {
118 for (var i
= 0, arr2
= Array(arr
.length
); i
< arr
.length
; i
++) arr2
[i
] = arr
[i
];
122 return Array
.from(arr
);
126 var toString
= Object
.prototype.toString
;
127 var hasOwn
= Object
.prototype.hasOwnProperty
;
128 var now
= Date
.now
|| function () {
129 return new Date().getTime();
133 document
: window
&& window
.document
!== undefined,
134 setTimeout
: setTimeout
!== undefined
137 // Returns a new Array with the elements that are in a but not in b
138 function diff(a
, b
) {
143 for (i
= 0; i
< result
.length
; i
++) {
144 for (j
= 0; j
< b
.length
; j
++) {
145 if (result
[i
] === b
[j
]) {
156 * Determines whether an element exists in a given array or not.
160 * @param {Array} array
163 function inArray(elem
, array
) {
164 return array
.indexOf(elem
) !== -1;
168 * Makes a clone of an object using only Array or Object as base,
169 * and copies over the own enumerable properties.
171 * @param {Object} obj
172 * @return {Object} New object with only the own properties (recursively).
174 function objectValues(obj
) {
177 vals
= is("array", obj
) ? [] : {};
179 if (hasOwn
.call(obj
, key
)) {
181 vals
[key
] = val
=== Object(val
) ? objectValues(val
) : val
;
187 function extend(a
, b
, undefOnly
) {
188 for (var prop
in b
) {
189 if (hasOwn
.call(b
, prop
)) {
190 if (b
[prop
] === undefined) {
192 } else if (!(undefOnly
&& typeof a
[prop
] !== "undefined")) {
201 function objectType(obj
) {
202 if (typeof obj
=== "undefined") {
206 // Consider: typeof null === object
211 var match
= toString
.call(obj
).match(/^\[object\s(.*)\]$/),
212 type
= match
&& match
[1];
229 return type
.toLowerCase();
231 return typeof obj
=== "undefined" ? "undefined" : _typeof(obj
);
235 // Safe object type checking
236 function is(type
, obj
) {
237 return objectType(obj
) === type
;
240 // Based on Java's String.hashCode, a simple but not
241 // rigorously collision resistant hashing function
242 function generateHash(module
, testName
) {
243 var str
= module
+ "\x1C" + testName
;
246 for (var i
= 0; i
< str
.length
; i
++) {
247 hash
= (hash
<< 5) - hash
+ str
.charCodeAt(i
);
251 // Convert the possibly negative integer hash code into an 8 character hex string, which isn't
252 // strictly necessary but increases user understanding that the id is a SHA-like hash
253 var hex
= (0x100000000 + hash
).toString(16);
254 if (hex
.length
< 8) {
255 hex
= "0000000" + hex
;
258 return hex
.slice(-8);
261 // Test for equality any JavaScript type.
262 // Authors: Philippe Rathé <prathe@gmail.com>, David Chan <david@troi.org>
263 var equiv
= (function () {
265 // Value pairs queued for comparison. Used for breadth-first processing order, recursion
266 // detection and avoiding repeated comparison (see below for details).
267 // Elements are { a: val, b: val }.
270 var getProto
= Object
.getPrototypeOf
|| function (obj
) {
271 return obj
.__proto__
;
274 function useStrictEquality(a
, b
) {
276 // This only gets called if a and b are not strict equal, and is used to compare on
277 // the primitive values inside object wrappers. For example:
279 // `var j = new Number(1);`
280 // Neither a nor b can be null, as a !== b and they have the same type.
281 if ((typeof a
=== "undefined" ? "undefined" : _typeof(a
)) === "object") {
284 if ((typeof b
=== "undefined" ? "undefined" : _typeof(b
)) === "object") {
291 function compareConstructors(a
, b
) {
292 var protoA
= getProto(a
);
293 var protoB
= getProto(b
);
295 // Comparing constructors is more strict than using `instanceof`
296 if (a
.constructor === b
.constructor) {
301 // If the obj prototype descends from a null constructor, treat it
302 // as a null prototype.
303 if (protoA
&& protoA
.constructor === null) {
306 if (protoB
&& protoB
.constructor === null) {
310 // Allow objects with no prototype to be equivalent to
311 // objects with Object as their constructor.
312 if (protoA
=== null && protoB
=== Object
.prototype || protoB
=== null && protoA
=== Object
.prototype) {
319 function getRegExpFlags(regexp
) {
320 return "flags" in regexp
? regexp
.flags
: regexp
.toString().match(/[gimuy]*$/)[0];
323 function isContainer(val
) {
324 return ["object", "array", "map", "set"].indexOf(objectType(val
)) !== -1;
327 function breadthFirstCompareChild(a
, b
) {
329 // If a is a container not reference-equal to b, postpone the comparison to the
330 // end of the pairs queue -- unless (a, b) has been seen before, in which case skip
335 if (!isContainer(a
)) {
336 return typeEquiv(a
, b
);
338 if (pairs
.every(function (pair
) {
339 return pair
.a
!== a
|| pair
.b
!== b
;
342 // Not yet started comparing this pair
343 pairs
.push({ a
: a
, b
: b
});
349 "string": useStrictEquality
,
350 "boolean": useStrictEquality
,
351 "number": useStrictEquality
,
352 "null": useStrictEquality
,
353 "undefined": useStrictEquality
,
354 "symbol": useStrictEquality
,
355 "date": useStrictEquality
,
357 "nan": function nan() {
361 "regexp": function regexp(a
, b
) {
362 return a
.source
=== b
.source
&&
364 // Include flags in the comparison
365 getRegExpFlags(a
) === getRegExpFlags(b
);
368 // abort (identical references / instance methods were skipped earlier)
369 "function": function _function() {
373 "array": function array(a
, b
) {
377 if (len
!== b
.length
) {
383 for (i
= 0; i
< len
; i
++) {
385 // Compare non-containers; queue non-reference-equal containers
386 if (!breadthFirstCompareChild(a
[i
], b
[i
])) {
393 // Define sets a and b to be equivalent if for each element aVal in a, there
394 // is some element bVal in b such that aVal and bVal are equivalent. Element
395 // repetitions are not counted, so these are equivalent:
396 // a = new Set( [ {}, [], [] ] );
397 // b = new Set( [ {}, {}, [] ] );
398 "set": function set$$1(a
, b
) {
402 if (a
.size
!== b
.size
) {
404 // This optimization has certain quirks because of the lack of
405 // repetition counting. For instance, adding the same
406 // (reference-identical) element to two equivalent sets can
407 // make them non-equivalent.
411 a
.forEach(function (aVal
) {
413 // Short-circuit if the result is already known. (Using for...of
414 // with a break clause would be cleaner here, but it would cause
415 // a syntax error on older Javascript implementations even if
423 b
.forEach(function (bVal
) {
426 // Likewise, short-circuit if the result is already known
431 // Swap out the global pairs list, as the nested call to
432 // innerEquiv will clobber its contents
434 if (innerEquiv(bVal
, aVal
)) {
438 // Replace the global pairs list
450 // Define maps a and b to be equivalent if for each key-value pair (aKey, aVal)
451 // in a, there is some key-value pair (bKey, bVal) in b such that
452 // [ aKey, aVal ] and [ bKey, bVal ] are equivalent. Key repetitions are not
453 // counted, so these are equivalent:
454 // a = new Map( [ [ {}, 1 ], [ {}, 1 ], [ [], 1 ] ] );
455 // b = new Map( [ [ {}, 1 ], [ [], 1 ], [ [], 1 ] ] );
456 "map": function map(a
, b
) {
460 if (a
.size
!== b
.size
) {
462 // This optimization has certain quirks because of the lack of
463 // repetition counting. For instance, adding the same
464 // (reference-identical) key-value pair to two equivalent maps
465 // can make them non-equivalent.
469 a
.forEach(function (aVal
, aKey
) {
471 // Short-circuit if the result is already known. (Using for...of
472 // with a break clause would be cleaner here, but it would cause
473 // a syntax error on older Javascript implementations even if
481 b
.forEach(function (bVal
, bKey
) {
484 // Likewise, short-circuit if the result is already known
489 // Swap out the global pairs list, as the nested call to
490 // innerEquiv will clobber its contents
492 if (innerEquiv([bVal
, bKey
], [aVal
, aKey
])) {
496 // Replace the global pairs list
508 "object": function object(a
, b
) {
513 if (compareConstructors(a
, b
) === false) {
517 // Be strict: don't ensure hasOwnProperty and go deep
520 // Collect a's properties
523 // Skip OOP methods that look the same
524 if (a
.constructor !== Object
&& typeof a
.constructor !== "undefined" && typeof a
[i
] === "function" && typeof b
[i
] === "function" && a
[i
].toString() === b
[i
].toString()) {
528 // Compare non-containers; queue non-reference-equal containers
529 if (!breadthFirstCompareChild(a
[i
], b
[i
])) {
536 // Collect b's properties
540 // Ensures identical properties name
541 return typeEquiv(aProperties
.sort(), bProperties
.sort());
545 function typeEquiv(a
, b
) {
546 var type
= objectType(a
);
548 // Callbacks for containers will append to the pairs queue to achieve breadth-first
549 // search order. The pairs queue is also used to avoid reprocessing any pair of
550 // containers that are reference-equal to a previously visited pair (a special case
551 // this being recursion detection).
553 // Because of this approach, once typeEquiv returns a false value, it should not be
554 // called again without clearing the pair queue else it may wrongly report a visited
555 // pair as being equivalent.
556 return objectType(b
) === type
&& callbacks
[type
](a
, b
);
559 function innerEquiv(a
, b
) {
562 // We're done when there's nothing more to compare
563 if (arguments
.length
< 2) {
567 // Clear the global pair queue and add the top-level values being compared
568 pairs
= [{ a
: a
, b
: b
}];
570 for (i
= 0; i
< pairs
.length
; i
++) {
573 // Perform type-specific comparison on any pairs that are not strictly
574 // equal. For container types, that comparison will postpone comparison
575 // of any sub-container pair to the end of the pair queue. This gives
576 // breadth-first search order. It also avoids the reprocessing of
577 // reference-equal siblings, cousins etc, which can have a significant speed
578 // impact when comparing a container of small objects each of which has a
579 // reference to the same (singleton) large object.
580 if (pair
.a
!== pair
.b
&& !typeEquiv(pair
.a
, pair
.b
)) {
585 // ...across all consecutive argument pairs
586 return arguments
.length
=== 2 || innerEquiv
.apply(this, [].slice
.call(arguments
, 1));
590 var result
= innerEquiv
.apply(undefined, arguments
);
592 // Release any retained objects
599 * Config object: Maintain internal state
600 * Later exposed as QUnit.config
601 * `config` initialized at top of scope
605 // The queue of tests to run
608 // Block until document ready
611 // By default, run previously failed tests first
612 // very useful in combination with "Hide passed tests" checked
615 // By default, modify document.title when suite is done
618 // HTML Reporter: collapse every test except the first failing test
619 // If false, all failing tests will be expanded
622 // By default, scroll to top of the page when suite is done
625 // Depth up-to which object will be dumped
628 // When enabled, all tests must call expect()
629 requireExpects
: false,
631 // Placeholder for user-configurable form-exposed URL parameters
634 // Set of all modules.
637 // The first unnamed module
643 unskippedTestsRun
: 0,
654 // The storage module to use for reordering tests
655 storage
: localSessionStorage
658 // take a predefined QUnit.config and extend the defaults
659 var globalConfig
= window
&& window
.QUnit
&& window
.QUnit
.config
;
661 // only extend the global config if there is no QUnit overload
662 if (window
&& window
.QUnit
&& !window
.QUnit
.version
) {
663 extend(config
, globalConfig
);
666 // Push a loose unnamed module to the modules collection
667 config
.modules
.push(config
.currentModule
);
669 // Based on jsDump by Ariel Flesler
670 // http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html
671 var dump
= (function () {
672 function quote(str
) {
673 return "\"" + str
.toString().replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\"";
675 function literal(o) {
678 function join(pre, arr, post) {
679 var s = dump.separator(),
680 base = dump.indent(),
681 inner = dump.indent(1);
683 arr = arr.join("," + s + inner);
688 return [pre, inner + arr, base + post].join(s);
690 function array(arr, stack) {
694 if (dump.maxDepth && dump.depth > dump.maxDepth) {
695 return "[object Array
]";
700 ret[i] = this.parse(arr[i], undefined, stack);
703 return join("[", ret, "]");
706 function isArray(obj) {
710 toString.call(obj) === "[object Array
]" ||
713 typeof obj.length === "number
" && obj.item !== undefined && (obj.length ? obj.item(0) === obj[0] : obj.item(0) === null && obj[0] === undefined)
717 var reName = /^function (\w+)/,
720 // The objType is used mostly internally, you can fix a (custom) type in advance
721 parse: function parse(obj, objType, stack) {
726 objIndex = stack.indexOf(obj);
728 if (objIndex !== -1) {
729 return "recursion(" + (objIndex - stack.length) + ")";
732 objType = objType || this.typeOf(obj);
733 parser = this.parsers[objType];
734 parserType = typeof parser === "undefined" ? "undefined" : _typeof(parser);
736 if (parserType === "function") {
738 res = parser.call(this, obj, stack);
742 return parserType === "string
" ? parser : this.parsers.error;
744 typeOf: function typeOf(obj) {
749 } else if (typeof obj === "undefined") {
751 } else if (is("regexp
", obj)) {
753 } else if (is("date
", obj)) {
755 } else if (is("function", obj)) {
757 } else if (obj.setInterval !== undefined && obj.document !== undefined && obj.nodeType === undefined) {
759 } else if (obj.nodeType === 9) {
761 } else if (obj.nodeType) {
763 } else if (isArray(obj)) {
765 } else if (obj.constructor === Error.prototype.constructor) {
768 type = typeof obj === "undefined" ? "undefined" : _typeof(obj);
773 separator: function separator() {
774 if (this.multiline) {
775 return this.HTML ? "<br
/>" : "\n";
777 return this.HTML ? " " : " ";
781 // Extra can be a number, shortcut for increasing-calling-decreasing
782 indent: function indent(extra) {
783 if (!this.multiline) {
786 var chr = this.indentChar;
788 chr = chr.replace(/\t/g, " ").replace(/ /g, " ");
790 return new Array(this.depth + (extra || 0)).join(chr);
793 this.depth += a || 1;
795 down: function down(a) {
796 this.depth -= a || 1;
798 setParser: function setParser(name, parser) {
799 this.parsers[name] = parser;
802 // The next 3 are exposed so you can use them
807 maxDepth: config.maxDepth,
809 // This is the list of parsers, to modify them, use dump.setParser
812 document: "[Document
]",
813 error: function error(_error) {
814 return "Error(\"" + _error.message + "\")";
816 unknown: "[Unknown
]",
818 "undefined": "undefined",
819 "function": function _function(fn) {
820 var ret = "function",
823 // Functions never have name in IE
824 name = "name
" in fn ? fn.name : (reName.exec(fn) || [])[1];
831 ret = [ret, dump.parse(fn, "functionArgs
"), "){"].join("");
832 return join(ret, dump.parse(fn, "functionCode
"), "}");
837 object: function object(map, stack) {
842 nonEnumerableProperties,
845 if (dump.maxDepth && dump.depth > dump.maxDepth) {
846 return "[object Object
]";
855 // Some properties are not always enumerable on Error objects.
856 nonEnumerableProperties = ["message
", "name
"];
857 for (i in nonEnumerableProperties) {
858 key = nonEnumerableProperties[i];
859 if (key in map && !inArray(key, keys)) {
864 for (i = 0; i < keys.length; i++) {
867 ret.push(dump.parse(key, "key
") + ": " + dump.parse(val, undefined, stack));
870 return join("{", ret, "}");
872 node: function node(_node) {
876 open = dump.HTML ? "<
;" : "<",
877 close = dump.HTML ? ">
;" : ">",
878 tag = _node.nodeName.toLowerCase(),
880 attrs = _node.attributes;
883 for (i = 0, len = attrs.length; i < len; i++) {
884 val = attrs[i].nodeValue;
886 // IE6 includes all attributes in .attributes, even ones not explicitly
887 // set. Those have values like undefined, null, 0, false, "" or
889 if (val && val !== "inherit
") {
890 ret += " " + attrs[i].nodeName + "=" + dump.parse(val, "attribute
");
896 // Show content of TextNode or CDATASection
897 if (_node.nodeType === 3 || _node.nodeType === 4) {
898 ret += _node.nodeValue;
901 return ret + open + "/" + tag + close;
904 // Function calls it internally, it's the arguments part of the function
905 functionArgs: function functionArgs(fn) {
917 args[l] = String.fromCharCode(97 + l);
919 return " " + args.join(", ") + " ";
922 // Object calls it internally, the key part of an item in a map
925 // Function calls it internally, it's the content of the function
926 functionCode: "[code
]",
928 // Node calls it internally, it's a html attribute value
935 symbol: function symbol(sym) {
936 return sym.toString();
940 // If true, entities are escaped ( <, >, \t, space and \n )
946 // If true, items in a collection, are separated by a \n, else just a space.
953 var LISTENERS = Object.create(null);
954 var SUPPORTED_EVENTS = ["runStart
", "suiteStart
", "testStart
", "assertion
", "testEnd
", "suiteEnd
", "runEnd
"];
957 * Emits an event with the specified data to all currently registered listeners.
958 * Callbacks will fire in the order in which they are registered (FIFO). This
959 * function is not exposed publicly; it is used by QUnit internals to emit
964 * @param {String} eventName
965 * @param {Object} data
968 function emit(eventName, data) {
969 if (objectType(eventName) !== "string
") {
970 throw new TypeError("eventName must be a string when emitting an event
");
973 // Clone the callbacks in case one of them registers a new callback
974 var originalCallbacks = LISTENERS[eventName];
975 var callbacks = originalCallbacks ? [].concat(toConsumableArray(originalCallbacks)) : [];
977 for (var i = 0; i < callbacks.length; i++) {
983 * Registers a callback as a listener to the specified event.
987 * @param {String} eventName
988 * @param {Function} callback
991 function on(eventName, callback) {
992 if (objectType(eventName) !== "string
") {
993 throw new TypeError("eventName must be a string when registering a listener
");
994 } else if (!inArray(eventName, SUPPORTED_EVENTS)) {
995 var events = SUPPORTED_EVENTS.join(", ");
996 throw new Error("\"" + eventName + "\" is not a valid event
; must be one
of: " + events + ".");
997 } else if (objectType(callback) !== "function") {
998 throw new TypeError("callback must be a
function when registering a listener
");
1001 if (!LISTENERS[eventName]) {
1002 LISTENERS[eventName] = [];
1005 // Don't register the same callback more than once
1006 if (!inArray(callback, LISTENERS[eventName])) {
1007 LISTENERS[eventName].push(callback);
1011 // Register logging callbacks
1012 function registerLoggingCallbacks(obj) {
1016 callbackNames = ["begin
", "done
", "log
", "testStart
", "testDone
", "moduleStart
", "moduleDone
"];
1018 function registerLoggingCallback(key) {
1019 var loggingCallback = function loggingCallback(callback) {
1020 if (objectType(callback) !== "function") {
1021 throw new Error("QUnit logging methods require a callback
function as their first parameters
.");
1024 config.callbacks[key].push(callback);
1027 return loggingCallback;
1030 for (i = 0, l = callbackNames.length; i < l; i++) {
1031 key = callbackNames[i];
1033 // Initialize key collection of logging callback
1034 if (objectType(config.callbacks[key]) === "undefined") {
1035 config.callbacks[key] = [];
1038 obj[key] = registerLoggingCallback(key);
1042 function runLoggingCallbacks(key, args) {
1043 var i, l, callbacks;
1045 callbacks = config.callbacks[key];
1046 for (i = 0, l = callbacks.length; i < l; i++) {
1051 // Doesn't support IE9, it will return undefined on these browsers
1052 // See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack
1053 var fileName = (sourceFromStacktrace(0) || "").replace(/(:\d+)+\)?/, "").replace(/.+\//, "");
1055 function extractStacktrace(e, offset) {
1056 offset = offset === undefined ? 4 : offset;
1058 var stack, include, i;
1061 stack = e.stack.split("\n");
1062 if (/^error$/i.test(stack[0])) {
1067 for (i = offset; i < stack.length; i++) {
1068 if (stack[i].indexOf(fileName) !== -1) {
1071 include.push(stack[i]);
1073 if (include.length) {
1074 return include.join("\n");
1077 return stack[offset];
1081 function sourceFromStacktrace(offset) {
1082 var error = new Error();
1084 // Support: Safari <=7 only, IE <=10 - 11 only
1085 // Not all browsers generate the `stack` property for `new Error()`, see also #636
1094 return extractStacktrace(error, offset);
1097 var priorityCount = 0;
1098 var unitSampler = void 0;
1101 * Advances the ProcessingQueue to the next item if it is ready.
1102 * @param {Boolean} last
1104 function advance() {
1106 config.depth = (config.depth || 0) + 1;
1108 while (config.queue.length && !config.blocking) {
1109 var elapsedTime = now() - start;
1111 if (!defined.setTimeout || config.updateRate <= 0 || elapsedTime < config.updateRate) {
1112 if (priorityCount > 0) {
1116 config.queue.shift()();
1118 setTimeout(advance, 13);
1125 if (!config.blocking && !config.queue.length && config.depth === 0) {
1130 function addToQueueImmediate(callback) {
1131 if (objectType(callback) === "array
") {
1132 while (callback.length) {
1133 addToQueueImmediate(callback.pop());
1139 config.queue.unshift(callback);
1144 * Adds a function to the ProcessingQueue for execution.
1145 * @param {Function|Array} callback
1146 * @param {Boolean} priority
1147 * @param {String} seed
1149 function addToQueue(callback, prioritize, seed) {
1151 config.queue.splice(priorityCount++, 0, callback);
1154 unitSampler = unitSamplerGenerator(seed);
1157 // Insert into a random position after all prioritized items
1158 var index = Math.floor(unitSampler() * (config.queue.length - priorityCount + 1));
1159 config.queue.splice(priorityCount + index, 0, callback);
1161 config.queue.push(callback);
1166 * Creates a seeded "sample
" generator which is used for randomizing tests.
1168 function unitSamplerGenerator(seed) {
1170 // 32-bit xorshift, requires only a nonzero seed
1171 // http://excamera.com/sphinx/article-xorshift.html
1172 var sample = parseInt(generateHash(seed), 16) || -1;
1173 return function () {
1174 sample ^= sample << 13;
1175 sample ^= sample >>> 17;
1176 sample ^= sample << 5;
1178 // ECMAScript has no unsigned number type
1180 sample += 0x100000000;
1183 return sample / 0x100000000;
1188 * This function is called when the ProcessingQueue is done processing all
1189 * items. It handles emitting the final run events.
1192 var storage = config.storage;
1194 ProcessingQueue.finished = true;
1196 var runtime = now() - config.started;
1197 var passed = config.stats.all - config.stats.bad;
1199 emit("runEnd
", globalSuite.end(true));
1200 runLoggingCallbacks("done
", {
1202 failed: config.stats.bad,
1203 total: config.stats.all,
1207 // Clear own storage items if all tests passed
1208 if (storage && config.stats.bad === 0) {
1209 for (var i = storage.length - 1; i >= 0; i--) {
1210 var key = storage.key(i);
1212 if (key.indexOf("qunit
-test
-") === 0) {
1213 storage.removeItem(key);
1219 var ProcessingQueue = {
1222 addImmediate: addToQueueImmediate,
1226 var TestReport = function () {
1227 function TestReport(name, suite, options) {
1228 classCallCheck(this, TestReport);
1231 this.suiteName = suite.name;
1232 this.fullName = suite.fullName.concat(name);
1234 this.assertions = [];
1236 this.skipped = !!options.skip;
1237 this.todo = !!options.todo;
1239 this.valid = options.valid;
1241 this._startTime = 0;
1244 suite.pushTest(this);
1247 createClass(TestReport, [{
1249 value: function start(recordTime) {
1251 this._startTime = Date.now();
1256 suiteName: this.suiteName,
1257 fullName: this.fullName.slice()
1262 value: function end(recordTime) {
1264 this._endTime = Date.now();
1267 return extend(this.start(), {
1268 runtime: this.getRuntime(),
1269 status: this.getStatus(),
1270 errors: this.getFailedAssertions(),
1271 assertions: this.getAssertions()
1275 key: "pushAssertion
",
1276 value: function pushAssertion(assertion) {
1277 this.assertions.push(assertion);
1281 value: function getRuntime() {
1282 return this._endTime - this._startTime;
1286 value: function getStatus() {
1291 var testPassed = this.getFailedAssertions().length > 0 ? this.todo : !this.todo;
1295 } else if (this.todo) {
1302 key: "getFailedAssertions
",
1303 value: function getFailedAssertions() {
1304 return this.assertions.filter(function (assertion) {
1305 return !assertion.passed;
1309 key: "getAssertions
",
1310 value: function getAssertions() {
1311 return this.assertions.slice();
1314 // Remove actual and expected values from assertions. This is to prevent
1315 // leaking memory throughout a test suite.
1318 key: "slimAssertions
",
1319 value: function slimAssertions() {
1320 this.assertions = this.assertions.map(function (assertion) {
1321 delete assertion.actual;
1322 delete assertion.expected;
1330 var focused$1 = false;
1332 function Test(settings) {
1337 this.expected = null;
1338 this.assertions = [];
1340 this.module = config.currentModule;
1341 this.stack = sourceFromStacktrace(3);
1343 this.timeout = undefined;
1345 // If a module is skipped, all its tests and the tests of the child suites
1346 // should be treated as skipped even if they are defined as `only` or `todo`.
1347 // As for `todo` module, all its tests will be treated as `todo` except for
1348 // tests defined as `skip` which will be left intact.
1350 // So, if a test is defined as `todo` and is inside a skipped module, we should
1351 // then treat that test as if was defined as `skip`.
1352 if (this.module.skip) {
1353 settings.skip = true;
1354 settings.todo = false;
1356 // Skipped tests should be left intact
1357 } else if (this.module.todo && !settings.skip) {
1358 settings.todo = true;
1361 extend(this, settings);
1363 this.testReport = new TestReport(settings.testName, this.module.suiteReport, {
1364 todo: settings.todo,
1365 skip: settings.skip,
1369 // Register unique strings
1370 for (i = 0, l = this.module.tests; i < l.length; i++) {
1371 if (this.module.tests[i].name === this.testName) {
1372 this.testName += " ";
1376 this.testId = generateHash(this.module.name, this.testName);
1378 this.module.tests.push({
1379 name: this.testName,
1380 testId: this.testId,
1381 skip: !!settings.skip
1384 if (settings.skip) {
1386 // Skipped tests will fully ignore any sent callback
1387 this.callback = function () {};
1391 this.assert = new Assert(this);
1397 function getNotStartedModules(startModule) {
1398 var module = startModule,
1401 while (module && module.testsRun === 0) {
1402 modules.push(module);
1403 module = module.parentModule;
1410 before: function before() {
1413 module = this.module,
1414 notStartedModules = getNotStartedModules(module);
1416 for (i = notStartedModules.length - 1; i >= 0; i--) {
1417 startModule = notStartedModules[i];
1418 startModule.stats = { all: 0, bad: 0, started: now() };
1419 emit("suiteStart
", startModule.suiteReport.start(true));
1420 runLoggingCallbacks("moduleStart
", {
1421 name: startModule.name,
1422 tests: startModule.tests
1426 config.current = this;
1428 this.testEnvironment = extend({}, module.testEnvironment);
1430 this.started = now();
1431 emit("testStart
", this.testReport.start(true));
1432 runLoggingCallbacks("testStart
", {
1433 name: this.testName,
1434 module: module.name,
1435 testId: this.testId,
1436 previousFailure: this.previousFailure
1439 if (!config.pollution) {
1444 run: function run() {
1447 config.current = this;
1449 this.callbackStarted = now();
1451 if (config.notrycatch) {
1459 this.pushFailure("Died on test
#" + (this.assertions.length + 1) + " " + this.stack + ": " + (e.message || e), extractStacktrace(e, 0));
1461 // Else next test will carry the responsibility
1464 // Restart the tests if they're blocking
1465 if (config.blocking) {
1466 internalRecover(this);
1470 function runTest(test) {
1471 promise = test.callback.call(test.testEnvironment, test.assert);
1472 test.resolvePromise(promise);
1474 // If the test has a "lock
" on it, but the timeout is 0, then we push a
1475 // failure as the test should be synchronous.
1476 if (test.timeout === 0 && test.semaphore !== 0) {
1477 pushFailure("Test did not finish synchronously even though assert
.timeout( 0 ) was used
.", sourceFromStacktrace(2));
1482 after: function after() {
1486 queueHook: function queueHook(hook, hookName, hookOwner) {
1489 var callHook = function callHook() {
1490 var promise = hook.call(_this.testEnvironment, _this.assert);
1491 _this.resolvePromise(promise, hookName);
1494 var runHook = function runHook() {
1495 if (hookName === "before
") {
1496 if (hookOwner.unskippedTestsRun !== 0) {
1500 _this.preserveEnvironment = true;
1503 if (hookName === "after
" && hookOwner.unskippedTestsRun !== numberOfUnskippedTests(hookOwner) - 1 && config.queue.length > 2) {
1507 config.current = _this;
1508 if (config.notrycatch) {
1515 _this.pushFailure(hookName + " failed on
" + _this.testName + ": " + (error.message || error), extractStacktrace(error, 0));
1523 // Currently only used for module level hooks, can be used to add global level ones
1524 hooks: function hooks(handler) {
1527 function processHooks(test, module) {
1528 if (module.parentModule) {
1529 processHooks(test, module.parentModule);
1532 if (module.hooks[handler].length) {
1533 for (var i = 0; i < module.hooks[handler].length; i++) {
1534 hooks.push(test.queueHook(module.hooks[handler][i], handler, module));
1539 // Hooks are ignored on skipped tests
1541 processHooks(this, this.module);
1548 finish: function finish() {
1549 config.current = this;
1550 if (config.requireExpects && this.expected === null) {
1551 this.pushFailure("Expected number
of assertions to be defined
, but
expect() was
" + "not called
.", this.stack);
1552 } else if (this.expected !== null && this.expected !== this.assertions.length) {
1553 this.pushFailure("Expected
" + this.expected + " assertions
, but
" + this.assertions.length + " were run
", this.stack);
1554 } else if (this.expected === null && !this.assertions.length) {
1555 this.pushFailure("Expected at least one assertion
, but none were run
- call
" + "expect(0) to accept zero assertions
.", this.stack);
1559 module = this.module,
1560 moduleName = module.name,
1561 testName = this.testName,
1562 skipped = !!this.skip,
1565 storage = config.storage;
1567 this.runtime = now() - this.started;
1569 config.stats.all += this.assertions.length;
1570 module.stats.all += this.assertions.length;
1572 for (i = 0; i < this.assertions.length; i++) {
1573 if (!this.assertions[i].result) {
1580 notifyTestsRan(module, skipped);
1582 // Store result when possible
1585 storage.setItem("qunit
-test
-" + moduleName + "-" + testName, bad);
1587 storage.removeItem("qunit
-test
-" + moduleName + "-" + testName);
1591 // After emitting the js-reporters event we cleanup the assertion data to
1592 // avoid leaking it. It is not used by the legacy testDone callbacks.
1593 emit("testEnd
", this.testReport.end(true));
1594 this.testReport.slimAssertions();
1596 runLoggingCallbacks("testDone
", {
1602 passed: this.assertions.length - bad,
1603 total: this.assertions.length,
1604 runtime: skipped ? 0 : this.runtime,
1606 // HTML Reporter use
1607 assertions: this.assertions,
1608 testId: this.testId,
1614 if (module.testsRun === numberOfTests(module)) {
1615 logSuiteEnd(module);
1617 // Check if the parent modules, iteratively, are done. If that the case,
1618 // we emit the `suiteEnd` event and trigger `moduleDone` callback.
1619 var parent = module.parentModule;
1620 while (parent && parent.testsRun === numberOfTests(parent)) {
1621 logSuiteEnd(parent);
1622 parent = parent.parentModule;
1626 config.current = undefined;
1628 function logSuiteEnd(module) {
1629 emit("suiteEnd
", module.suiteReport.end(true));
1630 runLoggingCallbacks("moduleDone
", {
1632 tests: module.tests,
1633 failed: module.stats.bad,
1634 passed: module.stats.all - module.stats.bad,
1635 total: module.stats.all,
1636 runtime: now() - module.stats.started
1641 preserveTestEnvironment: function preserveTestEnvironment() {
1642 if (this.preserveEnvironment) {
1643 this.module.testEnvironment = this.testEnvironment;
1644 this.testEnvironment = extend({}, this.module.testEnvironment);
1648 queue: function queue() {
1651 if (!this.valid()) {
1655 function runTest() {
1657 // Each of these can by async
1658 ProcessingQueue.addImmediate([function () {
1660 }, test.hooks("before
"), function () {
1661 test.preserveTestEnvironment();
1662 }, test.hooks("beforeEach
"), function () {
1664 }, test.hooks("afterEach
").reverse(), test.hooks("after
").reverse(), function () {
1671 var previousFailCount = config.storage && +config.storage.getItem("qunit
-test
-" + this.module.name + "-" + this.testName);
1673 // Prioritize previously failed tests, detected from storage
1674 var prioritize = config.reorder && !!previousFailCount;
1676 this.previousFailure = !!previousFailCount;
1678 ProcessingQueue.add(runTest, prioritize, config.seed);
1680 // If the queue has already finished, we manually process the new test
1681 if (ProcessingQueue.finished) {
1682 ProcessingQueue.advance();
1687 pushResult: function pushResult(resultInfo) {
1688 if (this !== config.current) {
1689 throw new Error("Assertion occured after test had finished
.");
1692 // Destructure of resultInfo = { result, actual, expected, message, negative }
1695 module: this.module.name,
1696 name: this.testName,
1697 result: resultInfo.result,
1698 message: resultInfo.message,
1699 actual: resultInfo.actual,
1700 expected: resultInfo.expected,
1701 testId: this.testId,
1702 negative: resultInfo.negative || false,
1703 runtime: now() - this.started,
1707 if (!resultInfo.result) {
1708 source = resultInfo.source || sourceFromStacktrace();
1711 details.source = source;
1715 this.logAssertion(details);
1717 this.assertions.push({
1718 result: !!resultInfo.result,
1719 message: resultInfo.message
1723 pushFailure: function pushFailure(message, source, actual) {
1724 if (!(this instanceof Test)) {
1725 throw new Error("pushFailure() assertion outside test context
, was
" + sourceFromStacktrace(2));
1730 message: message || "error
",
1731 actual: actual || null,
1738 * Log assertion details using both the old QUnit.log interface and
1739 * QUnit.on( "assertion
" ) interface.
1743 logAssertion: function logAssertion(details) {
1744 runLoggingCallbacks("log
", details);
1747 passed: details.result,
1748 actual: details.actual,
1749 expected: details.expected,
1750 message: details.message,
1751 stack: details.source,
1754 this.testReport.pushAssertion(assertion);
1755 emit("assertion
", assertion);
1759 resolvePromise: function resolvePromise(promise, phase) {
1764 if (promise != null) {
1765 then = promise.then;
1766 if (objectType(then) === "function") {
1767 resume = internalStop(test);
1768 then.call(promise, function () {
1770 }, function (error) {
1771 message = "Promise rejected
" + (!phase ? "during
" : phase.replace(/Each$/, "")) + " \"" + test.testName + "\": " + (error && error.message || error);
1772 test.pushFailure(message, extractStacktrace(error, 0));
1774 // Else next test will carry the responsibility
1784 valid: function valid() {
1785 var filter = config.filter,
1786 regexFilter = /^(!?)\/([\w\W]*)\/(i?$)/.exec(filter),
1787 module = config.module && config.module.toLowerCase(),
1788 fullName = this.module.name + ": " + this.testName;
1790 function moduleChainNameMatch(testModule) {
1791 var testModuleName = testModule.name ? testModule.name.toLowerCase() : null;
1792 if (testModuleName === module) {
1794 } else if (testModule.parentModule) {
1795 return moduleChainNameMatch(testModule.parentModule);
1801 function moduleChainIdMatch(testModule) {
1802 return inArray(testModule.moduleId, config.moduleId) || testModule.parentModule && moduleChainIdMatch(testModule.parentModule);
1805 // Internally-generated tests are always valid
1806 if (this.callback && this.callback.validTest) {
1810 if (config.moduleId && config.moduleId.length > 0 && !moduleChainIdMatch(this.module)) {
1815 if (config.testId && config.testId.length > 0 && !inArray(this.testId, config.testId)) {
1820 if (module && !moduleChainNameMatch(this.module)) {
1828 return regexFilter ? this.regexFilter(!!regexFilter[1], regexFilter[2], regexFilter[3], fullName) : this.stringFilter(filter, fullName);
1831 regexFilter: function regexFilter(exclude, pattern, flags, fullName) {
1832 var regex = new RegExp(pattern, flags);
1833 var match = regex.test(fullName);
1835 return match !== exclude;
1838 stringFilter: function stringFilter(filter, fullName) {
1839 filter = filter.toLowerCase();
1840 fullName = fullName.toLowerCase();
1842 var include = filter.charAt(0) !== "!";
1844 filter = filter.slice(1);
1847 // If the filter matches, we need to honour include
1848 if (fullName.indexOf(filter) !== -1) {
1852 // Otherwise, do the opposite
1857 function pushFailure() {
1858 if (!config.current) {
1859 throw new Error("pushFailure() assertion outside test context
, in " + sourceFromStacktrace(2));
1862 // Gets current test obj
1863 var currentTest = config.current;
1865 return currentTest.pushFailure.apply(currentTest, arguments);
1868 function saveGlobal() {
1869 config.pollution = [];
1871 if (config.noglobals) {
1872 for (var key in global$1) {
1873 if (hasOwn.call(global$1, key)) {
1875 // In Opera sometimes DOM element ids show up here, ignore them
1876 if (/^qunit-test-output/.test(key)) {
1879 config.pollution.push(key);
1885 function checkPollution() {
1888 old = config.pollution;
1892 newGlobals = diff(config.pollution, old);
1893 if (newGlobals.length > 0) {
1894 pushFailure("Introduced global
variable(s
): " + newGlobals.join(", "));
1897 deletedGlobals = diff(old, config.pollution);
1898 if (deletedGlobals.length > 0) {
1899 pushFailure("Deleted global
variable(s
): " + deletedGlobals.join(", "));
1903 // Will be exposed as QUnit.test
1904 function test(testName, callback) {
1909 var newTest = new Test({
1917 function todo(testName, callback) {
1922 var newTest = new Test({
1931 // Will be exposed as QUnit.skip
1932 function skip(testName) {
1937 var test = new Test({
1945 // Will be exposed as QUnit.only
1946 function only(testName, callback) {
1951 config.queue.length = 0;
1954 var newTest = new Test({
1962 // Put a hold on processing and return a function that will release it.
1963 function internalStop(test) {
1964 test.semaphore += 1;
1965 config.blocking = true;
1967 // Set a recovery timeout, if so configured.
1968 if (defined.setTimeout) {
1969 var timeoutDuration = void 0;
1971 if (typeof test.timeout === "number
") {
1972 timeoutDuration = test.timeout;
1973 } else if (typeof config.testTimeout === "number
") {
1974 timeoutDuration = config.testTimeout;
1977 if (typeof timeoutDuration === "number
" && timeoutDuration > 0) {
1978 clearTimeout(config.timeout);
1979 config.timeout = setTimeout(function () {
1980 pushFailure("Test took longer than
" + timeoutDuration + "ms
; test timed out
.", sourceFromStacktrace(2));
1981 internalRecover(test);
1982 }, timeoutDuration);
1986 var released = false;
1987 return function resume() {
1993 test.semaphore -= 1;
1994 internalStart(test);
1998 // Forcefully release all processing holds.
1999 function internalRecover(test) {
2001 internalStart(test);
2004 // Release a processing hold, scheduling a resumption attempt if no holds remain.
2005 function internalStart(test) {
2007 // If semaphore is non-numeric, throw error
2008 if (isNaN(test.semaphore)) {
2011 pushFailure("Invalid value on test
.semaphore
", sourceFromStacktrace(2));
2015 // Don't start until equal number of stop-calls
2016 if (test.semaphore > 0) {
2020 // Throw an Error if start is called more often than stop
2021 if (test.semaphore < 0) {
2024 pushFailure("Tried to restart test
while already
started (test
's semaphore was 0 already)", sourceFromStacktrace(2));
2028 // Add a slight delay to allow more assertions etc.
2029 if (defined.setTimeout) {
2030 if (config.timeout) {
2031 clearTimeout(config.timeout);
2033 config.timeout = setTimeout(function () {
2034 if (test.semaphore > 0) {
2038 if (config.timeout) {
2039 clearTimeout(config.timeout);
2049 function collectTests(module) {
2050 var tests = [].concat(module.tests);
2051 var modules = [].concat(toConsumableArray(module.childModules));
2053 // Do a breadth-first traversal of the child modules
2054 while (modules.length) {
2055 var nextModule = modules.shift();
2056 tests.push.apply(tests, nextModule.tests);
2057 modules.push.apply(modules, toConsumableArray(nextModule.childModules));
2063 function numberOfTests(module) {
2064 return collectTests(module).length;
2067 function numberOfUnskippedTests(module) {
2068 return collectTests(module).filter(function (test) {
2073 function notifyTestsRan(module, skipped) {
2076 module.unskippedTestsRun++;
2078 while (module = module.parentModule) {
2081 module.unskippedTestsRun++;
2087 * Returns a function that proxies to the given method name on the globals
2088 * console object. The proxy will also detect if the console doesn't exist and
2089 * will appropriately no
-op
. This allows support
for IE9
, which doesn
't have a
2090 * console if the developer tools are not open.
2092 function consoleProxy(method) {
2093 return function () {
2095 console[method].apply(console, arguments);
2101 warn: consoleProxy("warn")
2104 var Assert = function () {
2105 function Assert(testContext) {
2106 classCallCheck(this, Assert);
2108 this.test = testContext;
2113 createClass(Assert, [{
2115 value: function timeout(duration) {
2116 if (typeof duration !== "number") {
2117 throw new Error("You must pass a number as the duration to assert.timeout");
2120 this.test.timeout = duration;
2123 // Documents a "step", which is a string value, in a test as a passing assertion
2127 value: function step(message) {
2128 var result = !!message;
2130 this.test.steps.push(message);
2132 return this.pushResult({
2134 message: message || "You must provide a message to assert.step"
2138 // Verifies the steps in a test match a given array of string values
2142 value: function verifySteps(steps, message) {
2143 this.deepEqual(this.test.steps, steps, message);
2146 // Specify the number of expected assertions to guarantee that failed test
2147 // (no assertions are run at all) don't slip through
.
2151 value
: function expect(asserts
) {
2152 if (arguments
.length
=== 1) {
2153 this.test
.expected
= asserts
;
2155 return this.test
.expected
;
2159 // Put a hold on processing and return a function that will release it a maximum of once.
2163 value
: function async(count
) {
2164 var test
$$1 = this.test
;
2167 acceptCallCount
= count
;
2169 if (typeof acceptCallCount
=== "undefined") {
2170 acceptCallCount
= 1;
2173 var resume
= internalStop(test
$$1);
2175 return function done() {
2176 if (config
.current
!== test
$$1) {
2177 throw Error("assert.async callback called after test finished.");
2181 test
$$1.pushFailure("Too many calls to the `assert.async` callback", sourceFromStacktrace(2));
2185 acceptCallCount
-= 1;
2186 if (acceptCallCount
> 0) {
2195 // Exports test.push() to the user API
2196 // Alias of pushResult.
2200 value
: function push(result
, actual
, expected
, message
, negative
) {
2201 Logger
.warn("assert.push is deprecated and will be removed in QUnit 3.0." + " Please use assert.pushResult instead (https://api.qunitjs.com/assert/pushResult).");
2203 var currentAssert
= this instanceof Assert
? this : config
.current
.assert
;
2204 return currentAssert
.pushResult({
2214 value
: function pushResult(resultInfo
) {
2216 // Destructure of resultInfo = { result, actual, expected, message, negative }
2218 var currentTest
= assert
instanceof Assert
&& assert
.test
|| config
.current
;
2220 // Backwards compatibility fix.
2221 // Allows the direct use of global exported assertions and QUnit.assert.*
2222 // Although, it's use is not recommended as it can leak assertions
2223 // to other tests from async tests, because we only get a reference to the current test,
2224 // not exactly the test where assertion were intended to be called.
2226 throw new Error("assertion outside test context, in " + sourceFromStacktrace(2));
2229 if (!(assert
instanceof Assert
)) {
2230 assert
= currentTest
.assert
;
2233 return assert
.test
.pushResult(resultInfo
);
2237 value
: function ok(result
, message
) {
2239 message
= result
? "okay" : "failed, expected argument to be truthy, was: " + dump
.parse(result
);
2251 value
: function notOk(result
, message
) {
2253 message
= !result
? "okay" : "failed, expected argument to be falsy, was: " + dump
.parse(result
);
2265 value
: function equal(actual
, expected
, message
) {
2267 // eslint-disable-next-line eqeqeq
2268 var result
= expected
== actual
;
2279 value
: function notEqual(actual
, expected
, message
) {
2281 // eslint-disable-next-line eqeqeq
2282 var result
= expected
!= actual
;
2294 value
: function propEqual(actual
, expected
, message
) {
2295 actual
= objectValues(actual
);
2296 expected
= objectValues(expected
);
2299 result
: equiv(actual
, expected
),
2306 key
: "notPropEqual",
2307 value
: function notPropEqual(actual
, expected
, message
) {
2308 actual
= objectValues(actual
);
2309 expected
= objectValues(expected
);
2312 result
: !equiv(actual
, expected
),
2321 value
: function deepEqual(actual
, expected
, message
) {
2323 result
: equiv(actual
, expected
),
2330 key
: "notDeepEqual",
2331 value
: function notDeepEqual(actual
, expected
, message
) {
2333 result
: !equiv(actual
, expected
),
2342 value
: function strictEqual(actual
, expected
, message
) {
2344 result
: expected
=== actual
,
2351 key
: "notStrictEqual",
2352 value
: function notStrictEqual(actual
, expected
, message
) {
2354 result
: expected
!== actual
,
2363 value
: function throws(block
, expected
, message
) {
2364 var actual
= void 0,
2367 var currentTest
= this instanceof Assert
&& this.test
|| config
.current
;
2369 // 'expected' is optional unless doing string comparison
2370 if (objectType(expected
) === "string") {
2371 if (message
== null) {
2375 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.");
2379 currentTest
.ignoreGlobalErrors
= true;
2381 block
.call(currentTest
.testEnvironment
);
2385 currentTest
.ignoreGlobalErrors
= false;
2388 var expectedType
= objectType(expected
);
2390 // We don't want to validate thrown error
2395 // Expected is a regexp
2396 } else if (expectedType
=== "regexp") {
2397 result
= expected
.test(errorString(actual
));
2399 // Expected is a constructor, maybe an Error constructor
2400 } else if (expectedType
=== "function" && actual
instanceof expected
) {
2403 // Expected is an Error object
2404 } else if (expectedType
=== "object") {
2405 result
= actual
instanceof expected
.constructor && actual
.name
=== expected
.name
&& actual
.message
=== expected
.message
;
2407 // Expected is a validation function which returns true if validation passed
2408 } else if (expectedType
=== "function" && expected
.call({}, actual
) === true) {
2414 currentTest
.assert
.pushResult({
2425 // Provide an alternative to assert.throws(), for environments that consider throws a reserved word
2426 // Known to us are: Closure Compiler, Narwhal
2427 // eslint-disable-next-line dot-notation
2430 Assert
.prototype.raises
= Assert
.prototype["throws"];
2433 * Converts an error into a simple string for comparisons.
2435 * @param {Error} error
2438 function errorString(error
) {
2439 var resultErrorString
= error
.toString();
2441 if (resultErrorString
.substring(0, 7) === "[object") {
2442 var name
= error
.name
? error
.name
.toString() : "Error";
2443 var message
= error
.message
? error
.message
.toString() : "";
2445 if (name
&& message
) {
2446 return name
+ ": " + message
;
2449 } else if (message
) {
2455 return resultErrorString
;
2459 /* global module, exports, define */
2460 function exportQUnit(QUnit
) {
2462 if (defined
.document
) {
2464 // QUnit may be defined when it is preconfigured but then only QUnit and QUnit.config may be defined.
2465 if (window
.QUnit
&& window
.QUnit
.version
) {
2466 throw new Error("QUnit has already been defined.");
2469 window
.QUnit
= QUnit
;
2473 if (typeof module
!== "undefined" && module
&& module
.exports
) {
2474 module
.exports
= QUnit
;
2476 // For consistency with CommonJS environments' exports
2477 module
.exports
.QUnit
= QUnit
;
2480 // For CommonJS with exports, but without module.exports, like Rhino
2481 if (typeof exports
!== "undefined" && exports
) {
2482 exports
.QUnit
= QUnit
;
2485 if (typeof define
=== "function" && define
.amd
) {
2486 define(function () {
2489 QUnit
.config
.autostart
= false;
2492 // For Web/Service Workers
2493 if (self
$1 && self
$1.WorkerGlobalScope
&& self
$1 instanceof self
$1.WorkerGlobalScope
) {
2494 self
$1.QUnit
= QUnit
;
2498 var SuiteReport = function () {
2499 function SuiteReport(name
, parentSuite
) {
2500 classCallCheck(this, SuiteReport
);
2503 this.fullName
= parentSuite
? parentSuite
.fullName
.concat(name
) : [];
2506 this.childSuites
= [];
2509 parentSuite
.pushChildSuite(this);
2513 createClass(SuiteReport
, [{
2515 value
: function start(recordTime
) {
2517 this._startTime
= Date
.now();
2522 fullName
: this.fullName
.slice(),
2523 tests
: this.tests
.map(function (test
) {
2524 return test
.start();
2526 childSuites
: this.childSuites
.map(function (suite
) {
2527 return suite
.start();
2530 total
: this.getTestCounts().total
2536 value
: function end(recordTime
) {
2538 this._endTime
= Date
.now();
2543 fullName
: this.fullName
.slice(),
2544 tests
: this.tests
.map(function (test
) {
2547 childSuites
: this.childSuites
.map(function (suite
) {
2550 testCounts
: this.getTestCounts(),
2551 runtime
: this.getRuntime(),
2552 status
: this.getStatus()
2556 key
: "pushChildSuite",
2557 value
: function pushChildSuite(suite
) {
2558 this.childSuites
.push(suite
);
2562 value
: function pushTest(test
) {
2563 this.tests
.push(test
);
2567 value
: function getRuntime() {
2568 return this._endTime
- this._startTime
;
2571 key
: "getTestCounts",
2572 value
: function getTestCounts() {
2573 var counts
= arguments
.length
> 0 && arguments
[0] !== undefined ? arguments
[0] : { passed
: 0, failed
: 0, skipped
: 0, todo
: 0, total
: 0 };
2575 counts
= this.tests
.reduce(function (counts
, test
) {
2577 counts
[test
.getStatus()]++;
2584 return this.childSuites
.reduce(function (counts
, suite
) {
2585 return suite
.getTestCounts(counts
);
2590 value
: function getStatus() {
2591 var _getTestCounts
= this.getTestCounts(),
2592 total
= _getTestCounts
.total
,
2593 failed
= _getTestCounts
.failed
,
2594 skipped
= _getTestCounts
.skipped
,
2595 todo
= _getTestCounts
.todo
;
2600 if (skipped
=== total
) {
2602 } else if (todo
=== total
) {
2613 // Handle an unhandled exception. By convention, returns true if further
2614 // error handling should be suppressed and false otherwise.
2615 // In this case, we will only suppress further error handling if the
2616 // "ignoreGlobalErrors" configuration option is enabled.
2617 function onError(error
) {
2618 for (var _len
= arguments
.length
, args
= Array(_len
> 1 ? _len
- 1 : 0), _key
= 1; _key
< _len
; _key
++) {
2619 args
[_key
- 1] = arguments
[_key
];
2622 if (config
.current
) {
2623 if (config
.current
.ignoreGlobalErrors
) {
2626 pushFailure
.apply(undefined, [error
.message
, error
.fileName
+ ":" + error
.lineNumber
].concat(args
));
2628 test("global failure", extend(function () {
2629 pushFailure
.apply(undefined, [error
.message
, error
.fileName
+ ":" + error
.lineNumber
].concat(args
));
2630 }, { validTest
: true }));
2636 var focused
= false;
2638 var globalSuite
= new SuiteReport();
2640 // The initial "currentModule" represents the global (or top-level) module that
2641 // is not explicitly defined by the user, therefore we add the "globalSuite" to
2642 // it since each module has a suiteReport associated with it.
2643 config
.currentModule
.suiteReport
= globalSuite
;
2645 var moduleStack
= [];
2646 var globalStartCalled
= false;
2647 var runStarted
= false;
2649 // Figure out if we're running the tests from a server or not
2650 QUnit
.isLocal
= !(defined
.document
&& window
.location
.protocol
!== "file:");
2652 // Expose the current QUnit version
2653 QUnit
.version
= "2.4.0";
2655 function createModule(name
, testEnvironment
, modifiers
) {
2656 var parentModule
= moduleStack
.length
? moduleStack
.slice(-1)[0] : null;
2657 var moduleName
= parentModule
!== null ? [parentModule
.name
, name
].join(" > ") : name
;
2658 var parentSuite
= parentModule
? parentModule
.suiteReport
: globalSuite
;
2660 var skip
$$1 = parentModule
!== null && parentModule
.skip
|| modifiers
.skip
;
2661 var todo
$$1 = parentModule
!== null && parentModule
.todo
|| modifiers
.todo
;
2665 parentModule
: parentModule
,
2667 moduleId
: generateHash(moduleName
),
2669 unskippedTestsRun
: 0,
2671 suiteReport
: new SuiteReport(name
, parentSuite
),
2673 // Pass along `skip` and `todo` properties from parent module, in case
2674 // there is one, to childs. And use own otherwise.
2675 // This property will be used to mark own tests and tests of child suites
2676 // as either `skipped` or `todo`.
2678 todo
: skip
$$1 ? false : todo
$$1
2683 parentModule
.childModules
.push(module
);
2684 extend(env
, parentModule
.testEnvironment
);
2686 extend(env
, testEnvironment
);
2687 module
.testEnvironment
= env
;
2689 config
.modules
.push(module
);
2693 function processModule(name
, options
, executeNow
) {
2694 var modifiers
= arguments
.length
> 3 && arguments
[3] !== undefined ? arguments
[3] : {};
2696 var module
= createModule(name
, options
, modifiers
);
2698 // Move any hooks to a 'hooks' object
2699 var testEnvironment
= module
.testEnvironment
;
2700 var hooks
= module
.hooks
= {};
2702 setHookFromEnvironment(hooks
, testEnvironment
, "before");
2703 setHookFromEnvironment(hooks
, testEnvironment
, "beforeEach");
2704 setHookFromEnvironment(hooks
, testEnvironment
, "afterEach");
2705 setHookFromEnvironment(hooks
, testEnvironment
, "after");
2707 function setHookFromEnvironment(hooks
, environment
, name
) {
2708 var potentialHook
= environment
[name
];
2709 hooks
[name
] = typeof potentialHook
=== "function" ? [potentialHook
] : [];
2710 delete environment
[name
];
2714 before
: setHookFunction(module
, "before"),
2715 beforeEach
: setHookFunction(module
, "beforeEach"),
2716 afterEach
: setHookFunction(module
, "afterEach"),
2717 after
: setHookFunction(module
, "after")
2720 var currentModule
= config
.currentModule
;
2721 if (objectType(executeNow
) === "function") {
2722 moduleStack
.push(module
);
2723 config
.currentModule
= module
;
2724 executeNow
.call(module
.testEnvironment
, moduleFns
);
2726 module
= module
.parentModule
|| currentModule
;
2729 config
.currentModule
= module
;
2732 // TODO: extract this to a new file alongside its related functions
2733 function module
$1(name
, options
, executeNow
) {
2738 if (arguments
.length
=== 2) {
2739 if (objectType(options
) === "function") {
2740 executeNow
= options
;
2741 options
= undefined;
2745 processModule(name
, options
, executeNow
);
2748 module
$1.only = function () {
2753 config
.modules
.length
= 0;
2754 config
.queue
.length
= 0;
2756 module
$1.apply(undefined, arguments
);
2761 module
$1.skip = function (name
, options
, executeNow
) {
2766 if (arguments
.length
=== 2) {
2767 if (objectType(options
) === "function") {
2768 executeNow
= options
;
2769 options
= undefined;
2773 processModule(name
, options
, executeNow
, { skip
: true });
2776 module
$1.todo = function (name
, options
, executeNow
) {
2781 if (arguments
.length
=== 2) {
2782 if (objectType(options
) === "function") {
2783 executeNow
= options
;
2784 options
= undefined;
2788 processModule(name
, options
, executeNow
, { todo
: true });
2804 start
: function start(count
) {
2805 var globalStartAlreadyCalled
= globalStartCalled
;
2807 if (!config
.current
) {
2808 globalStartCalled
= true;
2811 throw new Error("Called start() while test already started running");
2812 } else if (globalStartAlreadyCalled
|| count
> 1) {
2813 throw new Error("Called start() outside of a test context too many times");
2814 } else if (config
.autostart
) {
2815 throw new Error("Called start() outside of a test context when " + "QUnit.config.autostart was true");
2816 } else if (!config
.pageLoaded
) {
2818 // The page isn't completely loaded yet, so we set autostart and then
2819 // load if we're in Node or wait for the browser's load event.
2820 config
.autostart
= true;
2822 // Starts from Node even if .load was not previously called. We still return
2823 // early otherwise we'll wind up "beginning" twice.
2824 if (!defined
.document
) {
2831 throw new Error("QUnit.start cannot be called inside a test context.");
2841 objectType
: objectType
,
2845 load
: function load() {
2846 config
.pageLoaded
= true;
2848 // Initialize the configuration options
2850 stats
: { all
: 0, bad
: 0 },
2858 config
.blocking
= false;
2860 if (config
.autostart
) {
2866 stack
: function stack(offset
) {
2867 offset
= (offset
|| 0) + 2;
2868 return sourceFromStacktrace(offset
);
2874 QUnit
.pushFailure
= pushFailure
;
2875 QUnit
.assert
= Assert
.prototype;
2876 QUnit
.equiv
= equiv
;
2879 registerLoggingCallbacks(QUnit
);
2881 function scheduleBegin() {
2885 // Add a slight delay to allow definition of more modules and tests.
2886 if (defined
.setTimeout
) {
2887 setTimeout(function () {
2900 // If the test run hasn't officially begun yet
2901 if (!config
.started
) {
2903 // Record the time of the test run's beginning
2904 config
.started
= now();
2906 // Delete the loose unnamed module if unused.
2907 if (config
.modules
[0].name
=== "" && config
.modules
[0].tests
.length
=== 0) {
2908 config
.modules
.shift();
2911 // Avoid unnecessary information by not logging modules' test environments
2912 for (i
= 0, l
= config
.modules
.length
; i
< l
; i
++) {
2914 name
: config
.modules
[i
].name
,
2915 tests
: config
.modules
[i
].tests
2919 // The test run is officially beginning now
2920 emit("runStart", globalSuite
.start(true));
2921 runLoggingCallbacks("begin", {
2922 totalTests
: Test
.count
,
2927 config
.blocking
= false;
2928 ProcessingQueue
.advance();
2931 function setHookFunction(module
, hookName
) {
2932 return function setHook(callback
) {
2933 module
.hooks
[hookName
].push(callback
);
2941 if (typeof window
=== "undefined" || typeof document
=== "undefined") {
2945 var config
= QUnit
.config
,
2946 hasOwn
= Object
.prototype.hasOwnProperty
;
2948 // Stores fixture HTML for resetting later
2949 function storeFixture() {
2951 // Avoid overwriting user-defined values
2952 if (hasOwn
.call(config
, "fixture")) {
2956 var fixture
= document
.getElementById("qunit-fixture");
2958 config
.fixture
= fixture
.innerHTML
;
2962 QUnit
.begin(storeFixture
);
2964 // Resets the fixture DOM element if available.
2965 function resetFixture() {
2966 if (config
.fixture
== null) {
2970 var fixture
= document
.getElementById("qunit-fixture");
2972 fixture
.innerHTML
= config
.fixture
;
2976 QUnit
.testStart(resetFixture
);
2981 // Only interact with URLs via window.location
2982 var location
= typeof window
!== "undefined" && window
.location
;
2987 var urlParams
= getUrlParams();
2989 QUnit
.urlParams
= urlParams
;
2991 // Match module/test by inclusion in an array
2992 QUnit
.config
.moduleId
= [].concat(urlParams
.moduleId
|| []);
2993 QUnit
.config
.testId
= [].concat(urlParams
.testId
|| []);
2995 // Exact case-insensitive match of the module name
2996 QUnit
.config
.module
= urlParams
.module
;
2998 // Regular expression or case-insenstive substring match against "moduleName: testName"
2999 QUnit
.config
.filter
= urlParams
.filter
;
3001 // Test order randomization
3002 if (urlParams
.seed
=== true) {
3004 // Generate a random seed if the option is specified without a value
3005 QUnit
.config
.seed
= Math
.random().toString(36).slice(2);
3006 } else if (urlParams
.seed
) {
3007 QUnit
.config
.seed
= urlParams
.seed
;
3010 // Add URL-parameter-mapped config values with UI form rendering data
3011 QUnit
.config
.urlConfig
.push({
3013 label
: "Hide passed tests",
3014 tooltip
: "Only show tests and assertions that fail. Stored as query-strings."
3017 label
: "Check for Globals",
3018 tooltip
: "Enabling this will test if any test introduces new properties on the " + "global object (`window` in Browsers). Stored as query-strings."
3021 label
: "No try-catch",
3022 tooltip
: "Enabling this will run tests outside of a try-catch block. Makes debugging " + "exceptions in IE reasonable. Stored as query-strings."
3025 QUnit
.begin(function () {
3028 urlConfig
= QUnit
.config
.urlConfig
;
3030 for (i
= 0; i
< urlConfig
.length
; i
++) {
3032 // Options can be either strings or objects with nonempty "id" properties
3033 option
= QUnit
.config
.urlConfig
[i
];
3034 if (typeof option
!== "string") {
3038 if (QUnit
.config
[option
] === undefined) {
3039 QUnit
.config
[option
] = urlParams
[option
];
3044 function getUrlParams() {
3045 var i
, param
, name
, value
;
3046 var urlParams
= Object
.create(null);
3047 var params
= location
.search
.slice(1).split("&");
3048 var length
= params
.length
;
3050 for (i
= 0; i
< length
; i
++) {
3052 param
= params
[i
].split("=");
3053 name
= decodeQueryParam(param
[0]);
3055 // Allow just a key to turn on a flag, e.g., test.html?noglobals
3056 value
= param
.length
=== 1 || decodeQueryParam(param
.slice(1).join("="));
3057 if (name
in urlParams
) {
3058 urlParams
[name
] = [].concat(urlParams
[name
], value
);
3060 urlParams
[name
] = value
;
3068 function decodeQueryParam(param
) {
3069 return decodeURIComponent(param
.replace(/\+/g, "%20"));
3080 // Escape text for attribute or text content.
3081 function escapeText(s
) {
3087 // Both single quotes and double quotes (for attributes)
3088 return s
.replace(/['"<>&]/g, function (s
) {
3106 // Don't load the HTML Reporter on non-browser environments
3107 if (typeof window
=== "undefined" || !window
.document
) {
3111 var config
= QUnit
.config
,
3112 document
$$1 = window
.document
,
3113 collapseNext
= false,
3114 hasOwn
= Object
.prototype.hasOwnProperty
,
3115 unfilteredUrl
= setUrl({ filter
: undefined, module
: undefined,
3116 moduleId
: undefined, testId
: undefined }),
3119 function addEvent(elem
, type
, fn
) {
3120 elem
.addEventListener(type
, fn
, false);
3123 function removeEvent(elem
, type
, fn
) {
3124 elem
.removeEventListener(type
, fn
, false);
3127 function addEvents(elems
, type
, fn
) {
3128 var i
= elems
.length
;
3130 addEvent(elems
[i
], type
, fn
);
3134 function hasClass(elem
, name
) {
3135 return (" " + elem
.className
+ " ").indexOf(" " + name
+ " ") >= 0;
3138 function addClass(elem
, name
) {
3139 if (!hasClass(elem
, name
)) {
3140 elem
.className
+= (elem
.className
? " " : "") + name
;
3144 function toggleClass(elem
, name
, force
) {
3145 if (force
|| typeof force
=== "undefined" && !hasClass(elem
, name
)) {
3146 addClass(elem
, name
);
3148 removeClass(elem
, name
);
3152 function removeClass(elem
, name
) {
3153 var set = " " + elem
.className
+ " ";
3155 // Class name may appear multiple times
3156 while (set.indexOf(" " + name
+ " ") >= 0) {
3157 set = set.replace(" " + name
+ " ", " ");
3160 // Trim for prettiness
3161 elem
.className
= typeof set.trim
=== "function" ? set.trim() : set.replace(/^\s+|\s+$/g, "");
3165 return document
$$1.getElementById
&& document
$$1.getElementById(name
);
3168 function abortTests() {
3169 var abortButton
= id("qunit-abort-tests-button");
3171 abortButton
.disabled
= true;
3172 abortButton
.innerHTML
= "Aborting...";
3174 QUnit
.config
.queue
.length
= 0;
3178 function interceptNavigation(ev
) {
3181 if (ev
&& ev
.preventDefault
) {
3182 ev
.preventDefault();
3188 function getUrlConfigHtml() {
3195 urlConfig
= config
.urlConfig
,
3198 for (i
= 0; i
< urlConfig
.length
; i
++) {
3200 // Options can be either strings or objects with nonempty "id" properties
3201 val
= config
.urlConfig
[i
];
3202 if (typeof val
=== "string") {
3209 escaped
= escapeText(val
.id
);
3210 escapedTooltip
= escapeText(val
.tooltip
);
3212 if (!val
.value
|| typeof val
.value
=== "string") {
3213 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>";
3215 urlConfigHtml
+= "<label for='qunit-urlconfig-" + escaped
+ "' title='" + escapedTooltip
+ "'>" + val
.label
+ ": </label><select id='qunit-urlconfig-" + escaped
+ "' name='" + escaped
+ "' title='" + escapedTooltip
+ "'><option></option>";
3217 if (QUnit
.is("array", val
.value
)) {
3218 for (j
= 0; j
< val
.value
.length
; j
++) {
3219 escaped
= escapeText(val
.value
[j
]);
3220 urlConfigHtml
+= "<option value='" + escaped
+ "'" + (config
[val
.id
] === val
.value
[j
] ? (selection
= true) && " selected='selected'" : "") + ">" + escaped
+ "</option>";
3223 for (j
in val
.value
) {
3224 if (hasOwn
.call(val
.value
, j
)) {
3225 urlConfigHtml
+= "<option value='" + escapeText(j
) + "'" + (config
[val
.id
] === j
? (selection
= true) && " selected='selected'" : "") + ">" + escapeText(val
.value
[j
]) + "</option>";
3229 if (config
[val
.id
] && !selection
) {
3230 escaped
= escapeText(config
[val
.id
]);
3231 urlConfigHtml
+= "<option value='" + escaped
+ "' selected='selected' disabled='disabled'>" + escaped
+ "</option>";
3233 urlConfigHtml
+= "</select>";
3237 return urlConfigHtml
;
3240 // Handle "click" events on toolbar checkboxes and "change" for select menus.
3241 // Updates the URL with the new state of `config.urlConfig` values.
3242 function toolbarChanged() {
3249 // Detect if field is a select menu or a checkbox
3250 if ("selectedIndex" in field
) {
3251 value
= field
.options
[field
.selectedIndex
].value
|| undefined;
3253 value
= field
.checked
? field
.defaultValue
|| true : undefined;
3256 params
[field
.name
] = value
;
3257 updatedUrl
= setUrl(params
);
3259 // Check if we can apply the change without a page refresh
3260 if ("hidepassed" === field
.name
&& "replaceState" in window
.history
) {
3261 QUnit
.urlParams
[field
.name
] = value
;
3262 config
[field
.name
] = value
|| false;
3263 tests
= id("qunit-tests");
3265 toggleClass(tests
, "hidepass", value
|| false);
3267 window
.history
.replaceState(null, "", updatedUrl
);
3269 window
.location
= updatedUrl
;
3273 function setUrl(params
) {
3278 location
= window
.location
;
3280 params
= QUnit
.extend(QUnit
.extend({}, QUnit
.urlParams
), params
);
3282 for (key
in params
) {
3284 // Skip inherited or undefined properties
3285 if (hasOwn
.call(params
, key
) && params
[key
] !== undefined) {
3287 // Output a parameter for each value of this key (but usually just one)
3288 arrValue
= [].concat(params
[key
]);
3289 for (i
= 0; i
< arrValue
.length
; i
++) {
3290 querystring
+= encodeURIComponent(key
);
3291 if (arrValue
[i
] !== true) {
3292 querystring
+= "=" + encodeURIComponent(arrValue
[i
]);
3298 return location
.protocol
+ "//" + location
.host
+ location
.pathname
+ querystring
.slice(0, -1);
3301 function applyUrlParams() {
3303 selectedModules
= [],
3304 modulesList
= id("qunit-modulefilter-dropdown-list").getElementsByTagName("input"),
3305 filter
= id("qunit-filter-input").value
;
3307 for (i
= 0; i
< modulesList
.length
; i
++) {
3308 if (modulesList
[i
].checked
) {
3309 selectedModules
.push(modulesList
[i
].value
);
3313 window
.location
= setUrl({
3314 filter
: filter
=== "" ? undefined : filter
,
3315 moduleId
: selectedModules
.length
=== 0 ? undefined : selectedModules
,
3317 // Remove module and testId filter
3323 function toolbarUrlConfigContainer() {
3324 var urlConfigContainer
= document
$$1.createElement("span");
3326 urlConfigContainer
.innerHTML
= getUrlConfigHtml();
3327 addClass(urlConfigContainer
, "qunit-url-config");
3329 addEvents(urlConfigContainer
.getElementsByTagName("input"), "change", toolbarChanged
);
3330 addEvents(urlConfigContainer
.getElementsByTagName("select"), "change", toolbarChanged
);
3332 return urlConfigContainer
;
3335 function abortTestsButton() {
3336 var button
= document
$$1.createElement("button");
3337 button
.id
= "qunit-abort-tests-button";
3338 button
.innerHTML
= "Abort";
3339 addEvent(button
, "click", abortTests
);
3343 function toolbarLooseFilter() {
3344 var filter
= document
$$1.createElement("form"),
3345 label
= document
$$1.createElement("label"),
3346 input
= document
$$1.createElement("input"),
3347 button
= document
$$1.createElement("button");
3349 addClass(filter
, "qunit-filter");
3351 label
.innerHTML
= "Filter: ";
3353 input
.type
= "text";
3354 input
.value
= config
.filter
|| "";
3355 input
.name
= "filter";
3356 input
.id
= "qunit-filter-input";
3358 button
.innerHTML
= "Go";
3360 label
.appendChild(input
);
3362 filter
.appendChild(label
);
3363 filter
.appendChild(document
$$1.createTextNode(" "));
3364 filter
.appendChild(button
);
3365 addEvent(filter
, "submit", interceptNavigation
);
3370 function moduleListHtml() {
3375 for (i
= 0; i
< config
.modules
.length
; i
++) {
3376 if (config
.modules
[i
].name
!== "") {
3377 checked
= config
.moduleId
.indexOf(config
.modules
[i
].moduleId
) > -1;
3378 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>";
3385 function toolbarModuleFilter() {
3389 moduleFilter
= document
$$1.createElement("form"),
3390 label
= document
$$1.createElement("label"),
3391 moduleSearch
= document
$$1.createElement("input"),
3392 dropDown
= document
$$1.createElement("div"),
3393 actions
= document
$$1.createElement("span"),
3394 dropDownList
= document
$$1.createElement("ul"),
3397 moduleSearch
.id
= "qunit-modulefilter-search";
3398 addEvent(moduleSearch
, "input", searchInput
);
3399 addEvent(moduleSearch
, "input", searchFocus
);
3400 addEvent(moduleSearch
, "focus", searchFocus
);
3401 addEvent(moduleSearch
, "click", searchFocus
);
3403 label
.id
= "qunit-modulefilter-search-container";
3404 label
.innerHTML
= "Module: ";
3405 label
.appendChild(moduleSearch
);
3407 actions
.id
= "qunit-modulefilter-actions";
3408 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>";
3409 allCheckbox
= actions
.lastChild
.firstChild
;
3410 commit
= actions
.firstChild
;
3411 reset
= commit
.nextSibling
;
3412 addEvent(commit
, "click", applyUrlParams
);
3414 dropDownList
.id
= "qunit-modulefilter-dropdown-list";
3415 dropDownList
.innerHTML
= moduleListHtml();
3417 dropDown
.id
= "qunit-modulefilter-dropdown";
3418 dropDown
.style
.display
= "none";
3419 dropDown
.appendChild(actions
);
3420 dropDown
.appendChild(dropDownList
);
3421 addEvent(dropDown
, "change", selectionChange
);
3424 moduleFilter
.id
= "qunit-modulefilter";
3425 moduleFilter
.appendChild(label
);
3426 moduleFilter
.appendChild(dropDown
);
3427 addEvent(moduleFilter
, "submit", interceptNavigation
);
3428 addEvent(moduleFilter
, "reset", function () {
3430 // Let the reset happen, then update styles
3431 window
.setTimeout(selectionChange
);
3434 // Enables show/hide for the dropdown
3435 function searchFocus() {
3436 if (dropDown
.style
.display
!== "none") {
3440 dropDown
.style
.display
= "block";
3441 addEvent(document
$$1, "click", hideHandler
);
3442 addEvent(document
$$1, "keydown", hideHandler
);
3444 // Hide on Escape keydown or outside-container click
3445 function hideHandler(e
) {
3446 var inContainer
= moduleFilter
.contains(e
.target
);
3448 if (e
.keyCode
=== 27 || !inContainer
) {
3449 if (e
.keyCode
=== 27 && inContainer
) {
3450 moduleSearch
.focus();
3452 dropDown
.style
.display
= "none";
3453 removeEvent(document
$$1, "click", hideHandler
);
3454 removeEvent(document
$$1, "keydown", hideHandler
);
3455 moduleSearch
.value
= "";
3461 // Processes module search box input
3462 function searchInput() {
3465 searchText
= moduleSearch
.value
.toLowerCase(),
3466 listItems
= dropDownList
.children
;
3468 for (i
= 0; i
< listItems
.length
; i
++) {
3469 item
= listItems
[i
];
3470 if (!searchText
|| item
.textContent
.toLowerCase().indexOf(searchText
) > -1) {
3471 item
.style
.display
= "";
3473 item
.style
.display
= "none";
3478 // Processes selection changes
3479 function selectionChange(evt
) {
3482 checkbox
= evt
&& evt
.target
|| allCheckbox
,
3483 modulesList
= dropDownList
.getElementsByTagName("input"),
3486 toggleClass(checkbox
.parentNode
, "checked", checkbox
.checked
);
3489 if (checkbox
.checked
&& checkbox
!== allCheckbox
) {
3490 allCheckbox
.checked
= false;
3491 removeClass(allCheckbox
.parentNode
, "checked");
3493 for (i
= 0; i
< modulesList
.length
; i
++) {
3494 item
= modulesList
[i
];
3496 toggleClass(item
.parentNode
, "checked", item
.checked
);
3497 } else if (checkbox
=== allCheckbox
&& checkbox
.checked
) {
3498 item
.checked
= false;
3499 removeClass(item
.parentNode
, "checked");
3501 dirty
= dirty
|| item
.checked
!== item
.defaultChecked
;
3503 selectedNames
.push(item
.parentNode
.textContent
);
3507 commit
.style
.display
= reset
.style
.display
= dirty
? "" : "none";
3508 moduleSearch
.placeholder
= selectedNames
.join(", ") || allCheckbox
.parentNode
.textContent
;
3509 moduleSearch
.title
= "Type to filter list. Current selection:\n" + (selectedNames
.join("\n") || allCheckbox
.parentNode
.textContent
);
3512 return moduleFilter
;
3515 function appendToolbar() {
3516 var toolbar
= id("qunit-testrunner-toolbar");
3519 toolbar
.appendChild(toolbarUrlConfigContainer());
3520 toolbar
.appendChild(toolbarModuleFilter());
3521 toolbar
.appendChild(toolbarLooseFilter());
3522 toolbar
.appendChild(document
$$1.createElement("div")).className
= "clearfix";
3526 function appendHeader() {
3527 var header
= id("qunit-header");
3530 header
.innerHTML
= "<a href='" + escapeText(unfilteredUrl
) + "'>" + header
.innerHTML
+ "</a> ";
3534 function appendBanner() {
3535 var banner
= id("qunit-banner");
3538 banner
.className
= "";
3542 function appendTestResults() {
3543 var tests
= id("qunit-tests"),
3544 result
= id("qunit-testresult"),
3548 result
.parentNode
.removeChild(result
);
3552 tests
.innerHTML
= "";
3553 result
= document
$$1.createElement("p");
3554 result
.id
= "qunit-testresult";
3555 result
.className
= "result";
3556 tests
.parentNode
.insertBefore(result
, tests
);
3557 result
.innerHTML
= "<div id=\"qunit-testresult-display\">Running...<br /> </div>" + "<div id=\"qunit-testresult-controls\"></div>" + "<div class=\"clearfix\"></div>";
3558 controls
= id("qunit-testresult-controls");
3562 controls
.appendChild(abortTestsButton());
3566 function appendFilteredTest() {
3567 var testId
= QUnit
.config
.testId
;
3568 if (!testId
|| testId
.length
<= 0) {
3571 return "<div id='qunit-filteredTest'>Rerunning selected tests: " + escapeText(testId
.join(", ")) + " <a id='qunit-clearFilter' href='" + escapeText(unfilteredUrl
) + "'>Run all tests</a></div>";
3574 function appendUserAgent() {
3575 var userAgent
= id("qunit-userAgent");
3578 userAgent
.innerHTML
= "";
3579 userAgent
.appendChild(document
$$1.createTextNode("QUnit " + QUnit
.version
+ "; " + navigator
.userAgent
));
3583 function appendInterface() {
3584 var qunit
= id("qunit");
3587 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>";
3592 appendTestResults();
3597 function appendTestsList(modules
) {
3598 var i
, l
, x
, z
, test
, moduleObj
;
3600 for (i
= 0, l
= modules
.length
; i
< l
; i
++) {
3601 moduleObj
= modules
[i
];
3603 for (x
= 0, z
= moduleObj
.tests
.length
; x
< z
; x
++) {
3604 test
= moduleObj
.tests
[x
];
3606 appendTest(test
.name
, test
.testId
, moduleObj
.name
);
3611 function appendTest(name
, testId
, moduleName
) {
3616 tests
= id("qunit-tests");
3622 title
= document
$$1.createElement("strong");
3623 title
.innerHTML
= getNameHtml(name
, moduleName
);
3625 rerunTrigger
= document
$$1.createElement("a");
3626 rerunTrigger
.innerHTML
= "Rerun";
3627 rerunTrigger
.href
= setUrl({ testId
: testId
});
3629 testBlock
= document
$$1.createElement("li");
3630 testBlock
.appendChild(title
);
3631 testBlock
.appendChild(rerunTrigger
);
3632 testBlock
.id
= "qunit-test-output-" + testId
;
3634 assertList
= document
$$1.createElement("ol");
3635 assertList
.className
= "qunit-assert-list";
3637 testBlock
.appendChild(assertList
);
3639 tests
.appendChild(testBlock
);
3642 // HTML Reporter initialization and load
3643 QUnit
.begin(function (details
) {
3644 var i
, moduleObj
, tests
;
3646 // Sort modules by name for the picker
3647 for (i
= 0; i
< details
.modules
.length
; i
++) {
3648 moduleObj
= details
.modules
[i
];
3649 if (moduleObj
.name
) {
3650 modulesList
.push(moduleObj
.name
);
3653 modulesList
.sort(function (a
, b
) {
3654 return a
.localeCompare(b
);
3657 // Initialize QUnit elements
3659 appendTestsList(details
.modules
);
3660 tests
= id("qunit-tests");
3661 if (tests
&& config
.hidepassed
) {
3662 addClass(tests
, "hidepass");
3666 QUnit
.done(function (details
) {
3667 var banner
= id("qunit-banner"),
3668 tests
= id("qunit-tests"),
3669 abortButton
= id("qunit-abort-tests-button"),
3670 totalTests
= stats
.passedTests
+ stats
.skippedTests
+ stats
.todoTests
+ stats
.failedTests
,
3671 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(""),
3676 // Update remaing tests to aborted
3677 if (abortButton
&& abortButton
.disabled
) {
3678 html
= "Tests aborted after " + details
.runtime
+ " milliseconds.";
3680 for (var i
= 0; i
< tests
.children
.length
; i
++) {
3681 test
= tests
.children
[i
];
3682 if (test
.className
=== "" || test
.className
=== "running") {
3683 test
.className
= "aborted";
3684 assertList
= test
.getElementsByTagName("ol")[0];
3685 assertLi
= document
$$1.createElement("li");
3686 assertLi
.className
= "fail";
3687 assertLi
.innerHTML
= "Test aborted.";
3688 assertList
.appendChild(assertLi
);
3693 if (banner
&& (!abortButton
|| abortButton
.disabled
=== false)) {
3694 banner
.className
= stats
.failedTests
? "qunit-fail" : "qunit-pass";
3698 abortButton
.parentNode
.removeChild(abortButton
);
3702 id("qunit-testresult-display").innerHTML
= html
;
3705 if (config
.altertitle
&& document
$$1.title
) {
3707 // Show ✖ for good, ✔ for bad suite result in title
3708 // use escape sequences in case file gets loaded with non-utf-8-charset
3709 document
$$1.title
= [stats
.failedTests
? "\u2716" : "\u2714", document
$$1.title
.replace(/^[\u2714\u2716] /i, "")].join(" ");
3712 // Scroll back to top to show results
3713 if (config
.scrolltop
&& window
.scrollTo
) {
3714 window
.scrollTo(0, 0);
3718 function getNameHtml(name
, module
) {
3722 nameHtml
= "<span class='module-name'>" + escapeText(module
) + "</span>: ";
3725 nameHtml
+= "<span class='test-name'>" + escapeText(name
) + "</span>";
3730 QUnit
.testStart(function (details
) {
3731 var running
, testBlock
, bad
;
3733 testBlock
= id("qunit-test-output-" + details
.testId
);
3735 testBlock
.className
= "running";
3738 // Report later registered tests
3739 appendTest(details
.name
, details
.testId
, details
.module
);
3742 running
= id("qunit-testresult-display");
3744 bad
= QUnit
.config
.reorder
&& details
.previousFailure
;
3746 running
.innerHTML
= (bad
? "Rerunning previously failed test: <br />" : "Running: <br />") + getNameHtml(details
.name
, details
.module
);
3750 function stripHtml(string
) {
3752 // Strip tags, html entity and whitespaces
3753 return string
.replace(/<\/?[^>]+(>|$)/g, "").replace(/\"/g, "").replace(/\s+/g, "");
3756 QUnit
.log(function (details
) {
3764 testItem
= id("qunit-test-output-" + details
.testId
);
3770 message
= escapeText(details
.message
) || (details
.result
? "okay" : "failed");
3771 message
= "<span class='test-message'>" + message
+ "</span>";
3772 message
+= "<span class='runtime'>@ " + details
.runtime
+ " ms</span>";
3774 // The pushFailure doesn't provide details.expected
3775 // when it calls, it's implicit to also not show expected and diff stuff
3776 // Also, we need to check details.expected existence, as it can exist and be undefined
3777 if (!details
.result
&& hasOwn
.call(details
, "expected")) {
3778 if (details
.negative
) {
3779 expected
= "NOT " + QUnit
.dump
.parse(details
.expected
);
3781 expected
= QUnit
.dump
.parse(details
.expected
);
3784 actual
= QUnit
.dump
.parse(details
.actual
);
3785 message
+= "<table><tr class='test-expected'><th>Expected: </th><td><pre>" + escapeText(expected
) + "</pre></td></tr>";
3787 if (actual
!== expected
) {
3789 message
+= "<tr class='test-actual'><th>Result: </th><td><pre>" + escapeText(actual
) + "</pre></td></tr>";
3791 if (typeof details
.actual
=== "number" && typeof details
.expected
=== "number") {
3792 if (!isNaN(details
.actual
) && !isNaN(details
.expected
)) {
3794 diff
= details
.actual
- details
.expected
;
3795 diff
= (diff
> 0 ? "+" : "") + diff
;
3797 } else if (typeof details
.actual
!== "boolean" && typeof details
.expected
!== "boolean") {
3798 diff
= QUnit
.diff(expected
, actual
);
3800 // don't show diff if there is zero overlap
3801 showDiff
= stripHtml(diff
).length
!== stripHtml(expected
).length
+ stripHtml(actual
).length
;
3805 message
+= "<tr class='test-diff'><th>Diff: </th><td><pre>" + diff
+ "</pre></td></tr>";
3807 } else if (expected
.indexOf("[object Array]") !== -1 || expected
.indexOf("[object Object]") !== -1) {
3808 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>";
3810 message
+= "<tr class='test-message'><th>Message: </th><td>" + "Diff suppressed as the expected and actual results have an equivalent" + " serialization</td></tr>";
3813 if (details
.source
) {
3814 message
+= "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText(details
.source
) + "</pre></td></tr>";
3817 message
+= "</table>";
3819 // This occurs when pushFailure is set and we have an extracted stack trace
3820 } else if (!details
.result
&& details
.source
) {
3821 message
+= "<table>" + "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText(details
.source
) + "</pre></td></tr>" + "</table>";
3824 assertList
= testItem
.getElementsByTagName("ol")[0];
3826 assertLi
= document
$$1.createElement("li");
3827 assertLi
.className
= details
.result
? "pass" : "fail";
3828 assertLi
.innerHTML
= message
;
3829 assertList
.appendChild(assertLi
);
3832 QUnit
.testDone(function (details
) {
3842 tests
= id("qunit-tests");
3848 testItem
= id("qunit-test-output-" + details
.testId
);
3850 assertList
= testItem
.getElementsByTagName("ol")[0];
3852 good
= details
.passed
;
3853 bad
= details
.failed
;
3855 // This test passed if it has no unexpected failed assertions
3856 var testPassed
= details
.failed
> 0 ? details
.todo
: !details
.todo
;
3860 // Collapse the passing tests
3861 addClass(assertList
, "qunit-collapsed");
3862 } else if (config
.collapse
) {
3863 if (!collapseNext
) {
3865 // Skip collapsing the first failing test
3866 collapseNext
= true;
3869 // Collapse remaining tests
3870 addClass(assertList
, "qunit-collapsed");
3874 // The testItem.firstChild is the test name
3875 testTitle
= testItem
.firstChild
;
3877 testCounts
= bad
? "<b class='failed'>" + bad
+ "</b>, " + "<b class='passed'>" + good
+ "</b>, " : "";
3879 testTitle
.innerHTML
+= " <b class='counts'>(" + testCounts
+ details
.assertions
.length
+ ")</b>";
3881 if (details
.skipped
) {
3882 stats
.skippedTests
++;
3884 testItem
.className
= "skipped";
3885 skipped
= document
$$1.createElement("em");
3886 skipped
.className
= "qunit-skipped-label";
3887 skipped
.innerHTML
= "skipped";
3888 testItem
.insertBefore(skipped
, testTitle
);
3890 addEvent(testTitle
, "click", function () {
3891 toggleClass(assertList
, "qunit-collapsed");
3894 testItem
.className
= testPassed
? "pass" : "fail";
3897 var todoLabel
= document
$$1.createElement("em");
3898 todoLabel
.className
= "qunit-todo-label";
3899 todoLabel
.innerHTML
= "todo";
3900 testItem
.className
+= " todo";
3901 testItem
.insertBefore(todoLabel
, testTitle
);
3904 time
= document
$$1.createElement("span");
3905 time
.className
= "runtime";
3906 time
.innerHTML
= details
.runtime
+ " ms";
3907 testItem
.insertBefore(time
, assertList
);
3910 stats
.failedTests
++;
3911 } else if (details
.todo
) {
3914 stats
.passedTests
++;
3918 // Show the source of the test when showing assertions
3919 if (details
.source
) {
3920 sourceName
= document
$$1.createElement("p");
3921 sourceName
.innerHTML
= "<strong>Source: </strong>" + details
.source
;
3922 addClass(sourceName
, "qunit-source");
3924 addClass(sourceName
, "qunit-collapsed");
3926 addEvent(testTitle
, "click", function () {
3927 toggleClass(sourceName
, "qunit-collapsed");
3929 testItem
.appendChild(sourceName
);
3933 // Avoid readyState issue with phantomjs
3935 var notPhantom = function (p
) {
3936 return !(p
&& p
.version
&& p
.version
.major
> 0);
3939 if (notPhantom
&& document
$$1.readyState
=== "complete") {
3942 addEvent(window
, "load", QUnit
.load
);
3945 // Wrap window.onerror. We will call the original window.onerror to see if
3946 // the existing handler fully handles the error; if not, we will call the
3947 // QUnit.onError function.
3948 var originalWindowOnError
= window
.onerror
;
3950 // Cover uncaught exceptions
3951 // Returning true will suppress the default browser handler,
3952 // returning false will let it run.
3953 window
.onerror = function (message
, fileName
, lineNumber
) {
3955 if (originalWindowOnError
) {
3956 for (var _len
= arguments
.length
, args
= Array(_len
> 3 ? _len
- 3 : 0), _key
= 3; _key
< _len
; _key
++) {
3957 args
[_key
- 3] = arguments
[_key
];
3960 ret
= originalWindowOnError
.call
.apply(originalWindowOnError
, [this, message
, fileName
, lineNumber
].concat(args
));
3963 // Treat return value as window.onerror itself does,
3964 // Only do our handling if not suppressed.
3969 lineNumber
: lineNumber
3972 ret
= QUnit
.onError(error
);
3980 * This file is a modified version of google-diff-match-patch's JavaScript implementation
3981 * (https://code.google.com/p/google-diff-match-patch/source/browse/trunk/javascript/diff_match_patch_uncompressed.js),
3982 * modifications are licensed as more fully set forth in LICENSE.txt.
3984 * The original source of google-diff-match-patch is attributable and licensed as follows:
3986 * Copyright 2006 Google Inc.
3987 * https://code.google.com/p/google-diff-match-patch/
3989 * Licensed under the Apache License, Version 2.0 (the "License");
3990 * you may not use this file except in compliance with the License.
3991 * You may obtain a copy of the License at
3993 * https://www.apache.org/licenses/LICENSE-2.0
3995 * Unless required by applicable law or agreed to in writing, software
3996 * distributed under the License is distributed on an "AS IS" BASIS,
3997 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3998 * See the License for the specific language governing permissions and
3999 * limitations under the License.
4002 * https://code.google.com/p/google-diff-match-patch/
4004 * Usage: QUnit.diff(expected, actual)
4007 QUnit
.diff = function () {
4008 function DiffMatchPatch() {}
4013 * The data structure representing a diff is an array of tuples:
4014 * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
4015 * which means: delete 'Hello', add 'Goodbye' and keep ' world.'
4017 var DIFF_DELETE
= -1,
4022 * Find the differences between two texts. Simplifies the problem by stripping
4023 * any common prefix or suffix off the texts before diffing.
4024 * @param {string} text1 Old string to be diffed.
4025 * @param {string} text2 New string to be diffed.
4026 * @param {boolean=} optChecklines Optional speedup flag. If present and false,
4027 * then don't run a line-level diff first to identify the changed areas.
4028 * Defaults to true, which does a faster, slightly less optimal diff.
4029 * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
4031 DiffMatchPatch
.prototype.DiffMain = function (text1
, text2
, optChecklines
) {
4032 var deadline
, checklines
, commonlength
, commonprefix
, commonsuffix
, diffs
;
4034 // The diff must be complete in up to 1 second.
4035 deadline
= new Date().getTime() + 1000;
4037 // Check for null inputs.
4038 if (text1
=== null || text2
=== null) {
4039 throw new Error("Null input. (DiffMain)");
4042 // Check for equality (speedup).
4043 if (text1
=== text2
) {
4045 return [[DIFF_EQUAL
, text1
]];
4050 if (typeof optChecklines
=== "undefined") {
4051 optChecklines
= true;
4054 checklines
= optChecklines
;
4056 // Trim off common prefix (speedup).
4057 commonlength
= this.diffCommonPrefix(text1
, text2
);
4058 commonprefix
= text1
.substring(0, commonlength
);
4059 text1
= text1
.substring(commonlength
);
4060 text2
= text2
.substring(commonlength
);
4062 // Trim off common suffix (speedup).
4063 commonlength
= this.diffCommonSuffix(text1
, text2
);
4064 commonsuffix
= text1
.substring(text1
.length
- commonlength
);
4065 text1
= text1
.substring(0, text1
.length
- commonlength
);
4066 text2
= text2
.substring(0, text2
.length
- commonlength
);
4068 // Compute the diff on the middle block.
4069 diffs
= this.diffCompute(text1
, text2
, checklines
, deadline
);
4071 // Restore the prefix and suffix.
4073 diffs
.unshift([DIFF_EQUAL
, commonprefix
]);
4076 diffs
.push([DIFF_EQUAL
, commonsuffix
]);
4078 this.diffCleanupMerge(diffs
);
4083 * Reduce the number of edits by eliminating operationally trivial equalities.
4084 * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
4086 DiffMatchPatch
.prototype.diffCleanupEfficiency = function (diffs
) {
4087 var changes
, equalities
, equalitiesLength
, lastequality
, pointer
, preIns
, preDel
, postIns
, postDel
;
4089 equalities
= []; // Stack of indices where equalities are found.
4090 equalitiesLength
= 0; // Keeping our own length var is faster in JS.
4091 /** @type {?string} */
4092 lastequality
= null;
4094 // Always equal to diffs[equalities[equalitiesLength - 1]][1]
4095 pointer
= 0; // Index of current position.
4097 // Is there an insertion operation before the last equality.
4100 // Is there a deletion operation before the last equality.
4103 // Is there an insertion operation after the last equality.
4106 // Is there a deletion operation after the last equality.
4108 while (pointer
< diffs
.length
) {
4111 if (diffs
[pointer
][0] === DIFF_EQUAL
) {
4112 if (diffs
[pointer
][1].length
< 4 && (postIns
|| postDel
)) {
4115 equalities
[equalitiesLength
++] = pointer
;
4118 lastequality
= diffs
[pointer
][1];
4121 // Not a candidate, and can never become one.
4122 equalitiesLength
= 0;
4123 lastequality
= null;
4125 postIns
= postDel
= false;
4127 // An insertion or deletion.
4130 if (diffs
[pointer
][0] === DIFF_DELETE
) {
4137 * Five types to be split:
4138 * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
4139 * <ins>A</ins>X<ins>C</ins><del>D</del>
4140 * <ins>A</ins><del>B</del>X<ins>C</ins>
4141 * <ins>A</del>X<ins>C</ins><del>D</del>
4142 * <ins>A</ins><del>B</del>X<del>C</del>
4144 if (lastequality
&& (preIns
&& preDel
&& postIns
&& postDel
|| lastequality
.length
< 2 && preIns
+ preDel
+ postIns
+ postDel
=== 3)) {
4146 // Duplicate record.
4147 diffs
.splice(equalities
[equalitiesLength
- 1], 0, [DIFF_DELETE
, lastequality
]);
4149 // Change second copy to insert.
4150 diffs
[equalities
[equalitiesLength
- 1] + 1][0] = DIFF_INSERT
;
4151 equalitiesLength
--; // Throw away the equality we just deleted;
4152 lastequality
= null;
4153 if (preIns
&& preDel
) {
4155 // No changes made which could affect previous entry, keep going.
4156 postIns
= postDel
= true;
4157 equalitiesLength
= 0;
4159 equalitiesLength
--; // Throw away the previous equality.
4160 pointer
= equalitiesLength
> 0 ? equalities
[equalitiesLength
- 1] : -1;
4161 postIns
= postDel
= false;
4170 this.diffCleanupMerge(diffs
);
4175 * Convert a diff array into a pretty HTML report.
4176 * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
4177 * @param {integer} string to be beautified.
4178 * @return {string} HTML representation.
4180 DiffMatchPatch
.prototype.diffPrettyHtml = function (diffs
) {
4185 for (x
= 0; x
< diffs
.length
; x
++) {
4186 op
= diffs
[x
][0]; // Operation (insert, delete, equal)
4187 data
= diffs
[x
][1]; // Text of change.
4190 html
[x
] = "<ins>" + escapeText(data
) + "</ins>";
4193 html
[x
] = "<del>" + escapeText(data
) + "</del>";
4196 html
[x
] = "<span>" + escapeText(data
) + "</span>";
4200 return html
.join("");
4204 * Determine the common prefix of two strings.
4205 * @param {string} text1 First string.
4206 * @param {string} text2 Second string.
4207 * @return {number} The number of characters common to the start of each
4210 DiffMatchPatch
.prototype.diffCommonPrefix = function (text1
, text2
) {
4211 var pointermid
, pointermax
, pointermin
, pointerstart
;
4213 // Quick check for common null cases.
4214 if (!text1
|| !text2
|| text1
.charAt(0) !== text2
.charAt(0)) {
4219 // Performance analysis: https://neil.fraser.name/news/2007/10/09/
4221 pointermax
= Math
.min(text1
.length
, text2
.length
);
4222 pointermid
= pointermax
;
4224 while (pointermin
< pointermid
) {
4225 if (text1
.substring(pointerstart
, pointermid
) === text2
.substring(pointerstart
, pointermid
)) {
4226 pointermin
= pointermid
;
4227 pointerstart
= pointermin
;
4229 pointermax
= pointermid
;
4231 pointermid
= Math
.floor((pointermax
- pointermin
) / 2 + pointermin
);
4237 * Determine the common suffix of two strings.
4238 * @param {string} text1 First string.
4239 * @param {string} text2 Second string.
4240 * @return {number} The number of characters common to the end of each string.
4242 DiffMatchPatch
.prototype.diffCommonSuffix = function (text1
, text2
) {
4243 var pointermid
, pointermax
, pointermin
, pointerend
;
4245 // Quick check for common null cases.
4246 if (!text1
|| !text2
|| text1
.charAt(text1
.length
- 1) !== text2
.charAt(text2
.length
- 1)) {
4251 // Performance analysis: https://neil.fraser.name/news/2007/10/09/
4253 pointermax
= Math
.min(text1
.length
, text2
.length
);
4254 pointermid
= pointermax
;
4256 while (pointermin
< pointermid
) {
4257 if (text1
.substring(text1
.length
- pointermid
, text1
.length
- pointerend
) === text2
.substring(text2
.length
- pointermid
, text2
.length
- pointerend
)) {
4258 pointermin
= pointermid
;
4259 pointerend
= pointermin
;
4261 pointermax
= pointermid
;
4263 pointermid
= Math
.floor((pointermax
- pointermin
) / 2 + pointermin
);
4269 * Find the differences between two texts. Assumes that the texts do not
4270 * have any common prefix or suffix.
4271 * @param {string} text1 Old string to be diffed.
4272 * @param {string} text2 New string to be diffed.
4273 * @param {boolean} checklines Speedup flag. If false, then don't run a
4274 * line-level diff first to identify the changed areas.
4275 * If true, then run a faster, slightly less optimal diff.
4276 * @param {number} deadline Time when the diff should be complete by.
4277 * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
4280 DiffMatchPatch
.prototype.diffCompute = function (text1
, text2
, checklines
, deadline
) {
4281 var diffs
, longtext
, shorttext
, i
, hm
, text1A
, text2A
, text1B
, text2B
, midCommon
, diffsA
, diffsB
;
4285 // Just add some text (speedup).
4286 return [[DIFF_INSERT
, text2
]];
4291 // Just delete some text (speedup).
4292 return [[DIFF_DELETE
, text1
]];
4295 longtext
= text1
.length
> text2
.length
? text1
: text2
;
4296 shorttext
= text1
.length
> text2
.length
? text2
: text1
;
4297 i
= longtext
.indexOf(shorttext
);
4300 // Shorter text is inside the longer text (speedup).
4301 diffs
= [[DIFF_INSERT
, longtext
.substring(0, i
)], [DIFF_EQUAL
, shorttext
], [DIFF_INSERT
, longtext
.substring(i
+ shorttext
.length
)]];
4303 // Swap insertions for deletions if diff is reversed.
4304 if (text1
.length
> text2
.length
) {
4305 diffs
[0][0] = diffs
[2][0] = DIFF_DELETE
;
4310 if (shorttext
.length
=== 1) {
4312 // Single character string.
4313 // After the previous speedup, the character can't be an equality.
4314 return [[DIFF_DELETE
, text1
], [DIFF_INSERT
, text2
]];
4317 // Check to see if the problem can be split in two.
4318 hm
= this.diffHalfMatch(text1
, text2
);
4321 // A half-match was found, sort out the return data.
4328 // Send both pairs off for separate processing.
4329 diffsA
= this.DiffMain(text1A
, text2A
, checklines
, deadline
);
4330 diffsB
= this.DiffMain(text1B
, text2B
, checklines
, deadline
);
4332 // Merge the results.
4333 return diffsA
.concat([[DIFF_EQUAL
, midCommon
]], diffsB
);
4336 if (checklines
&& text1
.length
> 100 && text2
.length
> 100) {
4337 return this.diffLineMode(text1
, text2
, deadline
);
4340 return this.diffBisect(text1
, text2
, deadline
);
4344 * Do the two texts share a substring which is at least half the length of the
4346 * This speedup can produce non-minimal diffs.
4347 * @param {string} text1 First string.
4348 * @param {string} text2 Second string.
4349 * @return {Array.<string>} Five element Array, containing the prefix of
4350 * text1, the suffix of text1, the prefix of text2, the suffix of
4351 * text2 and the common middle. Or null if there was no match.
4354 DiffMatchPatch
.prototype.diffHalfMatch = function (text1
, text2
) {
4355 var longtext
, shorttext
, dmp
, text1A
, text2B
, text2A
, text1B
, midCommon
, hm1
, hm2
, hm
;
4357 longtext
= text1
.length
> text2
.length
? text1
: text2
;
4358 shorttext
= text1
.length
> text2
.length
? text2
: text1
;
4359 if (longtext
.length
< 4 || shorttext
.length
* 2 < longtext
.length
) {
4360 return null; // Pointless.
4362 dmp
= this; // 'this' becomes 'window' in a closure.
4365 * Does a substring of shorttext exist within longtext such that the substring
4366 * is at least half the length of longtext?
4367 * Closure, but does not reference any external variables.
4368 * @param {string} longtext Longer string.
4369 * @param {string} shorttext Shorter string.
4370 * @param {number} i Start index of quarter length substring within longtext.
4371 * @return {Array.<string>} Five element Array, containing the prefix of
4372 * longtext, the suffix of longtext, the prefix of shorttext, the suffix
4373 * of shorttext and the common middle. Or null if there was no match.
4376 function diffHalfMatchI(longtext
, shorttext
, i
) {
4377 var seed
, j
, bestCommon
, prefixLength
, suffixLength
, bestLongtextA
, bestLongtextB
, bestShorttextA
, bestShorttextB
;
4379 // Start with a 1/4 length substring at position i as a seed.
4380 seed
= longtext
.substring(i
, i
+ Math
.floor(longtext
.length
/ 4));
4383 while ((j
= shorttext
.indexOf(seed
, j
+ 1)) !== -1) {
4384 prefixLength
= dmp
.diffCommonPrefix(longtext
.substring(i
), shorttext
.substring(j
));
4385 suffixLength
= dmp
.diffCommonSuffix(longtext
.substring(0, i
), shorttext
.substring(0, j
));
4386 if (bestCommon
.length
< suffixLength
+ prefixLength
) {
4387 bestCommon
= shorttext
.substring(j
- suffixLength
, j
) + shorttext
.substring(j
, j
+ prefixLength
);
4388 bestLongtextA
= longtext
.substring(0, i
- suffixLength
);
4389 bestLongtextB
= longtext
.substring(i
+ prefixLength
);
4390 bestShorttextA
= shorttext
.substring(0, j
- suffixLength
);
4391 bestShorttextB
= shorttext
.substring(j
+ prefixLength
);
4394 if (bestCommon
.length
* 2 >= longtext
.length
) {
4395 return [bestLongtextA
, bestLongtextB
, bestShorttextA
, bestShorttextB
, bestCommon
];
4401 // First check if the second quarter is the seed for a half-match.
4402 hm1
= diffHalfMatchI(longtext
, shorttext
, Math
.ceil(longtext
.length
/ 4));
4404 // Check again based on the third quarter.
4405 hm2
= diffHalfMatchI(longtext
, shorttext
, Math
.ceil(longtext
.length
/ 2));
4414 // Both matched. Select the longest.
4415 hm
= hm1
[4].length
> hm2
[4].length
? hm1
: hm2
;
4418 // A half-match was found, sort out the return data.
4419 if (text1
.length
> text2
.length
) {
4431 return [text1A
, text1B
, text2A
, text2B
, midCommon
];
4435 * Do a quick line-level diff on both strings, then rediff the parts for
4437 * This speedup can produce non-minimal diffs.
4438 * @param {string} text1 Old string to be diffed.
4439 * @param {string} text2 New string to be diffed.
4440 * @param {number} deadline Time when the diff should be complete by.
4441 * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
4444 DiffMatchPatch
.prototype.diffLineMode = function (text1
, text2
, deadline
) {
4445 var a
, diffs
, linearray
, pointer
, countInsert
, countDelete
, textInsert
, textDelete
, j
;
4447 // Scan the text on a line-by-line basis first.
4448 a
= this.diffLinesToChars(text1
, text2
);
4451 linearray
= a
.lineArray
;
4453 diffs
= this.DiffMain(text1
, text2
, false, deadline
);
4455 // Convert the diff back to original text.
4456 this.diffCharsToLines(diffs
, linearray
);
4458 // Eliminate freak matches (e.g. blank lines)
4459 this.diffCleanupSemantic(diffs
);
4461 // Rediff any replacement blocks, this time character-by-character.
4462 // Add a dummy entry at the end.
4463 diffs
.push([DIFF_EQUAL
, ""]);
4469 while (pointer
< diffs
.length
) {
4470 switch (diffs
[pointer
][0]) {
4473 textInsert
+= diffs
[pointer
][1];
4477 textDelete
+= diffs
[pointer
][1];
4481 // Upon reaching an equality, check for prior redundancies.
4482 if (countDelete
>= 1 && countInsert
>= 1) {
4484 // Delete the offending records and add the merged ones.
4485 diffs
.splice(pointer
- countDelete
- countInsert
, countDelete
+ countInsert
);
4486 pointer
= pointer
- countDelete
- countInsert
;
4487 a
= this.DiffMain(textDelete
, textInsert
, false, deadline
);
4488 for (j
= a
.length
- 1; j
>= 0; j
--) {
4489 diffs
.splice(pointer
, 0, a
[j
]);
4491 pointer
= pointer
+ a
.length
;
4501 diffs
.pop(); // Remove the dummy entry at the end.
4507 * Find the 'middle snake' of a diff, split the problem in two
4508 * and return the recursively constructed diff.
4509 * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
4510 * @param {string} text1 Old string to be diffed.
4511 * @param {string} text2 New string to be diffed.
4512 * @param {number} deadline Time at which to bail if not yet complete.
4513 * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
4516 DiffMatchPatch
.prototype.diffBisect = function (text1
, text2
, deadline
) {
4517 var text1Length
, text2Length
, maxD
, vOffset
, vLength
, v1
, v2
, x
, delta
, front
, k1start
, k1end
, k2start
, k2end
, k2Offset
, k1Offset
, x1
, x2
, y1
, y2
, d
, k1
, k2
;
4519 // Cache the text lengths to prevent multiple calls.
4520 text1Length
= text1
.length
;
4521 text2Length
= text2
.length
;
4522 maxD
= Math
.ceil((text1Length
+ text2Length
) / 2);
4525 v1
= new Array(vLength
);
4526 v2
= new Array(vLength
);
4528 // Setting all elements to -1 is faster in Chrome & Firefox than mixing
4529 // integers and undefined.
4530 for (x
= 0; x
< vLength
; x
++) {
4534 v1
[vOffset
+ 1] = 0;
4535 v2
[vOffset
+ 1] = 0;
4536 delta
= text1Length
- text2Length
;
4538 // If the total number of characters is odd, then the front path will collide
4539 // with the reverse path.
4540 front
= delta
% 2 !== 0;
4542 // Offsets for start and end of k loop.
4543 // Prevents mapping of space beyond the grid.
4548 for (d
= 0; d
< maxD
; d
++) {
4550 // Bail out if deadline is reached.
4551 if (new Date().getTime() > deadline
) {
4555 // Walk the front path one step.
4556 for (k1
= -d
+ k1start
; k1
<= d
- k1end
; k1
+= 2) {
4557 k1Offset
= vOffset
+ k1
;
4558 if (k1
=== -d
|| k1
!== d
&& v1
[k1Offset
- 1] < v1
[k1Offset
+ 1]) {
4559 x1
= v1
[k1Offset
+ 1];
4561 x1
= v1
[k1Offset
- 1] + 1;
4564 while (x1
< text1Length
&& y1
< text2Length
&& text1
.charAt(x1
) === text2
.charAt(y1
)) {
4569 if (x1
> text1Length
) {
4571 // Ran off the right of the graph.
4573 } else if (y1
> text2Length
) {
4575 // Ran off the bottom of the graph.
4578 k2Offset
= vOffset
+ delta
- k1
;
4579 if (k2Offset
>= 0 && k2Offset
< vLength
&& v2
[k2Offset
] !== -1) {
4581 // Mirror x2 onto top-left coordinate system.
4582 x2
= text1Length
- v2
[k2Offset
];
4585 // Overlap detected.
4586 return this.diffBisectSplit(text1
, text2
, x1
, y1
, deadline
);
4592 // Walk the reverse path one step.
4593 for (k2
= -d
+ k2start
; k2
<= d
- k2end
; k2
+= 2) {
4594 k2Offset
= vOffset
+ k2
;
4595 if (k2
=== -d
|| k2
!== d
&& v2
[k2Offset
- 1] < v2
[k2Offset
+ 1]) {
4596 x2
= v2
[k2Offset
+ 1];
4598 x2
= v2
[k2Offset
- 1] + 1;
4601 while (x2
< text1Length
&& y2
< text2Length
&& text1
.charAt(text1Length
- x2
- 1) === text2
.charAt(text2Length
- y2
- 1)) {
4606 if (x2
> text1Length
) {
4608 // Ran off the left of the graph.
4610 } else if (y2
> text2Length
) {
4612 // Ran off the top of the graph.
4614 } else if (!front
) {
4615 k1Offset
= vOffset
+ delta
- k2
;
4616 if (k1Offset
>= 0 && k1Offset
< vLength
&& v1
[k1Offset
] !== -1) {
4618 y1
= vOffset
+ x1
- k1Offset
;
4620 // Mirror x2 onto top-left coordinate system.
4621 x2
= text1Length
- x2
;
4624 // Overlap detected.
4625 return this.diffBisectSplit(text1
, text2
, x1
, y1
, deadline
);
4632 // Diff took too long and hit the deadline or
4633 // number of diffs equals number of characters, no commonality at all.
4634 return [[DIFF_DELETE
, text1
], [DIFF_INSERT
, text2
]];
4638 * Given the location of the 'middle snake', split the diff in two parts
4640 * @param {string} text1 Old string to be diffed.
4641 * @param {string} text2 New string to be diffed.
4642 * @param {number} x Index of split point in text1.
4643 * @param {number} y Index of split point in text2.
4644 * @param {number} deadline Time at which to bail if not yet complete.
4645 * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
4648 DiffMatchPatch
.prototype.diffBisectSplit = function (text1
, text2
, x
, y
, deadline
) {
4649 var text1a
, text1b
, text2a
, text2b
, diffs
, diffsb
;
4650 text1a
= text1
.substring(0, x
);
4651 text2a
= text2
.substring(0, y
);
4652 text1b
= text1
.substring(x
);
4653 text2b
= text2
.substring(y
);
4655 // Compute both diffs serially.
4656 diffs
= this.DiffMain(text1a
, text2a
, false, deadline
);
4657 diffsb
= this.DiffMain(text1b
, text2b
, false, deadline
);
4659 return diffs
.concat(diffsb
);
4663 * Reduce the number of edits by eliminating semantically trivial equalities.
4664 * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
4666 DiffMatchPatch
.prototype.diffCleanupSemantic = function (diffs
) {
4667 var changes
, equalities
, equalitiesLength
, lastequality
, pointer
, lengthInsertions2
, lengthDeletions2
, lengthInsertions1
, lengthDeletions1
, deletion
, insertion
, overlapLength1
, overlapLength2
;
4669 equalities
= []; // Stack of indices where equalities are found.
4670 equalitiesLength
= 0; // Keeping our own length var is faster in JS.
4671 /** @type {?string} */
4672 lastequality
= null;
4674 // Always equal to diffs[equalities[equalitiesLength - 1]][1]
4675 pointer
= 0; // Index of current position.
4677 // Number of characters that changed prior to the equality.
4678 lengthInsertions1
= 0;
4679 lengthDeletions1
= 0;
4681 // Number of characters that changed after the equality.
4682 lengthInsertions2
= 0;
4683 lengthDeletions2
= 0;
4684 while (pointer
< diffs
.length
) {
4685 if (diffs
[pointer
][0] === DIFF_EQUAL
) {
4687 equalities
[equalitiesLength
++] = pointer
;
4688 lengthInsertions1
= lengthInsertions2
;
4689 lengthDeletions1
= lengthDeletions2
;
4690 lengthInsertions2
= 0;
4691 lengthDeletions2
= 0;
4692 lastequality
= diffs
[pointer
][1];
4694 // An insertion or deletion.
4695 if (diffs
[pointer
][0] === DIFF_INSERT
) {
4696 lengthInsertions2
+= diffs
[pointer
][1].length
;
4698 lengthDeletions2
+= diffs
[pointer
][1].length
;
4701 // Eliminate an equality that is smaller or equal to the edits on both
4703 if (lastequality
&& lastequality
.length
<= Math
.max(lengthInsertions1
, lengthDeletions1
) && lastequality
.length
<= Math
.max(lengthInsertions2
, lengthDeletions2
)) {
4705 // Duplicate record.
4706 diffs
.splice(equalities
[equalitiesLength
- 1], 0, [DIFF_DELETE
, lastequality
]);
4708 // Change second copy to insert.
4709 diffs
[equalities
[equalitiesLength
- 1] + 1][0] = DIFF_INSERT
;
4711 // Throw away the equality we just deleted.
4714 // Throw away the previous equality (it needs to be reevaluated).
4716 pointer
= equalitiesLength
> 0 ? equalities
[equalitiesLength
- 1] : -1;
4718 // Reset the counters.
4719 lengthInsertions1
= 0;
4720 lengthDeletions1
= 0;
4721 lengthInsertions2
= 0;
4722 lengthDeletions2
= 0;
4723 lastequality
= null;
4730 // Normalize the diff.
4732 this.diffCleanupMerge(diffs
);
4735 // Find any overlaps between deletions and insertions.
4736 // e.g: <del>abcxxx</del><ins>xxxdef</ins>
4737 // -> <del>abc</del>xxx<ins>def</ins>
4738 // e.g: <del>xxxabc</del><ins>defxxx</ins>
4739 // -> <ins>def</ins>xxx<del>abc</del>
4740 // Only extract an overlap if it is as big as the edit ahead or behind it.
4742 while (pointer
< diffs
.length
) {
4743 if (diffs
[pointer
- 1][0] === DIFF_DELETE
&& diffs
[pointer
][0] === DIFF_INSERT
) {
4744 deletion
= diffs
[pointer
- 1][1];
4745 insertion
= diffs
[pointer
][1];
4746 overlapLength1
= this.diffCommonOverlap(deletion
, insertion
);
4747 overlapLength2
= this.diffCommonOverlap(insertion
, deletion
);
4748 if (overlapLength1
>= overlapLength2
) {
4749 if (overlapLength1
>= deletion
.length
/ 2 || overlapLength1
>= insertion
.length
/ 2) {
4751 // Overlap found. Insert an equality and trim the surrounding edits.
4752 diffs
.splice(pointer
, 0, [DIFF_EQUAL
, insertion
.substring(0, overlapLength1
)]);
4753 diffs
[pointer
- 1][1] = deletion
.substring(0, deletion
.length
- overlapLength1
);
4754 diffs
[pointer
+ 1][1] = insertion
.substring(overlapLength1
);
4758 if (overlapLength2
>= deletion
.length
/ 2 || overlapLength2
>= insertion
.length
/ 2) {
4760 // Reverse overlap found.
4761 // Insert an equality and swap and trim the surrounding edits.
4762 diffs
.splice(pointer
, 0, [DIFF_EQUAL
, deletion
.substring(0, overlapLength2
)]);
4764 diffs
[pointer
- 1][0] = DIFF_INSERT
;
4765 diffs
[pointer
- 1][1] = insertion
.substring(0, insertion
.length
- overlapLength2
);
4766 diffs
[pointer
+ 1][0] = DIFF_DELETE
;
4767 diffs
[pointer
+ 1][1] = deletion
.substring(overlapLength2
);
4778 * Determine if the suffix of one string is the prefix of another.
4779 * @param {string} text1 First string.
4780 * @param {string} text2 Second string.
4781 * @return {number} The number of characters common to the end of the first
4782 * string and the start of the second string.
4785 DiffMatchPatch
.prototype.diffCommonOverlap = function (text1
, text2
) {
4786 var text1Length
, text2Length
, textLength
, best
, length
, pattern
, found
;
4788 // Cache the text lengths to prevent multiple calls.
4789 text1Length
= text1
.length
;
4790 text2Length
= text2
.length
;
4792 // Eliminate the null case.
4793 if (text1Length
=== 0 || text2Length
=== 0) {
4797 // Truncate the longer string.
4798 if (text1Length
> text2Length
) {
4799 text1
= text1
.substring(text1Length
- text2Length
);
4800 } else if (text1Length
< text2Length
) {
4801 text2
= text2
.substring(0, text1Length
);
4803 textLength
= Math
.min(text1Length
, text2Length
);
4805 // Quick check for the worst case.
4806 if (text1
=== text2
) {
4810 // Start by looking for a single character match
4811 // and increase length until no match is found.
4812 // Performance analysis: https://neil.fraser.name/news/2010/11/04/
4816 pattern
= text1
.substring(textLength
- length
);
4817 found
= text2
.indexOf(pattern
);
4822 if (found
=== 0 || text1
.substring(textLength
- length
) === text2
.substring(0, length
)) {
4830 * Split two texts into an array of strings. Reduce the texts to a string of
4831 * hashes where each Unicode character represents one line.
4832 * @param {string} text1 First string.
4833 * @param {string} text2 Second string.
4834 * @return {{chars1: string, chars2: string, lineArray: !Array.<string>}}
4835 * An object containing the encoded text1, the encoded text2 and
4836 * the array of unique strings.
4837 * The zeroth element of the array of unique strings is intentionally blank.
4840 DiffMatchPatch
.prototype.diffLinesToChars = function (text1
, text2
) {
4841 var lineArray
, lineHash
, chars1
, chars2
;
4842 lineArray
= []; // E.g. lineArray[4] === 'Hello\n'
4843 lineHash
= {}; // E.g. lineHash['Hello\n'] === 4
4845 // '\x00' is a valid character, but various debuggers don't like it.
4846 // So we'll insert a junk entry to avoid generating a null character.
4850 * Split a text into an array of strings. Reduce the texts to a string of
4851 * hashes where each Unicode character represents one line.
4852 * Modifies linearray and linehash through being a closure.
4853 * @param {string} text String to encode.
4854 * @return {string} Encoded string.
4857 function diffLinesToCharsMunge(text
) {
4858 var chars
, lineStart
, lineEnd
, lineArrayLength
, line
;
4861 // Walk the text, pulling out a substring for each line.
4862 // text.split('\n') would would temporarily double our memory footprint.
4863 // Modifying text would create many large strings to garbage collect.
4867 // Keeping our own length variable is faster than looking it up.
4868 lineArrayLength
= lineArray
.length
;
4869 while (lineEnd
< text
.length
- 1) {
4870 lineEnd
= text
.indexOf("\n", lineStart
);
4871 if (lineEnd
=== -1) {
4872 lineEnd
= text
.length
- 1;
4874 line
= text
.substring(lineStart
, lineEnd
+ 1);
4875 lineStart
= lineEnd
+ 1;
4877 if (lineHash
.hasOwnProperty
? lineHash
.hasOwnProperty(line
) : lineHash
[line
] !== undefined) {
4878 chars
+= String
.fromCharCode(lineHash
[line
]);
4880 chars
+= String
.fromCharCode(lineArrayLength
);
4881 lineHash
[line
] = lineArrayLength
;
4882 lineArray
[lineArrayLength
++] = line
;
4888 chars1
= diffLinesToCharsMunge(text1
);
4889 chars2
= diffLinesToCharsMunge(text2
);
4893 lineArray
: lineArray
4898 * Rehydrate the text in a diff from a string of line hashes to real lines of
4900 * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
4901 * @param {!Array.<string>} lineArray Array of unique strings.
4904 DiffMatchPatch
.prototype.diffCharsToLines = function (diffs
, lineArray
) {
4905 var x
, chars
, text
, y
;
4906 for (x
= 0; x
< diffs
.length
; x
++) {
4907 chars
= diffs
[x
][1];
4909 for (y
= 0; y
< chars
.length
; y
++) {
4910 text
[y
] = lineArray
[chars
.charCodeAt(y
)];
4912 diffs
[x
][1] = text
.join("");
4917 * Reorder and merge like edit sections. Merge equalities.
4918 * Any edit section can move as long as it doesn't cross an equality.
4919 * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
4921 DiffMatchPatch
.prototype.diffCleanupMerge = function (diffs
) {
4922 var pointer
, countDelete
, countInsert
, textInsert
, textDelete
, commonlength
, changes
, diffPointer
, position
;
4923 diffs
.push([DIFF_EQUAL
, ""]); // Add a dummy entry at the end.
4930 while (pointer
< diffs
.length
) {
4931 switch (diffs
[pointer
][0]) {
4934 textInsert
+= diffs
[pointer
][1];
4939 textDelete
+= diffs
[pointer
][1];
4944 // Upon reaching an equality, check for prior redundancies.
4945 if (countDelete
+ countInsert
> 1) {
4946 if (countDelete
!== 0 && countInsert
!== 0) {
4948 // Factor out any common prefixes.
4949 commonlength
= this.diffCommonPrefix(textInsert
, textDelete
);
4950 if (commonlength
!== 0) {
4951 if (pointer
- countDelete
- countInsert
> 0 && diffs
[pointer
- countDelete
- countInsert
- 1][0] === DIFF_EQUAL
) {
4952 diffs
[pointer
- countDelete
- countInsert
- 1][1] += textInsert
.substring(0, commonlength
);
4954 diffs
.splice(0, 0, [DIFF_EQUAL
, textInsert
.substring(0, commonlength
)]);
4957 textInsert
= textInsert
.substring(commonlength
);
4958 textDelete
= textDelete
.substring(commonlength
);
4961 // Factor out any common suffixies.
4962 commonlength
= this.diffCommonSuffix(textInsert
, textDelete
);
4963 if (commonlength
!== 0) {
4964 diffs
[pointer
][1] = textInsert
.substring(textInsert
.length
- commonlength
) + diffs
[pointer
][1];
4965 textInsert
= textInsert
.substring(0, textInsert
.length
- commonlength
);
4966 textDelete
= textDelete
.substring(0, textDelete
.length
- commonlength
);
4970 // Delete the offending records and add the merged ones.
4971 if (countDelete
=== 0) {
4972 diffs
.splice(pointer
- countInsert
, countDelete
+ countInsert
, [DIFF_INSERT
, textInsert
]);
4973 } else if (countInsert
=== 0) {
4974 diffs
.splice(pointer
- countDelete
, countDelete
+ countInsert
, [DIFF_DELETE
, textDelete
]);
4976 diffs
.splice(pointer
- countDelete
- countInsert
, countDelete
+ countInsert
, [DIFF_DELETE
, textDelete
], [DIFF_INSERT
, textInsert
]);
4978 pointer
= pointer
- countDelete
- countInsert
+ (countDelete
? 1 : 0) + (countInsert
? 1 : 0) + 1;
4979 } else if (pointer
!== 0 && diffs
[pointer
- 1][0] === DIFF_EQUAL
) {
4981 // Merge this equality with the previous one.
4982 diffs
[pointer
- 1][1] += diffs
[pointer
][1];
4983 diffs
.splice(pointer
, 1);
4994 if (diffs
[diffs
.length
- 1][1] === "") {
4995 diffs
.pop(); // Remove the dummy entry at the end.
4998 // Second pass: look for single edits surrounded on both sides by equalities
4999 // which can be shifted sideways to eliminate an equality.
5000 // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
5004 // Intentionally ignore the first and last element (don't need checking).
5005 while (pointer
< diffs
.length
- 1) {
5006 if (diffs
[pointer
- 1][0] === DIFF_EQUAL
&& diffs
[pointer
+ 1][0] === DIFF_EQUAL
) {
5008 diffPointer
= diffs
[pointer
][1];
5009 position
= diffPointer
.substring(diffPointer
.length
- diffs
[pointer
- 1][1].length
);
5011 // This is a single edit surrounded by equalities.
5012 if (position
=== diffs
[pointer
- 1][1]) {
5014 // Shift the edit over the previous equality.
5015 diffs
[pointer
][1] = diffs
[pointer
- 1][1] + diffs
[pointer
][1].substring(0, diffs
[pointer
][1].length
- diffs
[pointer
- 1][1].length
);
5016 diffs
[pointer
+ 1][1] = diffs
[pointer
- 1][1] + diffs
[pointer
+ 1][1];
5017 diffs
.splice(pointer
- 1, 1);
5019 } else if (diffPointer
.substring(0, diffs
[pointer
+ 1][1].length
) === diffs
[pointer
+ 1][1]) {
5021 // Shift the edit over the next equality.
5022 diffs
[pointer
- 1][1] += diffs
[pointer
+ 1][1];
5023 diffs
[pointer
][1] = diffs
[pointer
][1].substring(diffs
[pointer
+ 1][1].length
) + diffs
[pointer
+ 1][1];
5024 diffs
.splice(pointer
+ 1, 1);
5031 // If shifts were made, the diff needs reordering and another shift sweep.
5033 this.diffCleanupMerge(diffs
);
5037 return function (o
, n
) {
5038 var diff
, output
, text
;
5039 diff
= new DiffMatchPatch();
5040 output
= diff
.DiffMain(o
, n
);
5041 diff
.diffCleanupEfficiency(output
);
5042 text
= diff
.diffPrettyHtml(output
);
5048 }((function() { return this; }())));