New Upstream Snapshot - node-seedrandom
Ready changes
Summary
Merged new upstream version: 3.0.5+ds (was: 2.4.4+dfsg+~2.4.30).
Resulting package
Built on 2023-01-06T15:20 (took 3m30s)
The resulting binary packages can be installed (if you have the apt repository enabled) by running one of:
apt install -t fresh-snapshots node-seedrandom
Diff
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..6852ab1
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,8 @@
+language: node_js
+sudo: false
+node_js:
+- '7'
+- '8'
+- '9'
+- '10'
+- '11'
diff --git a/Gruntfile.js b/Gruntfile.js
index 554f356..41585ec 100644
--- a/Gruntfile.js
+++ b/Gruntfile.js
@@ -3,19 +3,14 @@ module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
- bowercopy: {
- options: {
- clean: true
- },
- test: {
- options: {
- destPrefix: "test/lib"
- },
- files: {
- "qunit.js" : "qunit/qunit/qunit.js",
- "qunit.css" : "qunit/qunit/qunit.css",
- "require.js" : "requirejs/require.js"
- }
+ copy: {
+ browsertest: {
+ files: [
+ { expand: true, cwd: 'node_modules/qunit/qunit', src: 'qunit.*' ,
+ dest: 'test/lib'},
+ { expand: true, cwd: 'node_modules/requirejs', src: 'require.js',
+ dest: 'test/lib'}
+ ],
}
},
uglify: {
@@ -66,22 +61,14 @@ module.exports = function(grunt) {
}
}
},
- mochacov: {
- options: {
- files: [
- 'test/cryptotest.js',
- 'test/nodetest.js',
- 'test/prngtest.js'
- ]
- },
+ mocha_nyc: {
coverage: {
- options: {
- coveralls: true
- }
+ src: 'test/*test.js'
},
- test: {
+ coveralls: {
+ src: 'test/*test.js',
options: {
- reporter: 'dot'
+ coverage: true
}
}
},
@@ -92,17 +79,19 @@ module.exports = function(grunt) {
}
});
- grunt.loadNpmTasks('grunt-bowercopy');
+ grunt.event.on('coverage', require('coveralls').handleInput);
+
+ grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.loadNpmTasks('grunt-contrib-uglify');
- grunt.loadNpmTasks('grunt-mocha-cov');
+ grunt.loadNpmTasks('grunt-mocha-nyc');
grunt.loadNpmTasks('grunt-release');
grunt.loadNpmTasks('grunt-browserify');
- grunt.registerTask("test",
- ["browserify", "connect", "qunit", "mochacov:test"]);
+ grunt.registerTask("test", ["copy:browsertest", "browserify",
+ "connect", "qunit", "mocha_nyc:coverage"]);
grunt.registerTask("default", ["uglify", "test"]);
- grunt.registerTask("travis", ["default", "mochacov:coverage"]);
+ grunt.registerTask("travis", ["default", "mocha_nyc:coveralls"]);
};
diff --git a/README.md b/README.md
index 580bed7..9518915 100644
--- a/README.md
+++ b/README.md
@@ -6,11 +6,11 @@ seedrandom.js
Seeded random number generator for JavaScript.
-Version 2.4.4
+Version 3.0.5
Author: David Bau
-Date: 2018-08-14
+Date: 2019-09-14
Can be used as a plain script, a Node.js module or an AMD module.
@@ -19,38 +19,52 @@ Script tag usage
----------------
```html
-<script src="//cdnjs.cloudflare.com/ajax/libs/seedrandom/2.4.4/seedrandom.min.js">
+<script src="//cdnjs.cloudflare.com/ajax/libs/seedrandom/3.0.5/seedrandom.min.js">
</script>
```
```js
-// Sets Math.random to a PRNG initialized using the given explicit seed.
-Math.seedrandom('hello.');
-console.log(Math.random()); // Always 0.9282578795792454
-console.log(Math.random()); // Always 0.3752569768646784
-
-// Sets Math.random to an ARC4-based PRNG that is autoseeded using the
-// current time, dom state, and other accumulated local entropy.
-// The generated seed string is returned.
-Math.seedrandom();
-console.log(Math.random()); // Reasonably unpredictable.
-
-// Seeds using the given explicit seed mixed with accumulated entropy.
-Math.seedrandom('added entropy.', { entropy: true });
-console.log(Math.random()); // As unpredictable as added entropy.
-
-// Use "new" to create a local prng without altering Math.random.
+// Make a predictable pseudorandom number generator.
var myrng = new Math.seedrandom('hello.');
console.log(myrng()); // Always 0.9282578795792454
+console.log(myrng()); // Always 0.3752569768646784
// Use "quick" to get only 32 bits of randomness in a float.
-console.log(myrng.quick()); // Always 0.3752569768112153
+console.log(myrng.quick()); // Always 0.7316977467853576
// Use "int32" to get a 32 bit (signed) integer
-console.log(myrng.int32()); // Always 986220731
+console.log(myrng.int32()); // Always 1966374204
+
+// Calling seedrandom with no arguments creates an ARC4-based PRNG
+// that is autoseeded using the current time, dom state, and other
+// accumulated local entropy.
+var prng = new Math.seedrandom();
+console.log(prng()); // Reasonably unpredictable.
+
+// Seeds using the given explicit seed mixed with accumulated entropy.
+prng = new Math.seedrandom('added entropy.', { entropy: true });
+console.log(prng()); // As unpredictable as added entropy.
+
+// Warning: if you call Math.seedrandom without `new`, it replaces
+// Math.random with the predictable new Math.seedrandom(...), as follows:
+Math.seedrandom('hello.');
+console.log(Math.random()); // Always 0.9282578795792454
+console.log(Math.random()); // Always 0.3752569768646784
```
+**Note**: calling `Math.seedrandom('constant')` without `new` will make
+`Math.random()` predictable globally, which is intended to be useful for
+derandomizing code for testing, but should not be done in a production library.
+If you need a local seeded PRNG, use `myrng = new Math.seedrandom('seed')`
+instead. For example, [cryptico](https://www.npmjs.com/package/cryptico),
+an RSA encryption package, [uses the wrong form](
+https://github.com/wwwtyro/cryptico/blob/9291ece6/api.js#L264),
+and thus secretly makes `Math.random()` perfectly predictable.
+The cryptico library (and any other library that does this)
+should not be trusted in a security-sensitive application.
+
+
Other Fast PRNG Algorithms
--------------------------
@@ -59,7 +73,7 @@ extremely fast Alea PRNG:
```html
-<script src="//cdnjs.cloudflare.com/ajax/libs/seedrandom/2.4.4/lib/alea.min.js">
+<script src="//cdnjs.cloudflare.com/ajax/libs/seedrandom/3.0.5/lib/alea.min.js">
</script>
```
@@ -97,8 +111,8 @@ instance. `quick` is just the 32-bit version of the RC4-based PRNG
originally packaged with seedrandom.)
-Node.js usage
--------------
+CJS / Node.js usage
+-------------------
```
npm install seedrandom
@@ -127,6 +141,9 @@ var rng2 = seedrandom.xor4096('hello.')
console.log(rng2());
```
+Starting in version 3, when using via require('seedrandom'), the global
+`Math.seedrandom` is no longer available.
+
Require.js usage
----------------
@@ -149,7 +166,7 @@ Network seeding
---------------
```html
-<script src=//cdnjs.cloudflare.com/ajax/libs/seedrandom/2.4.4/seedrandom.min.js>
+<script src=//cdnjs.cloudflare.com/ajax/libs/seedrandom/3.0.5/seedrandom.min.js>
</script>
<!-- Seeds using urandom bits from a server. -->
<script src=//jsonlib.appspot.com/urandom?callback=Math.seedrandom>
@@ -242,6 +259,9 @@ The random number sequence is the same as version 1.0 for string seeds.
* Version 2.4.2 adds an implementation of Baagoe's very fast Alea PRNG.
* Version 2.4.3 ignores nodejs crypto when under browserify.
* Version 2.4.4 avoids strict mode problem with global this reference.
+* Version 3.0.1 removes Math.seedrandom for require('seedrandom') users.
+* Version 3.0.3 updates package.json for CDN entrypoints.
+* Version 3.0.5 removes eval to avoid triggering content-security policy.
The standard ARC4 key scheduler cycles short keys, which means that
seedrandom('ab') is equivalent to seedrandom('abab') and 'ababab'.
@@ -279,7 +299,7 @@ numbers on Opera at about 0.0005 ms per seeded Math.random().
LICENSE (MIT)
-------------
-Copyright 2018 David Bau.
+Copyright 2019 David Bau.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
diff --git a/component.json b/component.json
index 1a6b3da..43fea29 100644
--- a/component.json
+++ b/component.json
@@ -1,6 +1,6 @@
{
"name": "seedrandom",
- "version": "2.4.4",
+ "version": "3.0.0",
"description": "Seeded random number generator for Javascript",
"repository": "davidbau/seedrandom",
"main": "seedrandom.js",
diff --git a/debian/changelog b/debian/changelog
index 56ed86b..d7e66cc 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,8 +1,9 @@
-node-seedrandom (2.4.4+dfsg+~2.4.30-2) UNRELEASED; urgency=medium
+node-seedrandom (3.0.5+ds-1) UNRELEASED; urgency=medium
* Update standards version to 4.6.2, no changes needed.
+ * New upstream release.
- -- Debian Janitor <janitor@jelmer.uk> Fri, 06 Jan 2023 11:18:27 -0000
+ -- Debian Janitor <janitor@jelmer.uk> Fri, 06 Jan 2023 15:17:56 -0000
node-seedrandom (2.4.4+dfsg+~2.4.30-1) unstable; urgency=medium
diff --git a/lib/alea.js b/lib/alea.js
index f912ffd..478b956 100644
--- a/lib/alea.js
+++ b/lib/alea.js
@@ -11,10 +11,10 @@
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
-//
+//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
-//
+//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -79,7 +79,7 @@ function Mash() {
var n = 0xefc8249d;
var mash = function(data) {
- data = data.toString();
+ data = String(data);
for (var i = 0; i < data.length; i++) {
n += data.charCodeAt(i);
var h = 0.02519603282416938 * n;
diff --git a/package.json b/package.json
index 52c34c2..86aad13 100644
--- a/package.json
+++ b/package.json
@@ -1,9 +1,10 @@
{
"name": "seedrandom",
-
- "version": "2.4.4",
+ "version": "3.0.5",
"description": "Seeded random number generator for Javascript.",
"main": "index.js",
+ "jsdelivr": "seedrandom.min.js",
+ "unpkg": "seedrandom.min.js",
"keywords": [
"seed",
"random",
@@ -40,17 +41,20 @@
},
"devDependencies": {
"blanket": "latest",
+ "coveralls": "latest",
"grunt": "latest",
- "grunt-bowercopy": "latest",
"grunt-browserify": "latest",
+ "grunt-release": "davidbau/grunt-release",
"grunt-cli": "latest",
"grunt-contrib-connect": "latest",
+ "grunt-contrib-copy": "latest",
"grunt-contrib-qunit": "latest",
"grunt-contrib-uglify": "latest",
- "grunt-mocha-cov": "latest",
- "grunt-release": "latest",
- "phantomjs-prebuilt": "latest",
+ "grunt-mocha-nyc": "latest",
+ "mocha": "latest",
+ "nyc": "latest",
"proxyquire": "latest",
+ "qunit": "latest",
"requirejs": "latest"
}
}
diff --git a/seedrandom.js b/seedrandom.js
index a9e1024..12d7ee1 100644
--- a/seedrandom.js
+++ b/seedrandom.js
@@ -1,5 +1,5 @@
/*
-Copyright 2014 David Bau.
+Copyright 2019 David Bau.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
@@ -22,15 +22,12 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
-(function (pool, math) {
+(function (global, pool, math) {
//
// The following constants are related to IEEE 754 limits.
//
-// Detect the global object, even if operating in strict mode.
-// http://stackoverflow.com/a/14387057/265298
-var global = (0, eval)('this'),
- width = 256, // each RC4 output is 0 <= x < 256
+var width = 256, // each RC4 output is 0 <= x < 256
chunks = 6, // at least six RC4 outputs for each double
digits = 52, // there are 52 significant digits in a double
rngname = 'random', // rngname: name for Math.random and Math.seedrandom
@@ -105,7 +102,6 @@ function seedrandom(seed, options, callback) {
'global' in options ? options.global : (this == math),
options.state);
}
-math['seed' + rngname] = seedrandom;
//
// ARC4
@@ -241,10 +237,17 @@ if ((typeof module) == 'object' && module.exports) {
} catch (ex) {}
} else if ((typeof define) == 'function' && define.amd) {
define(function() { return seedrandom; });
+} else {
+ // When included as a plain script, set up Math.seedrandom global.
+ math['seed' + rngname] = seedrandom;
}
+
// End anonymous scope, and pass initial values.
})(
+ // global: `self` in browsers (including strict mode and web workers),
+ // otherwise `this` in Node and other environments
+ (typeof self !== 'undefined') ? self : this,
[], // pool: entropy pool starts empty
Math // math: package containing random, pow, and seedrandom
);
diff --git a/test/altprng.html b/test/altprng.html
deleted file mode 100644
index 781679b..0000000
--- a/test/altprng.html
+++ /dev/null
@@ -1,30 +0,0 @@
-<html>
-<head>
-<link rel="stylesheet" href="lib/qunit.css">
-</head>
-<body>
-<div id="qunit"></div>
-<div id="qunit-fixture"></div>
-<script src="../lib/xor4096.min.js"></script>
-<script src="lib/qunit.js"></script>
-<script>
-QUnit.module("Alternative PRNG Test");
-
-QUnit.test("Verify that we can use xor4096", function(assert) {
-// Use xor4096 for Richard Brent's xorgens-4096 algorithm.
-var xorgen = new xor4096('hello.');
-
-// By default provides 32 bits of randomness in a float.
-assert.equal(xorgen(), 0.9798525865189731);
-
-// Use "double" to get 56 bits of randomness.
-assert.equal(xorgen.double(), 0.03583478477375346);
-
-// Use "int32" to get a 32 bit (signed) integer.
-assert.equal(xorgen.int32(), 1341429986);
-
-});
-</script>
-</html>
-
-
diff --git a/test/autoseed.html b/test/autoseed.html
deleted file mode 100644
index 2738f24..0000000
--- a/test/autoseed.html
+++ /dev/null
@@ -1,46 +0,0 @@
-<html>
-<head>
-<link rel="stylesheet" href="lib/qunit.css">
-</head>
-<body>
-<div id="qunit"></div>
-<div id="qunit-fixture"></div>
-<script src="lib/qunit.js"></script>
-<script src="../seedrandom.js"></script>
-<script>
-QUnit.module("Simple Test");
-
-QUnit.test("Check that we can reproduce a seed", function(assert) {
- var seed;
- var time = new Date().getTime();
- var seediter = 50;
- for (var k = 0; k < seediter; ++k) {
- seed = Math.seedrandom();
- }
- var seedtime = (new Date().getTime() - time) / seediter;
-
- time = new Date().getTime();
- var vals = [];
- var iters = 1000;
- var j;
- for (j = 0; j < iters; ++j) {
- var saw = Math.random();
- vals.push(saw);
- }
- time = new Date().getTime() - time;
- var errors = 0;
- Math.seedrandom(seed);
- for (j = 0; j < vals.length; ++j) {
- var saw = vals[j];
- var got = Math.random();
- assert.equal(saw, got, saw + " vs " + got);
- }
-
- assert.ok(true, '' +
- 'Seeding took ' + seedtime + ' ms per seedrandom' +
- ' in ' + time + ' ms for ' + iters +
- ' calls, ' + (time / iters) + ' ms per random()' + '');
-});
-</script>
-</body>
-</html>
diff --git a/test/bitgen.js b/test/bitgen.js
deleted file mode 100755
index c3563d5..0000000
--- a/test/bitgen.js
+++ /dev/null
@@ -1,45 +0,0 @@
-#!/usr/bin/env node
-var seedrandom = require('../seedrandom');
-
-// process.on('SIGPIPE', process.exit);
-function epipeBomb(stream, callback) {
- if (stream == null) stream = process.stdout;
- if (callback == null) callback = process.exit;
-
- function epipeFilter(err) {
- if (err.code === 'EPIPE') return callback();
-
- // If there's more than one error handler (ie, us),
- // then the error won't be bubbled up anyway
- if (stream.listeners('error').length <= 1) {
- stream.removeAllListeners(); // Pretend we were never here
- stream.emit('error', err); // Then emit as if we were never here
- stream.on('error', epipeFilter);// Reattach, ready for the next error!
- }
- }
-
- stream.on('error', epipeFilter);
-}
-
-epipeBomb();
-
-var bufsize = 1024 * 256,
- buf = new Buffer(bufsize * 4),
- prng = seedrandom(0),
- count = parseInt(process.argv[2]) || Infinity;
-function dowrite() {
- while (count > 0) {
- for (var j = 0; j < bufsize; ++j) {
- buf.writeUInt32BE(Math.floor(
- prng() * 256 * 256 * 256 * 256
- ), j * 4);
- }
- count -= bufsize * 32;
- if (!process.stdout.write(buf)) {
- process.stdout.once('drain', function() { setTimeout(dowrite, 0) });
- return;
- }
- }
-}
-
-dowrite();
diff --git a/test/browserified.html b/test/browserified.html
deleted file mode 100644
index 724654e..0000000
--- a/test/browserified.html
+++ /dev/null
@@ -1,23 +0,0 @@
-<html>
-<head>
-<link rel="stylesheet" href="lib/qunit.css">
-</head>
-<body>
-<div id="qunit"></div>
-<div id="qunit-fixture"></div>
-<script src="lib/qunit.js"></script>
-<script>
-function describe(name, fn) {
- QUnit.module(name);
- fn();
-}
-function it(desc, fn) {
- QUnit.test(desc, function(a) {
- fn();
- a.ok(true);
- });
-}
-</script>
-<script src="browserified.js"></script>
-</body>
-</html>
diff --git a/test/cryptotest.js b/test/cryptotest.js
deleted file mode 100644
index 1686e59..0000000
--- a/test/cryptotest.js
+++ /dev/null
@@ -1,57 +0,0 @@
-var proxyquire = require('proxyquire');
-var assert = require("assert");
-var Module = require("module");
-
-describe("Crypto API Test", function() {
-
-var crypto_stub = {};
-var original = Math.random;
-var rng, r;
-
-// Load seedrandom in absence of any crypto package.
-it("should be able to seed without crypto", function() {
- var noncrypto_sr = proxyquire('../seedrandom', { crypto: null });
- rng = noncrypto_sr('hello.');
- assert.equal(typeof(rng), 'function', "Should return a function.");
- r = rng();
- assert.equal(r, 0.9282578795792454, "Should be 'hello.'#1");
- assert(original === Math.random, "Should not change Math.random.");
- assert(original !== rng, "PRNG should not be Math.random.");
- var noncrypto_sr = proxyquire('../seedrandom', { crypto: null });
- result = noncrypto_sr();
- assert.equal(typeof(result), 'function', "Should return function.");
- assert(original === Math.random, "Should not change Math.random.");
- r = result();
- assert(r != 0.9282578795792454, "Should not be 'hello.'#1");
- assert(r != 0.7316977468919549, "Should not be 'hello.'#3");
- assert(r != 0.23144008215179881, "Should not be '\\0'#1");
- assert(r != 0.7220382488550928, "Should not be '\\1'#1");
- // Recache original seedrandom.
- proxyquire('../seedrandom', {});
-});
-
-// Load seedrandom with zeroed-out crypto package.
-it("should be able to seed ('hello.') with zero crypto", function() {
- var zerocrypto_sr = proxyquire('../seedrandom', {
- crypto: { randomBytes: function(n) {
- result = []; while (n-- > 0) { result.push(1); } return result; } }
- });
- rng = zerocrypto_sr('hello.');
- assert.equal(typeof(rng), 'function', "Should return a function.");
- r = rng();
- assert.equal(r, 0.9282578795792454 , "Should be 'hello.'#1");
- assert(original === Math.random, "Should not change Math.random.");
- assert(original !== rng, "PRNG should not be Math.random.");
- rng = zerocrypto_sr();
- assert.equal(typeof(rng), 'function', "Should return function.");
- assert(original === Math.random, "Should not change Math.random.");
- r = rng();
- assert.equal(r, 0.7220382488550928, "Should be '\\1'#1");
- r = rng();
- assert.equal(r, 0.0259971860493045, "Should be '\\1'#2");
- // Recache original seedrandom.
- proxyquire('../seedrandom', {});
-});
-
-
-});
diff --git a/test/lib/qunit.css b/test/lib/qunit.css
deleted file mode 100644
index 593a65f..0000000
--- a/test/lib/qunit.css
+++ /dev/null
@@ -1,415 +0,0 @@
-/*!
- * QUnit 2.1.0
- * https://qunitjs.com/
- *
- * Copyright jQuery Foundation and other contributors
- * Released under the MIT license
- * https://jquery.org/license
- *
- * Date: 2016-12-06T04:45Z
- */
-
-/** Font Family and Sizes */
-
-#qunit-tests, #qunit-header, #qunit-banner, #qunit-testrunner-toolbar, #qunit-filteredTest, #qunit-userAgent, #qunit-testresult {
- font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial, sans-serif;
-}
-
-#qunit-testrunner-toolbar, #qunit-filteredTest, #qunit-userAgent, #qunit-testresult, #qunit-tests li { font-size: small; }
-#qunit-tests { font-size: smaller; }
-
-
-/** Resets */
-
-#qunit-tests, #qunit-header, #qunit-banner, #qunit-filteredTest, #qunit-userAgent, #qunit-testresult, #qunit-modulefilter {
- margin: 0;
- padding: 0;
-}
-
-
-/** Header (excluding toolbar) */
-
-#qunit-header {
- padding: 0.5em 0 0.5em 1em;
-
- color: #8699A4;
- background-color: #0D3349;
-
- font-size: 1.5em;
- line-height: 1em;
- font-weight: 400;
-
- border-radius: 5px 5px 0 0;
-}
-
-#qunit-header a {
- text-decoration: none;
- color: #C2CCD1;
-}
-
-#qunit-header a:hover,
-#qunit-header a:focus {
- color: #FFF;
-}
-
-#qunit-banner {
- height: 5px;
-}
-
-#qunit-filteredTest {
- padding: 0.5em 1em 0.5em 1em;
- color: #366097;
- background-color: #F4FF77;
-}
-
-#qunit-userAgent {
- padding: 0.5em 1em 0.5em 1em;
- color: #FFF;
- background-color: #2B81AF;
- text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px;
-}
-
-
-/** Toolbar */
-
-#qunit-testrunner-toolbar {
- padding: 0.5em 1em 0.5em 1em;
- color: #5E740B;
- background-color: #EEE;
-}
-
-#qunit-testrunner-toolbar .clearfix {
- height: 0;
- clear: both;
-}
-
-#qunit-testrunner-toolbar label {
- display: inline-block;
-}
-
-#qunit-testrunner-toolbar input[type=checkbox],
-#qunit-testrunner-toolbar input[type=radio] {
- margin: 3px;
- vertical-align: -2px;
-}
-
-#qunit-testrunner-toolbar input[type=text] {
- box-sizing: border-box;
- height: 1.6em;
-}
-
-.qunit-url-config,
-.qunit-filter,
-#qunit-modulefilter {
- display: inline-block;
- line-height: 2.1em;
-}
-
-.qunit-filter,
-#qunit-modulefilter {
- float: right;
- position: relative;
- margin-left: 1em;
-}
-
-.qunit-url-config label {
- margin-right: 0.5em;
-}
-
-#qunit-modulefilter-search {
- box-sizing: border-box;
- width: 400px;
-}
-
-#qunit-modulefilter-search-container:after {
- position: absolute;
- right: 0.3em;
- content: "\25bc";
- color: black;
-}
-
-#qunit-modulefilter-dropdown {
- /* align with #qunit-modulefilter-search */
- box-sizing: border-box;
- width: 400px;
- position: absolute;
- right: 0;
- top: 50%;
- margin-top: 0.8em;
-
- border: 1px solid #D3D3D3;
- border-top: none;
- border-radius: 0 0 .25em .25em;
- color: #000;
- background-color: #F5F5F5;
- z-index: 99;
-}
-
-#qunit-modulefilter-dropdown a {
- color: inherit;
- text-decoration: none;
-}
-
-#qunit-modulefilter-dropdown .clickable.checked {
- font-weight: bold;
- color: #000;
- background-color: #D2E0E6;
-}
-
-#qunit-modulefilter-dropdown .clickable:hover {
- color: #FFF;
- background-color: #0D3349;
-}
-
-#qunit-modulefilter-actions {
- display: block;
- overflow: auto;
-
- /* align with #qunit-modulefilter-dropdown-list */
- font: smaller/1.5em sans-serif;
-}
-
-#qunit-modulefilter-dropdown #qunit-modulefilter-actions > * {
- box-sizing: border-box;
- max-height: 2.8em;
- display: block;
- padding: 0.4em;
-}
-
-#qunit-modulefilter-dropdown #qunit-modulefilter-actions > button {
- float: right;
- font: inherit;
-}
-
-#qunit-modulefilter-dropdown #qunit-modulefilter-actions > :last-child {
- /* insert padding to align with checkbox margins */
- padding-left: 3px;
-}
-
-#qunit-modulefilter-dropdown-list {
- max-height: 200px;
- overflow-y: auto;
- margin: 0;
- border-top: 2px groove threedhighlight;
- padding: 0.4em 0 0;
- font: smaller/1.5em sans-serif;
-}
-
-#qunit-modulefilter-dropdown-list li {
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-#qunit-modulefilter-dropdown-list .clickable {
- display: block;
- padding-left: 0.15em;
-}
-
-
-/** Tests: Pass/Fail */
-
-#qunit-tests {
- list-style-position: inside;
-}
-
-#qunit-tests li {
- padding: 0.4em 1em 0.4em 1em;
- border-bottom: 1px solid #FFF;
- list-style-position: inside;
-}
-
-#qunit-tests > li {
- display: none;
-}
-
-#qunit-tests li.running,
-#qunit-tests li.pass,
-#qunit-tests li.fail,
-#qunit-tests li.skipped {
- display: list-item;
-}
-
-#qunit-tests.hidepass {
- position: relative;
-}
-
-#qunit-tests.hidepass li.running,
-#qunit-tests.hidepass li.pass {
- visibility: hidden;
- position: absolute;
- width: 0;
- height: 0;
- padding: 0;
- border: 0;
- margin: 0;
-}
-
-#qunit-tests li strong {
- cursor: pointer;
-}
-
-#qunit-tests li.skipped strong {
- cursor: default;
-}
-
-#qunit-tests li a {
- padding: 0.5em;
- color: #C2CCD1;
- text-decoration: none;
-}
-
-#qunit-tests li p a {
- padding: 0.25em;
- color: #6B6464;
-}
-#qunit-tests li a:hover,
-#qunit-tests li a:focus {
- color: #000;
-}
-
-#qunit-tests li .runtime {
- float: right;
- font-size: smaller;
-}
-
-.qunit-assert-list {
- margin-top: 0.5em;
- padding: 0.5em;
-
- background-color: #FFF;
-
- border-radius: 5px;
-}
-
-.qunit-source {
- margin: 0.6em 0 0.3em;
-}
-
-.qunit-collapsed {
- display: none;
-}
-
-#qunit-tests table {
- border-collapse: collapse;
- margin-top: 0.2em;
-}
-
-#qunit-tests th {
- text-align: right;
- vertical-align: top;
- padding: 0 0.5em 0 0;
-}
-
-#qunit-tests td {
- vertical-align: top;
-}
-
-#qunit-tests pre {
- margin: 0;
- white-space: pre-wrap;
- word-wrap: break-word;
-}
-
-#qunit-tests del {
- color: #374E0C;
- background-color: #E0F2BE;
- text-decoration: none;
-}
-
-#qunit-tests ins {
- color: #500;
- background-color: #FFCACA;
- text-decoration: none;
-}
-
-/*** Test Counts */
-
-#qunit-tests b.counts { color: #000; }
-#qunit-tests b.passed { color: #5E740B; }
-#qunit-tests b.failed { color: #710909; }
-
-#qunit-tests li li {
- padding: 5px;
- background-color: #FFF;
- border-bottom: none;
- list-style-position: inside;
-}
-
-/*** Passing Styles */
-
-#qunit-tests li li.pass {
- color: #3C510C;
- background-color: #FFF;
- border-left: 10px solid #C6E746;
-}
-
-#qunit-tests .pass { color: #528CE0; background-color: #D2E0E6; }
-#qunit-tests .pass .test-name { color: #366097; }
-
-#qunit-tests .pass .test-actual,
-#qunit-tests .pass .test-expected { color: #999; }
-
-#qunit-banner.qunit-pass { background-color: #C6E746; }
-
-/*** Failing Styles */
-
-#qunit-tests li li.fail {
- color: #710909;
- background-color: #FFF;
- border-left: 10px solid #EE5757;
- white-space: pre;
-}
-
-#qunit-tests > li:last-child {
- border-radius: 0 0 5px 5px;
-}
-
-#qunit-tests .fail { color: #000; background-color: #EE5757; }
-#qunit-tests .fail .test-name,
-#qunit-tests .fail .module-name { color: #000; }
-
-#qunit-tests .fail .test-actual { color: #EE5757; }
-#qunit-tests .fail .test-expected { color: #008000; }
-
-#qunit-banner.qunit-fail { background-color: #EE5757; }
-
-/*** Skipped tests */
-
-#qunit-tests .skipped {
- background-color: #EBECE9;
-}
-
-#qunit-tests .qunit-skipped-label {
- background-color: #F4FF77;
- display: inline-block;
- font-style: normal;
- color: #366097;
- line-height: 1.8em;
- padding: 0 0.5em;
- margin: -0.4em 0.4em -0.4em 0;
-}
-
-/** Result */
-
-#qunit-testresult {
- padding: 0.5em 1em 0.5em 1em;
-
- color: #2B81AF;
- background-color: #D2E0E6;
-
- border-bottom: 1px solid #FFF;
-}
-#qunit-testresult .module-name {
- font-weight: 700;
-}
-
-/** Fixture */
-
-#qunit-fixture {
- position: absolute;
- top: -10000px;
- left: -10000px;
- width: 1000px;
- height: 1000px;
-}
diff --git a/test/lib/qunit.js b/test/lib/qunit.js
deleted file mode 100644
index 8b5e69e..0000000
--- a/test/lib/qunit.js
+++ /dev/null
@@ -1,4349 +0,0 @@
-/*!
- * QUnit 2.1.0
- * https://qunitjs.com/
- *
- * Copyright jQuery Foundation and other contributors
- * Released under the MIT license
- * https://jquery.org/license
- *
- * Date: 2016-12-06T04:45Z
- */
-(function (global$1) {
- 'use strict';
-
- global$1 = 'default' in global$1 ? global$1['default'] : global$1;
-
- var window = global$1.window;
- var console = global$1.console;
- var setTimeout = global$1.setTimeout;
- var clearTimeout = global$1.clearTimeout;
-
- var document = window && window.document;
- var navigator = window && window.navigator;
- var sessionStorage = window && window.sessionStorage;
-
- var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
- return typeof obj;
- } : function (obj) {
- return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
- };
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- var get$1 = function get$1(object, property, receiver) {
- if (object === null) object = Function.prototype;
- var desc = Object.getOwnPropertyDescriptor(object, property);
-
- if (desc === undefined) {
- var parent = Object.getPrototypeOf(object);
-
- if (parent === null) {
- return undefined;
- } else {
- return get$1(parent, property, receiver);
- }
- } else if ("value" in desc) {
- return desc.value;
- } else {
- var getter = desc.get;
-
- if (getter === undefined) {
- return undefined;
- }
-
- return getter.call(receiver);
- }
- };
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- var set$1 = function set$1(object, property, value, receiver) {
- var desc = Object.getOwnPropertyDescriptor(object, property);
-
- if (desc === undefined) {
- var parent = Object.getPrototypeOf(object);
-
- if (parent !== null) {
- set$1(parent, property, value, receiver);
- }
- } else if ("value" in desc && desc.writable) {
- desc.value = value;
- } else {
- var setter = desc.set;
-
- if (setter !== undefined) {
- setter.call(receiver, value);
- }
- }
-
- return value;
- };
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- var toConsumableArray = function (arr) {
- if (Array.isArray(arr)) {
- for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
-
- return arr2;
- } else {
- return Array.from(arr);
- }
- };
-
- var toString = Object.prototype.toString;
- var hasOwn = Object.prototype.hasOwnProperty;
- var now = Date.now || function () {
- return new Date().getTime();
- };
-
- var defined = {
- document: window && window.document !== undefined,
- setTimeout: setTimeout !== undefined
- };
-
- // Returns a new Array with the elements that are in a but not in b
- function diff(a, b) {
- var i,
- j,
- result = a.slice();
-
- for (i = 0; i < result.length; i++) {
- for (j = 0; j < b.length; j++) {
- if (result[i] === b[j]) {
- result.splice(i, 1);
- i--;
- break;
- }
- }
- }
- return result;
- }
-
- // From jquery.js
- function inArray(elem, array) {
- if (array.indexOf) {
- return array.indexOf(elem);
- }
-
- for (var i = 0, length = array.length; i < length; i++) {
- if (array[i] === elem) {
- return i;
- }
- }
-
- return -1;
- }
-
- /**
- * Makes a clone of an object using only Array or Object as base,
- * and copies over the own enumerable properties.
- *
- * @param {Object} obj
- * @return {Object} New object with only the own properties (recursively).
- */
- function objectValues(obj) {
- var key,
- val,
- vals = is("array", obj) ? [] : {};
- for (key in obj) {
- if (hasOwn.call(obj, key)) {
- val = obj[key];
- vals[key] = val === Object(val) ? objectValues(val) : val;
- }
- }
- return vals;
- }
-
- function extend(a, b, undefOnly) {
- for (var prop in b) {
- if (hasOwn.call(b, prop)) {
- if (b[prop] === undefined) {
- delete a[prop];
- } else if (!(undefOnly && typeof a[prop] !== "undefined")) {
- a[prop] = b[prop];
- }
- }
- }
-
- return a;
- }
-
- function objectType(obj) {
- if (typeof obj === "undefined") {
- return "undefined";
- }
-
- // Consider: typeof null === object
- if (obj === null) {
- return "null";
- }
-
- var match = toString.call(obj).match(/^\[object\s(.*)\]$/),
- type = match && match[1];
-
- switch (type) {
- case "Number":
- if (isNaN(obj)) {
- return "nan";
- }
- return "number";
- case "String":
- case "Boolean":
- case "Array":
- case "Set":
- case "Map":
- case "Date":
- case "RegExp":
- case "Function":
- case "Symbol":
- return type.toLowerCase();
- }
-
- if ((typeof obj === "undefined" ? "undefined" : _typeof(obj)) === "object") {
- return "object";
- }
- }
-
- // Safe object type checking
- function is(type, obj) {
- return objectType(obj) === type;
- }
-
- // Test for equality any JavaScript type.
- // Author: Philippe Rathé <prathe@gmail.com>
- var equiv = (function () {
-
- // Stack to decide between skip/abort functions
- var callers = [];
-
- // Stack to avoiding loops from circular referencing
- var parents = [];
- var parentsB = [];
-
- var getProto = Object.getPrototypeOf || function (obj) {
- return obj.__proto__;
- };
-
- function useStrictEquality(b, a) {
-
- // To catch short annotation VS 'new' annotation of a declaration. e.g.:
- // `var i = 1;`
- // `var j = new Number(1);`
- if ((typeof a === "undefined" ? "undefined" : _typeof(a)) === "object") {
- a = a.valueOf();
- }
- if ((typeof b === "undefined" ? "undefined" : _typeof(b)) === "object") {
- b = b.valueOf();
- }
-
- return a === b;
- }
-
- function compareConstructors(a, b) {
- var protoA = getProto(a);
- var protoB = getProto(b);
-
- // Comparing constructors is more strict than using `instanceof`
- if (a.constructor === b.constructor) {
- return true;
- }
-
- // Ref #851
- // If the obj prototype descends from a null constructor, treat it
- // as a null prototype.
- if (protoA && protoA.constructor === null) {
- protoA = null;
- }
- if (protoB && protoB.constructor === null) {
- protoB = null;
- }
-
- // Allow objects with no prototype to be equivalent to
- // objects with Object as their constructor.
- if (protoA === null && protoB === Object.prototype || protoB === null && protoA === Object.prototype) {
- return true;
- }
-
- return false;
- }
-
- function getRegExpFlags(regexp) {
- return "flags" in regexp ? regexp.flags : regexp.toString().match(/[gimuy]*$/)[0];
- }
-
- var callbacks = {
- "string": useStrictEquality,
- "boolean": useStrictEquality,
- "number": useStrictEquality,
- "null": useStrictEquality,
- "undefined": useStrictEquality,
- "symbol": useStrictEquality,
- "date": useStrictEquality,
-
- "nan": function nan() {
- return true;
- },
-
- "regexp": function regexp(b, a) {
- return a.source === b.source &&
-
- // Include flags in the comparison
- getRegExpFlags(a) === getRegExpFlags(b);
- },
-
- // - skip when the property is a method of an instance (OOP)
- // - abort otherwise,
- // initial === would have catch identical references anyway
- "function": function _function(b, a) {
-
- var caller = callers[callers.length - 1];
- return caller !== Object && typeof caller !== "undefined" && a.toString() === b.toString();
- },
-
- "array": function array(b, a) {
- var i, j, len, loop, aCircular, bCircular;
-
- len = a.length;
- if (len !== b.length) {
-
- // Safe and faster
- return false;
- }
-
- // Track reference to avoid circular references
- parents.push(a);
- parentsB.push(b);
- for (i = 0; i < len; i++) {
- loop = false;
- for (j = 0; j < parents.length; j++) {
- aCircular = parents[j] === a[i];
- bCircular = parentsB[j] === b[i];
- if (aCircular || bCircular) {
- if (a[i] === b[i] || aCircular && bCircular) {
- loop = true;
- } else {
- parents.pop();
- parentsB.pop();
- return false;
- }
- }
- }
- if (!loop && !innerEquiv(a[i], b[i])) {
- parents.pop();
- parentsB.pop();
- return false;
- }
- }
- parents.pop();
- parentsB.pop();
- return true;
- },
-
- "set": function set(b, a) {
- var innerEq,
- outerEq = true;
-
- if (a.size !== b.size) {
- return false;
- }
-
- a.forEach(function (aVal) {
- innerEq = false;
-
- b.forEach(function (bVal) {
- if (innerEquiv(bVal, aVal)) {
- innerEq = true;
- }
- });
-
- if (!innerEq) {
- outerEq = false;
- }
- });
-
- return outerEq;
- },
-
- "map": function map(b, a) {
- var innerEq,
- outerEq = true;
-
- if (a.size !== b.size) {
- return false;
- }
-
- a.forEach(function (aVal, aKey) {
- innerEq = false;
-
- b.forEach(function (bVal, bKey) {
- if (innerEquiv([bVal, bKey], [aVal, aKey])) {
- innerEq = true;
- }
- });
-
- if (!innerEq) {
- outerEq = false;
- }
- });
-
- return outerEq;
- },
-
- "object": function object(b, a) {
- var i, j, loop, aCircular, bCircular;
-
- // Default to true
- var eq = true;
- var aProperties = [];
- var bProperties = [];
-
- if (compareConstructors(a, b) === false) {
- return false;
- }
-
- // Stack constructor before traversing properties
- callers.push(a.constructor);
-
- // Track reference to avoid circular references
- parents.push(a);
- parentsB.push(b);
-
- // Be strict: don't ensure hasOwnProperty and go deep
- for (i in a) {
- loop = false;
- for (j = 0; j < parents.length; j++) {
- aCircular = parents[j] === a[i];
- bCircular = parentsB[j] === b[i];
- if (aCircular || bCircular) {
- if (a[i] === b[i] || aCircular && bCircular) {
- loop = true;
- } else {
- eq = false;
- break;
- }
- }
- }
- aProperties.push(i);
- if (!loop && !innerEquiv(a[i], b[i])) {
- eq = false;
- break;
- }
- }
-
- parents.pop();
- parentsB.pop();
-
- // Unstack, we are done
- callers.pop();
-
- for (i in b) {
-
- // Collect b's properties
- bProperties.push(i);
- }
-
- // Ensures identical properties name
- return eq && innerEquiv(aProperties.sort(), bProperties.sort());
- }
- };
-
- function typeEquiv(a, b) {
- var type = objectType(a);
- return objectType(b) === type && callbacks[type](b, a);
- }
-
- // The real equiv function
- function innerEquiv(a, b) {
-
- // We're done when there's nothing more to compare
- if (arguments.length < 2) {
- return true;
- }
-
- // Require type-specific equality
- return (a === b || typeEquiv(a, b)) && (
-
- // ...across all consecutive argument pairs
- arguments.length === 2 || innerEquiv.apply(this, [].slice.call(arguments, 1)));
- }
-
- return innerEquiv;
- })();
-
- /**
- * Config object: Maintain internal state
- * Later exposed as QUnit.config
- * `config` initialized at top of scope
- */
- var config = {
-
- // The queue of tests to run
- queue: [],
-
- // Block until document ready
- blocking: true,
-
- // By default, run previously failed tests first
- // very useful in combination with "Hide passed tests" checked
- reorder: true,
-
- // By default, modify document.title when suite is done
- altertitle: true,
-
- // HTML Reporter: collapse every test except the first failing test
- // If false, all failing tests will be expanded
- collapse: true,
-
- // By default, scroll to top of the page when suite is done
- scrolltop: true,
-
- // Depth up-to which object will be dumped
- maxDepth: 5,
-
- // When enabled, all tests must call expect()
- requireExpects: false,
-
- // Placeholder for user-configurable form-exposed URL parameters
- urlConfig: [],
-
- // Set of all modules.
- modules: [],
-
- // Stack of nested modules
- moduleStack: [],
-
- // The first unnamed module
- currentModule: {
- name: "",
- tests: [],
- childModules: [],
- testsRun: 0
- },
-
- callbacks: {},
-
- // The storage module to use for reordering tests
- storage: sessionStorage
- };
-
- // take a predefined QUnit.config and extend the defaults
- var globalConfig = window && window.QUnit && window.QUnit.config;
-
- // only extend the global config if there is no QUnit overload
- if (window && window.QUnit && !window.QUnit.version) {
- extend(config, globalConfig);
- }
-
- // Push a loose unnamed module to the modules collection
- config.modules.push(config.currentModule);
-
- // Based on jsDump by Ariel Flesler
- // http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html
- var dump = (function () {
- function quote(str) {
- return "\"" + str.toString().replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\"";
- }
- function literal(o) {
- return o + "";
- }
- function join(pre, arr, post) {
- var s = dump.separator(),
- base = dump.indent(),
- inner = dump.indent(1);
- if (arr.join) {
- arr = arr.join("," + s + inner);
- }
- if (!arr) {
- return pre + post;
- }
- return [pre, inner + arr, base + post].join(s);
- }
- function array(arr, stack) {
- var i = arr.length,
- ret = new Array(i);
-
- if (dump.maxDepth && dump.depth > dump.maxDepth) {
- return "[object Array]";
- }
-
- this.up();
- while (i--) {
- ret[i] = this.parse(arr[i], undefined, stack);
- }
- this.down();
- return join("[", ret, "]");
- }
-
- function isArray(obj) {
- return (
-
- //Native Arrays
- toString.call(obj) === "[object Array]" ||
-
- // NodeList objects
- typeof obj.length === "number" && obj.item !== undefined && (obj.length ? obj.item(0) === obj[0] : obj.item(0) === null && obj[0] === undefined)
- );
- }
-
- var reName = /^function (\w+)/,
- dump = {
-
- // The objType is used mostly internally, you can fix a (custom) type in advance
- parse: function parse(obj, objType, stack) {
- stack = stack || [];
- var res,
- parser,
- parserType,
- inStack = inArray(obj, stack);
-
- if (inStack !== -1) {
- return "recursion(" + (inStack - stack.length) + ")";
- }
-
- objType = objType || this.typeOf(obj);
- parser = this.parsers[objType];
- parserType = typeof parser === "undefined" ? "undefined" : _typeof(parser);
-
- if (parserType === "function") {
- stack.push(obj);
- res = parser.call(this, obj, stack);
- stack.pop();
- return res;
- }
- return parserType === "string" ? parser : this.parsers.error;
- },
- typeOf: function typeOf(obj) {
- var type;
-
- if (obj === null) {
- type = "null";
- } else if (typeof obj === "undefined") {
- type = "undefined";
- } else if (is("regexp", obj)) {
- type = "regexp";
- } else if (is("date", obj)) {
- type = "date";
- } else if (is("function", obj)) {
- type = "function";
- } else if (obj.setInterval !== undefined && obj.document !== undefined && obj.nodeType === undefined) {
- type = "window";
- } else if (obj.nodeType === 9) {
- type = "document";
- } else if (obj.nodeType) {
- type = "node";
- } else if (isArray(obj)) {
- type = "array";
- } else if (obj.constructor === Error.prototype.constructor) {
- type = "error";
- } else {
- type = typeof obj === "undefined" ? "undefined" : _typeof(obj);
- }
- return type;
- },
-
- separator: function separator() {
- if (this.multiline) {
- return this.HTML ? "<br />" : "\n";
- } else {
- return this.HTML ? " " : " ";
- }
- },
-
- // Extra can be a number, shortcut for increasing-calling-decreasing
- indent: function indent(extra) {
- if (!this.multiline) {
- return "";
- }
- var chr = this.indentChar;
- if (this.HTML) {
- chr = chr.replace(/\t/g, " ").replace(/ /g, " ");
- }
- return new Array(this.depth + (extra || 0)).join(chr);
- },
- up: function up(a) {
- this.depth += a || 1;
- },
- down: function down(a) {
- this.depth -= a || 1;
- },
- setParser: function setParser(name, parser) {
- this.parsers[name] = parser;
- },
-
- // The next 3 are exposed so you can use them
- quote: quote,
- literal: literal,
- join: join,
- depth: 1,
- maxDepth: config.maxDepth,
-
- // This is the list of parsers, to modify them, use dump.setParser
- parsers: {
- window: "[Window]",
- document: "[Document]",
- error: function error(_error) {
- return "Error(\"" + _error.message + "\")";
- },
- unknown: "[Unknown]",
- "null": "null",
- "undefined": "undefined",
- "function": function _function(fn) {
- var ret = "function",
-
-
- // Functions never have name in IE
- name = "name" in fn ? fn.name : (reName.exec(fn) || [])[1];
-
- if (name) {
- ret += " " + name;
- }
- ret += "(";
-
- ret = [ret, dump.parse(fn, "functionArgs"), "){"].join("");
- return join(ret, dump.parse(fn, "functionCode"), "}");
- },
- array: array,
- nodelist: array,
- "arguments": array,
- object: function object(map, stack) {
- var keys,
- key,
- val,
- i,
- nonEnumerableProperties,
- ret = [];
-
- if (dump.maxDepth && dump.depth > dump.maxDepth) {
- return "[object Object]";
- }
-
- dump.up();
- keys = [];
- for (key in map) {
- keys.push(key);
- }
-
- // Some properties are not always enumerable on Error objects.
- nonEnumerableProperties = ["message", "name"];
- for (i in nonEnumerableProperties) {
- key = nonEnumerableProperties[i];
- if (key in map && inArray(key, keys) < 0) {
- keys.push(key);
- }
- }
- keys.sort();
- for (i = 0; i < keys.length; i++) {
- key = keys[i];
- val = map[key];
- ret.push(dump.parse(key, "key") + ": " + dump.parse(val, undefined, stack));
- }
- dump.down();
- return join("{", ret, "}");
- },
- node: function node(_node) {
- var len,
- i,
- val,
- open = dump.HTML ? "<" : "<",
- close = dump.HTML ? ">" : ">",
- tag = _node.nodeName.toLowerCase(),
- ret = open + tag,
- attrs = _node.attributes;
-
- if (attrs) {
- for (i = 0, len = attrs.length; i < len; i++) {
- val = attrs[i].nodeValue;
-
- // IE6 includes all attributes in .attributes, even ones not explicitly
- // set. Those have values like undefined, null, 0, false, "" or
- // "inherit".
- if (val && val !== "inherit") {
- ret += " " + attrs[i].nodeName + "=" + dump.parse(val, "attribute");
- }
- }
- }
- ret += close;
-
- // Show content of TextNode or CDATASection
- if (_node.nodeType === 3 || _node.nodeType === 4) {
- ret += _node.nodeValue;
- }
-
- return ret + open + "/" + tag + close;
- },
-
- // Function calls it internally, it's the arguments part of the function
- functionArgs: function functionArgs(fn) {
- var args,
- l = fn.length;
-
- if (!l) {
- return "";
- }
-
- args = new Array(l);
- while (l--) {
-
- // 97 is 'a'
- args[l] = String.fromCharCode(97 + l);
- }
- return " " + args.join(", ") + " ";
- },
-
- // Object calls it internally, the key part of an item in a map
- key: quote,
-
- // Function calls it internally, it's the content of the function
- functionCode: "[code]",
-
- // Node calls it internally, it's a html attribute value
- attribute: quote,
- string: quote,
- date: quote,
- regexp: literal,
- number: literal,
- "boolean": literal,
- symbol: function symbol(sym) {
- return sym.toString();
- }
- },
-
- // If true, entities are escaped ( <, >, \t, space and \n )
- HTML: false,
-
- // Indentation unit
- indentChar: " ",
-
- // If true, items in a collection, are separated by a \n, else just a space.
- multiline: true
- };
-
- return dump;
- })();
-
- // Register logging callbacks
- function registerLoggingCallbacks(obj) {
- var i,
- l,
- key,
- callbackNames = ["begin", "done", "log", "testStart", "testDone", "moduleStart", "moduleDone"];
-
- function registerLoggingCallback(key) {
- var loggingCallback = function loggingCallback(callback) {
- if (objectType(callback) !== "function") {
- throw new Error("QUnit logging methods require a callback function as their first parameters.");
- }
-
- config.callbacks[key].push(callback);
- };
-
- return loggingCallback;
- }
-
- for (i = 0, l = callbackNames.length; i < l; i++) {
- key = callbackNames[i];
-
- // Initialize key collection of logging callback
- if (objectType(config.callbacks[key]) === "undefined") {
- config.callbacks[key] = [];
- }
-
- obj[key] = registerLoggingCallback(key);
- }
- }
-
- function runLoggingCallbacks(key, args) {
- var i, l, callbacks;
-
- callbacks = config.callbacks[key];
- for (i = 0, l = callbacks.length; i < l; i++) {
- callbacks[i](args);
- }
- }
-
- // Doesn't support IE9, it will return undefined on these browsers
- // See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack
- var fileName = (sourceFromStacktrace(0) || "").replace(/(:\d+)+\)?/, "").replace(/.+\//, "");
-
- function extractStacktrace(e, offset) {
- offset = offset === undefined ? 4 : offset;
-
- var stack, include, i;
-
- if (e && e.stack) {
- stack = e.stack.split("\n");
- if (/^error$/i.test(stack[0])) {
- stack.shift();
- }
- if (fileName) {
- include = [];
- for (i = offset; i < stack.length; i++) {
- if (stack[i].indexOf(fileName) !== -1) {
- break;
- }
- include.push(stack[i]);
- }
- if (include.length) {
- return include.join("\n");
- }
- }
- return stack[offset];
- }
- }
-
- function sourceFromStacktrace(offset) {
- var error = new Error();
-
- // Support: Safari <=7 only, IE <=10 - 11 only
- // Not all browsers generate the `stack` property for `new Error()`, see also #636
- if (!error.stack) {
- try {
- throw error;
- } catch (err) {
- error = err;
- }
- }
-
- return extractStacktrace(error, offset);
- }
-
- var unitSampler;
- var focused = false;
- var priorityCount = 0;
-
- function Test(settings) {
- var i, l;
-
- ++Test.count;
-
- this.expected = null;
- extend(this, settings);
- this.assertions = [];
- this.semaphore = 0;
- this.usedAsync = false;
- this.module = config.currentModule;
- this.stack = sourceFromStacktrace(3);
-
- // Register unique strings
- for (i = 0, l = this.module.tests; i < l.length; i++) {
- if (this.module.tests[i].name === this.testName) {
- this.testName += " ";
- }
- }
-
- this.testId = generateHash(this.module.name, this.testName);
-
- this.module.tests.push({
- name: this.testName,
- testId: this.testId
- });
-
- if (settings.skip) {
-
- // Skipped tests will fully ignore any sent callback
- this.callback = function () {};
- this.async = false;
- this.expected = 0;
- } else {
- this.assert = new Assert(this);
- }
- }
-
- Test.count = 0;
-
- function getNotStartedModules(startModule) {
- var module = startModule,
- modules = [];
-
- while (module && module.testsRun === 0) {
- modules.push(module);
- module = module.parentModule;
- }
-
- return modules;
- }
-
- Test.prototype = {
- before: function before() {
- var i,
- startModule,
- module = this.module,
- notStartedModules = getNotStartedModules(module);
-
- for (i = notStartedModules.length - 1; i >= 0; i--) {
- startModule = notStartedModules[i];
- startModule.stats = { all: 0, bad: 0, started: now() };
- runLoggingCallbacks("moduleStart", {
- name: startModule.name,
- tests: startModule.tests
- });
- }
-
- config.current = this;
-
- if (module.testEnvironment) {
- delete module.testEnvironment.before;
- delete module.testEnvironment.beforeEach;
- delete module.testEnvironment.afterEach;
- delete module.testEnvironment.after;
- }
- this.testEnvironment = extend({}, module.testEnvironment);
-
- this.started = now();
- runLoggingCallbacks("testStart", {
- name: this.testName,
- module: module.name,
- testId: this.testId,
- previousFailure: this.previousFailure
- });
-
- if (!config.pollution) {
- saveGlobal();
- }
- },
-
- run: function run() {
- var promise;
-
- config.current = this;
-
- this.callbackStarted = now();
-
- if (config.notrycatch) {
- runTest(this);
- return;
- }
-
- try {
- runTest(this);
- } catch (e) {
- this.pushFailure("Died on test #" + (this.assertions.length + 1) + " " + this.stack + ": " + (e.message || e), extractStacktrace(e, 0));
-
- // Else next test will carry the responsibility
- saveGlobal();
-
- // Restart the tests if they're blocking
- if (config.blocking) {
- internalRecover(this);
- }
- }
-
- function runTest(test) {
- promise = test.callback.call(test.testEnvironment, test.assert);
- test.resolvePromise(promise);
- }
- },
-
- after: function after() {
- checkPollution();
- },
-
- queueHook: function queueHook(hook, hookName, hookOwner) {
- var promise,
- test = this;
- return function runHook() {
- if (hookName === "before") {
- if (hookOwner.testsRun !== 0) {
- return;
- }
-
- test.preserveEnvironment = true;
- }
-
- if (hookName === "after" && hookOwner.testsRun !== numberOfTests(hookOwner) - 1) {
- return;
- }
-
- config.current = test;
- if (config.notrycatch) {
- callHook();
- return;
- }
- try {
- callHook();
- } catch (error) {
- test.pushFailure(hookName + " failed on " + test.testName + ": " + (error.message || error), extractStacktrace(error, 0));
- }
-
- function callHook() {
- promise = hook.call(test.testEnvironment, test.assert);
- test.resolvePromise(promise, hookName);
- }
- };
- },
-
- // Currently only used for module level hooks, can be used to add global level ones
- hooks: function hooks(handler) {
- var hooks = [];
-
- function processHooks(test, module) {
- if (module.parentModule) {
- processHooks(test, module.parentModule);
- }
- if (module.testEnvironment && objectType(module.testEnvironment[handler]) === "function") {
- hooks.push(test.queueHook(module.testEnvironment[handler], handler, module));
- }
- }
-
- // Hooks are ignored on skipped tests
- if (!this.skip) {
- processHooks(this, this.module);
- }
- return hooks;
- },
-
- finish: function finish() {
- config.current = this;
- if (config.requireExpects && this.expected === null) {
- this.pushFailure("Expected number of assertions to be defined, but expect() was " + "not called.", this.stack);
- } else if (this.expected !== null && this.expected !== this.assertions.length) {
- this.pushFailure("Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack);
- } else if (this.expected === null && !this.assertions.length) {
- this.pushFailure("Expected at least one assertion, but none were run - call " + "expect(0) to accept zero assertions.", this.stack);
- }
-
- var i,
- module = this.module,
- moduleName = module.name,
- testName = this.testName,
- skipped = !!this.skip,
- bad = 0,
- storage = config.storage;
-
- this.runtime = now() - this.started;
-
- config.stats.all += this.assertions.length;
- module.stats.all += this.assertions.length;
-
- for (i = 0; i < this.assertions.length; i++) {
- if (!this.assertions[i].result) {
- bad++;
- config.stats.bad++;
- module.stats.bad++;
- }
- }
-
- notifyTestsRan(module);
-
- // Store result when possible
- if (storage) {
- if (bad) {
- storage.setItem("qunit-test-" + moduleName + "-" + testName, bad);
- } else {
- storage.removeItem("qunit-test-" + moduleName + "-" + testName);
- }
- }
-
- runLoggingCallbacks("testDone", {
- name: testName,
- module: moduleName,
- skipped: skipped,
- failed: bad,
- passed: this.assertions.length - bad,
- total: this.assertions.length,
- runtime: skipped ? 0 : this.runtime,
-
- // HTML Reporter use
- assertions: this.assertions,
- testId: this.testId,
-
- // Source of Test
- source: this.stack
- });
-
- if (module.testsRun === numberOfTests(module)) {
- runLoggingCallbacks("moduleDone", {
- name: module.name,
- tests: module.tests,
- failed: module.stats.bad,
- passed: module.stats.all - module.stats.bad,
- total: module.stats.all,
- runtime: now() - module.stats.started
- });
- }
-
- config.current = undefined;
- },
-
- preserveTestEnvironment: function preserveTestEnvironment() {
- if (this.preserveEnvironment) {
- this.module.testEnvironment = this.testEnvironment;
- this.testEnvironment = extend({}, this.module.testEnvironment);
- }
- },
-
- queue: function queue() {
- var priority,
- previousFailCount,
- test = this;
-
- if (!this.valid()) {
- return;
- }
-
- function run() {
-
- // Each of these can by async
- synchronize([function () {
- test.before();
- }, test.hooks("before"), function () {
- test.preserveTestEnvironment();
- }, test.hooks("beforeEach"), function () {
- test.run();
- }, test.hooks("afterEach").reverse(), test.hooks("after").reverse(), function () {
- test.after();
- }, function () {
- test.finish();
- }]);
- }
-
- previousFailCount = config.storage && +config.storage.getItem("qunit-test-" + this.module.name + "-" + this.testName);
-
- // Prioritize previously failed tests, detected from storage
- priority = config.reorder && previousFailCount;
-
- this.previousFailure = !!previousFailCount;
-
- return synchronize(run, priority, config.seed);
- },
-
- pushResult: function pushResult(resultInfo) {
-
- // Destructure of resultInfo = { result, actual, expected, message, negative }
- var source,
- details = {
- module: this.module.name,
- name: this.testName,
- result: resultInfo.result,
- message: resultInfo.message,
- actual: resultInfo.actual,
- expected: resultInfo.expected,
- testId: this.testId,
- negative: resultInfo.negative || false,
- runtime: now() - this.started
- };
-
- if (!resultInfo.result) {
- source = sourceFromStacktrace();
-
- if (source) {
- details.source = source;
- }
- }
-
- runLoggingCallbacks("log", details);
-
- this.assertions.push({
- result: !!resultInfo.result,
- message: resultInfo.message
- });
- },
-
- pushFailure: function pushFailure(message, source, actual) {
- if (!(this instanceof Test)) {
- throw new Error("pushFailure() assertion outside test context, was " + sourceFromStacktrace(2));
- }
-
- var details = {
- module: this.module.name,
- name: this.testName,
- result: false,
- message: message || "error",
- actual: actual || null,
- testId: this.testId,
- runtime: now() - this.started
- };
-
- if (source) {
- details.source = source;
- }
-
- runLoggingCallbacks("log", details);
-
- this.assertions.push({
- result: false,
- message: message
- });
- },
-
- resolvePromise: function resolvePromise(promise, phase) {
- var then,
- resume,
- message,
- test = this;
- if (promise != null) {
- then = promise.then;
- if (objectType(then) === "function") {
- resume = internalStop(test);
- then.call(promise, function () {
- resume();
- }, function (error) {
- message = "Promise rejected " + (!phase ? "during" : phase.replace(/Each$/, "")) + " \"" + test.testName + "\": " + (error && error.message || error);
- test.pushFailure(message, extractStacktrace(error, 0));
-
- // Else next test will carry the responsibility
- saveGlobal();
-
- // Unblock
- resume();
- });
- }
- }
- },
-
- valid: function valid() {
- var filter = config.filter,
- regexFilter = /^(!?)\/([\w\W]*)\/(i?$)/.exec(filter),
- module = config.module && config.module.toLowerCase(),
- fullName = this.module.name + ": " + this.testName;
-
- function moduleChainNameMatch(testModule) {
- var testModuleName = testModule.name ? testModule.name.toLowerCase() : null;
- if (testModuleName === module) {
- return true;
- } else if (testModule.parentModule) {
- return moduleChainNameMatch(testModule.parentModule);
- } else {
- return false;
- }
- }
-
- function moduleChainIdMatch(testModule) {
- return inArray(testModule.moduleId, config.moduleId) > -1 || testModule.parentModule && moduleChainIdMatch(testModule.parentModule);
- }
-
- // Internally-generated tests are always valid
- if (this.callback && this.callback.validTest) {
- return true;
- }
-
- if (config.moduleId && config.moduleId.length > 0 && !moduleChainIdMatch(this.module)) {
-
- return false;
- }
-
- if (config.testId && config.testId.length > 0 && inArray(this.testId, config.testId) < 0) {
-
- return false;
- }
-
- if (module && !moduleChainNameMatch(this.module)) {
- return false;
- }
-
- if (!filter) {
- return true;
- }
-
- return regexFilter ? this.regexFilter(!!regexFilter[1], regexFilter[2], regexFilter[3], fullName) : this.stringFilter(filter, fullName);
- },
-
- regexFilter: function regexFilter(exclude, pattern, flags, fullName) {
- var regex = new RegExp(pattern, flags);
- var match = regex.test(fullName);
-
- return match !== exclude;
- },
-
- stringFilter: function stringFilter(filter, fullName) {
- filter = filter.toLowerCase();
- fullName = fullName.toLowerCase();
-
- var include = filter.charAt(0) !== "!";
- if (!include) {
- filter = filter.slice(1);
- }
-
- // If the filter matches, we need to honour include
- if (fullName.indexOf(filter) !== -1) {
- return include;
- }
-
- // Otherwise, do the opposite
- return !include;
- }
- };
-
- function pushFailure() {
- if (!config.current) {
- throw new Error("pushFailure() assertion outside test context, in " + sourceFromStacktrace(2));
- }
-
- // Gets current test obj
- var currentTest = config.current;
-
- return currentTest.pushFailure.apply(currentTest, arguments);
- }
-
- // Based on Java's String.hashCode, a simple but not
- // rigorously collision resistant hashing function
- function generateHash(module, testName) {
- var hex,
- i = 0,
- hash = 0,
- str = module + "\x1C" + testName,
- len = str.length;
-
- for (; i < len; i++) {
- hash = (hash << 5) - hash + str.charCodeAt(i);
- hash |= 0;
- }
-
- // Convert the possibly negative integer hash code into an 8 character hex string, which isn't
- // strictly necessary but increases user understanding that the id is a SHA-like hash
- hex = (0x100000000 + hash).toString(16);
- if (hex.length < 8) {
- hex = "0000000" + hex;
- }
-
- return hex.slice(-8);
- }
-
- function synchronize(callback, priority, seed) {
- var last = !priority,
- index;
-
- if (objectType(callback) === "array") {
- while (callback.length) {
- synchronize(callback.shift());
- }
- return;
- }
-
- if (priority) {
- config.queue.splice(priorityCount++, 0, callback);
- } else if (seed) {
- if (!unitSampler) {
- unitSampler = unitSamplerGenerator(seed);
- }
-
- // Insert into a random position after all priority items
- index = Math.floor(unitSampler() * (config.queue.length - priorityCount + 1));
- config.queue.splice(priorityCount + index, 0, callback);
- } else {
- config.queue.push(callback);
- }
-
- if (internalState.autorun && !config.blocking) {
- process(last);
- }
- }
-
- function unitSamplerGenerator(seed) {
-
- // 32-bit xorshift, requires only a nonzero seed
- // http://excamera.com/sphinx/article-xorshift.html
- var sample = parseInt(generateHash(seed), 16) || -1;
- return function () {
- sample ^= sample << 13;
- sample ^= sample >>> 17;
- sample ^= sample << 5;
-
- // ECMAScript has no unsigned number type
- if (sample < 0) {
- sample += 0x100000000;
- }
-
- return sample / 0x100000000;
- };
- }
-
- function saveGlobal() {
- config.pollution = [];
-
- if (config.noglobals) {
- for (var key in global$1) {
- if (hasOwn.call(global$1, key)) {
-
- // In Opera sometimes DOM element ids show up here, ignore them
- if (/^qunit-test-output/.test(key)) {
- continue;
- }
- config.pollution.push(key);
- }
- }
- }
- }
-
- function checkPollution() {
- var newGlobals,
- deletedGlobals,
- old = config.pollution;
-
- saveGlobal();
-
- newGlobals = diff(config.pollution, old);
- if (newGlobals.length > 0) {
- pushFailure("Introduced global variable(s): " + newGlobals.join(", "));
- }
-
- deletedGlobals = diff(old, config.pollution);
- if (deletedGlobals.length > 0) {
- pushFailure("Deleted global variable(s): " + deletedGlobals.join(", "));
- }
- }
-
- // Will be exposed as QUnit.test
- function test(testName, callback) {
- if (focused) {
- return;
- }
-
- var newTest;
-
- newTest = new Test({
- testName: testName,
- callback: callback
- });
-
- newTest.queue();
- }
-
- // Will be exposed as QUnit.skip
- function skip(testName) {
- if (focused) {
- return;
- }
-
- var test = new Test({
- testName: testName,
- skip: true
- });
-
- test.queue();
- }
-
- // Will be exposed as QUnit.only
- function only(testName, callback) {
- var newTest;
-
- if (focused) {
- return;
- }
-
- config.queue.length = 0;
- focused = true;
-
- newTest = new Test({
- testName: testName,
- callback: callback
- });
-
- newTest.queue();
- }
-
- // Put a hold on processing and return a function that will release it.
- function internalStop(test) {
- var released = false;
-
- test.semaphore += 1;
- config.blocking = true;
-
- // Set a recovery timeout, if so configured.
- if (config.testTimeout && defined.setTimeout) {
- clearTimeout(config.timeout);
- config.timeout = setTimeout(function () {
- pushFailure("Test timed out", sourceFromStacktrace(2));
- internalRecover(test);
- }, config.testTimeout);
- }
-
- return function resume() {
- if (released) {
- return;
- }
-
- released = true;
- test.semaphore -= 1;
- internalStart(test);
- };
- }
-
- // Forcefully release all processing holds.
- function internalRecover(test) {
- test.semaphore = 0;
- internalStart(test);
- }
-
- // Release a processing hold, scheduling a resumption attempt if no holds remain.
- function internalStart(test) {
-
- // If semaphore is non-numeric, throw error
- if (isNaN(test.semaphore)) {
- test.semaphore = 0;
-
- pushFailure("Invalid value on test.semaphore", sourceFromStacktrace(2));
- return;
- }
-
- // Don't start until equal number of stop-calls
- if (test.semaphore > 0) {
- return;
- }
-
- // Throw an Error if start is called more often than stop
- if (test.semaphore < 0) {
- test.semaphore = 0;
-
- pushFailure("Tried to restart test while already started (test's semaphore was 0 already)", sourceFromStacktrace(2));
- return;
- }
-
- // Add a slight delay to allow more assertions etc.
- if (defined.setTimeout) {
- if (config.timeout) {
- clearTimeout(config.timeout);
- }
- config.timeout = setTimeout(function () {
- if (test.semaphore > 0) {
- return;
- }
-
- if (config.timeout) {
- clearTimeout(config.timeout);
- }
-
- begin();
- }, 13);
- } else {
- begin();
- }
- }
-
- function numberOfTests(module) {
- var count = module.tests.length,
- modules = [].concat(toConsumableArray(module.childModules));
-
- // Do a breadth-first traversal of the child modules
- while (modules.length) {
- var nextModule = modules.shift();
- count += nextModule.tests.length;
- modules.push.apply(modules, toConsumableArray(nextModule.childModules));
- }
-
- return count;
- }
-
- function notifyTestsRan(module) {
- module.testsRun++;
- while (module = module.parentModule) {
- module.testsRun++;
- }
- }
-
- function Assert(testContext) {
- this.test = testContext;
- }
-
- // Assert helpers
- Assert.prototype = {
-
- // Specify the number of expected assertions to guarantee that failed test
- // (no assertions are run at all) don't slip through.
- expect: function expect(asserts) {
- if (arguments.length === 1) {
- this.test.expected = asserts;
- } else {
- return this.test.expected;
- }
- },
-
- // Put a hold on processing and return a function that will release it a maximum of once.
- async: function async(count) {
- var resume,
- test$$1 = this.test,
- popped = false,
- acceptCallCount = count;
-
- if (typeof acceptCallCount === "undefined") {
- acceptCallCount = 1;
- }
-
- test$$1.usedAsync = true;
- resume = internalStop(test$$1);
-
- return function done() {
-
- if (popped) {
- test$$1.pushFailure("Too many calls to the `assert.async` callback", sourceFromStacktrace(2));
- return;
- }
- acceptCallCount -= 1;
- if (acceptCallCount > 0) {
- return;
- }
-
- popped = true;
- resume();
- };
- },
-
- // Exports test.push() to the user API
- // Alias of pushResult.
- push: function push(result, actual, expected, message, negative) {
- var currentAssert = this instanceof Assert ? this : config.current.assert;
- return currentAssert.pushResult({
- result: result,
- actual: actual,
- expected: expected,
- message: message,
- negative: negative
- });
- },
-
- pushResult: function pushResult(resultInfo) {
-
- // Destructure of resultInfo = { result, actual, expected, message, negative }
- var assert = this,
- currentTest = assert instanceof Assert && assert.test || config.current;
-
- // Backwards compatibility fix.
- // Allows the direct use of global exported assertions and QUnit.assert.*
- // Although, it's use is not recommended as it can leak assertions
- // to other tests from async tests, because we only get a reference to the current test,
- // not exactly the test where assertion were intended to be called.
- if (!currentTest) {
- throw new Error("assertion outside test context, in " + sourceFromStacktrace(2));
- }
-
- if (currentTest.usedAsync === true && currentTest.semaphore === 0) {
- currentTest.pushFailure("Assertion after the final `assert.async` was resolved", sourceFromStacktrace(2));
-
- // Allow this assertion to continue running anyway...
- }
-
- if (!(assert instanceof Assert)) {
- assert = currentTest.assert;
- }
-
- return assert.test.pushResult(resultInfo);
- },
-
- ok: function ok(result, message) {
- message = message || (result ? "okay" : "failed, expected argument to be truthy, was: " + dump.parse(result));
- this.pushResult({
- result: !!result,
- actual: result,
- expected: true,
- message: message
- });
- },
-
- notOk: function notOk(result, message) {
- message = message || (!result ? "okay" : "failed, expected argument to be falsy, was: " + dump.parse(result));
- this.pushResult({
- result: !result,
- actual: result,
- expected: false,
- message: message
- });
- },
-
- equal: function equal(actual, expected, message) {
-
- // eslint-disable-next-line eqeqeq
- var result = expected == actual;
-
- this.pushResult({
- result: result,
- actual: actual,
- expected: expected,
- message: message
- });
- },
-
- notEqual: function notEqual(actual, expected, message) {
-
- // eslint-disable-next-line eqeqeq
- var result = expected != actual;
-
- this.pushResult({
- result: result,
- actual: actual,
- expected: expected,
- message: message,
- negative: true
- });
- },
-
- propEqual: function propEqual(actual, expected, message) {
- actual = objectValues(actual);
- expected = objectValues(expected);
- this.pushResult({
- result: equiv(actual, expected),
- actual: actual,
- expected: expected,
- message: message
- });
- },
-
- notPropEqual: function notPropEqual(actual, expected, message) {
- actual = objectValues(actual);
- expected = objectValues(expected);
- this.pushResult({
- result: !equiv(actual, expected),
- actual: actual,
- expected: expected,
- message: message,
- negative: true
- });
- },
-
- deepEqual: function deepEqual(actual, expected, message) {
- this.pushResult({
- result: equiv(actual, expected),
- actual: actual,
- expected: expected,
- message: message
- });
- },
-
- notDeepEqual: function notDeepEqual(actual, expected, message) {
- this.pushResult({
- result: !equiv(actual, expected),
- actual: actual,
- expected: expected,
- message: message,
- negative: true
- });
- },
-
- strictEqual: function strictEqual(actual, expected, message) {
- this.pushResult({
- result: expected === actual,
- actual: actual,
- expected: expected,
- message: message
- });
- },
-
- notStrictEqual: function notStrictEqual(actual, expected, message) {
- this.pushResult({
- result: expected !== actual,
- actual: actual,
- expected: expected,
- message: message,
- negative: true
- });
- },
-
- "throws": function throws(block, expected, message) {
- var actual,
- expectedType,
- expectedOutput = expected,
- ok = false,
- currentTest = this instanceof Assert && this.test || config.current;
-
- // 'expected' is optional unless doing string comparison
- if (objectType(expected) === "string") {
- if (message == null) {
- message = expected;
- expected = null;
- } else {
- 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." + "Details in our upgrade guide at https://qunitjs.com/upgrade-guide-2.x/");
- }
- }
-
- currentTest.ignoreGlobalErrors = true;
- try {
- block.call(currentTest.testEnvironment);
- } catch (e) {
- actual = e;
- }
- currentTest.ignoreGlobalErrors = false;
-
- if (actual) {
- expectedType = objectType(expected);
-
- // We don't want to validate thrown error
- if (!expected) {
- ok = true;
- expectedOutput = null;
-
- // Expected is a regexp
- } else if (expectedType === "regexp") {
- ok = expected.test(errorString(actual));
-
- // Expected is a constructor, maybe an Error constructor
- } else if (expectedType === "function" && actual instanceof expected) {
- ok = true;
-
- // Expected is an Error object
- } else if (expectedType === "object") {
- ok = actual instanceof expected.constructor && actual.name === expected.name && actual.message === expected.message;
-
- // Expected is a validation function which returns true if validation passed
- } else if (expectedType === "function" && expected.call({}, actual) === true) {
- expectedOutput = null;
- ok = true;
- }
- }
-
- currentTest.assert.pushResult({
- result: ok,
- actual: actual,
- expected: expectedOutput,
- message: message
- });
- }
- };
-
- // Provide an alternative to assert.throws(), for environments that consider throws a reserved word
- // Known to us are: Closure Compiler, Narwhal
- (function () {
-
- // eslint-disable-next-line dot-notation
- Assert.prototype.raises = Assert.prototype["throws"];
- })();
-
- function errorString(error) {
- var name,
- message,
- resultErrorString = error.toString();
- if (resultErrorString.substring(0, 7) === "[object") {
- name = error.name ? error.name.toString() : "Error";
- message = error.message ? error.message.toString() : "";
- if (name && message) {
- return name + ": " + message;
- } else if (name) {
- return name;
- } else if (message) {
- return message;
- } else {
- return "Error";
- }
- } else {
- return resultErrorString;
- }
- }
-
- /* global module, exports, define */
- function applyDeprecated(name) {
- return function () {
- throw new Error(name + " is removed in QUnit 2.0.\n" + "Details in our upgrade guide at https://qunitjs.com/upgrade-guide-2.x/");
- };
- }
-
- function exportQUnit(QUnit) {
-
- Object.keys(Assert.prototype).forEach(function (key) {
- QUnit[key] = applyDeprecated("`QUnit." + key + "`");
- });
-
- QUnit.asyncTest = function () {
- throw new Error("asyncTest is removed in QUnit 2.0, use QUnit.test() with assert.async() instead.\n" + "Details in our upgrade guide at https://qunitjs.com/upgrade-guide-2.x/");
- };
-
- QUnit.stop = function () {
- throw new Error("QUnit.stop is removed in QUnit 2.0, use QUnit.test() with assert.async() instead.\n" + "Details in our upgrade guide at https://qunitjs.com/upgrade-guide-2.x/");
- };
-
- function resetThrower() {
- throw new Error("QUnit.reset is removed in QUnit 2.0 without replacement.\n" + "Details in our upgrade guide at https://qunitjs.com/upgrade-guide-2.x/");
- }
-
- Object.defineProperty(QUnit, "reset", {
- get: function get() {
- return resetThrower;
- },
- set: resetThrower
- });
-
- if (defined.document) {
-
- // QUnit may be defined when it is preconfigured but then only QUnit and QUnit.config may be defined.
- if (window.QUnit && window.QUnit.version) {
- throw new Error("QUnit has already been defined.");
- }
-
- ["test", "module", "expect", "start", "ok", "notOk", "equal", "notEqual", "propEqual", "notPropEqual", "deepEqual", "notDeepEqual", "strictEqual", "notStrictEqual", "throws", "raises"].forEach(function (key) {
- window[key] = applyDeprecated("The global `" + key + "`");
- });
-
- window.QUnit = QUnit;
- }
-
- // For nodejs
- if (typeof module !== "undefined" && module && module.exports) {
- module.exports = QUnit;
-
- // For consistency with CommonJS environments' exports
- module.exports.QUnit = QUnit;
- }
-
- // For CommonJS with exports, but without module.exports, like Rhino
- if (typeof exports !== "undefined" && exports) {
- exports.QUnit = QUnit;
- }
-
- if (typeof define === "function" && define.amd) {
- define(function () {
- return QUnit;
- });
- QUnit.config.autostart = false;
- }
- }
-
- (function () {
- if (!defined.document) {
- return;
- }
-
- // `onErrorFnPrev` initialized at top of scope
- // Preserve other handlers
- var onErrorFnPrev = window.onerror;
-
- // Cover uncaught exceptions
- // Returning true will suppress the default browser handler,
- // returning false will let it run.
- window.onerror = function (error, filePath, linerNr) {
- var ret = false;
- if (onErrorFnPrev) {
- ret = onErrorFnPrev(error, filePath, linerNr);
- }
-
- // Treat return value as window.onerror itself does,
- // Only do our handling if not suppressed.
- if (ret !== true) {
- if (config.current) {
- if (config.current.ignoreGlobalErrors) {
- return true;
- }
- pushFailure(error, filePath + ":" + linerNr);
- } else {
- test("global failure", extend(function () {
- pushFailure(error, filePath + ":" + linerNr);
- }, { validTest: true }));
- }
- return false;
- }
-
- return ret;
- };
- })();
-
- var QUnit = {};
-
- var globalStartCalled = false;
- var runStarted = false;
-
- var internalState = {
- autorun: false
- };
-
- // Figure out if we're running the tests from a server or not
- QUnit.isLocal = !(defined.document && window.location.protocol !== "file:");
-
- // Expose the current QUnit version
- QUnit.version = "2.1.0";
-
- extend(QUnit, {
-
- // Call on start of module test to prepend name to all tests
- module: function module(name, testEnvironment, executeNow) {
- var module, moduleFns;
- var currentModule = config.currentModule;
-
- if (arguments.length === 2) {
- if (objectType(testEnvironment) === "function") {
- executeNow = testEnvironment;
- testEnvironment = undefined;
- }
- }
-
- module = createModule();
-
- if (testEnvironment && (testEnvironment.setup || testEnvironment.teardown)) {
- console.warn("Module's `setup` and `teardown` are not hooks anymore on QUnit 2.0, use " + "`beforeEach` and `afterEach` instead\n" + "Details in our upgrade guide at https://qunitjs.com/upgrade-guide-2.x/");
- }
-
- moduleFns = {
- before: setHook(module, "before"),
- beforeEach: setHook(module, "beforeEach"),
- afterEach: setHook(module, "afterEach"),
- after: setHook(module, "after")
- };
-
- if (objectType(executeNow) === "function") {
- config.moduleStack.push(module);
- setCurrentModule(module);
- executeNow.call(module.testEnvironment, moduleFns);
- config.moduleStack.pop();
- module = module.parentModule || currentModule;
- }
-
- setCurrentModule(module);
-
- function createModule() {
- var parentModule = config.moduleStack.length ? config.moduleStack.slice(-1)[0] : null;
- var moduleName = parentModule !== null ? [parentModule.name, name].join(" > ") : name;
- var module = {
- name: moduleName,
- parentModule: parentModule,
- tests: [],
- moduleId: generateHash(moduleName),
- testsRun: 0,
- childModules: []
- };
-
- var env = {};
- if (parentModule) {
- parentModule.childModules.push(module);
- extend(env, parentModule.testEnvironment);
- delete env.beforeEach;
- delete env.afterEach;
- }
- extend(env, testEnvironment);
- module.testEnvironment = env;
-
- config.modules.push(module);
- return module;
- }
-
- function setCurrentModule(module) {
- config.currentModule = module;
- }
- },
-
- test: test,
-
- skip: skip,
-
- only: only,
-
- start: function start(count) {
- var globalStartAlreadyCalled = globalStartCalled;
-
- if (!config.current) {
- globalStartCalled = true;
-
- if (runStarted) {
- throw new Error("Called start() while test already started running");
- } else if (globalStartAlreadyCalled || count > 1) {
- throw new Error("Called start() outside of a test context too many times");
- } else if (config.autostart) {
- throw new Error("Called start() outside of a test context when " + "QUnit.config.autostart was true");
- } else if (!config.pageLoaded) {
-
- // The page isn't completely loaded yet, so bail out and let `QUnit.load` handle it
- config.autostart = true;
- return;
- }
- } else {
- throw new Error("QUnit.start cannot be called inside a test context. This feature is removed in " + "QUnit 2.0. For async tests, use QUnit.test() with assert.async() instead.\n" + "Details in our upgrade guide at https://qunitjs.com/upgrade-guide-2.x/");
- }
-
- scheduleBegin();
- },
-
- config: config,
-
- is: is,
-
- objectType: objectType,
-
- extend: extend,
-
- load: function load() {
- config.pageLoaded = true;
-
- // Initialize the configuration options
- extend(config, {
- stats: { all: 0, bad: 0 },
- started: 0,
- updateRate: 1000,
- autostart: true,
- filter: ""
- }, true);
-
- if (!runStarted) {
- config.blocking = false;
-
- if (config.autostart) {
- scheduleBegin();
- }
- }
- },
-
- stack: function stack(offset) {
- offset = (offset || 0) + 2;
- return sourceFromStacktrace(offset);
- }
- });
-
- QUnit.pushFailure = pushFailure;
- QUnit.assert = Assert.prototype;
- QUnit.equiv = equiv;
- QUnit.dump = dump;
-
- // 3.0 TODO: Remove
- function jsDumpThrower() {
- throw new Error("QUnit.jsDump is removed in QUnit 2.0, use QUnit.dump instead.\n" + "Details in our upgrade guide at https://qunitjs.com/upgrade-guide-2.x/");
- }
-
- Object.defineProperty(QUnit, "jsDump", {
- get: jsDumpThrower,
- set: jsDumpThrower
- });
-
- registerLoggingCallbacks(QUnit);
-
- function scheduleBegin() {
-
- runStarted = true;
-
- // Add a slight delay to allow definition of more modules and tests.
- if (defined.setTimeout) {
- setTimeout(function () {
- begin();
- }, 13);
- } else {
- begin();
- }
- }
-
- function begin() {
- var i,
- l,
- modulesLog = [];
-
- // If the test run hasn't officially begun yet
- if (!config.started) {
-
- // Record the time of the test run's beginning
- config.started = now();
-
- // Delete the loose unnamed module if unused.
- if (config.modules[0].name === "" && config.modules[0].tests.length === 0) {
- config.modules.shift();
- }
-
- // Avoid unnecessary information by not logging modules' test environments
- for (i = 0, l = config.modules.length; i < l; i++) {
- modulesLog.push({
- name: config.modules[i].name,
- tests: config.modules[i].tests
- });
- }
-
- // The test run is officially beginning now
- runLoggingCallbacks("begin", {
- totalTests: Test.count,
- modules: modulesLog
- });
- }
-
- config.blocking = false;
- process(true);
- }
-
- function process(last) {
- function next() {
- process(last);
- }
- var start = now();
- config.depth = (config.depth || 0) + 1;
-
- while (config.queue.length && !config.blocking) {
- if (!defined.setTimeout || config.updateRate <= 0 || now() - start < config.updateRate) {
- if (config.current) {
-
- // Reset async tracking for each phase of the Test lifecycle
- config.current.usedAsync = false;
- }
- config.queue.shift()();
- } else {
- setTimeout(next, 13);
- break;
- }
- }
- config.depth--;
- if (last && !config.blocking && !config.queue.length && config.depth === 0) {
- done$1();
- }
- }
-
- function done$1() {
- var runtime,
- passed,
- i,
- key,
- storage = config.storage;
-
- internalState.autorun = true;
-
- runtime = now() - config.started;
- passed = config.stats.all - config.stats.bad;
-
- runLoggingCallbacks("done", {
- failed: config.stats.bad,
- passed: passed,
- total: config.stats.all,
- runtime: runtime
- });
-
- // Clear own storage items if all tests passed
- if (storage && config.stats.bad === 0) {
- for (i = storage.length - 1; i >= 0; i--) {
- key = storage.key(i);
- if (key.indexOf("qunit-test-") === 0) {
- storage.removeItem(key);
- }
- }
- }
- }
-
- function setHook(module, hookName) {
- if (module.testEnvironment === undefined) {
- module.testEnvironment = {};
- }
-
- return function (callback) {
- module.testEnvironment[hookName] = callback;
- };
- }
-
- exportQUnit(QUnit);
-
- (function () {
-
- if (typeof window === "undefined" || typeof document === "undefined") {
- return;
- }
-
- var config = QUnit.config,
- hasOwn = Object.prototype.hasOwnProperty;
-
- // Stores fixture HTML for resetting later
- function storeFixture() {
-
- // Avoid overwriting user-defined values
- if (hasOwn.call(config, "fixture")) {
- return;
- }
-
- var fixture = document.getElementById("qunit-fixture");
- if (fixture) {
- config.fixture = fixture.innerHTML;
- }
- }
-
- QUnit.begin(storeFixture);
-
- // Resets the fixture DOM element if available.
- function resetFixture() {
- if (config.fixture == null) {
- return;
- }
-
- var fixture = document.getElementById("qunit-fixture");
- if (fixture) {
- fixture.innerHTML = config.fixture;
- }
- }
-
- QUnit.testStart(resetFixture);
- })();
-
- // Escape text for attribute or text content.
- function escapeText(s) {
- if (!s) {
- return "";
- }
- s = s + "";
-
- // Both single quotes and double quotes (for attributes)
- return s.replace(/['"<>&]/g, function (s) {
- switch (s) {
- case "'":
- return "'";
- case "\"":
- return """;
- case "<":
- return "<";
- case ">":
- return ">";
- case "&":
- return "&";
- }
- });
- }
-
- (function () {
-
- // Don't load the HTML Reporter on non-browser environments
- if (typeof window === "undefined" || !window.document) {
- return;
- }
-
- QUnit.init = function () {
- throw new Error("QUnit.init is removed in QUnit 2.0, use QUnit.test() with assert.async() instead.\n" + "Details in our upgrade guide at https://qunitjs.com/upgrade-guide-2.x/");
- };
-
- var config = QUnit.config,
- document$$1 = window.document,
- collapseNext = false,
- hasOwn = Object.prototype.hasOwnProperty,
- unfilteredUrl = setUrl({ filter: undefined, module: undefined,
- moduleId: undefined, testId: undefined }),
- modulesList = [];
-
- function addEvent(elem, type, fn) {
- elem.addEventListener(type, fn, false);
- }
-
- function removeEvent(elem, type, fn) {
- elem.removeEventListener(type, fn, false);
- }
-
- function addEvents(elems, type, fn) {
- var i = elems.length;
- while (i--) {
- addEvent(elems[i], type, fn);
- }
- }
-
- function hasClass(elem, name) {
- return (" " + elem.className + " ").indexOf(" " + name + " ") >= 0;
- }
-
- function addClass(elem, name) {
- if (!hasClass(elem, name)) {
- elem.className += (elem.className ? " " : "") + name;
- }
- }
-
- function toggleClass(elem, name, force) {
- if (force || typeof force === "undefined" && !hasClass(elem, name)) {
- addClass(elem, name);
- } else {
- removeClass(elem, name);
- }
- }
-
- function removeClass(elem, name) {
- var set = " " + elem.className + " ";
-
- // Class name may appear multiple times
- while (set.indexOf(" " + name + " ") >= 0) {
- set = set.replace(" " + name + " ", " ");
- }
-
- // Trim for prettiness
- elem.className = typeof set.trim === "function" ? set.trim() : set.replace(/^\s+|\s+$/g, "");
- }
-
- function id(name) {
- return document$$1.getElementById && document$$1.getElementById(name);
- }
-
- function interceptNavigation(ev) {
- applyUrlParams();
-
- if (ev && ev.preventDefault) {
- ev.preventDefault();
- }
-
- return false;
- }
-
- function getUrlConfigHtml() {
- var i,
- j,
- val,
- escaped,
- escapedTooltip,
- selection = false,
- urlConfig = config.urlConfig,
- urlConfigHtml = "";
-
- for (i = 0; i < urlConfig.length; i++) {
-
- // Options can be either strings or objects with nonempty "id" properties
- val = config.urlConfig[i];
- if (typeof val === "string") {
- val = {
- id: val,
- label: val
- };
- }
-
- escaped = escapeText(val.id);
- escapedTooltip = escapeText(val.tooltip);
-
- if (!val.value || typeof val.value === "string") {
- 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>";
- } else {
- urlConfigHtml += "<label for='qunit-urlconfig-" + escaped + "' title='" + escapedTooltip + "'>" + val.label + ": </label><select id='qunit-urlconfig-" + escaped + "' name='" + escaped + "' title='" + escapedTooltip + "'><option></option>";
-
- if (QUnit.is("array", val.value)) {
- for (j = 0; j < val.value.length; j++) {
- escaped = escapeText(val.value[j]);
- urlConfigHtml += "<option value='" + escaped + "'" + (config[val.id] === val.value[j] ? (selection = true) && " selected='selected'" : "") + ">" + escaped + "</option>";
- }
- } else {
- for (j in val.value) {
- if (hasOwn.call(val.value, j)) {
- urlConfigHtml += "<option value='" + escapeText(j) + "'" + (config[val.id] === j ? (selection = true) && " selected='selected'" : "") + ">" + escapeText(val.value[j]) + "</option>";
- }
- }
- }
- if (config[val.id] && !selection) {
- escaped = escapeText(config[val.id]);
- urlConfigHtml += "<option value='" + escaped + "' selected='selected' disabled='disabled'>" + escaped + "</option>";
- }
- urlConfigHtml += "</select>";
- }
- }
-
- return urlConfigHtml;
- }
-
- // Handle "click" events on toolbar checkboxes and "change" for select menus.
- // Updates the URL with the new state of `config.urlConfig` values.
- function toolbarChanged() {
- var updatedUrl,
- value,
- tests,
- field = this,
- params = {};
-
- // Detect if field is a select menu or a checkbox
- if ("selectedIndex" in field) {
- value = field.options[field.selectedIndex].value || undefined;
- } else {
- value = field.checked ? field.defaultValue || true : undefined;
- }
-
- params[field.name] = value;
- updatedUrl = setUrl(params);
-
- // Check if we can apply the change without a page refresh
- if ("hidepassed" === field.name && "replaceState" in window.history) {
- QUnit.urlParams[field.name] = value;
- config[field.name] = value || false;
- tests = id("qunit-tests");
- if (tests) {
- toggleClass(tests, "hidepass", value || false);
- }
- window.history.replaceState(null, "", updatedUrl);
- } else {
- window.location = updatedUrl;
- }
- }
-
- function setUrl(params) {
- var key,
- arrValue,
- i,
- querystring = "?",
- location = window.location;
-
- params = QUnit.extend(QUnit.extend({}, QUnit.urlParams), params);
-
- for (key in params) {
-
- // Skip inherited or undefined properties
- if (hasOwn.call(params, key) && params[key] !== undefined) {
-
- // Output a parameter for each value of this key (but usually just one)
- arrValue = [].concat(params[key]);
- for (i = 0; i < arrValue.length; i++) {
- querystring += encodeURIComponent(key);
- if (arrValue[i] !== true) {
- querystring += "=" + encodeURIComponent(arrValue[i]);
- }
- querystring += "&";
- }
- }
- }
- return location.protocol + "//" + location.host + location.pathname + querystring.slice(0, -1);
- }
-
- function applyUrlParams() {
- var i,
- selectedModules = [],
- modulesList = id("qunit-modulefilter-dropdown-list").getElementsByTagName("input"),
- filter = id("qunit-filter-input").value;
-
- for (i = 0; i < modulesList.length; i++) {
- if (modulesList[i].checked) {
- selectedModules.push(modulesList[i].value);
- }
- }
-
- window.location = setUrl({
- filter: filter === "" ? undefined : filter,
- moduleId: selectedModules.length === 0 ? undefined : selectedModules,
-
- // Remove module and testId filter
- module: undefined,
- testId: undefined
- });
- }
-
- function toolbarUrlConfigContainer() {
- var urlConfigContainer = document$$1.createElement("span");
-
- urlConfigContainer.innerHTML = getUrlConfigHtml();
- addClass(urlConfigContainer, "qunit-url-config");
-
- addEvents(urlConfigContainer.getElementsByTagName("input"), "change", toolbarChanged);
- addEvents(urlConfigContainer.getElementsByTagName("select"), "change", toolbarChanged);
-
- return urlConfigContainer;
- }
-
- function toolbarLooseFilter() {
- var filter = document$$1.createElement("form"),
- label = document$$1.createElement("label"),
- input = document$$1.createElement("input"),
- button = document$$1.createElement("button");
-
- addClass(filter, "qunit-filter");
-
- label.innerHTML = "Filter: ";
-
- input.type = "text";
- input.value = config.filter || "";
- input.name = "filter";
- input.id = "qunit-filter-input";
-
- button.innerHTML = "Go";
-
- label.appendChild(input);
-
- filter.appendChild(label);
- filter.appendChild(document$$1.createTextNode(" "));
- filter.appendChild(button);
- addEvent(filter, "submit", interceptNavigation);
-
- return filter;
- }
-
- function moduleListHtml() {
- var i,
- checked,
- html = "";
-
- for (i = 0; i < config.modules.length; i++) {
- if (config.modules[i].name !== "") {
- checked = config.moduleId.indexOf(config.modules[i].moduleId) > -1;
- 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>";
- }
- }
-
- return html;
- }
-
- function toolbarModuleFilter() {
- var allCheckbox,
- commit,
- reset,
- moduleFilter = document$$1.createElement("form"),
- label = document$$1.createElement("label"),
- moduleSearch = document$$1.createElement("input"),
- dropDown = document$$1.createElement("div"),
- actions = document$$1.createElement("span"),
- dropDownList = document$$1.createElement("ul"),
- dirty = false;
-
- moduleSearch.id = "qunit-modulefilter-search";
- addEvent(moduleSearch, "input", searchInput);
- addEvent(moduleSearch, "input", searchFocus);
- addEvent(moduleSearch, "focus", searchFocus);
- addEvent(moduleSearch, "click", searchFocus);
-
- label.id = "qunit-modulefilter-search-container";
- label.innerHTML = "Module: ";
- label.appendChild(moduleSearch);
-
- actions.id = "qunit-modulefilter-actions";
- 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>";
- allCheckbox = actions.lastChild.firstChild;
- commit = actions.firstChild;
- reset = commit.nextSibling;
- addEvent(commit, "click", applyUrlParams);
-
- dropDownList.id = "qunit-modulefilter-dropdown-list";
- dropDownList.innerHTML = moduleListHtml();
-
- dropDown.id = "qunit-modulefilter-dropdown";
- dropDown.style.display = "none";
- dropDown.appendChild(actions);
- dropDown.appendChild(dropDownList);
- addEvent(dropDown, "change", selectionChange);
- selectionChange();
-
- moduleFilter.id = "qunit-modulefilter";
- moduleFilter.appendChild(label);
- moduleFilter.appendChild(dropDown);
- addEvent(moduleFilter, "submit", interceptNavigation);
- addEvent(moduleFilter, "reset", function () {
-
- // Let the reset happen, then update styles
- window.setTimeout(selectionChange);
- });
-
- // Enables show/hide for the dropdown
- function searchFocus() {
- if (dropDown.style.display !== "none") {
- return;
- }
-
- dropDown.style.display = "block";
- addEvent(document$$1, "click", hideHandler);
- addEvent(document$$1, "keydown", hideHandler);
-
- // Hide on Escape keydown or outside-container click
- function hideHandler(e) {
- var inContainer = moduleFilter.contains(e.target);
-
- if (e.keyCode === 27 || !inContainer) {
- if (e.keyCode === 27 && inContainer) {
- moduleSearch.focus();
- }
- dropDown.style.display = "none";
- removeEvent(document$$1, "click", hideHandler);
- removeEvent(document$$1, "keydown", hideHandler);
- moduleSearch.value = "";
- searchInput();
- }
- }
- }
-
- // Processes module search box input
- function searchInput() {
- var i,
- item,
- searchText = moduleSearch.value.toLowerCase(),
- listItems = dropDownList.children;
-
- for (i = 0; i < listItems.length; i++) {
- item = listItems[i];
- if (!searchText || item.textContent.toLowerCase().indexOf(searchText) > -1) {
- item.style.display = "";
- } else {
- item.style.display = "none";
- }
- }
- }
-
- // Processes selection changes
- function selectionChange(evt) {
- var i,
- item,
- checkbox = evt && evt.target || allCheckbox,
- modulesList = dropDownList.getElementsByTagName("input"),
- selectedNames = [];
-
- toggleClass(checkbox.parentNode, "checked", checkbox.checked);
-
- dirty = false;
- if (checkbox.checked && checkbox !== allCheckbox) {
- allCheckbox.checked = false;
- removeClass(allCheckbox.parentNode, "checked");
- }
- for (i = 0; i < modulesList.length; i++) {
- item = modulesList[i];
- if (!evt) {
- toggleClass(item.parentNode, "checked", item.checked);
- } else if (checkbox === allCheckbox && checkbox.checked) {
- item.checked = false;
- removeClass(item.parentNode, "checked");
- }
- dirty = dirty || item.checked !== item.defaultChecked;
- if (item.checked) {
- selectedNames.push(item.parentNode.textContent);
- }
- }
-
- commit.style.display = reset.style.display = dirty ? "" : "none";
- moduleSearch.placeholder = selectedNames.join(", ") || allCheckbox.parentNode.textContent;
- moduleSearch.title = "Type to filter list. Current selection:\n" + (selectedNames.join("\n") || allCheckbox.parentNode.textContent);
- }
-
- return moduleFilter;
- }
-
- function appendToolbar() {
- var toolbar = id("qunit-testrunner-toolbar");
-
- if (toolbar) {
- toolbar.appendChild(toolbarUrlConfigContainer());
- toolbar.appendChild(toolbarModuleFilter());
- toolbar.appendChild(toolbarLooseFilter());
- toolbar.appendChild(document$$1.createElement("div")).className = "clearfix";
- }
- }
-
- function appendHeader() {
- var header = id("qunit-header");
-
- if (header) {
- header.innerHTML = "<a href='" + escapeText(unfilteredUrl) + "'>" + header.innerHTML + "</a> ";
- }
- }
-
- function appendBanner() {
- var banner = id("qunit-banner");
-
- if (banner) {
- banner.className = "";
- }
- }
-
- function appendTestResults() {
- var tests = id("qunit-tests"),
- result = id("qunit-testresult");
-
- if (result) {
- result.parentNode.removeChild(result);
- }
-
- if (tests) {
- tests.innerHTML = "";
- result = document$$1.createElement("p");
- result.id = "qunit-testresult";
- result.className = "result";
- tests.parentNode.insertBefore(result, tests);
- result.innerHTML = "Running...<br /> ";
- }
- }
-
- function appendFilteredTest() {
- var testId = QUnit.config.testId;
- if (!testId || testId.length <= 0) {
- return "";
- }
- return "<div id='qunit-filteredTest'>Rerunning selected tests: " + escapeText(testId.join(", ")) + " <a id='qunit-clearFilter' href='" + escapeText(unfilteredUrl) + "'>Run all tests</a></div>";
- }
-
- function appendUserAgent() {
- var userAgent = id("qunit-userAgent");
-
- if (userAgent) {
- userAgent.innerHTML = "";
- userAgent.appendChild(document$$1.createTextNode("QUnit " + QUnit.version + "; " + navigator.userAgent));
- }
- }
-
- function appendInterface() {
- var qunit = id("qunit");
-
- if (qunit) {
- 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>";
- }
-
- appendHeader();
- appendBanner();
- appendTestResults();
- appendUserAgent();
- appendToolbar();
- }
-
- function appendTestsList(modules) {
- var i, l, x, z, test, moduleObj;
-
- for (i = 0, l = modules.length; i < l; i++) {
- moduleObj = modules[i];
-
- for (x = 0, z = moduleObj.tests.length; x < z; x++) {
- test = moduleObj.tests[x];
-
- appendTest(test.name, test.testId, moduleObj.name);
- }
- }
- }
-
- function appendTest(name, testId, moduleName) {
- var title,
- rerunTrigger,
- testBlock,
- assertList,
- tests = id("qunit-tests");
-
- if (!tests) {
- return;
- }
-
- title = document$$1.createElement("strong");
- title.innerHTML = getNameHtml(name, moduleName);
-
- rerunTrigger = document$$1.createElement("a");
- rerunTrigger.innerHTML = "Rerun";
- rerunTrigger.href = setUrl({ testId: testId });
-
- testBlock = document$$1.createElement("li");
- testBlock.appendChild(title);
- testBlock.appendChild(rerunTrigger);
- testBlock.id = "qunit-test-output-" + testId;
-
- assertList = document$$1.createElement("ol");
- assertList.className = "qunit-assert-list";
-
- testBlock.appendChild(assertList);
-
- tests.appendChild(testBlock);
- }
-
- // HTML Reporter initialization and load
- QUnit.begin(function (details) {
- var i, moduleObj, tests;
-
- // Sort modules by name for the picker
- for (i = 0; i < details.modules.length; i++) {
- moduleObj = details.modules[i];
- if (moduleObj.name) {
- modulesList.push(moduleObj.name);
- }
- }
- modulesList.sort(function (a, b) {
- return a.localeCompare(b);
- });
-
- // Initialize QUnit elements
- appendInterface();
- appendTestsList(details.modules);
- tests = id("qunit-tests");
- if (tests && config.hidepassed) {
- addClass(tests, "hidepass");
- }
- });
-
- QUnit.done(function (details) {
- var banner = id("qunit-banner"),
- tests = id("qunit-tests"),
- html = ["Tests completed in ", details.runtime, " milliseconds.<br />", "<span class='passed'>", details.passed, "</span> assertions of <span class='total'>", details.total, "</span> passed, <span class='failed'>", details.failed, "</span> failed."].join("");
-
- if (banner) {
- banner.className = details.failed ? "qunit-fail" : "qunit-pass";
- }
-
- if (tests) {
- id("qunit-testresult").innerHTML = html;
- }
-
- if (config.altertitle && document$$1.title) {
-
- // Show ✖ for good, ✔ for bad suite result in title
- // use escape sequences in case file gets loaded with non-utf-8-charset
- document$$1.title = [details.failed ? "\u2716" : "\u2714", document$$1.title.replace(/^[\u2714\u2716] /i, "")].join(" ");
- }
-
- // Scroll back to top to show results
- if (config.scrolltop && window.scrollTo) {
- window.scrollTo(0, 0);
- }
- });
-
- function getNameHtml(name, module) {
- var nameHtml = "";
-
- if (module) {
- nameHtml = "<span class='module-name'>" + escapeText(module) + "</span>: ";
- }
-
- nameHtml += "<span class='test-name'>" + escapeText(name) + "</span>";
-
- return nameHtml;
- }
-
- QUnit.testStart(function (details) {
- var running, testBlock, bad;
-
- testBlock = id("qunit-test-output-" + details.testId);
- if (testBlock) {
- testBlock.className = "running";
- } else {
-
- // Report later registered tests
- appendTest(details.name, details.testId, details.module);
- }
-
- running = id("qunit-testresult");
- if (running) {
- bad = QUnit.config.reorder && details.previousFailure;
-
- running.innerHTML = (bad ? "Rerunning previously failed test: <br />" : "Running: <br />") + getNameHtml(details.name, details.module);
- }
- });
-
- function stripHtml(string) {
-
- // Strip tags, html entity and whitespaces
- return string.replace(/<\/?[^>]+(>|$)/g, "").replace(/\"/g, "").replace(/\s+/g, "");
- }
-
- QUnit.log(function (details) {
- var assertList,
- assertLi,
- message,
- expected,
- actual,
- diff,
- showDiff = false,
- testItem = id("qunit-test-output-" + details.testId);
-
- if (!testItem) {
- return;
- }
-
- message = escapeText(details.message) || (details.result ? "okay" : "failed");
- message = "<span class='test-message'>" + message + "</span>";
- message += "<span class='runtime'>@ " + details.runtime + " ms</span>";
-
- // The pushFailure doesn't provide details.expected
- // when it calls, it's implicit to also not show expected and diff stuff
- // Also, we need to check details.expected existence, as it can exist and be undefined
- if (!details.result && hasOwn.call(details, "expected")) {
- if (details.negative) {
- expected = "NOT " + QUnit.dump.parse(details.expected);
- } else {
- expected = QUnit.dump.parse(details.expected);
- }
-
- actual = QUnit.dump.parse(details.actual);
- message += "<table><tr class='test-expected'><th>Expected: </th><td><pre>" + escapeText(expected) + "</pre></td></tr>";
-
- if (actual !== expected) {
-
- message += "<tr class='test-actual'><th>Result: </th><td><pre>" + escapeText(actual) + "</pre></td></tr>";
-
- // Don't show diff if actual or expected are booleans
- if (!/^(true|false)$/.test(actual) && !/^(true|false)$/.test(expected)) {
- diff = QUnit.diff(expected, actual);
- showDiff = stripHtml(diff).length !== stripHtml(expected).length + stripHtml(actual).length;
- }
-
- // Don't show diff if expected and actual are totally different
- if (showDiff) {
- message += "<tr class='test-diff'><th>Diff: </th><td><pre>" + diff + "</pre></td></tr>";
- }
- } else if (expected.indexOf("[object Array]") !== -1 || expected.indexOf("[object Object]") !== -1) {
- 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>";
- } else {
- message += "<tr class='test-message'><th>Message: </th><td>" + "Diff suppressed as the expected and actual results have an equivalent" + " serialization</td></tr>";
- }
-
- if (details.source) {
- message += "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText(details.source) + "</pre></td></tr>";
- }
-
- message += "</table>";
-
- // This occurs when pushFailure is set and we have an extracted stack trace
- } else if (!details.result && details.source) {
- message += "<table>" + "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText(details.source) + "</pre></td></tr>" + "</table>";
- }
-
- assertList = testItem.getElementsByTagName("ol")[0];
-
- assertLi = document$$1.createElement("li");
- assertLi.className = details.result ? "pass" : "fail";
- assertLi.innerHTML = message;
- assertList.appendChild(assertLi);
- });
-
- QUnit.testDone(function (details) {
- var testTitle,
- time,
- testItem,
- assertList,
- good,
- bad,
- testCounts,
- skipped,
- sourceName,
- tests = id("qunit-tests");
-
- if (!tests) {
- return;
- }
-
- testItem = id("qunit-test-output-" + details.testId);
-
- assertList = testItem.getElementsByTagName("ol")[0];
-
- good = details.passed;
- bad = details.failed;
-
- if (bad === 0) {
-
- // Collapse the passing tests
- addClass(assertList, "qunit-collapsed");
- } else if (config.collapse) {
- if (!collapseNext) {
-
- // Skip collapsing the first failing test
- collapseNext = true;
- } else {
-
- // Collapse remaining tests
- addClass(assertList, "qunit-collapsed");
- }
- }
-
- // The testItem.firstChild is the test name
- testTitle = testItem.firstChild;
-
- testCounts = bad ? "<b class='failed'>" + bad + "</b>, " + "<b class='passed'>" + good + "</b>, " : "";
-
- testTitle.innerHTML += " <b class='counts'>(" + testCounts + details.assertions.length + ")</b>";
-
- if (details.skipped) {
- testItem.className = "skipped";
- skipped = document$$1.createElement("em");
- skipped.className = "qunit-skipped-label";
- skipped.innerHTML = "skipped";
- testItem.insertBefore(skipped, testTitle);
- } else {
- addEvent(testTitle, "click", function () {
- toggleClass(assertList, "qunit-collapsed");
- });
-
- testItem.className = bad ? "fail" : "pass";
-
- time = document$$1.createElement("span");
- time.className = "runtime";
- time.innerHTML = details.runtime + " ms";
- testItem.insertBefore(time, assertList);
- }
-
- // Show the source of the test when showing assertions
- if (details.source) {
- sourceName = document$$1.createElement("p");
- sourceName.innerHTML = "<strong>Source: </strong>" + details.source;
- addClass(sourceName, "qunit-source");
- if (bad === 0) {
- addClass(sourceName, "qunit-collapsed");
- }
- addEvent(testTitle, "click", function () {
- toggleClass(sourceName, "qunit-collapsed");
- });
- testItem.appendChild(sourceName);
- }
- });
-
- // Avoid readyState issue with phantomjs
- // Ref: #818
- var notPhantom = function (p) {
- return !(p && p.version && p.version.major > 0);
- }(window.phantom);
-
- if (notPhantom && document$$1.readyState === "complete") {
- QUnit.load();
- } else {
- addEvent(window, "load", QUnit.load);
- }
- })();
-
- /*
- * This file is a modified version of google-diff-match-patch's JavaScript implementation
- * (https://code.google.com/p/google-diff-match-patch/source/browse/trunk/javascript/diff_match_patch_uncompressed.js),
- * modifications are licensed as more fully set forth in LICENSE.txt.
- *
- * The original source of google-diff-match-patch is attributable and licensed as follows:
- *
- * Copyright 2006 Google Inc.
- * https://code.google.com/p/google-diff-match-patch/
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * More Info:
- * https://code.google.com/p/google-diff-match-patch/
- *
- * Usage: QUnit.diff(expected, actual)
- *
- */
- QUnit.diff = function () {
- function DiffMatchPatch() {}
-
- // DIFF FUNCTIONS
-
- /**
- * The data structure representing a diff is an array of tuples:
- * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
- * which means: delete 'Hello', add 'Goodbye' and keep ' world.'
- */
- var DIFF_DELETE = -1,
- DIFF_INSERT = 1,
- DIFF_EQUAL = 0;
-
- /**
- * Find the differences between two texts. Simplifies the problem by stripping
- * any common prefix or suffix off the texts before diffing.
- * @param {string} text1 Old string to be diffed.
- * @param {string} text2 New string to be diffed.
- * @param {boolean=} optChecklines Optional speedup flag. If present and false,
- * then don't run a line-level diff first to identify the changed areas.
- * Defaults to true, which does a faster, slightly less optimal diff.
- * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
- */
- DiffMatchPatch.prototype.DiffMain = function (text1, text2, optChecklines) {
- var deadline, checklines, commonlength, commonprefix, commonsuffix, diffs;
-
- // The diff must be complete in up to 1 second.
- deadline = new Date().getTime() + 1000;
-
- // Check for null inputs.
- if (text1 === null || text2 === null) {
- throw new Error("Null input. (DiffMain)");
- }
-
- // Check for equality (speedup).
- if (text1 === text2) {
- if (text1) {
- return [[DIFF_EQUAL, text1]];
- }
- return [];
- }
-
- if (typeof optChecklines === "undefined") {
- optChecklines = true;
- }
-
- checklines = optChecklines;
-
- // Trim off common prefix (speedup).
- commonlength = this.diffCommonPrefix(text1, text2);
- commonprefix = text1.substring(0, commonlength);
- text1 = text1.substring(commonlength);
- text2 = text2.substring(commonlength);
-
- // Trim off common suffix (speedup).
- commonlength = this.diffCommonSuffix(text1, text2);
- commonsuffix = text1.substring(text1.length - commonlength);
- text1 = text1.substring(0, text1.length - commonlength);
- text2 = text2.substring(0, text2.length - commonlength);
-
- // Compute the diff on the middle block.
- diffs = this.diffCompute(text1, text2, checklines, deadline);
-
- // Restore the prefix and suffix.
- if (commonprefix) {
- diffs.unshift([DIFF_EQUAL, commonprefix]);
- }
- if (commonsuffix) {
- diffs.push([DIFF_EQUAL, commonsuffix]);
- }
- this.diffCleanupMerge(diffs);
- return diffs;
- };
-
- /**
- * Reduce the number of edits by eliminating operationally trivial equalities.
- * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
- */
- DiffMatchPatch.prototype.diffCleanupEfficiency = function (diffs) {
- var changes, equalities, equalitiesLength, lastequality, pointer, preIns, preDel, postIns, postDel;
- changes = false;
- equalities = []; // Stack of indices where equalities are found.
- equalitiesLength = 0; // Keeping our own length var is faster in JS.
- /** @type {?string} */
- lastequality = null;
-
- // Always equal to diffs[equalities[equalitiesLength - 1]][1]
- pointer = 0; // Index of current position.
-
- // Is there an insertion operation before the last equality.
- preIns = false;
-
- // Is there a deletion operation before the last equality.
- preDel = false;
-
- // Is there an insertion operation after the last equality.
- postIns = false;
-
- // Is there a deletion operation after the last equality.
- postDel = false;
- while (pointer < diffs.length) {
-
- // Equality found.
- if (diffs[pointer][0] === DIFF_EQUAL) {
- if (diffs[pointer][1].length < 4 && (postIns || postDel)) {
-
- // Candidate found.
- equalities[equalitiesLength++] = pointer;
- preIns = postIns;
- preDel = postDel;
- lastequality = diffs[pointer][1];
- } else {
-
- // Not a candidate, and can never become one.
- equalitiesLength = 0;
- lastequality = null;
- }
- postIns = postDel = false;
-
- // An insertion or deletion.
- } else {
-
- if (diffs[pointer][0] === DIFF_DELETE) {
- postDel = true;
- } else {
- postIns = true;
- }
-
- /*
- * Five types to be split:
- * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
- * <ins>A</ins>X<ins>C</ins><del>D</del>
- * <ins>A</ins><del>B</del>X<ins>C</ins>
- * <ins>A</del>X<ins>C</ins><del>D</del>
- * <ins>A</ins><del>B</del>X<del>C</del>
- */
- if (lastequality && (preIns && preDel && postIns && postDel || lastequality.length < 2 && preIns + preDel + postIns + postDel === 3)) {
-
- // Duplicate record.
- diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastequality]);
-
- // Change second copy to insert.
- diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
- equalitiesLength--; // Throw away the equality we just deleted;
- lastequality = null;
- if (preIns && preDel) {
-
- // No changes made which could affect previous entry, keep going.
- postIns = postDel = true;
- equalitiesLength = 0;
- } else {
- equalitiesLength--; // Throw away the previous equality.
- pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
- postIns = postDel = false;
- }
- changes = true;
- }
- }
- pointer++;
- }
-
- if (changes) {
- this.diffCleanupMerge(diffs);
- }
- };
-
- /**
- * Convert a diff array into a pretty HTML report.
- * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
- * @param {integer} string to be beautified.
- * @return {string} HTML representation.
- */
- DiffMatchPatch.prototype.diffPrettyHtml = function (diffs) {
- var op,
- data,
- x,
- html = [];
- for (x = 0; x < diffs.length; x++) {
- op = diffs[x][0]; // Operation (insert, delete, equal)
- data = diffs[x][1]; // Text of change.
- switch (op) {
- case DIFF_INSERT:
- html[x] = "<ins>" + escapeText(data) + "</ins>";
- break;
- case DIFF_DELETE:
- html[x] = "<del>" + escapeText(data) + "</del>";
- break;
- case DIFF_EQUAL:
- html[x] = "<span>" + escapeText(data) + "</span>";
- break;
- }
- }
- return html.join("");
- };
-
- /**
- * Determine the common prefix of two strings.
- * @param {string} text1 First string.
- * @param {string} text2 Second string.
- * @return {number} The number of characters common to the start of each
- * string.
- */
- DiffMatchPatch.prototype.diffCommonPrefix = function (text1, text2) {
- var pointermid, pointermax, pointermin, pointerstart;
-
- // Quick check for common null cases.
- if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) {
- return 0;
- }
-
- // Binary search.
- // Performance analysis: https://neil.fraser.name/news/2007/10/09/
- pointermin = 0;
- pointermax = Math.min(text1.length, text2.length);
- pointermid = pointermax;
- pointerstart = 0;
- while (pointermin < pointermid) {
- if (text1.substring(pointerstart, pointermid) === text2.substring(pointerstart, pointermid)) {
- pointermin = pointermid;
- pointerstart = pointermin;
- } else {
- pointermax = pointermid;
- }
- pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
- }
- return pointermid;
- };
-
- /**
- * Determine the common suffix of two strings.
- * @param {string} text1 First string.
- * @param {string} text2 Second string.
- * @return {number} The number of characters common to the end of each string.
- */
- DiffMatchPatch.prototype.diffCommonSuffix = function (text1, text2) {
- var pointermid, pointermax, pointermin, pointerend;
-
- // Quick check for common null cases.
- if (!text1 || !text2 || text1.charAt(text1.length - 1) !== text2.charAt(text2.length - 1)) {
- return 0;
- }
-
- // Binary search.
- // Performance analysis: https://neil.fraser.name/news/2007/10/09/
- pointermin = 0;
- pointermax = Math.min(text1.length, text2.length);
- pointermid = pointermax;
- pointerend = 0;
- while (pointermin < pointermid) {
- if (text1.substring(text1.length - pointermid, text1.length - pointerend) === text2.substring(text2.length - pointermid, text2.length - pointerend)) {
- pointermin = pointermid;
- pointerend = pointermin;
- } else {
- pointermax = pointermid;
- }
- pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
- }
- return pointermid;
- };
-
- /**
- * Find the differences between two texts. Assumes that the texts do not
- * have any common prefix or suffix.
- * @param {string} text1 Old string to be diffed.
- * @param {string} text2 New string to be diffed.
- * @param {boolean} checklines Speedup flag. If false, then don't run a
- * line-level diff first to identify the changed areas.
- * If true, then run a faster, slightly less optimal diff.
- * @param {number} deadline Time when the diff should be complete by.
- * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
- * @private
- */
- DiffMatchPatch.prototype.diffCompute = function (text1, text2, checklines, deadline) {
- var diffs, longtext, shorttext, i, hm, text1A, text2A, text1B, text2B, midCommon, diffsA, diffsB;
-
- if (!text1) {
-
- // Just add some text (speedup).
- return [[DIFF_INSERT, text2]];
- }
-
- if (!text2) {
-
- // Just delete some text (speedup).
- return [[DIFF_DELETE, text1]];
- }
-
- longtext = text1.length > text2.length ? text1 : text2;
- shorttext = text1.length > text2.length ? text2 : text1;
- i = longtext.indexOf(shorttext);
- if (i !== -1) {
-
- // Shorter text is inside the longer text (speedup).
- diffs = [[DIFF_INSERT, longtext.substring(0, i)], [DIFF_EQUAL, shorttext], [DIFF_INSERT, longtext.substring(i + shorttext.length)]];
-
- // Swap insertions for deletions if diff is reversed.
- if (text1.length > text2.length) {
- diffs[0][0] = diffs[2][0] = DIFF_DELETE;
- }
- return diffs;
- }
-
- if (shorttext.length === 1) {
-
- // Single character string.
- // After the previous speedup, the character can't be an equality.
- return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
- }
-
- // Check to see if the problem can be split in two.
- hm = this.diffHalfMatch(text1, text2);
- if (hm) {
-
- // A half-match was found, sort out the return data.
- text1A = hm[0];
- text1B = hm[1];
- text2A = hm[2];
- text2B = hm[3];
- midCommon = hm[4];
-
- // Send both pairs off for separate processing.
- diffsA = this.DiffMain(text1A, text2A, checklines, deadline);
- diffsB = this.DiffMain(text1B, text2B, checklines, deadline);
-
- // Merge the results.
- return diffsA.concat([[DIFF_EQUAL, midCommon]], diffsB);
- }
-
- if (checklines && text1.length > 100 && text2.length > 100) {
- return this.diffLineMode(text1, text2, deadline);
- }
-
- return this.diffBisect(text1, text2, deadline);
- };
-
- /**
- * Do the two texts share a substring which is at least half the length of the
- * longer text?
- * This speedup can produce non-minimal diffs.
- * @param {string} text1 First string.
- * @param {string} text2 Second string.
- * @return {Array.<string>} Five element Array, containing the prefix of
- * text1, the suffix of text1, the prefix of text2, the suffix of
- * text2 and the common middle. Or null if there was no match.
- * @private
- */
- DiffMatchPatch.prototype.diffHalfMatch = function (text1, text2) {
- var longtext, shorttext, dmp, text1A, text2B, text2A, text1B, midCommon, hm1, hm2, hm;
-
- longtext = text1.length > text2.length ? text1 : text2;
- shorttext = text1.length > text2.length ? text2 : text1;
- if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {
- return null; // Pointless.
- }
- dmp = this; // 'this' becomes 'window' in a closure.
-
- /**
- * Does a substring of shorttext exist within longtext such that the substring
- * is at least half the length of longtext?
- * Closure, but does not reference any external variables.
- * @param {string} longtext Longer string.
- * @param {string} shorttext Shorter string.
- * @param {number} i Start index of quarter length substring within longtext.
- * @return {Array.<string>} Five element Array, containing the prefix of
- * longtext, the suffix of longtext, the prefix of shorttext, the suffix
- * of shorttext and the common middle. Or null if there was no match.
- * @private
- */
- function diffHalfMatchI(longtext, shorttext, i) {
- var seed, j, bestCommon, prefixLength, suffixLength, bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB;
-
- // Start with a 1/4 length substring at position i as a seed.
- seed = longtext.substring(i, i + Math.floor(longtext.length / 4));
- j = -1;
- bestCommon = "";
- while ((j = shorttext.indexOf(seed, j + 1)) !== -1) {
- prefixLength = dmp.diffCommonPrefix(longtext.substring(i), shorttext.substring(j));
- suffixLength = dmp.diffCommonSuffix(longtext.substring(0, i), shorttext.substring(0, j));
- if (bestCommon.length < suffixLength + prefixLength) {
- bestCommon = shorttext.substring(j - suffixLength, j) + shorttext.substring(j, j + prefixLength);
- bestLongtextA = longtext.substring(0, i - suffixLength);
- bestLongtextB = longtext.substring(i + prefixLength);
- bestShorttextA = shorttext.substring(0, j - suffixLength);
- bestShorttextB = shorttext.substring(j + prefixLength);
- }
- }
- if (bestCommon.length * 2 >= longtext.length) {
- return [bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB, bestCommon];
- } else {
- return null;
- }
- }
-
- // First check if the second quarter is the seed for a half-match.
- hm1 = diffHalfMatchI(longtext, shorttext, Math.ceil(longtext.length / 4));
-
- // Check again based on the third quarter.
- hm2 = diffHalfMatchI(longtext, shorttext, Math.ceil(longtext.length / 2));
- if (!hm1 && !hm2) {
- return null;
- } else if (!hm2) {
- hm = hm1;
- } else if (!hm1) {
- hm = hm2;
- } else {
-
- // Both matched. Select the longest.
- hm = hm1[4].length > hm2[4].length ? hm1 : hm2;
- }
-
- // A half-match was found, sort out the return data.
- if (text1.length > text2.length) {
- text1A = hm[0];
- text1B = hm[1];
- text2A = hm[2];
- text2B = hm[3];
- } else {
- text2A = hm[0];
- text2B = hm[1];
- text1A = hm[2];
- text1B = hm[3];
- }
- midCommon = hm[4];
- return [text1A, text1B, text2A, text2B, midCommon];
- };
-
- /**
- * Do a quick line-level diff on both strings, then rediff the parts for
- * greater accuracy.
- * This speedup can produce non-minimal diffs.
- * @param {string} text1 Old string to be diffed.
- * @param {string} text2 New string to be diffed.
- * @param {number} deadline Time when the diff should be complete by.
- * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
- * @private
- */
- DiffMatchPatch.prototype.diffLineMode = function (text1, text2, deadline) {
- var a, diffs, linearray, pointer, countInsert, countDelete, textInsert, textDelete, j;
-
- // Scan the text on a line-by-line basis first.
- a = this.diffLinesToChars(text1, text2);
- text1 = a.chars1;
- text2 = a.chars2;
- linearray = a.lineArray;
-
- diffs = this.DiffMain(text1, text2, false, deadline);
-
- // Convert the diff back to original text.
- this.diffCharsToLines(diffs, linearray);
-
- // Eliminate freak matches (e.g. blank lines)
- this.diffCleanupSemantic(diffs);
-
- // Rediff any replacement blocks, this time character-by-character.
- // Add a dummy entry at the end.
- diffs.push([DIFF_EQUAL, ""]);
- pointer = 0;
- countDelete = 0;
- countInsert = 0;
- textDelete = "";
- textInsert = "";
- while (pointer < diffs.length) {
- switch (diffs[pointer][0]) {
- case DIFF_INSERT:
- countInsert++;
- textInsert += diffs[pointer][1];
- break;
- case DIFF_DELETE:
- countDelete++;
- textDelete += diffs[pointer][1];
- break;
- case DIFF_EQUAL:
-
- // Upon reaching an equality, check for prior redundancies.
- if (countDelete >= 1 && countInsert >= 1) {
-
- // Delete the offending records and add the merged ones.
- diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert);
- pointer = pointer - countDelete - countInsert;
- a = this.DiffMain(textDelete, textInsert, false, deadline);
- for (j = a.length - 1; j >= 0; j--) {
- diffs.splice(pointer, 0, a[j]);
- }
- pointer = pointer + a.length;
- }
- countInsert = 0;
- countDelete = 0;
- textDelete = "";
- textInsert = "";
- break;
- }
- pointer++;
- }
- diffs.pop(); // Remove the dummy entry at the end.
-
- return diffs;
- };
-
- /**
- * Find the 'middle snake' of a diff, split the problem in two
- * and return the recursively constructed diff.
- * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
- * @param {string} text1 Old string to be diffed.
- * @param {string} text2 New string to be diffed.
- * @param {number} deadline Time at which to bail if not yet complete.
- * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
- * @private
- */
- DiffMatchPatch.prototype.diffBisect = function (text1, text2, deadline) {
- var text1Length, text2Length, maxD, vOffset, vLength, v1, v2, x, delta, front, k1start, k1end, k2start, k2end, k2Offset, k1Offset, x1, x2, y1, y2, d, k1, k2;
-
- // Cache the text lengths to prevent multiple calls.
- text1Length = text1.length;
- text2Length = text2.length;
- maxD = Math.ceil((text1Length + text2Length) / 2);
- vOffset = maxD;
- vLength = 2 * maxD;
- v1 = new Array(vLength);
- v2 = new Array(vLength);
-
- // Setting all elements to -1 is faster in Chrome & Firefox than mixing
- // integers and undefined.
- for (x = 0; x < vLength; x++) {
- v1[x] = -1;
- v2[x] = -1;
- }
- v1[vOffset + 1] = 0;
- v2[vOffset + 1] = 0;
- delta = text1Length - text2Length;
-
- // If the total number of characters is odd, then the front path will collide
- // with the reverse path.
- front = delta % 2 !== 0;
-
- // Offsets for start and end of k loop.
- // Prevents mapping of space beyond the grid.
- k1start = 0;
- k1end = 0;
- k2start = 0;
- k2end = 0;
- for (d = 0; d < maxD; d++) {
-
- // Bail out if deadline is reached.
- if (new Date().getTime() > deadline) {
- break;
- }
-
- // Walk the front path one step.
- for (k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
- k1Offset = vOffset + k1;
- if (k1 === -d || k1 !== d && v1[k1Offset - 1] < v1[k1Offset + 1]) {
- x1 = v1[k1Offset + 1];
- } else {
- x1 = v1[k1Offset - 1] + 1;
- }
- y1 = x1 - k1;
- while (x1 < text1Length && y1 < text2Length && text1.charAt(x1) === text2.charAt(y1)) {
- x1++;
- y1++;
- }
- v1[k1Offset] = x1;
- if (x1 > text1Length) {
-
- // Ran off the right of the graph.
- k1end += 2;
- } else if (y1 > text2Length) {
-
- // Ran off the bottom of the graph.
- k1start += 2;
- } else if (front) {
- k2Offset = vOffset + delta - k1;
- if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] !== -1) {
-
- // Mirror x2 onto top-left coordinate system.
- x2 = text1Length - v2[k2Offset];
- if (x1 >= x2) {
-
- // Overlap detected.
- return this.diffBisectSplit(text1, text2, x1, y1, deadline);
- }
- }
- }
- }
-
- // Walk the reverse path one step.
- for (k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
- k2Offset = vOffset + k2;
- if (k2 === -d || k2 !== d && v2[k2Offset - 1] < v2[k2Offset + 1]) {
- x2 = v2[k2Offset + 1];
- } else {
- x2 = v2[k2Offset - 1] + 1;
- }
- y2 = x2 - k2;
- while (x2 < text1Length && y2 < text2Length && text1.charAt(text1Length - x2 - 1) === text2.charAt(text2Length - y2 - 1)) {
- x2++;
- y2++;
- }
- v2[k2Offset] = x2;
- if (x2 > text1Length) {
-
- // Ran off the left of the graph.
- k2end += 2;
- } else if (y2 > text2Length) {
-
- // Ran off the top of the graph.
- k2start += 2;
- } else if (!front) {
- k1Offset = vOffset + delta - k2;
- if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] !== -1) {
- x1 = v1[k1Offset];
- y1 = vOffset + x1 - k1Offset;
-
- // Mirror x2 onto top-left coordinate system.
- x2 = text1Length - x2;
- if (x1 >= x2) {
-
- // Overlap detected.
- return this.diffBisectSplit(text1, text2, x1, y1, deadline);
- }
- }
- }
- }
- }
-
- // Diff took too long and hit the deadline or
- // number of diffs equals number of characters, no commonality at all.
- return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
- };
-
- /**
- * Given the location of the 'middle snake', split the diff in two parts
- * and recurse.
- * @param {string} text1 Old string to be diffed.
- * @param {string} text2 New string to be diffed.
- * @param {number} x Index of split point in text1.
- * @param {number} y Index of split point in text2.
- * @param {number} deadline Time at which to bail if not yet complete.
- * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
- * @private
- */
- DiffMatchPatch.prototype.diffBisectSplit = function (text1, text2, x, y, deadline) {
- var text1a, text1b, text2a, text2b, diffs, diffsb;
- text1a = text1.substring(0, x);
- text2a = text2.substring(0, y);
- text1b = text1.substring(x);
- text2b = text2.substring(y);
-
- // Compute both diffs serially.
- diffs = this.DiffMain(text1a, text2a, false, deadline);
- diffsb = this.DiffMain(text1b, text2b, false, deadline);
-
- return diffs.concat(diffsb);
- };
-
- /**
- * Reduce the number of edits by eliminating semantically trivial equalities.
- * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
- */
- DiffMatchPatch.prototype.diffCleanupSemantic = function (diffs) {
- var changes, equalities, equalitiesLength, lastequality, pointer, lengthInsertions2, lengthDeletions2, lengthInsertions1, lengthDeletions1, deletion, insertion, overlapLength1, overlapLength2;
- changes = false;
- equalities = []; // Stack of indices where equalities are found.
- equalitiesLength = 0; // Keeping our own length var is faster in JS.
- /** @type {?string} */
- lastequality = null;
-
- // Always equal to diffs[equalities[equalitiesLength - 1]][1]
- pointer = 0; // Index of current position.
-
- // Number of characters that changed prior to the equality.
- lengthInsertions1 = 0;
- lengthDeletions1 = 0;
-
- // Number of characters that changed after the equality.
- lengthInsertions2 = 0;
- lengthDeletions2 = 0;
- while (pointer < diffs.length) {
- if (diffs[pointer][0] === DIFF_EQUAL) {
- // Equality found.
- equalities[equalitiesLength++] = pointer;
- lengthInsertions1 = lengthInsertions2;
- lengthDeletions1 = lengthDeletions2;
- lengthInsertions2 = 0;
- lengthDeletions2 = 0;
- lastequality = diffs[pointer][1];
- } else {
- // An insertion or deletion.
- if (diffs[pointer][0] === DIFF_INSERT) {
- lengthInsertions2 += diffs[pointer][1].length;
- } else {
- lengthDeletions2 += diffs[pointer][1].length;
- }
-
- // Eliminate an equality that is smaller or equal to the edits on both
- // sides of it.
- if (lastequality && lastequality.length <= Math.max(lengthInsertions1, lengthDeletions1) && lastequality.length <= Math.max(lengthInsertions2, lengthDeletions2)) {
-
- // Duplicate record.
- diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastequality]);
-
- // Change second copy to insert.
- diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
-
- // Throw away the equality we just deleted.
- equalitiesLength--;
-
- // Throw away the previous equality (it needs to be reevaluated).
- equalitiesLength--;
- pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
-
- // Reset the counters.
- lengthInsertions1 = 0;
- lengthDeletions1 = 0;
- lengthInsertions2 = 0;
- lengthDeletions2 = 0;
- lastequality = null;
- changes = true;
- }
- }
- pointer++;
- }
-
- // Normalize the diff.
- if (changes) {
- this.diffCleanupMerge(diffs);
- }
-
- // Find any overlaps between deletions and insertions.
- // e.g: <del>abcxxx</del><ins>xxxdef</ins>
- // -> <del>abc</del>xxx<ins>def</ins>
- // e.g: <del>xxxabc</del><ins>defxxx</ins>
- // -> <ins>def</ins>xxx<del>abc</del>
- // Only extract an overlap if it is as big as the edit ahead or behind it.
- pointer = 1;
- while (pointer < diffs.length) {
- if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) {
- deletion = diffs[pointer - 1][1];
- insertion = diffs[pointer][1];
- overlapLength1 = this.diffCommonOverlap(deletion, insertion);
- overlapLength2 = this.diffCommonOverlap(insertion, deletion);
- if (overlapLength1 >= overlapLength2) {
- if (overlapLength1 >= deletion.length / 2 || overlapLength1 >= insertion.length / 2) {
-
- // Overlap found. Insert an equality and trim the surrounding edits.
- diffs.splice(pointer, 0, [DIFF_EQUAL, insertion.substring(0, overlapLength1)]);
- diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlapLength1);
- diffs[pointer + 1][1] = insertion.substring(overlapLength1);
- pointer++;
- }
- } else {
- if (overlapLength2 >= deletion.length / 2 || overlapLength2 >= insertion.length / 2) {
-
- // Reverse overlap found.
- // Insert an equality and swap and trim the surrounding edits.
- diffs.splice(pointer, 0, [DIFF_EQUAL, deletion.substring(0, overlapLength2)]);
-
- diffs[pointer - 1][0] = DIFF_INSERT;
- diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlapLength2);
- diffs[pointer + 1][0] = DIFF_DELETE;
- diffs[pointer + 1][1] = deletion.substring(overlapLength2);
- pointer++;
- }
- }
- pointer++;
- }
- pointer++;
- }
- };
-
- /**
- * Determine if the suffix of one string is the prefix of another.
- * @param {string} text1 First string.
- * @param {string} text2 Second string.
- * @return {number} The number of characters common to the end of the first
- * string and the start of the second string.
- * @private
- */
- DiffMatchPatch.prototype.diffCommonOverlap = function (text1, text2) {
- var text1Length, text2Length, textLength, best, length, pattern, found;
-
- // Cache the text lengths to prevent multiple calls.
- text1Length = text1.length;
- text2Length = text2.length;
-
- // Eliminate the null case.
- if (text1Length === 0 || text2Length === 0) {
- return 0;
- }
-
- // Truncate the longer string.
- if (text1Length > text2Length) {
- text1 = text1.substring(text1Length - text2Length);
- } else if (text1Length < text2Length) {
- text2 = text2.substring(0, text1Length);
- }
- textLength = Math.min(text1Length, text2Length);
-
- // Quick check for the worst case.
- if (text1 === text2) {
- return textLength;
- }
-
- // Start by looking for a single character match
- // and increase length until no match is found.
- // Performance analysis: https://neil.fraser.name/news/2010/11/04/
- best = 0;
- length = 1;
- while (true) {
- pattern = text1.substring(textLength - length);
- found = text2.indexOf(pattern);
- if (found === -1) {
- return best;
- }
- length += found;
- if (found === 0 || text1.substring(textLength - length) === text2.substring(0, length)) {
- best = length;
- length++;
- }
- }
- };
-
- /**
- * Split two texts into an array of strings. Reduce the texts to a string of
- * hashes where each Unicode character represents one line.
- * @param {string} text1 First string.
- * @param {string} text2 Second string.
- * @return {{chars1: string, chars2: string, lineArray: !Array.<string>}}
- * An object containing the encoded text1, the encoded text2 and
- * the array of unique strings.
- * The zeroth element of the array of unique strings is intentionally blank.
- * @private
- */
- DiffMatchPatch.prototype.diffLinesToChars = function (text1, text2) {
- var lineArray, lineHash, chars1, chars2;
- lineArray = []; // E.g. lineArray[4] === 'Hello\n'
- lineHash = {}; // E.g. lineHash['Hello\n'] === 4
-
- // '\x00' is a valid character, but various debuggers don't like it.
- // So we'll insert a junk entry to avoid generating a null character.
- lineArray[0] = "";
-
- /**
- * Split a text into an array of strings. Reduce the texts to a string of
- * hashes where each Unicode character represents one line.
- * Modifies linearray and linehash through being a closure.
- * @param {string} text String to encode.
- * @return {string} Encoded string.
- * @private
- */
- function diffLinesToCharsMunge(text) {
- var chars, lineStart, lineEnd, lineArrayLength, line;
- chars = "";
-
- // Walk the text, pulling out a substring for each line.
- // text.split('\n') would would temporarily double our memory footprint.
- // Modifying text would create many large strings to garbage collect.
- lineStart = 0;
- lineEnd = -1;
-
- // Keeping our own length variable is faster than looking it up.
- lineArrayLength = lineArray.length;
- while (lineEnd < text.length - 1) {
- lineEnd = text.indexOf("\n", lineStart);
- if (lineEnd === -1) {
- lineEnd = text.length - 1;
- }
- line = text.substring(lineStart, lineEnd + 1);
- lineStart = lineEnd + 1;
-
- if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : lineHash[line] !== undefined) {
- chars += String.fromCharCode(lineHash[line]);
- } else {
- chars += String.fromCharCode(lineArrayLength);
- lineHash[line] = lineArrayLength;
- lineArray[lineArrayLength++] = line;
- }
- }
- return chars;
- }
-
- chars1 = diffLinesToCharsMunge(text1);
- chars2 = diffLinesToCharsMunge(text2);
- return {
- chars1: chars1,
- chars2: chars2,
- lineArray: lineArray
- };
- };
-
- /**
- * Rehydrate the text in a diff from a string of line hashes to real lines of
- * text.
- * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
- * @param {!Array.<string>} lineArray Array of unique strings.
- * @private
- */
- DiffMatchPatch.prototype.diffCharsToLines = function (diffs, lineArray) {
- var x, chars, text, y;
- for (x = 0; x < diffs.length; x++) {
- chars = diffs[x][1];
- text = [];
- for (y = 0; y < chars.length; y++) {
- text[y] = lineArray[chars.charCodeAt(y)];
- }
- diffs[x][1] = text.join("");
- }
- };
-
- /**
- * Reorder and merge like edit sections. Merge equalities.
- * Any edit section can move as long as it doesn't cross an equality.
- * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
- */
- DiffMatchPatch.prototype.diffCleanupMerge = function (diffs) {
- var pointer, countDelete, countInsert, textInsert, textDelete, commonlength, changes, diffPointer, position;
- diffs.push([DIFF_EQUAL, ""]); // Add a dummy entry at the end.
- pointer = 0;
- countDelete = 0;
- countInsert = 0;
- textDelete = "";
- textInsert = "";
-
- while (pointer < diffs.length) {
- switch (diffs[pointer][0]) {
- case DIFF_INSERT:
- countInsert++;
- textInsert += diffs[pointer][1];
- pointer++;
- break;
- case DIFF_DELETE:
- countDelete++;
- textDelete += diffs[pointer][1];
- pointer++;
- break;
- case DIFF_EQUAL:
-
- // Upon reaching an equality, check for prior redundancies.
- if (countDelete + countInsert > 1) {
- if (countDelete !== 0 && countInsert !== 0) {
-
- // Factor out any common prefixes.
- commonlength = this.diffCommonPrefix(textInsert, textDelete);
- if (commonlength !== 0) {
- if (pointer - countDelete - countInsert > 0 && diffs[pointer - countDelete - countInsert - 1][0] === DIFF_EQUAL) {
- diffs[pointer - countDelete - countInsert - 1][1] += textInsert.substring(0, commonlength);
- } else {
- diffs.splice(0, 0, [DIFF_EQUAL, textInsert.substring(0, commonlength)]);
- pointer++;
- }
- textInsert = textInsert.substring(commonlength);
- textDelete = textDelete.substring(commonlength);
- }
-
- // Factor out any common suffixies.
- commonlength = this.diffCommonSuffix(textInsert, textDelete);
- if (commonlength !== 0) {
- diffs[pointer][1] = textInsert.substring(textInsert.length - commonlength) + diffs[pointer][1];
- textInsert = textInsert.substring(0, textInsert.length - commonlength);
- textDelete = textDelete.substring(0, textDelete.length - commonlength);
- }
- }
-
- // Delete the offending records and add the merged ones.
- if (countDelete === 0) {
- diffs.splice(pointer - countInsert, countDelete + countInsert, [DIFF_INSERT, textInsert]);
- } else if (countInsert === 0) {
- diffs.splice(pointer - countDelete, countDelete + countInsert, [DIFF_DELETE, textDelete]);
- } else {
- diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert, [DIFF_DELETE, textDelete], [DIFF_INSERT, textInsert]);
- }
- pointer = pointer - countDelete - countInsert + (countDelete ? 1 : 0) + (countInsert ? 1 : 0) + 1;
- } else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) {
-
- // Merge this equality with the previous one.
- diffs[pointer - 1][1] += diffs[pointer][1];
- diffs.splice(pointer, 1);
- } else {
- pointer++;
- }
- countInsert = 0;
- countDelete = 0;
- textDelete = "";
- textInsert = "";
- break;
- }
- }
- if (diffs[diffs.length - 1][1] === "") {
- diffs.pop(); // Remove the dummy entry at the end.
- }
-
- // Second pass: look for single edits surrounded on both sides by equalities
- // which can be shifted sideways to eliminate an equality.
- // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
- changes = false;
- pointer = 1;
-
- // Intentionally ignore the first and last element (don't need checking).
- while (pointer < diffs.length - 1) {
- if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) {
-
- diffPointer = diffs[pointer][1];
- position = diffPointer.substring(diffPointer.length - diffs[pointer - 1][1].length);
-
- // This is a single edit surrounded by equalities.
- if (position === diffs[pointer - 1][1]) {
-
- // Shift the edit over the previous equality.
- diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length);
- diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];
- diffs.splice(pointer - 1, 1);
- changes = true;
- } else if (diffPointer.substring(0, diffs[pointer + 1][1].length) === diffs[pointer + 1][1]) {
-
- // Shift the edit over the next equality.
- diffs[pointer - 1][1] += diffs[pointer + 1][1];
- diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1];
- diffs.splice(pointer + 1, 1);
- changes = true;
- }
- }
- pointer++;
- }
-
- // If shifts were made, the diff needs reordering and another shift sweep.
- if (changes) {
- this.diffCleanupMerge(diffs);
- }
- };
-
- return function (o, n) {
- var diff, output, text;
- diff = new DiffMatchPatch();
- output = diff.DiffMain(o, n);
- diff.diffCleanupEfficiency(output);
- text = diff.diffPrettyHtml(output);
-
- return text;
- };
- }();
-
- (function () {
-
- // Only interact with URLs via window.location
- var location = typeof window !== "undefined" && window.location;
- if (!location) {
- return;
- }
-
- var urlParams = getUrlParams();
-
- QUnit.urlParams = urlParams;
-
- // Match module/test by inclusion in an array
- QUnit.config.moduleId = [].concat(urlParams.moduleId || []);
- QUnit.config.testId = [].concat(urlParams.testId || []);
-
- // Exact case-insensitive match of the module name
- QUnit.config.module = urlParams.module;
-
- // Regular expression or case-insenstive substring match against "moduleName: testName"
- QUnit.config.filter = urlParams.filter;
-
- // Test order randomization
- if (urlParams.seed === true) {
-
- // Generate a random seed if the option is specified without a value
- QUnit.config.seed = Math.random().toString(36).slice(2);
- } else if (urlParams.seed) {
- QUnit.config.seed = urlParams.seed;
- }
-
- // Add URL-parameter-mapped config values with UI form rendering data
- QUnit.config.urlConfig.push({
- id: "hidepassed",
- label: "Hide passed tests",
- tooltip: "Only show tests and assertions that fail. Stored as query-strings."
- }, {
- id: "noglobals",
- label: "Check for Globals",
- tooltip: "Enabling this will test if any test introduces new properties on the " + "global object (`window` in Browsers). Stored as query-strings."
- }, {
- id: "notrycatch",
- label: "No try-catch",
- tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging " + "exceptions in IE reasonable. Stored as query-strings."
- });
-
- QUnit.begin(function () {
- var i,
- option,
- urlConfig = QUnit.config.urlConfig;
-
- for (i = 0; i < urlConfig.length; i++) {
-
- // Options can be either strings or objects with nonempty "id" properties
- option = QUnit.config.urlConfig[i];
- if (typeof option !== "string") {
- option = option.id;
- }
-
- if (QUnit.config[option] === undefined) {
- QUnit.config[option] = urlParams[option];
- }
- }
- });
-
- function getUrlParams() {
- var i, param, name, value;
- var urlParams = Object.create(null);
- var params = location.search.slice(1).split("&");
- var length = params.length;
-
- for (i = 0; i < length; i++) {
- if (params[i]) {
- param = params[i].split("=");
- name = decodeQueryParam(param[0]);
-
- // Allow just a key to turn on a flag, e.g., test.html?noglobals
- value = param.length === 1 || decodeQueryParam(param.slice(1).join("="));
- if (name in urlParams) {
- urlParams[name] = [].concat(urlParams[name], value);
- } else {
- urlParams[name] = value;
- }
- }
- }
-
- return urlParams;
- }
-
- function decodeQueryParam(param) {
- return decodeURIComponent(param.replace(/\+/g, "%20"));
- }
- })();
-
-}((function() { return this; }())));
diff --git a/test/lib/require.js b/test/lib/require.js
deleted file mode 100644
index 4db1424..0000000
--- a/test/lib/require.js
+++ /dev/null
@@ -1,2142 +0,0 @@
-/** vim: et:ts=4:sw=4:sts=4
- * @license RequireJS 2.3.2 Copyright jQuery Foundation and other contributors.
- * Released under MIT license, https://github.com/requirejs/requirejs/blob/master/LICENSE
- */
-//Not using strict: uneven strict support in browsers, #392, and causes
-//problems with requirejs.exec()/transpiler plugins that may not be strict.
-/*jslint regexp: true, nomen: true, sloppy: true */
-/*global window, navigator, document, importScripts, setTimeout, opera */
-
-var requirejs, require, define;
-(function (global, setTimeout) {
- var req, s, head, baseElement, dataMain, src,
- interactiveScript, currentlyAddingScript, mainScript, subPath,
- version = '2.3.2',
- commentRegExp = /\/\*[\s\S]*?\*\/|([^:"'=]|^)\/\/.*$/mg,
- cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
- jsSuffixRegExp = /\.js$/,
- currDirRegExp = /^\.\//,
- op = Object.prototype,
- ostring = op.toString,
- hasOwn = op.hasOwnProperty,
- isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document),
- isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
- //PS3 indicates loaded and complete, but need to wait for complete
- //specifically. Sequence is 'loading', 'loaded', execution,
- // then 'complete'. The UA check is unfortunate, but not sure how
- //to feature test w/o causing perf issues.
- readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
- /^complete$/ : /^(complete|loaded)$/,
- defContextName = '_',
- //Oh the tragedy, detecting opera. See the usage of isOpera for reason.
- isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
- contexts = {},
- cfg = {},
- globalDefQueue = [],
- useInteractive = false;
-
- //Could match something like ')//comment', do not lose the prefix to comment.
- function commentReplace(match, singlePrefix) {
- return singlePrefix || '';
- }
-
- function isFunction(it) {
- return ostring.call(it) === '[object Function]';
- }
-
- function isArray(it) {
- return ostring.call(it) === '[object Array]';
- }
-
- /**
- * Helper function for iterating over an array. If the func returns
- * a true value, it will break out of the loop.
- */
- function each(ary, func) {
- if (ary) {
- var i;
- for (i = 0; i < ary.length; i += 1) {
- if (ary[i] && func(ary[i], i, ary)) {
- break;
- }
- }
- }
- }
-
- /**
- * Helper function for iterating over an array backwards. If the func
- * returns a true value, it will break out of the loop.
- */
- function eachReverse(ary, func) {
- if (ary) {
- var i;
- for (i = ary.length - 1; i > -1; i -= 1) {
- if (ary[i] && func(ary[i], i, ary)) {
- break;
- }
- }
- }
- }
-
- function hasProp(obj, prop) {
- return hasOwn.call(obj, prop);
- }
-
- function getOwn(obj, prop) {
- return hasProp(obj, prop) && obj[prop];
- }
-
- /**
- * Cycles over properties in an object and calls a function for each
- * property value. If the function returns a truthy value, then the
- * iteration is stopped.
- */
- function eachProp(obj, func) {
- var prop;
- for (prop in obj) {
- if (hasProp(obj, prop)) {
- if (func(obj[prop], prop)) {
- break;
- }
- }
- }
- }
-
- /**
- * Simple function to mix in properties from source into target,
- * but only if target does not already have a property of the same name.
- */
- function mixin(target, source, force, deepStringMixin) {
- if (source) {
- eachProp(source, function (value, prop) {
- if (force || !hasProp(target, prop)) {
- if (deepStringMixin && typeof value === 'object' && value &&
- !isArray(value) && !isFunction(value) &&
- !(value instanceof RegExp)) {
-
- if (!target[prop]) {
- target[prop] = {};
- }
- mixin(target[prop], value, force, deepStringMixin);
- } else {
- target[prop] = value;
- }
- }
- });
- }
- return target;
- }
-
- //Similar to Function.prototype.bind, but the 'this' object is specified
- //first, since it is easier to read/figure out what 'this' will be.
- function bind(obj, fn) {
- return function () {
- return fn.apply(obj, arguments);
- };
- }
-
- function scripts() {
- return document.getElementsByTagName('script');
- }
-
- function defaultOnError(err) {
- throw err;
- }
-
- //Allow getting a global that is expressed in
- //dot notation, like 'a.b.c'.
- function getGlobal(value) {
- if (!value) {
- return value;
- }
- var g = global;
- each(value.split('.'), function (part) {
- g = g[part];
- });
- return g;
- }
-
- /**
- * Constructs an error with a pointer to an URL with more information.
- * @param {String} id the error ID that maps to an ID on a web page.
- * @param {String} message human readable error.
- * @param {Error} [err] the original error, if there is one.
- *
- * @returns {Error}
- */
- function makeError(id, msg, err, requireModules) {
- var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
- e.requireType = id;
- e.requireModules = requireModules;
- if (err) {
- e.originalError = err;
- }
- return e;
- }
-
- if (typeof define !== 'undefined') {
- //If a define is already in play via another AMD loader,
- //do not overwrite.
- return;
- }
-
- if (typeof requirejs !== 'undefined') {
- if (isFunction(requirejs)) {
- //Do not overwrite an existing requirejs instance.
- return;
- }
- cfg = requirejs;
- requirejs = undefined;
- }
-
- //Allow for a require config object
- if (typeof require !== 'undefined' && !isFunction(require)) {
- //assume it is a config object.
- cfg = require;
- require = undefined;
- }
-
- function newContext(contextName) {
- var inCheckLoaded, Module, context, handlers,
- checkLoadedTimeoutId,
- config = {
- //Defaults. Do not set a default for map
- //config to speed up normalize(), which
- //will run faster if there is no default.
- waitSeconds: 7,
- baseUrl: './',
- paths: {},
- bundles: {},
- pkgs: {},
- shim: {},
- config: {}
- },
- registry = {},
- //registry of just enabled modules, to speed
- //cycle breaking code when lots of modules
- //are registered, but not activated.
- enabledRegistry = {},
- undefEvents = {},
- defQueue = [],
- defined = {},
- urlFetched = {},
- bundlesMap = {},
- requireCounter = 1,
- unnormalizedCounter = 1;
-
- /**
- * Trims the . and .. from an array of path segments.
- * It will keep a leading path segment if a .. will become
- * the first path segment, to help with module name lookups,
- * which act like paths, but can be remapped. But the end result,
- * all paths that use this function should look normalized.
- * NOTE: this method MODIFIES the input array.
- * @param {Array} ary the array of path segments.
- */
- function trimDots(ary) {
- var i, part;
- for (i = 0; i < ary.length; i++) {
- part = ary[i];
- if (part === '.') {
- ary.splice(i, 1);
- i -= 1;
- } else if (part === '..') {
- // If at the start, or previous value is still ..,
- // keep them so that when converted to a path it may
- // still work when converted to a path, even though
- // as an ID it is less than ideal. In larger point
- // releases, may be better to just kick out an error.
- if (i === 0 || (i === 1 && ary[2] === '..') || ary[i - 1] === '..') {
- continue;
- } else if (i > 0) {
- ary.splice(i - 1, 2);
- i -= 2;
- }
- }
- }
- }
-
- /**
- * Given a relative module name, like ./something, normalize it to
- * a real name that can be mapped to a path.
- * @param {String} name the relative name
- * @param {String} baseName a real name that the name arg is relative
- * to.
- * @param {Boolean} applyMap apply the map config to the value. Should
- * only be done if this normalization is for a dependency ID.
- * @returns {String} normalized name
- */
- function normalize(name, baseName, applyMap) {
- var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex,
- foundMap, foundI, foundStarMap, starI, normalizedBaseParts,
- baseParts = (baseName && baseName.split('/')),
- map = config.map,
- starMap = map && map['*'];
-
- //Adjust any relative paths.
- if (name) {
- name = name.split('/');
- lastIndex = name.length - 1;
-
- // If wanting node ID compatibility, strip .js from end
- // of IDs. Have to do this here, and not in nameToUrl
- // because node allows either .js or non .js to map
- // to same file.
- if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
- name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
- }
-
- // Starts with a '.' so need the baseName
- if (name[0].charAt(0) === '.' && baseParts) {
- //Convert baseName to array, and lop off the last part,
- //so that . matches that 'directory' and not name of the baseName's
- //module. For instance, baseName of 'one/two/three', maps to
- //'one/two/three.js', but we want the directory, 'one/two' for
- //this normalization.
- normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
- name = normalizedBaseParts.concat(name);
- }
-
- trimDots(name);
- name = name.join('/');
- }
-
- //Apply map config if available.
- if (applyMap && map && (baseParts || starMap)) {
- nameParts = name.split('/');
-
- outerLoop: for (i = nameParts.length; i > 0; i -= 1) {
- nameSegment = nameParts.slice(0, i).join('/');
-
- if (baseParts) {
- //Find the longest baseName segment match in the config.
- //So, do joins on the biggest to smallest lengths of baseParts.
- for (j = baseParts.length; j > 0; j -= 1) {
- mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
-
- //baseName segment has config, find if it has one for
- //this name.
- if (mapValue) {
- mapValue = getOwn(mapValue, nameSegment);
- if (mapValue) {
- //Match, update name to the new value.
- foundMap = mapValue;
- foundI = i;
- break outerLoop;
- }
- }
- }
- }
-
- //Check for a star map match, but just hold on to it,
- //if there is a shorter segment match later in a matching
- //config, then favor over this star map.
- if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
- foundStarMap = getOwn(starMap, nameSegment);
- starI = i;
- }
- }
-
- if (!foundMap && foundStarMap) {
- foundMap = foundStarMap;
- foundI = starI;
- }
-
- if (foundMap) {
- nameParts.splice(0, foundI, foundMap);
- name = nameParts.join('/');
- }
- }
-
- // If the name points to a package's name, use
- // the package main instead.
- pkgMain = getOwn(config.pkgs, name);
-
- return pkgMain ? pkgMain : name;
- }
-
- function removeScript(name) {
- if (isBrowser) {
- each(scripts(), function (scriptNode) {
- if (scriptNode.getAttribute('data-requiremodule') === name &&
- scriptNode.getAttribute('data-requirecontext') === context.contextName) {
- scriptNode.parentNode.removeChild(scriptNode);
- return true;
- }
- });
- }
- }
-
- function hasPathFallback(id) {
- var pathConfig = getOwn(config.paths, id);
- if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
- //Pop off the first array value, since it failed, and
- //retry
- pathConfig.shift();
- context.require.undef(id);
-
- //Custom require that does not do map translation, since
- //ID is "absolute", already mapped/resolved.
- context.makeRequire(null, {
- skipMap: true
- })([id]);
-
- return true;
- }
- }
-
- //Turns a plugin!resource to [plugin, resource]
- //with the plugin being undefined if the name
- //did not have a plugin prefix.
- function splitPrefix(name) {
- var prefix,
- index = name ? name.indexOf('!') : -1;
- if (index > -1) {
- prefix = name.substring(0, index);
- name = name.substring(index + 1, name.length);
- }
- return [prefix, name];
- }
-
- /**
- * Creates a module mapping that includes plugin prefix, module
- * name, and path. If parentModuleMap is provided it will
- * also normalize the name via require.normalize()
- *
- * @param {String} name the module name
- * @param {String} [parentModuleMap] parent module map
- * for the module name, used to resolve relative names.
- * @param {Boolean} isNormalized: is the ID already normalized.
- * This is true if this call is done for a define() module ID.
- * @param {Boolean} applyMap: apply the map config to the ID.
- * Should only be true if this map is for a dependency.
- *
- * @returns {Object}
- */
- function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
- var url, pluginModule, suffix, nameParts,
- prefix = null,
- parentName = parentModuleMap ? parentModuleMap.name : null,
- originalName = name,
- isDefine = true,
- normalizedName = '';
-
- //If no name, then it means it is a require call, generate an
- //internal name.
- if (!name) {
- isDefine = false;
- name = '_@r' + (requireCounter += 1);
- }
-
- nameParts = splitPrefix(name);
- prefix = nameParts[0];
- name = nameParts[1];
-
- if (prefix) {
- prefix = normalize(prefix, parentName, applyMap);
- pluginModule = getOwn(defined, prefix);
- }
-
- //Account for relative paths if there is a base name.
- if (name) {
- if (prefix) {
- if (pluginModule && pluginModule.normalize) {
- //Plugin is loaded, use its normalize method.
- normalizedName = pluginModule.normalize(name, function (name) {
- return normalize(name, parentName, applyMap);
- });
- } else {
- // If nested plugin references, then do not try to
- // normalize, as it will not normalize correctly. This
- // places a restriction on resourceIds, and the longer
- // term solution is not to normalize until plugins are
- // loaded and all normalizations to allow for async
- // loading of a loader plugin. But for now, fixes the
- // common uses. Details in #1131
- normalizedName = name.indexOf('!') === -1 ?
- normalize(name, parentName, applyMap) :
- name;
- }
- } else {
- //A regular module.
- normalizedName = normalize(name, parentName, applyMap);
-
- //Normalized name may be a plugin ID due to map config
- //application in normalize. The map config values must
- //already be normalized, so do not need to redo that part.
- nameParts = splitPrefix(normalizedName);
- prefix = nameParts[0];
- normalizedName = nameParts[1];
- isNormalized = true;
-
- url = context.nameToUrl(normalizedName);
- }
- }
-
- //If the id is a plugin id that cannot be determined if it needs
- //normalization, stamp it with a unique ID so two matching relative
- //ids that may conflict can be separate.
- suffix = prefix && !pluginModule && !isNormalized ?
- '_unnormalized' + (unnormalizedCounter += 1) :
- '';
-
- return {
- prefix: prefix,
- name: normalizedName,
- parentMap: parentModuleMap,
- unnormalized: !!suffix,
- url: url,
- originalName: originalName,
- isDefine: isDefine,
- id: (prefix ?
- prefix + '!' + normalizedName :
- normalizedName) + suffix
- };
- }
-
- function getModule(depMap) {
- var id = depMap.id,
- mod = getOwn(registry, id);
-
- if (!mod) {
- mod = registry[id] = new context.Module(depMap);
- }
-
- return mod;
- }
-
- function on(depMap, name, fn) {
- var id = depMap.id,
- mod = getOwn(registry, id);
-
- if (hasProp(defined, id) &&
- (!mod || mod.defineEmitComplete)) {
- if (name === 'defined') {
- fn(defined[id]);
- }
- } else {
- mod = getModule(depMap);
- if (mod.error && name === 'error') {
- fn(mod.error);
- } else {
- mod.on(name, fn);
- }
- }
- }
-
- function onError(err, errback) {
- var ids = err.requireModules,
- notified = false;
-
- if (errback) {
- errback(err);
- } else {
- each(ids, function (id) {
- var mod = getOwn(registry, id);
- if (mod) {
- //Set error on module, so it skips timeout checks.
- mod.error = err;
- if (mod.events.error) {
- notified = true;
- mod.emit('error', err);
- }
- }
- });
-
- if (!notified) {
- req.onError(err);
- }
- }
- }
-
- /**
- * Internal method to transfer globalQueue items to this context's
- * defQueue.
- */
- function takeGlobalQueue() {
- //Push all the globalDefQueue items into the context's defQueue
- if (globalDefQueue.length) {
- each(globalDefQueue, function(queueItem) {
- var id = queueItem[0];
- if (typeof id === 'string') {
- context.defQueueMap[id] = true;
- }
- defQueue.push(queueItem);
- });
- globalDefQueue = [];
- }
- }
-
- handlers = {
- 'require': function (mod) {
- if (mod.require) {
- return mod.require;
- } else {
- return (mod.require = context.makeRequire(mod.map));
- }
- },
- 'exports': function (mod) {
- mod.usingExports = true;
- if (mod.map.isDefine) {
- if (mod.exports) {
- return (defined[mod.map.id] = mod.exports);
- } else {
- return (mod.exports = defined[mod.map.id] = {});
- }
- }
- },
- 'module': function (mod) {
- if (mod.module) {
- return mod.module;
- } else {
- return (mod.module = {
- id: mod.map.id,
- uri: mod.map.url,
- config: function () {
- return getOwn(config.config, mod.map.id) || {};
- },
- exports: mod.exports || (mod.exports = {})
- });
- }
- }
- };
-
- function cleanRegistry(id) {
- //Clean up machinery used for waiting modules.
- delete registry[id];
- delete enabledRegistry[id];
- }
-
- function breakCycle(mod, traced, processed) {
- var id = mod.map.id;
-
- if (mod.error) {
- mod.emit('error', mod.error);
- } else {
- traced[id] = true;
- each(mod.depMaps, function (depMap, i) {
- var depId = depMap.id,
- dep = getOwn(registry, depId);
-
- //Only force things that have not completed
- //being defined, so still in the registry,
- //and only if it has not been matched up
- //in the module already.
- if (dep && !mod.depMatched[i] && !processed[depId]) {
- if (getOwn(traced, depId)) {
- mod.defineDep(i, defined[depId]);
- mod.check(); //pass false?
- } else {
- breakCycle(dep, traced, processed);
- }
- }
- });
- processed[id] = true;
- }
- }
-
- function checkLoaded() {
- var err, usingPathFallback,
- waitInterval = config.waitSeconds * 1000,
- //It is possible to disable the wait interval by using waitSeconds of 0.
- expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
- noLoads = [],
- reqCalls = [],
- stillLoading = false,
- needCycleCheck = true;
-
- //Do not bother if this call was a result of a cycle break.
- if (inCheckLoaded) {
- return;
- }
-
- inCheckLoaded = true;
-
- //Figure out the state of all the modules.
- eachProp(enabledRegistry, function (mod) {
- var map = mod.map,
- modId = map.id;
-
- //Skip things that are not enabled or in error state.
- if (!mod.enabled) {
- return;
- }
-
- if (!map.isDefine) {
- reqCalls.push(mod);
- }
-
- if (!mod.error) {
- //If the module should be executed, and it has not
- //been inited and time is up, remember it.
- if (!mod.inited && expired) {
- if (hasPathFallback(modId)) {
- usingPathFallback = true;
- stillLoading = true;
- } else {
- noLoads.push(modId);
- removeScript(modId);
- }
- } else if (!mod.inited && mod.fetched && map.isDefine) {
- stillLoading = true;
- if (!map.prefix) {
- //No reason to keep looking for unfinished
- //loading. If the only stillLoading is a
- //plugin resource though, keep going,
- //because it may be that a plugin resource
- //is waiting on a non-plugin cycle.
- return (needCycleCheck = false);
- }
- }
- }
- });
-
- if (expired && noLoads.length) {
- //If wait time expired, throw error of unloaded modules.
- err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
- err.contextName = context.contextName;
- return onError(err);
- }
-
- //Not expired, check for a cycle.
- if (needCycleCheck) {
- each(reqCalls, function (mod) {
- breakCycle(mod, {}, {});
- });
- }
-
- //If still waiting on loads, and the waiting load is something
- //other than a plugin resource, or there are still outstanding
- //scripts, then just try back later.
- if ((!expired || usingPathFallback) && stillLoading) {
- //Something is still waiting to load. Wait for it, but only
- //if a timeout is not already in effect.
- if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
- checkLoadedTimeoutId = setTimeout(function () {
- checkLoadedTimeoutId = 0;
- checkLoaded();
- }, 50);
- }
- }
-
- inCheckLoaded = false;
- }
-
- Module = function (map) {
- this.events = getOwn(undefEvents, map.id) || {};
- this.map = map;
- this.shim = getOwn(config.shim, map.id);
- this.depExports = [];
- this.depMaps = [];
- this.depMatched = [];
- this.pluginMaps = {};
- this.depCount = 0;
-
- /* this.exports this.factory
- this.depMaps = [],
- this.enabled, this.fetched
- */
- };
-
- Module.prototype = {
- init: function (depMaps, factory, errback, options) {
- options = options || {};
-
- //Do not do more inits if already done. Can happen if there
- //are multiple define calls for the same module. That is not
- //a normal, common case, but it is also not unexpected.
- if (this.inited) {
- return;
- }
-
- this.factory = factory;
-
- if (errback) {
- //Register for errors on this module.
- this.on('error', errback);
- } else if (this.events.error) {
- //If no errback already, but there are error listeners
- //on this module, set up an errback to pass to the deps.
- errback = bind(this, function (err) {
- this.emit('error', err);
- });
- }
-
- //Do a copy of the dependency array, so that
- //source inputs are not modified. For example
- //"shim" deps are passed in here directly, and
- //doing a direct modification of the depMaps array
- //would affect that config.
- this.depMaps = depMaps && depMaps.slice(0);
-
- this.errback = errback;
-
- //Indicate this module has be initialized
- this.inited = true;
-
- this.ignore = options.ignore;
-
- //Could have option to init this module in enabled mode,
- //or could have been previously marked as enabled. However,
- //the dependencies are not known until init is called. So
- //if enabled previously, now trigger dependencies as enabled.
- if (options.enabled || this.enabled) {
- //Enable this module and dependencies.
- //Will call this.check()
- this.enable();
- } else {
- this.check();
- }
- },
-
- defineDep: function (i, depExports) {
- //Because of cycles, defined callback for a given
- //export can be called more than once.
- if (!this.depMatched[i]) {
- this.depMatched[i] = true;
- this.depCount -= 1;
- this.depExports[i] = depExports;
- }
- },
-
- fetch: function () {
- if (this.fetched) {
- return;
- }
- this.fetched = true;
-
- context.startTime = (new Date()).getTime();
-
- var map = this.map;
-
- //If the manager is for a plugin managed resource,
- //ask the plugin to load it now.
- if (this.shim) {
- context.makeRequire(this.map, {
- enableBuildCallback: true
- })(this.shim.deps || [], bind(this, function () {
- return map.prefix ? this.callPlugin() : this.load();
- }));
- } else {
- //Regular dependency.
- return map.prefix ? this.callPlugin() : this.load();
- }
- },
-
- load: function () {
- var url = this.map.url;
-
- //Regular dependency.
- if (!urlFetched[url]) {
- urlFetched[url] = true;
- context.load(this.map.id, url);
- }
- },
-
- /**
- * Checks if the module is ready to define itself, and if so,
- * define it.
- */
- check: function () {
- if (!this.enabled || this.enabling) {
- return;
- }
-
- var err, cjsModule,
- id = this.map.id,
- depExports = this.depExports,
- exports = this.exports,
- factory = this.factory;
-
- if (!this.inited) {
- // Only fetch if not already in the defQueue.
- if (!hasProp(context.defQueueMap, id)) {
- this.fetch();
- }
- } else if (this.error) {
- this.emit('error', this.error);
- } else if (!this.defining) {
- //The factory could trigger another require call
- //that would result in checking this module to
- //define itself again. If already in the process
- //of doing that, skip this work.
- this.defining = true;
-
- if (this.depCount < 1 && !this.defined) {
- if (isFunction(factory)) {
- //If there is an error listener, favor passing
- //to that instead of throwing an error. However,
- //only do it for define()'d modules. require
- //errbacks should not be called for failures in
- //their callbacks (#699). However if a global
- //onError is set, use that.
- if ((this.events.error && this.map.isDefine) ||
- req.onError !== defaultOnError) {
- try {
- exports = context.execCb(id, factory, depExports, exports);
- } catch (e) {
- err = e;
- }
- } else {
- exports = context.execCb(id, factory, depExports, exports);
- }
-
- // Favor return value over exports. If node/cjs in play,
- // then will not have a return value anyway. Favor
- // module.exports assignment over exports object.
- if (this.map.isDefine && exports === undefined) {
- cjsModule = this.module;
- if (cjsModule) {
- exports = cjsModule.exports;
- } else if (this.usingExports) {
- //exports already set the defined value.
- exports = this.exports;
- }
- }
-
- if (err) {
- err.requireMap = this.map;
- err.requireModules = this.map.isDefine ? [this.map.id] : null;
- err.requireType = this.map.isDefine ? 'define' : 'require';
- return onError((this.error = err));
- }
-
- } else {
- //Just a literal value
- exports = factory;
- }
-
- this.exports = exports;
-
- if (this.map.isDefine && !this.ignore) {
- defined[id] = exports;
-
- if (req.onResourceLoad) {
- var resLoadMaps = [];
- each(this.depMaps, function (depMap) {
- resLoadMaps.push(depMap.normalizedMap || depMap);
- });
- req.onResourceLoad(context, this.map, resLoadMaps);
- }
- }
-
- //Clean up
- cleanRegistry(id);
-
- this.defined = true;
- }
-
- //Finished the define stage. Allow calling check again
- //to allow define notifications below in the case of a
- //cycle.
- this.defining = false;
-
- if (this.defined && !this.defineEmitted) {
- this.defineEmitted = true;
- this.emit('defined', this.exports);
- this.defineEmitComplete = true;
- }
-
- }
- },
-
- callPlugin: function () {
- var map = this.map,
- id = map.id,
- //Map already normalized the prefix.
- pluginMap = makeModuleMap(map.prefix);
-
- //Mark this as a dependency for this plugin, so it
- //can be traced for cycles.
- this.depMaps.push(pluginMap);
-
- on(pluginMap, 'defined', bind(this, function (plugin) {
- var load, normalizedMap, normalizedMod,
- bundleId = getOwn(bundlesMap, this.map.id),
- name = this.map.name,
- parentName = this.map.parentMap ? this.map.parentMap.name : null,
- localRequire = context.makeRequire(map.parentMap, {
- enableBuildCallback: true
- });
-
- //If current map is not normalized, wait for that
- //normalized name to load instead of continuing.
- if (this.map.unnormalized) {
- //Normalize the ID if the plugin allows it.
- if (plugin.normalize) {
- name = plugin.normalize(name, function (name) {
- return normalize(name, parentName, true);
- }) || '';
- }
-
- //prefix and name should already be normalized, no need
- //for applying map config again either.
- normalizedMap = makeModuleMap(map.prefix + '!' + name,
- this.map.parentMap);
- on(normalizedMap,
- 'defined', bind(this, function (value) {
- this.map.normalizedMap = normalizedMap;
- this.init([], function () { return value; }, null, {
- enabled: true,
- ignore: true
- });
- }));
-
- normalizedMod = getOwn(registry, normalizedMap.id);
- if (normalizedMod) {
- //Mark this as a dependency for this plugin, so it
- //can be traced for cycles.
- this.depMaps.push(normalizedMap);
-
- if (this.events.error) {
- normalizedMod.on('error', bind(this, function (err) {
- this.emit('error', err);
- }));
- }
- normalizedMod.enable();
- }
-
- return;
- }
-
- //If a paths config, then just load that file instead to
- //resolve the plugin, as it is built into that paths layer.
- if (bundleId) {
- this.map.url = context.nameToUrl(bundleId);
- this.load();
- return;
- }
-
- load = bind(this, function (value) {
- this.init([], function () { return value; }, null, {
- enabled: true
- });
- });
-
- load.error = bind(this, function (err) {
- this.inited = true;
- this.error = err;
- err.requireModules = [id];
-
- //Remove temp unnormalized modules for this module,
- //since they will never be resolved otherwise now.
- eachProp(registry, function (mod) {
- if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
- cleanRegistry(mod.map.id);
- }
- });
-
- onError(err);
- });
-
- //Allow plugins to load other code without having to know the
- //context or how to 'complete' the load.
- load.fromText = bind(this, function (text, textAlt) {
- /*jslint evil: true */
- var moduleName = map.name,
- moduleMap = makeModuleMap(moduleName),
- hasInteractive = useInteractive;
-
- //As of 2.1.0, support just passing the text, to reinforce
- //fromText only being called once per resource. Still
- //support old style of passing moduleName but discard
- //that moduleName in favor of the internal ref.
- if (textAlt) {
- text = textAlt;
- }
-
- //Turn off interactive script matching for IE for any define
- //calls in the text, then turn it back on at the end.
- if (hasInteractive) {
- useInteractive = false;
- }
-
- //Prime the system by creating a module instance for
- //it.
- getModule(moduleMap);
-
- //Transfer any config to this other module.
- if (hasProp(config.config, id)) {
- config.config[moduleName] = config.config[id];
- }
-
- try {
- req.exec(text);
- } catch (e) {
- return onError(makeError('fromtexteval',
- 'fromText eval for ' + id +
- ' failed: ' + e,
- e,
- [id]));
- }
-
- if (hasInteractive) {
- useInteractive = true;
- }
-
- //Mark this as a dependency for the plugin
- //resource
- this.depMaps.push(moduleMap);
-
- //Support anonymous modules.
- context.completeLoad(moduleName);
-
- //Bind the value of that module to the value for this
- //resource ID.
- localRequire([moduleName], load);
- });
-
- //Use parentName here since the plugin's name is not reliable,
- //could be some weird string with no path that actually wants to
- //reference the parentName's path.
- plugin.load(map.name, localRequire, load, config);
- }));
-
- context.enable(pluginMap, this);
- this.pluginMaps[pluginMap.id] = pluginMap;
- },
-
- enable: function () {
- enabledRegistry[this.map.id] = this;
- this.enabled = true;
-
- //Set flag mentioning that the module is enabling,
- //so that immediate calls to the defined callbacks
- //for dependencies do not trigger inadvertent load
- //with the depCount still being zero.
- this.enabling = true;
-
- //Enable each dependency
- each(this.depMaps, bind(this, function (depMap, i) {
- var id, mod, handler;
-
- if (typeof depMap === 'string') {
- //Dependency needs to be converted to a depMap
- //and wired up to this module.
- depMap = makeModuleMap(depMap,
- (this.map.isDefine ? this.map : this.map.parentMap),
- false,
- !this.skipMap);
- this.depMaps[i] = depMap;
-
- handler = getOwn(handlers, depMap.id);
-
- if (handler) {
- this.depExports[i] = handler(this);
- return;
- }
-
- this.depCount += 1;
-
- on(depMap, 'defined', bind(this, function (depExports) {
- if (this.undefed) {
- return;
- }
- this.defineDep(i, depExports);
- this.check();
- }));
-
- if (this.errback) {
- on(depMap, 'error', bind(this, this.errback));
- } else if (this.events.error) {
- // No direct errback on this module, but something
- // else is listening for errors, so be sure to
- // propagate the error correctly.
- on(depMap, 'error', bind(this, function(err) {
- this.emit('error', err);
- }));
- }
- }
-
- id = depMap.id;
- mod = registry[id];
-
- //Skip special modules like 'require', 'exports', 'module'
- //Also, don't call enable if it is already enabled,
- //important in circular dependency cases.
- if (!hasProp(handlers, id) && mod && !mod.enabled) {
- context.enable(depMap, this);
- }
- }));
-
- //Enable each plugin that is used in
- //a dependency
- eachProp(this.pluginMaps, bind(this, function (pluginMap) {
- var mod = getOwn(registry, pluginMap.id);
- if (mod && !mod.enabled) {
- context.enable(pluginMap, this);
- }
- }));
-
- this.enabling = false;
-
- this.check();
- },
-
- on: function (name, cb) {
- var cbs = this.events[name];
- if (!cbs) {
- cbs = this.events[name] = [];
- }
- cbs.push(cb);
- },
-
- emit: function (name, evt) {
- each(this.events[name], function (cb) {
- cb(evt);
- });
- if (name === 'error') {
- //Now that the error handler was triggered, remove
- //the listeners, since this broken Module instance
- //can stay around for a while in the registry.
- delete this.events[name];
- }
- }
- };
-
- function callGetModule(args) {
- //Skip modules already defined.
- if (!hasProp(defined, args[0])) {
- getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
- }
- }
-
- function removeListener(node, func, name, ieName) {
- //Favor detachEvent because of IE9
- //issue, see attachEvent/addEventListener comment elsewhere
- //in this file.
- if (node.detachEvent && !isOpera) {
- //Probably IE. If not it will throw an error, which will be
- //useful to know.
- if (ieName) {
- node.detachEvent(ieName, func);
- }
- } else {
- node.removeEventListener(name, func, false);
- }
- }
-
- /**
- * Given an event from a script node, get the requirejs info from it,
- * and then removes the event listeners on the node.
- * @param {Event} evt
- * @returns {Object}
- */
- function getScriptData(evt) {
- //Using currentTarget instead of target for Firefox 2.0's sake. Not
- //all old browsers will be supported, but this one was easy enough
- //to support and still makes sense.
- var node = evt.currentTarget || evt.srcElement;
-
- //Remove the listeners once here.
- removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
- removeListener(node, context.onScriptError, 'error');
-
- return {
- node: node,
- id: node && node.getAttribute('data-requiremodule')
- };
- }
-
- function intakeDefines() {
- var args;
-
- //Any defined modules in the global queue, intake them now.
- takeGlobalQueue();
-
- //Make sure any remaining defQueue items get properly processed.
- while (defQueue.length) {
- args = defQueue.shift();
- if (args[0] === null) {
- return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' +
- args[args.length - 1]));
- } else {
- //args are id, deps, factory. Should be normalized by the
- //define() function.
- callGetModule(args);
- }
- }
- context.defQueueMap = {};
- }
-
- context = {
- config: config,
- contextName: contextName,
- registry: registry,
- defined: defined,
- urlFetched: urlFetched,
- defQueue: defQueue,
- defQueueMap: {},
- Module: Module,
- makeModuleMap: makeModuleMap,
- nextTick: req.nextTick,
- onError: onError,
-
- /**
- * Set a configuration for the context.
- * @param {Object} cfg config object to integrate.
- */
- configure: function (cfg) {
- //Make sure the baseUrl ends in a slash.
- if (cfg.baseUrl) {
- if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
- cfg.baseUrl += '/';
- }
- }
-
- // Convert old style urlArgs string to a function.
- if (typeof cfg.urlArgs === 'string') {
- var urlArgs = cfg.urlArgs;
- cfg.urlArgs = function(id, url) {
- return (url.indexOf('?') === -1 ? '?' : '&') + urlArgs;
- };
- }
-
- //Save off the paths since they require special processing,
- //they are additive.
- var shim = config.shim,
- objs = {
- paths: true,
- bundles: true,
- config: true,
- map: true
- };
-
- eachProp(cfg, function (value, prop) {
- if (objs[prop]) {
- if (!config[prop]) {
- config[prop] = {};
- }
- mixin(config[prop], value, true, true);
- } else {
- config[prop] = value;
- }
- });
-
- //Reverse map the bundles
- if (cfg.bundles) {
- eachProp(cfg.bundles, function (value, prop) {
- each(value, function (v) {
- if (v !== prop) {
- bundlesMap[v] = prop;
- }
- });
- });
- }
-
- //Merge shim
- if (cfg.shim) {
- eachProp(cfg.shim, function (value, id) {
- //Normalize the structure
- if (isArray(value)) {
- value = {
- deps: value
- };
- }
- if ((value.exports || value.init) && !value.exportsFn) {
- value.exportsFn = context.makeShimExports(value);
- }
- shim[id] = value;
- });
- config.shim = shim;
- }
-
- //Adjust packages if necessary.
- if (cfg.packages) {
- each(cfg.packages, function (pkgObj) {
- var location, name;
-
- pkgObj = typeof pkgObj === 'string' ? {name: pkgObj} : pkgObj;
-
- name = pkgObj.name;
- location = pkgObj.location;
- if (location) {
- config.paths[name] = pkgObj.location;
- }
-
- //Save pointer to main module ID for pkg name.
- //Remove leading dot in main, so main paths are normalized,
- //and remove any trailing .js, since different package
- //envs have different conventions: some use a module name,
- //some use a file name.
- config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main')
- .replace(currDirRegExp, '')
- .replace(jsSuffixRegExp, '');
- });
- }
-
- //If there are any "waiting to execute" modules in the registry,
- //update the maps for them, since their info, like URLs to load,
- //may have changed.
- eachProp(registry, function (mod, id) {
- //If module already has init called, since it is too
- //late to modify them, and ignore unnormalized ones
- //since they are transient.
- if (!mod.inited && !mod.map.unnormalized) {
- mod.map = makeModuleMap(id, null, true);
- }
- });
-
- //If a deps array or a config callback is specified, then call
- //require with those args. This is useful when require is defined as a
- //config object before require.js is loaded.
- if (cfg.deps || cfg.callback) {
- context.require(cfg.deps || [], cfg.callback);
- }
- },
-
- makeShimExports: function (value) {
- function fn() {
- var ret;
- if (value.init) {
- ret = value.init.apply(global, arguments);
- }
- return ret || (value.exports && getGlobal(value.exports));
- }
- return fn;
- },
-
- makeRequire: function (relMap, options) {
- options = options || {};
-
- function localRequire(deps, callback, errback) {
- var id, map, requireMod;
-
- if (options.enableBuildCallback && callback && isFunction(callback)) {
- callback.__requireJsBuild = true;
- }
-
- if (typeof deps === 'string') {
- if (isFunction(callback)) {
- //Invalid call
- return onError(makeError('requireargs', 'Invalid require call'), errback);
- }
-
- //If require|exports|module are requested, get the
- //value for them from the special handlers. Caveat:
- //this only works while module is being defined.
- if (relMap && hasProp(handlers, deps)) {
- return handlers[deps](registry[relMap.id]);
- }
-
- //Synchronous access to one module. If require.get is
- //available (as in the Node adapter), prefer that.
- if (req.get) {
- return req.get(context, deps, relMap, localRequire);
- }
-
- //Normalize module name, if it contains . or ..
- map = makeModuleMap(deps, relMap, false, true);
- id = map.id;
-
- if (!hasProp(defined, id)) {
- return onError(makeError('notloaded', 'Module name "' +
- id +
- '" has not been loaded yet for context: ' +
- contextName +
- (relMap ? '' : '. Use require([])')));
- }
- return defined[id];
- }
-
- //Grab defines waiting in the global queue.
- intakeDefines();
-
- //Mark all the dependencies as needing to be loaded.
- context.nextTick(function () {
- //Some defines could have been added since the
- //require call, collect them.
- intakeDefines();
-
- requireMod = getModule(makeModuleMap(null, relMap));
-
- //Store if map config should be applied to this require
- //call for dependencies.
- requireMod.skipMap = options.skipMap;
-
- requireMod.init(deps, callback, errback, {
- enabled: true
- });
-
- checkLoaded();
- });
-
- return localRequire;
- }
-
- mixin(localRequire, {
- isBrowser: isBrowser,
-
- /**
- * Converts a module name + .extension into an URL path.
- * *Requires* the use of a module name. It does not support using
- * plain URLs like nameToUrl.
- */
- toUrl: function (moduleNamePlusExt) {
- var ext,
- index = moduleNamePlusExt.lastIndexOf('.'),
- segment = moduleNamePlusExt.split('/')[0],
- isRelative = segment === '.' || segment === '..';
-
- //Have a file extension alias, and it is not the
- //dots from a relative path.
- if (index !== -1 && (!isRelative || index > 1)) {
- ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
- moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
- }
-
- return context.nameToUrl(normalize(moduleNamePlusExt,
- relMap && relMap.id, true), ext, true);
- },
-
- defined: function (id) {
- return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
- },
-
- specified: function (id) {
- id = makeModuleMap(id, relMap, false, true).id;
- return hasProp(defined, id) || hasProp(registry, id);
- }
- });
-
- //Only allow undef on top level require calls
- if (!relMap) {
- localRequire.undef = function (id) {
- //Bind any waiting define() calls to this context,
- //fix for #408
- takeGlobalQueue();
-
- var map = makeModuleMap(id, relMap, true),
- mod = getOwn(registry, id);
-
- mod.undefed = true;
- removeScript(id);
-
- delete defined[id];
- delete urlFetched[map.url];
- delete undefEvents[id];
-
- //Clean queued defines too. Go backwards
- //in array so that the splices do not
- //mess up the iteration.
- eachReverse(defQueue, function(args, i) {
- if (args[0] === id) {
- defQueue.splice(i, 1);
- }
- });
- delete context.defQueueMap[id];
-
- if (mod) {
- //Hold on to listeners in case the
- //module will be attempted to be reloaded
- //using a different config.
- if (mod.events.defined) {
- undefEvents[id] = mod.events;
- }
-
- cleanRegistry(id);
- }
- };
- }
-
- return localRequire;
- },
-
- /**
- * Called to enable a module if it is still in the registry
- * awaiting enablement. A second arg, parent, the parent module,
- * is passed in for context, when this method is overridden by
- * the optimizer. Not shown here to keep code compact.
- */
- enable: function (depMap) {
- var mod = getOwn(registry, depMap.id);
- if (mod) {
- getModule(depMap).enable();
- }
- },
-
- /**
- * Internal method used by environment adapters to complete a load event.
- * A load event could be a script load or just a load pass from a synchronous
- * load call.
- * @param {String} moduleName the name of the module to potentially complete.
- */
- completeLoad: function (moduleName) {
- var found, args, mod,
- shim = getOwn(config.shim, moduleName) || {},
- shExports = shim.exports;
-
- takeGlobalQueue();
-
- while (defQueue.length) {
- args = defQueue.shift();
- if (args[0] === null) {
- args[0] = moduleName;
- //If already found an anonymous module and bound it
- //to this name, then this is some other anon module
- //waiting for its completeLoad to fire.
- if (found) {
- break;
- }
- found = true;
- } else if (args[0] === moduleName) {
- //Found matching define call for this script!
- found = true;
- }
-
- callGetModule(args);
- }
- context.defQueueMap = {};
-
- //Do this after the cycle of callGetModule in case the result
- //of those calls/init calls changes the registry.
- mod = getOwn(registry, moduleName);
-
- if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
- if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
- if (hasPathFallback(moduleName)) {
- return;
- } else {
- return onError(makeError('nodefine',
- 'No define call for ' + moduleName,
- null,
- [moduleName]));
- }
- } else {
- //A script that does not call define(), so just simulate
- //the call for it.
- callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
- }
- }
-
- checkLoaded();
- },
-
- /**
- * Converts a module name to a file path. Supports cases where
- * moduleName may actually be just an URL.
- * Note that it **does not** call normalize on the moduleName,
- * it is assumed to have already been normalized. This is an
- * internal API, not a public one. Use toUrl for the public API.
- */
- nameToUrl: function (moduleName, ext, skipExt) {
- var paths, syms, i, parentModule, url,
- parentPath, bundleId,
- pkgMain = getOwn(config.pkgs, moduleName);
-
- if (pkgMain) {
- moduleName = pkgMain;
- }
-
- bundleId = getOwn(bundlesMap, moduleName);
-
- if (bundleId) {
- return context.nameToUrl(bundleId, ext, skipExt);
- }
-
- //If a colon is in the URL, it indicates a protocol is used and it is just
- //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
- //or ends with .js, then assume the user meant to use an url and not a module id.
- //The slash is important for protocol-less URLs as well as full paths.
- if (req.jsExtRegExp.test(moduleName)) {
- //Just a plain path, not module name lookup, so just return it.
- //Add extension if it is included. This is a bit wonky, only non-.js things pass
- //an extension, this method probably needs to be reworked.
- url = moduleName + (ext || '');
- } else {
- //A module that needs to be converted to a path.
- paths = config.paths;
-
- syms = moduleName.split('/');
- //For each module name segment, see if there is a path
- //registered for it. Start with most specific name
- //and work up from it.
- for (i = syms.length; i > 0; i -= 1) {
- parentModule = syms.slice(0, i).join('/');
-
- parentPath = getOwn(paths, parentModule);
- if (parentPath) {
- //If an array, it means there are a few choices,
- //Choose the one that is desired
- if (isArray(parentPath)) {
- parentPath = parentPath[0];
- }
- syms.splice(0, i, parentPath);
- break;
- }
- }
-
- //Join the path parts together, then figure out if baseUrl is needed.
- url = syms.join('/');
- url += (ext || (/^data\:|^blob\:|\?/.test(url) || skipExt ? '' : '.js'));
- url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
- }
-
- return config.urlArgs && !/^blob\:/.test(url) ?
- url + config.urlArgs(moduleName, url) : url;
- },
-
- //Delegates to req.load. Broken out as a separate function to
- //allow overriding in the optimizer.
- load: function (id, url) {
- req.load(context, id, url);
- },
-
- /**
- * Executes a module callback function. Broken out as a separate function
- * solely to allow the build system to sequence the files in the built
- * layer in the right sequence.
- *
- * @private
- */
- execCb: function (name, callback, args, exports) {
- return callback.apply(exports, args);
- },
-
- /**
- * callback for script loads, used to check status of loading.
- *
- * @param {Event} evt the event from the browser for the script
- * that was loaded.
- */
- onScriptLoad: function (evt) {
- //Using currentTarget instead of target for Firefox 2.0's sake. Not
- //all old browsers will be supported, but this one was easy enough
- //to support and still makes sense.
- if (evt.type === 'load' ||
- (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
- //Reset interactive script so a script node is not held onto for
- //to long.
- interactiveScript = null;
-
- //Pull out the name of the module and the context.
- var data = getScriptData(evt);
- context.completeLoad(data.id);
- }
- },
-
- /**
- * Callback for script errors.
- */
- onScriptError: function (evt) {
- var data = getScriptData(evt);
- if (!hasPathFallback(data.id)) {
- var parents = [];
- eachProp(registry, function(value, key) {
- if (key.indexOf('_@r') !== 0) {
- each(value.depMaps, function(depMap) {
- if (depMap.id === data.id) {
- parents.push(key);
- return true;
- }
- });
- }
- });
- return onError(makeError('scripterror', 'Script error for "' + data.id +
- (parents.length ?
- '", needed by: ' + parents.join(', ') :
- '"'), evt, [data.id]));
- }
- }
- };
-
- context.require = context.makeRequire();
- return context;
- }
-
- /**
- * Main entry point.
- *
- * If the only argument to require is a string, then the module that
- * is represented by that string is fetched for the appropriate context.
- *
- * If the first argument is an array, then it will be treated as an array
- * of dependency string names to fetch. An optional function callback can
- * be specified to execute when all of those dependencies are available.
- *
- * Make a local req variable to help Caja compliance (it assumes things
- * on a require that are not standardized), and to give a short
- * name for minification/local scope use.
- */
- req = requirejs = function (deps, callback, errback, optional) {
-
- //Find the right context, use default
- var context, config,
- contextName = defContextName;
-
- // Determine if have config object in the call.
- if (!isArray(deps) && typeof deps !== 'string') {
- // deps is a config object
- config = deps;
- if (isArray(callback)) {
- // Adjust args if there are dependencies
- deps = callback;
- callback = errback;
- errback = optional;
- } else {
- deps = [];
- }
- }
-
- if (config && config.context) {
- contextName = config.context;
- }
-
- context = getOwn(contexts, contextName);
- if (!context) {
- context = contexts[contextName] = req.s.newContext(contextName);
- }
-
- if (config) {
- context.configure(config);
- }
-
- return context.require(deps, callback, errback);
- };
-
- /**
- * Support require.config() to make it easier to cooperate with other
- * AMD loaders on globally agreed names.
- */
- req.config = function (config) {
- return req(config);
- };
-
- /**
- * Execute something after the current tick
- * of the event loop. Override for other envs
- * that have a better solution than setTimeout.
- * @param {Function} fn function to execute later.
- */
- req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
- setTimeout(fn, 4);
- } : function (fn) { fn(); };
-
- /**
- * Export require as a global, but only if it does not already exist.
- */
- if (!require) {
- require = req;
- }
-
- req.version = version;
-
- //Used to filter out dependencies that are already paths.
- req.jsExtRegExp = /^\/|:|\?|\.js$/;
- req.isBrowser = isBrowser;
- s = req.s = {
- contexts: contexts,
- newContext: newContext
- };
-
- //Create default context.
- req({});
-
- //Exports some context-sensitive methods on global require.
- each([
- 'toUrl',
- 'undef',
- 'defined',
- 'specified'
- ], function (prop) {
- //Reference from contexts instead of early binding to default context,
- //so that during builds, the latest instance of the default context
- //with its config gets used.
- req[prop] = function () {
- var ctx = contexts[defContextName];
- return ctx.require[prop].apply(ctx, arguments);
- };
- });
-
- if (isBrowser) {
- head = s.head = document.getElementsByTagName('head')[0];
- //If BASE tag is in play, using appendChild is a problem for IE6.
- //When that browser dies, this can be removed. Details in this jQuery bug:
- //http://dev.jquery.com/ticket/2709
- baseElement = document.getElementsByTagName('base')[0];
- if (baseElement) {
- head = s.head = baseElement.parentNode;
- }
- }
-
- /**
- * Any errors that require explicitly generates will be passed to this
- * function. Intercept/override it if you want custom error handling.
- * @param {Error} err the error object.
- */
- req.onError = defaultOnError;
-
- /**
- * Creates the node for the load command. Only used in browser envs.
- */
- req.createNode = function (config, moduleName, url) {
- var node = config.xhtml ?
- document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
- document.createElement('script');
- node.type = config.scriptType || 'text/javascript';
- node.charset = 'utf-8';
- node.async = true;
- return node;
- };
-
- /**
- * Does the request to load a module for the browser case.
- * Make this a separate function to allow other environments
- * to override it.
- *
- * @param {Object} context the require context to find state.
- * @param {String} moduleName the name of the module.
- * @param {Object} url the URL to the module.
- */
- req.load = function (context, moduleName, url) {
- var config = (context && context.config) || {},
- node;
- if (isBrowser) {
- //In the browser so use a script tag
- node = req.createNode(config, moduleName, url);
-
- node.setAttribute('data-requirecontext', context.contextName);
- node.setAttribute('data-requiremodule', moduleName);
-
- //Set up load listener. Test attachEvent first because IE9 has
- //a subtle issue in its addEventListener and script onload firings
- //that do not match the behavior of all other browsers with
- //addEventListener support, which fire the onload event for a
- //script right after the script execution. See:
- //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
- //UNFORTUNATELY Opera implements attachEvent but does not follow the script
- //script execution mode.
- if (node.attachEvent &&
- //Check if node.attachEvent is artificially added by custom script or
- //natively supported by browser
- //read https://github.com/requirejs/requirejs/issues/187
- //if we can NOT find [native code] then it must NOT natively supported.
- //in IE8, node.attachEvent does not have toString()
- //Note the test for "[native code" with no closing brace, see:
- //https://github.com/requirejs/requirejs/issues/273
- !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
- !isOpera) {
- //Probably IE. IE (at least 6-8) do not fire
- //script onload right after executing the script, so
- //we cannot tie the anonymous define call to a name.
- //However, IE reports the script as being in 'interactive'
- //readyState at the time of the define call.
- useInteractive = true;
-
- node.attachEvent('onreadystatechange', context.onScriptLoad);
- //It would be great to add an error handler here to catch
- //404s in IE9+. However, onreadystatechange will fire before
- //the error handler, so that does not help. If addEventListener
- //is used, then IE will fire error before load, but we cannot
- //use that pathway given the connect.microsoft.com issue
- //mentioned above about not doing the 'script execute,
- //then fire the script load event listener before execute
- //next script' that other browsers do.
- //Best hope: IE10 fixes the issues,
- //and then destroys all installs of IE 6-9.
- //node.attachEvent('onerror', context.onScriptError);
- } else {
- node.addEventListener('load', context.onScriptLoad, false);
- node.addEventListener('error', context.onScriptError, false);
- }
- node.src = url;
-
- //Calling onNodeCreated after all properties on the node have been
- //set, but before it is placed in the DOM.
- if (config.onNodeCreated) {
- config.onNodeCreated(node, config, moduleName, url);
- }
-
- //For some cache cases in IE 6-8, the script executes before the end
- //of the appendChild execution, so to tie an anonymous define
- //call to the module name (which is stored on the node), hold on
- //to a reference to this node, but clear after the DOM insertion.
- currentlyAddingScript = node;
- if (baseElement) {
- head.insertBefore(node, baseElement);
- } else {
- head.appendChild(node);
- }
- currentlyAddingScript = null;
-
- return node;
- } else if (isWebWorker) {
- try {
- //In a web worker, use importScripts. This is not a very
- //efficient use of importScripts, importScripts will block until
- //its script is downloaded and evaluated. However, if web workers
- //are in play, the expectation is that a build has been done so
- //that only one script needs to be loaded anyway. This may need
- //to be reevaluated if other use cases become common.
-
- // Post a task to the event loop to work around a bug in WebKit
- // where the worker gets garbage-collected after calling
- // importScripts(): https://webkit.org/b/153317
- setTimeout(function() {}, 0);
- importScripts(url);
-
- //Account for anonymous modules
- context.completeLoad(moduleName);
- } catch (e) {
- context.onError(makeError('importscripts',
- 'importScripts failed for ' +
- moduleName + ' at ' + url,
- e,
- [moduleName]));
- }
- }
- };
-
- function getInteractiveScript() {
- if (interactiveScript && interactiveScript.readyState === 'interactive') {
- return interactiveScript;
- }
-
- eachReverse(scripts(), function (script) {
- if (script.readyState === 'interactive') {
- return (interactiveScript = script);
- }
- });
- return interactiveScript;
- }
-
- //Look for a data-main script attribute, which could also adjust the baseUrl.
- if (isBrowser && !cfg.skipDataMain) {
- //Figure out baseUrl. Get it from the script tag with require.js in it.
- eachReverse(scripts(), function (script) {
- //Set the 'head' where we can append children by
- //using the script's parent.
- if (!head) {
- head = script.parentNode;
- }
-
- //Look for a data-main attribute to set main script for the page
- //to load. If it is there, the path to data main becomes the
- //baseUrl, if it is not already set.
- dataMain = script.getAttribute('data-main');
- if (dataMain) {
- //Preserve dataMain in case it is a path (i.e. contains '?')
- mainScript = dataMain;
-
- //Set final baseUrl if there is not already an explicit one,
- //but only do so if the data-main value is not a loader plugin
- //module ID.
- if (!cfg.baseUrl && mainScript.indexOf('!') === -1) {
- //Pull off the directory of data-main for use as the
- //baseUrl.
- src = mainScript.split('/');
- mainScript = src.pop();
- subPath = src.length ? src.join('/') + '/' : './';
-
- cfg.baseUrl = subPath;
- }
-
- //Strip off any trailing .js since mainScript is now
- //like a module name.
- mainScript = mainScript.replace(jsSuffixRegExp, '');
-
- //If mainScript is still a path, fall back to dataMain
- if (req.jsExtRegExp.test(mainScript)) {
- mainScript = dataMain;
- }
-
- //Put the data-main script in the files to load.
- cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript];
-
- return true;
- }
- });
- }
-
- /**
- * The function that handles definitions of modules. Differs from
- * require() in that a string for the module should be the first argument,
- * and the function to execute after dependencies are loaded should
- * return a value to define the module corresponding to the first argument's
- * name.
- */
- define = function (name, deps, callback) {
- var node, context;
-
- //Allow for anonymous modules
- if (typeof name !== 'string') {
- //Adjust args appropriately
- callback = deps;
- deps = name;
- name = null;
- }
-
- //This module may not have dependencies
- if (!isArray(deps)) {
- callback = deps;
- deps = null;
- }
-
- //If no name, and callback is a function, then figure out if it a
- //CommonJS thing with dependencies.
- if (!deps && isFunction(callback)) {
- deps = [];
- //Remove comments from the callback string,
- //look for require calls, and pull them into the dependencies,
- //but only if there are function args.
- if (callback.length) {
- callback
- .toString()
- .replace(commentRegExp, commentReplace)
- .replace(cjsRequireRegExp, function (match, dep) {
- deps.push(dep);
- });
-
- //May be a CommonJS thing even without require calls, but still
- //could use exports, and module. Avoid doing exports and module
- //work though if it just needs require.
- //REQUIRES the function to expect the CommonJS variables in the
- //order listed below.
- deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
- }
- }
-
- //If in IE 6-8 and hit an anonymous define() call, do the interactive
- //work.
- if (useInteractive) {
- node = currentlyAddingScript || getInteractiveScript();
- if (node) {
- if (!name) {
- name = node.getAttribute('data-requiremodule');
- }
- context = contexts[node.getAttribute('data-requirecontext')];
- }
- }
-
- //Always save off evaluating the def call until the script onload handler.
- //This allows multiple modules to be in a file without prematurely
- //tracing dependencies, and allows for anonymous module support,
- //where the module name is not known until the script onload event
- //occurs. If no context, use the global queue, and get it processed
- //in the onscript load callback.
- if (context) {
- context.defQueue.push([name, deps, callback]);
- context.defQueueMap[name] = true;
- } else {
- globalDefQueue.push([name, deps, callback]);
- }
- };
-
- define.amd = {
- jQuery: true
- };
-
- /**
- * Executes the text. Normally just uses eval, but can be modified
- * to use a better, environment-specific call. Only used for transpiling
- * loader plugins, not for plain JS modules.
- * @param {String} text the text to execute/evaluate.
- */
- req.exec = function (text) {
- /*jslint evil: true */
- return eval(text);
- };
-
- //Set up with config info.
- req(cfg);
-}(this, (typeof setTimeout === 'undefined' ? undefined : setTimeout)));
diff --git a/test/newapi.html b/test/newapi.html
deleted file mode 100644
index 0767be1..0000000
--- a/test/newapi.html
+++ /dev/null
@@ -1,44 +0,0 @@
-<html>
-<head>
-<link rel="stylesheet" href="lib/qunit.css">
-</head>
-<body>
-<div id="qunit"></div>
-<div id="qunit-fixture"></div>
-<script src="lib/qunit.js"></script>
-<script src="../seedrandom.min.js"></script>
-<script>
-QUnit.module("New API Test");
-
-QUnit.test("Check that we can use new", function(assert) {
-
-assert.ok(true, "Seeded random created with new:");
-var check = [];
-var prng = new Math.seedrandom(1);
-var r;
-for (var j = 0; j < 5; ++j) {
- r = prng();
- assert.ok(true, r);
- check.push(r);
-}
-assert.ok(true, "Native random:");
-for (var j = 0; j < 5; ++j) {
- r = Math.random();
- assert.ok(true, r);
- check.push(r);
-}
-var seed = Math.seedrandom(1);
-assert.ok(true, "Overridden random without new " +
- "(return value " + seed + "):");
-for (var j = 0; j < 10; ++j) {
- r = Math.random();
- if (j < 5) {
- assert.equal(check[j], r, r + " vs " + check[j]);
- } else {
- assert.ok(check[j] != r, "unequal: " + r + " vs " + check[j]);
- }
-}
-});
-</script>
-</body>
-</html>
diff --git a/test/nodetest.js b/test/nodetest.js
deleted file mode 100644
index ab90184..0000000
--- a/test/nodetest.js
+++ /dev/null
@@ -1,226 +0,0 @@
-var assert = require("assert");
-var seedrandom = require("../seedrandom");
-var requirejs = require("requirejs");
-
-// Stub out requirejs if in the browser via browserify.
-if (!requirejs.config) {
- requirejs = require;
-} else {
- requirejs.config({
- baseUrl: __dirname
- });
-}
-
-describe("Nodejs API Test", function() {
-
-it('should pass basic tests.', function() {
- var original = Math.random,
- result, r, xprng, obj, as2, as3, autoseed1, myrng,
- firstprng, secondprng, thirdprng, rng;
-
- result = Math.seedrandom('hello.');
- firstprng = Math.random;
- assert.ok(original !== firstprng, "Should change Math.random.");
- assert.equal(result, "hello.", "Should return short seed.");
- r = Math.random();
- assert.equal(r, 0.9282578795792454, "Should be 'hello.'#1");
- r = Math.random();
- assert.equal(r, 0.3752569768646784, "Should be 'hello.'#2");
-
- // should be able to autoseed
- result = Math.seedrandom();
- secondprng = Math.random;
- assert.ok(original !== secondprng, "Should change Math.random.");
- assert.ok(firstprng !== secondprng, "Should change Math.random.");
- assert.equal(result.length, 256, "Should return short seed.");
- r = Math.random();
- assert.ok(r > 0, "Should be posititive.");
- assert.ok(r < 1, "Should be less than 1.");
- assert.ok(r != 0.9282578795792454, "Should not be 'hello.'#1");
- assert.ok(r != 0.3752569768646784, "Should not be 'hello.'#2");
- assert.ok(r != 0.7316977468919549, "Should not be 'hello.'#3");
- autoseed1 = r;
-
- // should be able to add entropy.
- result = Math.seedrandom('added entropy.', { entropy:true });
- assert.equal(result.length, 256, "Should return short seed.");
- thirdprng = Math.random;
- assert.ok(thirdprng !== secondprng, "Should change Math.random.");
- r = Math.random();
- assert.ok(r != 0.597067214994467, "Should not be 'added entropy.'#1");
-
- // Reset to original Math.random.
- Math.random = original;
- // should be able to use new Math.seedrandom('hello.')
- myrng = new Math.seedrandom('hello.');
- assert.ok(original === Math.random, "Should not change Math.random.");
- assert.ok(original !== myrng, "PRNG should not be Math.random.");
- r = myrng();
- assert.equal(r, 0.9282578795792454, "Should be 'hello.'#1");
-
- // should be able to use seedrandom('hello.')"
- rng = seedrandom('hello.');
- assert.equal(typeof(rng), 'function', "Should return a function.");
- r = rng();
- assert.equal(r, 0.9282578795792454, "Should be 'hello.'#1");
- assert.ok(original === Math.random, "Should not change Math.random.");
- assert.ok(original !== rng, "PRNG should not be Math.random.");
-
- // Global PRNG: set Math.random.
- // should be able to use seedrandom('hello.', { global: true })
- result = seedrandom('hello.', { global: true });
- assert.equal(result, 'hello.', "Should return short seed.");
- assert.ok(original != Math.random, "Should change Math.random.");
- r = Math.random();
- assert.equal(r, 0.9282578795792454, "Should be 'hello.'#1");
-
- // Autoseeded non-global
- Math.random = original;
- // should be able to use seedrandom()
- result = seedrandom();
- assert.equal(typeof(result), 'function', "Should return function.");
- assert.ok(original === Math.random, "Should not change Math.random.");
- r = result();
- // got " + r);
- assert.ok(r != autoseed1, "Should not repeat previous autoseed.");
- assert.ok(r != 0.9282578795792454, "Should not be 'hello.'#1");
- assert.ok(r != 0.7316977468919549, "Should not be 'hello.'#3");
-
- // Mixing accumulated entropy.
- // should be able to use seedrandom('added entropy.', { entropy: true })
- rng = seedrandom('added entropy.', { entropy: true });
- r = result();
- // got " + r);
- assert.ok(r != autoseed1, "Should not repeat previous autoseed.");
- assert.ok(r != 0.597067214994467, "Should not be 'added entropy.'#1");
-
- // Legacy calling convention for mixing accumulated entropy.
- // should be able to use seedrandom('added entropy.', true)
- rng = seedrandom('added entropy.', true);
- r = result();
- // got " + r);
- assert.ok(r != autoseed1, "Should not repeat previous autoseed.");
- assert.ok(r != 0.597067214994467, "Should not be 'added entropy.'#1");
-
- // The pass option
- // should be able to use Math.seedrandom(null, { pass: ...
- obj = Math.seedrandom(null, { pass: function(prng, seed) {
- return { random: prng, seed: seed };
- }});
- assert.ok(original === Math.random, "Should not change Math.random.");
- assert.ok(original !== obj.random, "Should be different from Math.random.");
- assert.equal(typeof(obj.random), 'function', "Should return a PRNG function.");
- assert.equal(typeof(obj.seed), 'string', "Should return a seed.");
- as2 = obj.random();
- assert.ok(as2 != 0.9282578795792454, "Should not be 'hello.'#1");
- rng = seedrandom(obj.seed);
- as3 = rng();
- assert.equal(as2, as3, "Should be reproducible when using the seed.");
-
- // Exercise pass again, with explicit seed and global
- // should be able to use Math.seedrandom('hello.', { pass: ...
- result = Math.seedrandom('hello.', {
- global: 'abc',
- pass: function(prng, seed, global) {
- assert.equal(typeof(prng), 'function', "Callback arg #1 assert");
- assert.equal(seed, 'hello.', "Callback arg #2 assert");
- assert.equal(global, 'abc', "Callback arg #3 passed through.");
- assert.equal(prng(), 0.9282578795792454, "Should be 'hello.'#1");
- return 'def';
- }});
- assert.equal(result, 'def', "Should return value from callback.");
- assert.ok(original === Math.random, "Should not change Math.random.");
-
- // Legacy third argument callback argument:
- // should be able to use Math.seedrandom('hello.', { global: 50 }, callback)
- result = Math.seedrandom('hello.', { global: 50 },
- function(prng, seed, global) {
- assert.equal(typeof(prng), 'function', "Callback arg #1 assert");
- assert.equal(seed, 'hello.', "Callback arg #2 assert");
- assert.equal(global, 50, "Callback arg #3 assert");
- assert.equal(prng(), 0.9282578795792454, "Should be 'hello.'#1");
- return 'zzz';
- });
- assert.equal(result, 'zzz', "Should return value from callback.");
- assert.ok(original === Math.random, "Should not change Math.random.");
-
- // Global: false.
- // should be able to use new Math.seedrandom('hello.', {global: false})
- myrng = new Math.seedrandom('hello.', {global:false});
- assert.equal(typeof(myrng), 'function', "Should return a PRNG funciton.");
- assert.ok(original === Math.random, "Should not change Math.random.");
- assert.ok(original !== myrng, "PRNG should not be Math.random.");
- r = myrng();
- assert.equal(r, 0.9282578795792454, "Should be 'hello.'#1");
-
- // options = {} when a method of Math.
- // should be able to use Math.seedrandom('hello.', {})
- result = Math.seedrandom('hello.');
- xprng = Math.random;
- assert.ok(original !== xprng, "Should change Math.random.");
- assert.equal(result, "hello.", "Should return short seed.");
- r = Math.random();
- assert.equal(r, 0.9282578795792454, "Should be 'hello.'#1");
- r = Math.random();
- assert.equal(r, 0.3752569768646784, "Should be 'hello.'#2");
- Math.random = original;
-
- // options = {} when not a method of Math
- // should be able to use seedrandom('hello.', {})
- rng = seedrandom('hello.', {});
- assert.equal(typeof(rng), 'function', "Should return a function.");
- r = rng();
- assert.equal(r, 0.9282578795792454, "Should be 'hello.'#1");
- assert.ok(original === Math.random, "Should not change Math.random.");
- assert.ok(original !== rng, "PRNG should not be Math.random.");
-});
-
-it('should support state api.', function() {
- // Verify that there is no state method
- var dummy = seedrandom('hello');
- var unexpected = -1;
- var expected = -1;
- try {
- unexpected = dummy.state();
- } catch(e) {
- expected = 1;
- }
- assert.equal(unexpected, -1);
- assert.equal(expected, 1);
- var count = 0;
- for (var x in dummy) {
- if (x == 'state') count += 1;
- }
- assert.equal(count, 0);
-
- // Verify that a state method can be added
- var saveable = seedrandom("secret-seed", {state: true});
- var ordinary = seedrandom("secret-seed");
- for (var j = 0; j < 1e2; ++j) {
- assert.equal(ordinary(), saveable());
- }
- var virgin = seedrandom("secret-seed");
- var saved = saveable.state();
- var replica = seedrandom("", {state: saved});
- for (var j = 0; j < 1e2; ++j) {
- var r = replica();
- assert.equal(r, saveable());
- assert.equal(r, ordinary());
- assert.ok(r != virgin());
- }
-});
-
-it('should support requirejs in node.', function() {
- var original = Math.random;
- var rsr = requirejs('../seedrandom');
- var rng = rsr('hello.');
- assert.equal(typeof(rng), 'function', "Should return a function.");
- var r = rng();
- assert.equal(r, 0.9282578795792454, "Should be 'hello.'#1");
- assert.ok(original === Math.random, "Should not change Math.random.");
- assert.ok(original !== rng, "PRNG should not be Math.random.");
-});
-
-// End of test.
-
-});
diff --git a/test/options.html b/test/options.html
deleted file mode 100644
index d8ca26b..0000000
--- a/test/options.html
+++ /dev/null
@@ -1,195 +0,0 @@
-<html>
-<head>
-<link rel="stylesheet" href="lib/qunit.css">
-</head>
-<body>
-<div id="qunit"></div>
-<div id="qunit-fixture"></div>
-<script src="../seedrandom.min.js"></script>
-<script src="lib/qunit.js"></script>
-<script>
-QUnit.module("Options API Test");
-
-QUnit.test("Verify that we can use documented options", function(assert) {
-assert.ok(true, "Seeded random created with new:");
-
-var original = Math.random;
-
-assert.ok(true, "Using Math.seedrandom('hello.')");
-var result = Math.seedrandom('hello.');
-var firstprng = Math.random;
-assert.ok(original !== firstprng, "Should change Math.random.");
-assert.equal(result, "hello.", "Should return short seed.");
-var r = Math.random();
-assert.ok(true, "Got " + r);
-assert.equal(r, 0.9282578795792454, "Should be 'hello.'#1");
-r = Math.random();
-assert.ok(true, "Got " + r);
-assert.equal(r, 0.3752569768646784, "Should be 'hello.'#2");
-
-assert.ok(true, "Using Math.seedrandom()");
-result = Math.seedrandom();
-var secondprng = Math.random;
-assert.ok(original !== secondprng, "Should change Math.random.");
-assert.ok(firstprng !== secondprng, "Should change Math.random.");
-assert.equal(result.length, 256, "Should return short seed.");
-r = Math.random();
-assert.ok(true, "Got " + r);
-assert.ok(r != 0.9282578795792454, "Should not be 'hello.'#1");
-assert.ok(r != 0.7316977468919549, "Should not be 'hello.'#3");
-var autoseed1 = r;
-
-assert.ok(true, "Using Math.seedrandom('added entropy.', { entropy:true })");
-result = Math.seedrandom('added entropy.', { entropy:true });
-assert.equal(result.length, 256, "Should return short seed.");
-var thirdprng = Math.random;
-assert.ok(thirdprng !== secondprng, "Should change Math.random.");
-r = Math.random();
-assert.ok(true, "Got " + r);
-assert.ok(r != 0.597067214994467, "Should not be 'added entropy.'#1");
-
-// Reset to original Math.random.
-Math.random = original;
-assert.ok(true, "Using new Math.seedrandom('hello.')");
-var myrng = new Math.seedrandom('hello.');
-assert.ok(original === Math.random, "Should not change Math.random.");
-assert.ok(original !== myrng, "PRNG should not be Math.random.");
-r = myrng();
-assert.ok(true, "Got " + r);
-assert.equal(r, 0.9282578795792454, "Should be 'hello.'#1");
-
-// Use "quick" to get only 32 bits of randomness in a float.
-assert.equal(myrng.quick(), 0.3752569768112153, "Should be quick #1.1");
-
-// Use "int32" to get a 32 bit (signed) integer
-assert.equal(myrng.int32(), 986220731, "Should be int32 #1.2");
-
-// As if brought in by node.js
-var seedrandom = Math.seedrandom;
-
-assert.ok(true, "Using seedrandom('hello.')");
-var rng = seedrandom('hello.');
-assert.equal(typeof(rng), 'function', "Should return a function.");
-r = rng();
-assert.ok(true, "Got " + r);
-assert.equal(r, 0.9282578795792454, "Should be 'hello.'#1");
-assert.ok(original === Math.random, "Should not change Math.random.");
-assert.ok(original !== rng, "PRNG should not be Math.random.");
-
-// Global PRNG: set Math.random.
-assert.ok(true, "Using seedrandom('hello.', { global: true })");
-result = seedrandom('hello.', { global: true });
-assert.equal(result, 'hello.', "Should return short seed.");
-assert.ok(original != Math.random, "Should change Math.random.");
-r = Math.random();
-assert.ok(true, "Got " + r);
-assert.equal(r, 0.9282578795792454, "Should be 'hello.'#1");
-
-// Autoseeded non-global
-Math.random = original;
-assert.ok(true, "Using seedrandom()");
-result = seedrandom();
-assert.equal(typeof(result), 'function', "Should return function.");
-assert.ok(original === Math.random, "Should not change Math.random.");
-r = result();
-assert.ok(true, "Got " + r);
-assert.ok(r != autoseed1, "Should not repeat previous autoseed.");
-assert.ok(r != 0.9282578795792454, "Should not be 'hello.'#1");
-assert.ok(r != 0.7316977468919549, "Should not be 'hello.'#3");
-
-// Mixing accumulated entropy.
-assert.ok(true, "Using seedrandom('added entropy.', { entropy: true })");
-rng = seedrandom('added entropy.', { entropy: true });
-r = result();
-assert.ok(true, "Got " + r);
-assert.ok(r != autoseed1, "Should not repeat previous autoseed.");
-assert.ok(r != 0.597067214994467, "Should not be 'added entropy.'#1");
-
-// Legacy calling convention for mixing accumulated entropy.
-assert.ok(true, "Using seedrandom('added entropy.', true)");
-rng = seedrandom('added entropy.', true);
-r = result();
-assert.ok(true, "Got " + r);
-assert.ok(r != autoseed1, "Should not repeat previous autoseed.");
-assert.ok(r != 0.597067214994467, "Should not be 'added entropy.'#1");
-
-// The pass option
-assert.ok(true, "Using Math.seedrandom(null, { pass: ...");
-var obj = Math.seedrandom(null, { pass: function(prng, seed) {
- return { random: prng, seed: seed };
-}});
-assert.ok(original === Math.random, "Should not change Math.random.");
-assert.ok(original !== obj.random, "Should be different from Math.random.");
-assert.equal(typeof(obj.random), 'function', "Should return a PRNG function.");
-assert.equal(typeof(obj.seed), 'string', "Should return a seed.");
-var as2 = obj.random();
-assert.ok(as2 != 0.9282578795792454, "Should not be 'hello.'#1");
-rng = seedrandom(obj.seed);
-var as3 = rng();
-assert.equal(as2, as3, "Should be reproducible when using the seed.");
-
-// Exercise pass again, with explicit seed and global
-assert.ok(true, "Using Math.seedrandom('hello.', { pass: ...");
-result = Math.seedrandom('hello.', {
- global: 'abc',
- pass: function(prng, seed, global) {
- assert.equal(typeof(prng), 'function', "Callback arg #1 assert.ok");
- assert.equal(seed, 'hello.', "Callback arg #2 assert.ok");
- assert.equal(global, 'abc', "Callback arg #3 passed through.");
- assert.equal(prng(), 0.9282578795792454, "Should be 'hello.'#1");
- return 'def';
-}});
-assert.equal(result, 'def', "Should return value from callback.");
-assert.ok(original === Math.random, "Should not change Math.random.");
-
-// Legacy third argument callback argument:
-assert.ok(true, "Using Math.seedrandom('hello.', { global: 50 }, callback)");
-result = Math.seedrandom('hello.', { global: 50 },
- function(prng, seed, global) {
- assert.equal(typeof(prng), 'function', "Callback arg #1 assert.ok");
- assert.equal(seed, 'hello.', "Callback arg #2 assert.ok");
- assert.equal(global, 50, "Callback arg #3 assert.ok");
- assert.equal(prng(), 0.9282578795792454, "Should be 'hello.'#1");
- return 'zzz';
-});
-assert.equal(result, 'zzz', "Should return value from callback.");
-assert.ok(original === Math.random, "Should not change Math.random.");
-
-// Global: false.
-assert.ok(true, "Using new Math.seedrandom('hello.', {global: false})");
-myrng = new Math.seedrandom('hello.', {global:false});
-assert.equal(typeof(myrng), 'function', "Should return a PRNG funciton.");
-assert.ok(original === Math.random, "Should not change Math.random.");
-assert.ok(original !== myrng, "PRNG should not be Math.random.");
-r = myrng();
-assert.ok(true, "Got " + r);
-assert.equal(r, 0.9282578795792454, "Should be 'hello.'#1");
-
-// options = {} when a method of Math.
-assert.ok(true, "Using Math.seedrandom('hello.', {})");
-var result = Math.seedrandom('hello.');
-var xprng = Math.random;
-assert.ok(original !== xprng, "Should change Math.random.");
-assert.equal(result, "hello.", "Should return short seed.");
-var r = Math.random();
-assert.ok(true, "Got " + r);
-assert.equal(r, 0.9282578795792454, "Should be 'hello.'#1");
-r = Math.random();
-assert.ok(true, "Got " + r);
-assert.equal(r, 0.3752569768646784, "Should be 'hello.'#2");
-Math.random = original;
-
-// options = {} when not a method of Math
-assert.ok(true, "Using seedrandom('hello.', {})");
-rng = seedrandom('hello.', {});
-assert.equal(typeof(rng), 'function', "Should return a function.");
-r = rng();
-assert.ok(true, "Got " + r);
-assert.equal(r, 0.9282578795792454, "Should be 'hello.'#1");
-assert.ok(original === Math.random, "Should not change Math.random.");
-assert.ok(original !== rng, "PRNG should not be Math.random.");
-
-});
-</script>
-</body>
-</html>
diff --git a/test/out/dieharder-report.txt b/test/out/dieharder-report.txt
deleted file mode 100644
index 9e94668..0000000
--- a/test/out/dieharder-report.txt
+++ /dev/null
@@ -1,125 +0,0 @@
-#=============================================================================#
-# dieharder version 3.31.1 Copyright 2003 Robert G. Brown #
-#=============================================================================#
- rng_name |rands/second| Seed |
-stdin_input_raw| 8.07e+05 | 254212981|
-#=============================================================================#
- test_name |ntup| tsamples |psamples| p-value |Assessment
-#=============================================================================#
- diehard_birthdays| 0| 100| 100|0.55960061| PASSED
- diehard_operm5| 0| 1000000| 100|0.10062010| PASSED
- diehard_rank_32x32| 0| 40000| 100|0.70957907| PASSED
- diehard_rank_6x8| 0| 100000| 100|0.55953143| PASSED
- diehard_bitstream| 0| 2097152| 100|0.22843857| PASSED
- diehard_opso| 0| 2097152| 100|0.72251086| PASSED
- diehard_oqso| 0| 2097152| 100|0.30642074| PASSED
- diehard_dna| 0| 2097152| 100|0.30448899| PASSED
-diehard_count_1s_str| 0| 256000| 100|0.23557064| PASSED
-diehard_count_1s_byt| 0| 256000| 100|0.71300874| PASSED
- diehard_parking_lot| 0| 12000| 100|0.88217430| PASSED
- diehard_2dsphere| 2| 8000| 100|0.32366362| PASSED
- diehard_3dsphere| 3| 4000| 100|0.30804215| PASSED
- diehard_squeeze| 0| 100000| 100|0.97856588| PASSED
- diehard_sums| 0| 100| 100|0.01512286| PASSED
- diehard_runs| 0| 100000| 100|0.39065054| PASSED
- diehard_runs| 0| 100000| 100|0.10369088| PASSED
- diehard_craps| 0| 200000| 100|0.57875078| PASSED
- diehard_craps| 0| 200000| 100|0.96945165| PASSED
- marsaglia_tsang_gcd| 0| 10000000| 100|0.58793715| PASSED
- marsaglia_tsang_gcd| 0| 10000000| 100|0.59724594| PASSED
- sts_monobit| 1| 100000| 100|0.49155110| PASSED
- sts_runs| 2| 100000| 100|0.01880740| PASSED
- sts_serial| 1| 100000| 100|0.79060354| PASSED
- sts_serial| 2| 100000| 100|0.91055644| PASSED
- sts_serial| 3| 100000| 100|0.15984346| PASSED
- sts_serial| 3| 100000| 100|0.04426690| PASSED
- sts_serial| 4| 100000| 100|0.31589675| PASSED
- sts_serial| 4| 100000| 100|0.65789943| PASSED
- sts_serial| 5| 100000| 100|0.84228003| PASSED
- sts_serial| 5| 100000| 100|0.28748169| PASSED
- sts_serial| 6| 100000| 100|0.00092985| WEAK
- sts_serial| 6| 100000| 100|0.06074248| PASSED
- sts_serial| 7| 100000| 100|0.54740122| PASSED
- sts_serial| 7| 100000| 100|0.30286638| PASSED
- sts_serial| 8| 100000| 100|0.56593073| PASSED
- sts_serial| 8| 100000| 100|0.48256390| PASSED
- sts_serial| 9| 100000| 100|0.70850963| PASSED
- sts_serial| 9| 100000| 100|0.63732762| PASSED
- sts_serial| 10| 100000| 100|0.70209276| PASSED
- sts_serial| 10| 100000| 100|0.99576606| WEAK
- sts_serial| 11| 100000| 100|0.96272563| PASSED
- sts_serial| 11| 100000| 100|0.76682898| PASSED
- sts_serial| 12| 100000| 100|0.51522677| PASSED
- sts_serial| 12| 100000| 100|0.49381681| PASSED
- sts_serial| 13| 100000| 100|0.24260261| PASSED
- sts_serial| 13| 100000| 100|0.41953338| PASSED
- sts_serial| 14| 100000| 100|0.34770045| PASSED
- sts_serial| 14| 100000| 100|0.16117277| PASSED
- sts_serial| 15| 100000| 100|0.27319992| PASSED
- sts_serial| 15| 100000| 100|0.61170864| PASSED
- sts_serial| 16| 100000| 100|0.90638742| PASSED
- sts_serial| 16| 100000| 100|0.60186602| PASSED
- rgb_bitdist| 1| 100000| 100|0.72630216| PASSED
- rgb_bitdist| 2| 100000| 100|0.61396597| PASSED
- rgb_bitdist| 3| 100000| 100|0.40711729| PASSED
- rgb_bitdist| 4| 100000| 100|0.94730365| PASSED
- rgb_bitdist| 5| 100000| 100|0.95781972| PASSED
- rgb_bitdist| 6| 100000| 100|0.15054771| PASSED
- rgb_bitdist| 7| 100000| 100|0.25022202| PASSED
- rgb_bitdist| 8| 100000| 100|0.66027754| PASSED
- rgb_bitdist| 9| 100000| 100|0.86566842| PASSED
- rgb_bitdist| 10| 100000| 100|0.55219204| PASSED
- rgb_bitdist| 11| 100000| 100|0.73446935| PASSED
- rgb_bitdist| 12| 100000| 100|0.99761332| WEAK
-rgb_minimum_distance| 2| 10000| 1000|0.42222311| PASSED
-rgb_minimum_distance| 3| 10000| 1000|0.81566417| PASSED
-rgb_minimum_distance| 4| 10000| 1000|0.84024874| PASSED
-rgb_minimum_distance| 5| 10000| 1000|0.37732026| PASSED
- rgb_permutations| 2| 100000| 100|0.10996142| PASSED
- rgb_permutations| 3| 100000| 100|0.64682554| PASSED
- rgb_permutations| 4| 100000| 100|0.75843859| PASSED
- rgb_permutations| 5| 100000| 100|0.95248930| PASSED
- rgb_lagged_sum| 0| 1000000| 100|0.57812648| PASSED
- rgb_lagged_sum| 1| 1000000| 100|0.67863162| PASSED
- rgb_lagged_sum| 2| 1000000| 100|0.70003210| PASSED
- rgb_lagged_sum| 3| 1000000| 100|0.50312943| PASSED
- rgb_lagged_sum| 4| 1000000| 100|0.80009739| PASSED
- rgb_lagged_sum| 5| 1000000| 100|0.66383600| PASSED
- rgb_lagged_sum| 6| 1000000| 100|0.65640392| PASSED
- rgb_lagged_sum| 7| 1000000| 100|0.10710511| PASSED
- rgb_lagged_sum| 8| 1000000| 100|0.70414014| PASSED
- rgb_lagged_sum| 9| 1000000| 100|0.63857571| PASSED
- rgb_lagged_sum| 10| 1000000| 100|0.25221229| PASSED
- rgb_lagged_sum| 11| 1000000| 100|0.04199433| PASSED
- rgb_lagged_sum| 12| 1000000| 100|0.82738115| PASSED
- rgb_lagged_sum| 13| 1000000| 100|0.28316509| PASSED
- rgb_lagged_sum| 14| 1000000| 100|0.21184422| PASSED
- rgb_lagged_sum| 15| 1000000| 100|0.35537687| PASSED
- rgb_lagged_sum| 16| 1000000| 100|0.40157319| PASSED
- rgb_lagged_sum| 17| 1000000| 100|0.98108259| PASSED
- rgb_lagged_sum| 18| 1000000| 100|0.65892868| PASSED
- rgb_lagged_sum| 19| 1000000| 100|0.61659671| PASSED
- rgb_lagged_sum| 20| 1000000| 100|0.21462018| PASSED
- rgb_lagged_sum| 21| 1000000| 100|0.94489214| PASSED
- rgb_lagged_sum| 22| 1000000| 100|0.76019491| PASSED
- rgb_lagged_sum| 23| 1000000| 100|0.21024028| PASSED
- rgb_lagged_sum| 24| 1000000| 100|0.25249456| PASSED
- rgb_lagged_sum| 25| 1000000| 100|0.87385459| PASSED
- rgb_lagged_sum| 26| 1000000| 100|0.81553540| PASSED
- rgb_lagged_sum| 27| 1000000| 100|0.94450657| PASSED
- rgb_lagged_sum| 28| 1000000| 100|0.82470366| PASSED
- rgb_lagged_sum| 29| 1000000| 100|0.93993722| PASSED
- rgb_lagged_sum| 30| 1000000| 100|0.52675692| PASSED
- rgb_lagged_sum| 31| 1000000| 100|0.59975558| PASSED
- rgb_lagged_sum| 32| 1000000| 100|0.27951088| PASSED
- rgb_kstest_test| 0| 10000| 1000|0.49707175| PASSED
- dab_bytedistrib| 0| 51200000| 1|0.73019918| PASSED
- dab_dct| 256| 50000| 1|0.33856081| PASSED
-Preparing to run test 207. ntuple = 0
- dab_filltree| 32| 15000000| 1|0.92953640| PASSED
- dab_filltree| 32| 15000000| 1|0.10970674| PASSED
-Preparing to run test 208. ntuple = 0
- dab_filltree2| 0| 5000000| 1|0.88411850| PASSED
- dab_filltree2| 1| 5000000| 1|0.56835378| PASSED
-Preparing to run test 209. ntuple = 0
- dab_monobit2| 12| 65000000| 1|0.07987839| PASSED
diff --git a/test/prngtest.js b/test/prngtest.js
deleted file mode 100644
index c5ae03a..0000000
--- a/test/prngtest.js
+++ /dev/null
@@ -1,122 +0,0 @@
-// A simple smoke test and benchmark for the generators.
-
-var assert = require('assert');
-var xor128 = require('../lib/xor128');
-var xorwow = require('../lib/xorwow');
-var xs7 = require('../lib/xorshift7');
-var xor4096 = require('../lib/xor4096');
-var tychei = require('../lib/tychei');
-var alea = require('../lib/alea');
-var sr = require('../seedrandom');
-
-describe("XOR-Shift generator test", function() {
-
-var benchmarks = { native: { rand: Math.random, times: [] } };
-
-function test(label, alg, double1, float3, int4, hc, qc, ec, e2c) {
- var fn = alg(1);
- var fn2 = alg('hello.', { state: true });
- benchmarks[label] = {rand: fn.quick, times: []};
- it("should use " + label + " correctly", function() {
- if (double1 != null) assert.equal(fn.double(), double1);
- if (float3 != null) assert.equal(fn.quick(), float3);
- if (int4 != null) assert.equal(fn.int32(), int4);
- assert(fn() > 0);
- assert(fn() < 1);
- assert(fn2() > 0);
- // Internal state is visible only if requested.
- assert(!('state' in fn));
- assert('state' in fn2);
- var ss = fn2.state();
- var rs = fn2();
- assert(rs < 1);
- var j, h = 0, q = 0, e = 0, r, p, e2 = 0;
- for (j = 0; j < 1024; ++j) {
- r = fn();
- if (r < 0.5) h += 1;
- if (r < 0.25) q += 1;
- if (r < 0.125) e += 1;
- r2 = fn2();
- if (r2 < 0.125) e2 += 1;
- }
- if (hc != null) {
- assert.equal(h, hc);
- assert.equal(q, qc);
- assert.equal(e, ec);
- assert.equal(e2, e2c);
- h = q = e = p = 0;
- for (j = 0; j < 1024; ++j) {
- r = fn.double();
- if (r < 0.5) h += 1;
- if (r < 0.25) q += 1;
- if (r < 0.125) e += 1;
- if (fn.int32() >= 0) p += 1;
- }
- // Sanity-check double() and int32.
- assert(h >= 480 && h <= 543, h);
- assert(q >= 226 && q <= 286, q);
- assert(e >= 100 && e <= 156, e);
- assert(e2 >= 100 && e2 <= 156, e2);
- assert(p >= 482 && p <= 543, p);
- }
- var fn3 = alg(0, { state: ss });
- assert.equal(fn3(), rs);
- });
-}
-
-test("xor128", xor128,
- 0.7963797148975774, 0.22171171731315553, 317177041, 498, 236, 110, 115);
-test("xorwow", xorwow,
- 0.8178000247146859, 0.8407576507888734, 533150816, 519, 228, 121, 123);
-test("xorshift7", xs7,
- 0.21241471533241418, 0.9957620368804783, -1678071207, 510, 261, 143, 124);
-test("tychei", tychei,
- 0.42331440041340196, 0.9365617581643164, -884984569, 521, 242, 116, 126);
-test("seedrandom", sr,
- 0.1776348083296759, 0.2160690303426236, 1397712774, 526, 282, 131, 137);
-test("xor4096", xor4096,
- 0.1520436450538547, 0.4206166828516871, 1312695376, 496, 241, 113, 142);
-test("alea", alea,
- 0.5260470956849501, 0.47771977609954774, -1625913352, 494, 246, 125, 122);
-
-it("runs benchmarks", function() {
- var n = 4;
- var trials = 10;
- var top = 4;
- this.timeout(200 * n * trials);
- this.slow(30 * n * trials);
- var fn, k, start, end, j, t;
- for (k in benchmarks) {
- fn = benchmarks[k].rand;
- // warmup.
- for (j = 0; j < 1e5; ++j) fn();
- }
- for (t = 0; t < trials; ++t) {
- for (k in benchmarks) {
- fn = benchmarks[k].rand;
- start = +new Date;
- // benchmark.
- for (j = 0; j < n * 1e5; ++j) fn();
- end = +new Date;
- benchmarks[k].times.push(end - start);
- }
- }
- for (k in benchmarks) {
- benchmarks[k].times.sort();
- }
- function fastest(array) {
- var sum = 0;
- for (var j = 0; j < top; ++j) {
- sum += array[j];
- }
- return sum / top;
- }
- var nativetime = fastest(benchmarks.native.times);
- for (k in benchmarks) {
- var time = fastest(benchmarks[k].times);
- console.log(k+ ': ' + time / n + ' nanoseconds per call, ' +
- (time / nativetime).toFixed(1) + 'x native random.');
- }
-});
-
-});
diff --git a/test/qunitassert.js b/test/qunitassert.js
deleted file mode 100644
index 9b72d6e..0000000
--- a/test/qunitassert.js
+++ /dev/null
@@ -1,3 +0,0 @@
-// Use QUnit.assert to mimic node.assert.
-
-module.exports = QUnit.assert;
diff --git a/test/require.html b/test/require.html
deleted file mode 100644
index b8aac32..0000000
--- a/test/require.html
+++ /dev/null
@@ -1,57 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<link rel="stylesheet" href="lib/qunit.css">
-</head>
-<body>
-<div id="qunit"></div>
-<div id="qunit-fixture"></div>
-<script src="lib/require.js"></script>
-
-<script>
-
-require.config({
- paths: {
- 'qunit': 'lib/qunit',
- 'seedrandom': '/seedrandom.min'
- }
-});
-
-require(['qunit', 'seedrandom'], function(QUnit, seedrandom) {
- QUnit.start();
- QUnit.module('require.js test');
- QUnit.test('some normal test', function(assert) {
- assert.ok(true, "Seeded random created using module:");
- var check = [];
- var prng = seedrandom('predictable.');
- var r;
- for (var j = 0; j < 5; ++j) {
- r = prng();
- assert.ok(true, r + "");
- check.push(r);
- }
- assert.ok(true, "Native random:");
- for (var j = 0; j < 5; ++j) {
- r = Math.random();
- assert.ok(true, r + "");
- check.push(r);
- }
- // Verify against Math.seedrandom.
- var seed = Math.seedrandom('predictable.');
- assert.equal(seed, 'predictable.',
- "Seed should be returned from Math.seedrandom.");
- for (var j = 0; j < 10; ++j) {
- r = Math.random();
- if (j < 5) {
- assert.equal(check[j], r, "Equal: " + r + " vs " + check[j]);
- } else {
- assert.ok(check[j] != r, "Unqual: " + r + " vs " + check[j]);
- }
- }
- document.close();
- });
-});
-
-</script>
-</body>
-</html>
diff --git a/test/run_dieharder.sh b/test/run_dieharder.sh
deleted file mode 100755
index 89fb5e1..0000000
--- a/test/run_dieharder.sh
+++ /dev/null
@@ -1,5 +0,0 @@
-#!/bin/sh
-# http://www.phy.duke.edu/~rgb/General/dieharder.php
-# How to run dieharder against seedrandom:
-
-node bitgen.js | dieharder -g 200 -a | tee out/dieharder-report.txt
diff --git a/test/state.html b/test/state.html
deleted file mode 100644
index 609b4f0..0000000
--- a/test/state.html
+++ /dev/null
@@ -1,56 +0,0 @@
-<html>
-<head>
-<link rel="stylesheet" href="lib/qunit.css">
-</head>
-<body>
-<div id="qunit"></div>
-<div id="qunit-fixture"></div>
-<script src="../seedrandom.min.js"></script>
-<script src="lib/qunit.js"></script>
-<script>
-QUnit.module("Options API Test");
-
-QUnit.test("Verify that state method is not normally present",
-function(assert) {
-
-var seedrandom = Math.seedrandom;
-var dummy = seedrandom('hello');
-var unexpected = -1;
-var expected = -1;
-try {
- unexpected = dummy.state();
-} catch(e) {
- expected = 1;
-}
-assert.equal(unexpected, -1);
-assert.equal(expected, 1);
-var count = 0;
-for (var x in dummy) {
- if (x == 'state') count += 1;
-}
-assert.equal(count, 0);
-
-});
-
-QUnit.test("Verify that state option works as advertised", function(assert) {
-
-var seedrandom = Math.seedrandom;
-var saveable = seedrandom("secret-seed", {state: true});
-var ordinary = seedrandom("secret-seed");
-for (var j = 0; j < 1e3; ++j) {
- assert.equal(ordinary(), saveable());
-}
-var virgin = seedrandom("secret-seed");
-var saved = saveable.state();
-var replica = seedrandom("", {state: saved});
-for (var j = 0; j < 1e2; ++j) {
- var r = replica();
- assert.equal(r, saveable());
- assert.equal(r, ordinary());
- assert.ok(r != virgin());
-}
-
-});
-</script>
-</body>
-</html>
diff --git a/types-seedrandom/LICENSE b/types-seedrandom/LICENSE
deleted file mode 100755
index 9e841e7..0000000
--- a/types-seedrandom/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
- MIT License
-
- Copyright (c) Microsoft Corporation.
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in all
- copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- SOFTWARE
diff --git a/types-seedrandom/README.md b/types-seedrandom/README.md
deleted file mode 100755
index 8cd5ba7..0000000
--- a/types-seedrandom/README.md
+++ /dev/null
@@ -1,65 +0,0 @@
-# Installation
-> `npm install --save @types/seedrandom`
-
-# Summary
-This package contains type definitions for seedrandom (https://github.com/davidbau/seedrandom).
-
-# Details
-Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/seedrandom/v2.
-## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/seedrandom/v2/index.d.ts)
-````ts
-// Type definitions for seedrandom 2.4.2
-// Project: https://github.com/davidbau/seedrandom
-// Definitions by: Kern Handa <https://github.com/kernhanda>, Eugene Zaretskiy <https://github.com/EugeneZ>
-// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
-
-declare namespace seedrandom {
-
- export type State = {};
-
- interface prng {
- new (seed?: string, options?: seedRandomOptions, callback?: any): prng;
- (): number;
- quick(): number;
- int32(): number;
- double(): number;
- state(): State;
- }
-
- interface seedrandom_prng {
- (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback): prng;
- alea: (seed?: string, options?: seedRandomOptions) => prng;
- xor128: (seed?: string, options?: seedRandomOptions) => prng;
- tychei: (seed?: string, options?: seedRandomOptions) => prng;
- xorwow: (seed?: string, options?: seedRandomOptions) => prng;
- xor4096: (seed?: string, options?: seedRandomOptions) => prng;
- xorshift7: (seed?: string, options?: seedRandomOptions) => prng;
- quick: (seed?: string, options?: seedRandomOptions) => prng;
- }
-
- interface seedrandomCallback {
- (prng?: prng, shortseed?: string, global?: boolean, state?: State): prng;
- }
-
- interface seedRandomOptions {
- entropy?: boolean | undefined;
- 'global'?: boolean | undefined;
- state?: boolean | State | undefined;
- pass?: seedrandomCallback | undefined;
- }
-}
-
-declare var seedrandom: seedrandom.seedrandom_prng;
-
-export = seedrandom;
-export as namespace seedrandom;
-
-````
-
-### Additional Details
- * Last updated: Tue, 06 Jul 2021 16:34:28 GMT
- * Dependencies: none
- * Global values: `seedrandom`
-
-# Credits
-These definitions were written by [Kern Handa](https://github.com/kernhanda), and [Eugene Zaretskiy](https://github.com/EugeneZ).
diff --git a/types-seedrandom/index.d.ts b/types-seedrandom/index.d.ts
deleted file mode 100755
index 37a8351..0000000
--- a/types-seedrandom/index.d.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-// Type definitions for seedrandom 2.4.2
-// Project: https://github.com/davidbau/seedrandom
-// Definitions by: Kern Handa <https://github.com/kernhanda>, Eugene Zaretskiy <https://github.com/EugeneZ>
-// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
-
-declare namespace seedrandom {
-
- export type State = {};
-
- interface prng {
- new (seed?: string, options?: seedRandomOptions, callback?: any): prng;
- (): number;
- quick(): number;
- int32(): number;
- double(): number;
- state(): State;
- }
-
- interface seedrandom_prng {
- (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback): prng;
- alea: (seed?: string, options?: seedRandomOptions) => prng;
- xor128: (seed?: string, options?: seedRandomOptions) => prng;
- tychei: (seed?: string, options?: seedRandomOptions) => prng;
- xorwow: (seed?: string, options?: seedRandomOptions) => prng;
- xor4096: (seed?: string, options?: seedRandomOptions) => prng;
- xorshift7: (seed?: string, options?: seedRandomOptions) => prng;
- quick: (seed?: string, options?: seedRandomOptions) => prng;
- }
-
- interface seedrandomCallback {
- (prng?: prng, shortseed?: string, global?: boolean, state?: State): prng;
- }
-
- interface seedRandomOptions {
- entropy?: boolean | undefined;
- 'global'?: boolean | undefined;
- state?: boolean | State | undefined;
- pass?: seedrandomCallback | undefined;
- }
-}
-
-declare var seedrandom: seedrandom.seedrandom_prng;
-
-export = seedrandom;
-export as namespace seedrandom;
diff --git a/types-seedrandom/package.json b/types-seedrandom/package.json
deleted file mode 100755
index 5610eec..0000000
--- a/types-seedrandom/package.json
+++ /dev/null
@@ -1,30 +0,0 @@
-{
- "name": "@types/seedrandom",
- "version": "2.4.30",
- "description": "TypeScript definitions for seedrandom",
- "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/seedrandom",
- "license": "MIT",
- "contributors": [
- {
- "name": "Kern Handa",
- "url": "https://github.com/kernhanda",
- "githubUsername": "kernhanda"
- },
- {
- "name": "Eugene Zaretskiy",
- "url": "https://github.com/EugeneZ",
- "githubUsername": "EugeneZ"
- }
- ],
- "main": "",
- "types": "index.d.ts",
- "repository": {
- "type": "git",
- "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
- "directory": "types/seedrandom"
- },
- "scripts": {},
- "dependencies": {},
- "typesPublisherContentHash": "375653da4b2165533e189b35271f3c55e1d93138ee4381fc34df2516f072df2f",
- "typeScriptVersion": "3.6"
-}
\ No newline at end of file
Debdiff
[The following lists of changes regard files as different if they have different names, permissions or owners.]
Files in first set of .debs but not in second
-rw-r--r-- root/root /usr/share/nodejs/@types/seedrandom/index.d.ts -rw-r--r-- root/root /usr/share/nodejs/@types/seedrandom/package.json
Control files: lines which differ (wdiff format)
Provides: node-types-seedrandom (= 2.4.30)