[Pkg-javascript-commits] [node-jquery] 02/04: New upstream version 2.2.4+dfsg
Praveen Arimbrathodiyil
praveen at moszumanska.debian.org
Sun Dec 31 14:22:02 UTC 2017
This is an automated email from the git hooks/post-receive script.
praveen pushed a commit to branch master
in repository node-jquery.
commit a2d95c0afe75335cd7f0b620085e78b2cc1621e6
Author: Pirate Praveen <praveen at debian.org>
Date: Sun Dec 31 19:43:55 2017 +0530
New upstream version 2.2.4+dfsg
---
external/npo/npo.js | 5 -
external/qunit-assert-step/MIT-LICENSE.txt | 21 -
external/qunit-assert-step/qunit-assert-step.js | 26 -
external/qunit/LICENSE.txt | 36 -
external/qunit/MIT-LICENSE.txt | 21 -
external/qunit/qunit.css | 280 --
external/qunit/qunit.js | 2875 -----------
external/requirejs/require.js | 2076 --------
external/sinon/sinon-1.14.1.js | 5931 -----------------------
external/sizzle/LICENSE.txt | 36 -
external/sizzle/dist/sizzle.js | 2143 --------
external/sizzle/dist/sizzle.min.js | 3 -
external/sizzle/dist/sizzle.min.map | 1 -
13 files changed, 13454 deletions(-)
diff --git a/external/npo/npo.js b/external/npo/npo.js
deleted file mode 100644
index 1984691..0000000
--- a/external/npo/npo.js
+++ /dev/null
@@ -1,5 +0,0 @@
-/*! Native Promise Only
- v0.7.8-a (c) Kyle Simpson
- MIT License: http://getify.mit-license.org
-*/
-!function(t,n,e){n[t]=n[t]||e(),"undefined"!=typeof module&&module.exports?module.exports=n[t]:"function"==typeof define&&define.amd&&define(function(){return n[t]})}("Promise","undefined"!=typeof global?global:this,function(){"use strict";function t(t,n){l.add(t,n),h||(h=y(l.drain))}function n(t){var n,e=typeof t;return null==t||"object"!=e&&"function"!=e||(n=t.then),"function"==typeof n?n:!1}function e(){for(var t=0;t<this.chain.length;t++)o(this,1===this.state?this.chain[t].success:th [...]
diff --git a/external/qunit-assert-step/MIT-LICENSE.txt b/external/qunit-assert-step/MIT-LICENSE.txt
deleted file mode 100644
index aed5dc9..0000000
--- a/external/qunit-assert-step/MIT-LICENSE.txt
+++ /dev/null
@@ -1,21 +0,0 @@
-Copyright jQuery Foundation and other contributors
-http://jquery.com/
-
-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/external/qunit-assert-step/qunit-assert-step.js b/external/qunit-assert-step/qunit-assert-step.js
deleted file mode 100644
index 90bca18..0000000
--- a/external/qunit-assert-step/qunit-assert-step.js
+++ /dev/null
@@ -1,26 +0,0 @@
-QUnit.extend( QUnit.assert, {
-
- /**
- * Check the sequence/order
- *
- * @example test('Example unit test', function(assert) { assert.step(1); setTimeout(function () { assert.step(3); start(); }, 100); assert.step(2); stop(); });
- * @param Number expected The excepted step within the test()
- * @param String message (optional)
- */
- step: function (expected, message) {
- // increment internal step counter.
- QUnit.config.current.step++;
- if (typeof message === "undefined") {
- message = "step " + expected;
- }
- var actual = QUnit.config.current.step;
- QUnit.push(QUnit.equiv(actual, expected), actual, expected, message);
- }
-});
-
-/**
- * Reset the step counter for every test()
- */
-QUnit.testStart(function () {
- QUnit.config.current.step = 0;
-});
diff --git a/external/qunit/LICENSE.txt b/external/qunit/LICENSE.txt
deleted file mode 100644
index fb928a5..0000000
--- a/external/qunit/LICENSE.txt
+++ /dev/null
@@ -1,36 +0,0 @@
-Copyright jQuery Foundation and other contributors, https://jquery.org/
-
-This software consists of voluntary contributions made by many
-individuals. For exact contribution history, see the revision history
-available at https://github.com/jquery/qunit
-
-The following license applies to all parts of this software except as
-documented below:
-
-====
-
-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.
-
-====
-
-All files located in the node_modules and external directories are
-externally maintained libraries used by this software which have their
-own licenses; we recommend you read them, as their terms may differ from
-the terms above.
diff --git a/external/qunit/MIT-LICENSE.txt b/external/qunit/MIT-LICENSE.txt
deleted file mode 100644
index 957f26d..0000000
--- a/external/qunit/MIT-LICENSE.txt
+++ /dev/null
@@ -1,21 +0,0 @@
-Copyright 2013 jQuery Foundation and other contributors
-http://jquery.com/
-
-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/external/qunit/qunit.css b/external/qunit/qunit.css
deleted file mode 100644
index 0eb0b01..0000000
--- a/external/qunit/qunit.css
+++ /dev/null
@@ -1,280 +0,0 @@
-/*!
- * QUnit 1.17.1
- * http://qunitjs.com/
- *
- * Copyright jQuery Foundation and other contributors
- * Released under the MIT license
- * http://jquery.org/license
- *
- * Date: 2015-01-20T19:39Z
- */
-
-/** Font Family and Sizes */
-
-#qunit-tests, #qunit-header, #qunit-banner, #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult {
- font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial, sans-serif;
-}
-
-#qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult, #qunit-tests li { font-size: small; }
-#qunit-tests { font-size: smaller; }
-
-
-/** Resets */
-
-#qunit-tests, #qunit-header, #qunit-banner, #qunit-userAgent, #qunit-testresult, #qunit-modulefilter {
- margin: 0;
- padding: 0;
-}
-
-
-/** Header */
-
-#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-testrunner-toolbar label {
- display: inline-block;
- padding: 0 0.5em 0 0.1em;
-}
-
-#qunit-banner {
- height: 5px;
-}
-
-#qunit-testrunner-toolbar {
- padding: 0.5em 1em 0.5em 1em;
- color: #5E740B;
- background-color: #EEE;
- overflow: hidden;
-}
-
-#qunit-userAgent {
- padding: 0.5em 1em 0.5em 1em;
- background-color: #2B81AF;
- color: #FFF;
- text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px;
-}
-
-#qunit-modulefilter-container {
- float: right;
- padding: 0.2em;
-}
-
-.qunit-url-config {
- display: inline-block;
- padding: 0.1em;
-}
-
-.qunit-filter {
- display: block;
- float: right;
- margin-left: 1em;
-}
-
-/** 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 li.running,
-#qunit-tests.hidepass li.pass {
- display: none;
-}
-
-#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 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-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 {
- background-color: #E0F2BE;
- color: #374E0C;
- text-decoration: none;
-}
-
-#qunit-tests ins {
- background-color: #FFCACA;
- color: #500;
- 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/external/qunit/qunit.js b/external/qunit/qunit.js
deleted file mode 100644
index 006ca47..0000000
--- a/external/qunit/qunit.js
+++ /dev/null
@@ -1,2875 +0,0 @@
-/*!
- * QUnit 1.17.1
- * http://qunitjs.com/
- *
- * Copyright jQuery Foundation and other contributors
- * Released under the MIT license
- * http://jquery.org/license
- *
- * Date: 2015-01-20T19:39Z
- */
-
-(function( window ) {
-
-var QUnit,
- config,
- onErrorFnPrev,
- loggingCallbacks = {},
- fileName = ( sourceFromStacktrace( 0 ) || "" ).replace( /(:\d+)+\)?/, "" ).replace( /.+\//, "" ),
- toString = Object.prototype.toString,
- hasOwn = Object.prototype.hasOwnProperty,
- // Keep a local reference to Date (GH-283)
- Date = window.Date,
- now = Date.now || function() {
- return new Date().getTime();
- },
- globalStartCalled = false,
- runStarted = false,
- setTimeout = window.setTimeout,
- clearTimeout = window.clearTimeout,
- defined = {
- document: window.document !== undefined,
- setTimeout: window.setTimeout !== undefined,
- sessionStorage: (function() {
- var x = "qunit-test-string";
- try {
- sessionStorage.setItem( x, x );
- sessionStorage.removeItem( x );
- return true;
- } catch ( e ) {
- return false;
- }
- }())
- },
- /**
- * Provides a normalized error string, correcting an issue
- * with IE 7 (and prior) where Error.prototype.toString is
- * not properly implemented
- *
- * Based on http://es5.github.com/#x15.11.4.4
- *
- * @param {String|Error} error
- * @return {String} error message
- */
- errorString = function( error ) {
- var name, message,
- errorString = error.toString();
- if ( errorString.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 errorString;
- }
- },
- /**
- * 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).
- */
- objectValues = function( obj ) {
- var key, val,
- vals = QUnit.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;
- };
-
-QUnit = {};
-
-/**
- * Config object: Maintain internal state
- * Later exposed as QUnit.config
- * `config` initialized at top of scope
- */
-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,
-
- // by default, scroll to top of the page when suite is done
- scrolltop: true,
-
- // when enabled, all tests must call expect()
- requireExpects: false,
-
- // add checkboxes that are persisted in the query-string
- // when enabled, the id is set to `true` as a `QUnit.config` property
- urlConfig: [
- {
- 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 " +
- "`window` object. 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."
- }
- ],
-
- // Set of all modules.
- modules: [],
-
- // The first unnamed module
- currentModule: {
- name: "",
- tests: []
- },
-
- callbacks: {}
-};
-
-// Push a loose unnamed module to the modules collection
-config.modules.push( config.currentModule );
-
-// Initialize more QUnit.config and QUnit.urlParams
-(function() {
- var i, current,
- location = window.location || { search: "", protocol: "file:" },
- params = location.search.slice( 1 ).split( "&" ),
- length = params.length,
- urlParams = {};
-
- if ( params[ 0 ] ) {
- for ( i = 0; i < length; i++ ) {
- current = params[ i ].split( "=" );
- current[ 0 ] = decodeURIComponent( current[ 0 ] );
-
- // allow just a key to turn on a flag, e.g., test.html?noglobals
- current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true;
- if ( urlParams[ current[ 0 ] ] ) {
- urlParams[ current[ 0 ] ] = [].concat( urlParams[ current[ 0 ] ], current[ 1 ] );
- } else {
- urlParams[ current[ 0 ] ] = current[ 1 ];
- }
- }
- }
-
- if ( urlParams.filter === true ) {
- delete urlParams.filter;
- }
-
- QUnit.urlParams = urlParams;
-
- // String search anywhere in moduleName+testName
- config.filter = urlParams.filter;
-
- config.testId = [];
- if ( urlParams.testId ) {
-
- // Ensure that urlParams.testId is an array
- urlParams.testId = [].concat( urlParams.testId );
- for ( i = 0; i < urlParams.testId.length; i++ ) {
- config.testId.push( urlParams.testId[ i ] );
- }
- }
-
- // Figure out if we're running the tests from a server or not
- QUnit.isLocal = location.protocol === "file:";
-}());
-
-// Root QUnit object.
-// `QUnit` initialized at top of scope
-extend( QUnit, {
-
- // call on start of module test to prepend name to all tests
- module: function( name, testEnvironment ) {
- var currentModule = {
- name: name,
- testEnvironment: testEnvironment,
- tests: []
- };
-
- // DEPRECATED: handles setup/teardown functions,
- // beforeEach and afterEach should be used instead
- if ( testEnvironment && testEnvironment.setup ) {
- testEnvironment.beforeEach = testEnvironment.setup;
- delete testEnvironment.setup;
- }
- if ( testEnvironment && testEnvironment.teardown ) {
- testEnvironment.afterEach = testEnvironment.teardown;
- delete testEnvironment.teardown;
- }
-
- config.modules.push( currentModule );
- config.currentModule = currentModule;
- },
-
- // DEPRECATED: QUnit.asyncTest() will be removed in QUnit 2.0.
- asyncTest: function( testName, expected, callback ) {
- if ( arguments.length === 2 ) {
- callback = expected;
- expected = null;
- }
-
- QUnit.test( testName, expected, callback, true );
- },
-
- test: function( testName, expected, callback, async ) {
- var test;
-
- if ( arguments.length === 2 ) {
- callback = expected;
- expected = null;
- }
-
- test = new Test({
- testName: testName,
- expected: expected,
- async: async,
- callback: callback
- });
-
- test.queue();
- },
-
- skip: function( testName ) {
- var test = new Test({
- testName: testName,
- skip: true
- });
-
- test.queue();
- },
-
- // DEPRECATED: The functionality of QUnit.start() will be altered in QUnit 2.0.
- // In QUnit 2.0, invoking it will ONLY affect the `QUnit.config.autostart` blocking behavior.
- start: function( count ) {
- var globalStartAlreadyCalled = globalStartCalled;
-
- if ( !config.current ) {
- globalStartCalled = true;
-
- if ( runStarted ) {
- throw new Error( "Called start() outside of a test context while already started" );
- } 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 {
-
- // If a test is running, adjust its semaphore
- config.current.semaphore -= count || 1;
-
- // Don't start until equal number of stop-calls
- if ( config.current.semaphore > 0 ) {
- return;
- }
-
- // throw an Error if start is called more often than stop
- if ( config.current.semaphore < 0 ) {
- config.current.semaphore = 0;
-
- QUnit.pushFailure(
- "Called start() while already started (test's semaphore was 0 already)",
- sourceFromStacktrace( 2 )
- );
- return;
- }
- }
-
- resumeProcessing();
- },
-
- // DEPRECATED: QUnit.stop() will be removed in QUnit 2.0.
- stop: function( count ) {
-
- // If there isn't a test running, don't allow QUnit.stop() to be called
- if ( !config.current ) {
- throw new Error( "Called stop() outside of a test context" );
- }
-
- // If a test is running, adjust its semaphore
- config.current.semaphore += count || 1;
-
- pauseProcessing();
- },
-
- config: config,
-
- // Safe object type checking
- is: function( type, obj ) {
- return QUnit.objectType( obj ) === type;
- },
-
- objectType: function( 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 "Date":
- case "RegExp":
- case "Function":
- return type.toLowerCase();
- }
- if ( typeof obj === "object" ) {
- return "object";
- }
- return undefined;
- },
-
- extend: extend,
-
- load: function() {
- config.pageLoaded = true;
-
- // Initialize the configuration options
- extend( config, {
- stats: { all: 0, bad: 0 },
- moduleStats: { all: 0, bad: 0 },
- started: 0,
- updateRate: 1000,
- autostart: true,
- filter: ""
- }, true );
-
- config.blocking = false;
-
- if ( config.autostart ) {
- resumeProcessing();
- }
- }
-});
-
-// Register logging callbacks
-(function() {
- var i, l, key,
- callbacks = [ "begin", "done", "log", "testStart", "testDone",
- "moduleStart", "moduleDone" ];
-
- function registerLoggingCallback( key ) {
- var loggingCallback = function( callback ) {
- if ( QUnit.objectType( callback ) !== "function" ) {
- throw new Error(
- "QUnit logging methods require a callback function as their first parameters."
- );
- }
-
- config.callbacks[ key ].push( callback );
- };
-
- // DEPRECATED: This will be removed on QUnit 2.0.0+
- // Stores the registered functions allowing restoring
- // at verifyLoggingCallbacks() if modified
- loggingCallbacks[ key ] = loggingCallback;
-
- return loggingCallback;
- }
-
- for ( i = 0, l = callbacks.length; i < l; i++ ) {
- key = callbacks[ i ];
-
- // Initialize key collection of logging callback
- if ( QUnit.objectType( config.callbacks[ key ] ) === "undefined" ) {
- config.callbacks[ key ] = [];
- }
-
- QUnit[ key ] = registerLoggingCallback( key );
- }
-})();
-
-// `onErrorFnPrev` initialized at top of scope
-// Preserve other handlers
-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 ( QUnit.config.current ) {
- if ( QUnit.config.current.ignoreGlobalErrors ) {
- return true;
- }
- QUnit.pushFailure( error, filePath + ":" + linerNr );
- } else {
- QUnit.test( "global failure", extend(function() {
- QUnit.pushFailure( error, filePath + ":" + linerNr );
- }, { validTest: true } ) );
- }
- return false;
- }
-
- return ret;
-};
-
-function done() {
- var runtime, passed;
-
- config.autorun = true;
-
- // Log the last module results
- if ( config.previousModule ) {
- runLoggingCallbacks( "moduleDone", {
- name: config.previousModule.name,
- tests: config.previousModule.tests,
- failed: config.moduleStats.bad,
- passed: config.moduleStats.all - config.moduleStats.bad,
- total: config.moduleStats.all,
- runtime: now() - config.moduleStats.started
- });
- }
- delete config.previousModule;
-
- 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
- });
-}
-
-// Doesn't support IE6 to IE9
-// See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack
-function extractStacktrace( e, offset ) {
- offset = offset === undefined ? 4 : offset;
-
- var stack, include, i;
-
- if ( e.stacktrace ) {
-
- // Opera 12.x
- return e.stacktrace.split( "\n" )[ offset + 3 ];
- } else if ( e.stack ) {
-
- // Firefox, Chrome, Safari 6+, IE10+, PhantomJS and Node
- 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 ];
- } else if ( e.sourceURL ) {
-
- // Safari < 6
- // exclude useless self-reference for generated Error objects
- if ( /qunit.js$/.test( e.sourceURL ) ) {
- return;
- }
-
- // for actual exceptions, this is useful
- return e.sourceURL + ":" + e.line;
- }
-}
-
-function sourceFromStacktrace( offset ) {
- var e = new Error();
- if ( !e.stack ) {
- try {
- throw e;
- } catch ( err ) {
- // This should already be true in most browsers
- e = err;
- }
- }
- return extractStacktrace( e, offset );
-}
-
-function synchronize( callback, last ) {
- if ( QUnit.objectType( callback ) === "array" ) {
- while ( callback.length ) {
- synchronize( callback.shift() );
- }
- return;
- }
- config.queue.push( callback );
-
- if ( config.autorun && !config.blocking ) {
- process( last );
- }
-}
-
-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();
- }
-}
-
-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();
-
- verifyLoggingCallbacks();
-
- // 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 resumeProcessing() {
- runStarted = true;
-
- // A slight delay to allow this iteration of the event loop to finish (more assertions, etc.)
- if ( defined.setTimeout ) {
- setTimeout(function() {
- if ( config.current && config.current.semaphore > 0 ) {
- return;
- }
- if ( config.timeout ) {
- clearTimeout( config.timeout );
- }
-
- begin();
- }, 13 );
- } else {
- begin();
- }
-}
-
-function pauseProcessing() {
- config.blocking = true;
-
- if ( config.testTimeout && defined.setTimeout ) {
- clearTimeout( config.timeout );
- config.timeout = setTimeout(function() {
- if ( config.current ) {
- config.current.semaphore = 0;
- QUnit.pushFailure( "Test timed out", sourceFromStacktrace( 2 ) );
- } else {
- throw new Error( "Test timed out" );
- }
- resumeProcessing();
- }, config.testTimeout );
- }
-}
-
-function saveGlobal() {
- config.pollution = [];
-
- if ( config.noglobals ) {
- for ( var key in window ) {
- if ( hasOwn.call( window, 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 ) {
- QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join( ", " ) );
- }
-
- deletedGlobals = diff( old, config.pollution );
- if ( deletedGlobals.length > 0 ) {
- QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join( ", " ) );
- }
-}
-
-// 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;
-}
-
-function extend( a, b, undefOnly ) {
- for ( var prop in b ) {
- if ( hasOwn.call( b, prop ) ) {
-
- // Avoid "Member not found" error in IE8 caused by messing with window.constructor
- if ( !( prop === "constructor" && a === window ) ) {
- if ( b[ prop ] === undefined ) {
- delete a[ prop ];
- } else if ( !( undefOnly && typeof a[ prop ] !== "undefined" ) ) {
- a[ prop ] = b[ prop ];
- }
- }
- }
- }
-
- return a;
-}
-
-function runLoggingCallbacks( key, args ) {
- var i, l, callbacks;
-
- callbacks = config.callbacks[ key ];
- for ( i = 0, l = callbacks.length; i < l; i++ ) {
- callbacks[ i ]( args );
- }
-}
-
-// DEPRECATED: This will be removed on 2.0.0+
-// This function verifies if the loggingCallbacks were modified by the user
-// If so, it will restore it, assign the given callback and print a console warning
-function verifyLoggingCallbacks() {
- var loggingCallback, userCallback;
-
- for ( loggingCallback in loggingCallbacks ) {
- if ( QUnit[ loggingCallback ] !== loggingCallbacks[ loggingCallback ] ) {
-
- userCallback = QUnit[ loggingCallback ];
-
- // Restore the callback function
- QUnit[ loggingCallback ] = loggingCallbacks[ loggingCallback ];
-
- // Assign the deprecated given callback
- QUnit[ loggingCallback ]( userCallback );
-
- if ( window.console && window.console.warn ) {
- window.console.warn(
- "QUnit." + loggingCallback + " was replaced with a new value.\n" +
- "Please, check out the documentation on how to apply logging callbacks.\n" +
- "Reference: http://api.qunitjs.com/category/callbacks/"
- );
- }
- }
- }
-}
-
-// 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;
-}
-
-function Test( settings ) {
- var i, l;
-
- ++Test.count;
-
- 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;
-
-Test.prototype = {
- before: function() {
- if (
-
- // Emit moduleStart when we're switching from one module to another
- this.module !== config.previousModule ||
-
- // They could be equal (both undefined) but if the previousModule property doesn't
- // yet exist it means this is the first test in a suite that isn't wrapped in a
- // module, in which case we'll just emit a moduleStart event for 'undefined'.
- // Without this, reporters can get testStart before moduleStart which is a problem.
- !hasOwn.call( config, "previousModule" )
- ) {
- if ( hasOwn.call( config, "previousModule" ) ) {
- runLoggingCallbacks( "moduleDone", {
- name: config.previousModule.name,
- tests: config.previousModule.tests,
- failed: config.moduleStats.bad,
- passed: config.moduleStats.all - config.moduleStats.bad,
- total: config.moduleStats.all,
- runtime: now() - config.moduleStats.started
- });
- }
- config.previousModule = this.module;
- config.moduleStats = { all: 0, bad: 0, started: now() };
- runLoggingCallbacks( "moduleStart", {
- name: this.module.name,
- tests: this.module.tests
- });
- }
-
- config.current = this;
-
- this.testEnvironment = extend( {}, this.module.testEnvironment );
- delete this.testEnvironment.beforeEach;
- delete this.testEnvironment.afterEach;
-
- this.started = now();
- runLoggingCallbacks( "testStart", {
- name: this.testName,
- module: this.module.name,
- testId: this.testId
- });
-
- if ( !config.pollution ) {
- saveGlobal();
- }
- },
-
- run: function() {
- var promise;
-
- config.current = this;
-
- if ( this.async ) {
- QUnit.stop();
- }
-
- this.callbackStarted = now();
-
- if ( config.notrycatch ) {
- promise = this.callback.call( this.testEnvironment, this.assert );
- this.resolvePromise( promise );
- return;
- }
-
- try {
- promise = this.callback.call( this.testEnvironment, this.assert );
- this.resolvePromise( promise );
- } 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 ) {
- QUnit.start();
- }
- }
- },
-
- after: function() {
- checkPollution();
- },
-
- queueHook: function( hook, hookName ) {
- var promise,
- test = this;
- return function runHook() {
- config.current = test;
- if ( config.notrycatch ) {
- promise = hook.call( test.testEnvironment, test.assert );
- test.resolvePromise( promise, hookName );
- return;
- }
- try {
- promise = hook.call( test.testEnvironment, test.assert );
- test.resolvePromise( promise, hookName );
- } catch ( error ) {
- test.pushFailure( hookName + " failed on " + test.testName + ": " +
- ( error.message || error ), extractStacktrace( error, 0 ) );
- }
- };
- },
-
- // Currently only used for module level hooks, can be used to add global level ones
- hooks: function( handler ) {
- var hooks = [];
-
- // Hooks are ignored on skipped tests
- if ( this.skip ) {
- return hooks;
- }
-
- if ( this.module.testEnvironment &&
- QUnit.objectType( this.module.testEnvironment[ handler ] ) === "function" ) {
- hooks.push( this.queueHook( this.module.testEnvironment[ handler ], handler ) );
- }
-
- return hooks;
- },
-
- finish: function() {
- 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,
- bad = 0;
-
- this.runtime = now() - this.started;
- config.stats.all += this.assertions.length;
- config.moduleStats.all += this.assertions.length;
-
- for ( i = 0; i < this.assertions.length; i++ ) {
- if ( !this.assertions[ i ].result ) {
- bad++;
- config.stats.bad++;
- config.moduleStats.bad++;
- }
- }
-
- runLoggingCallbacks( "testDone", {
- name: this.testName,
- module: this.module.name,
- skipped: !!this.skip,
- failed: bad,
- passed: this.assertions.length - bad,
- total: this.assertions.length,
- runtime: this.runtime,
-
- // HTML Reporter use
- assertions: this.assertions,
- testId: this.testId,
-
- // DEPRECATED: this property will be removed in 2.0.0, use runtime instead
- duration: this.runtime
- });
-
- // QUnit.reset() is deprecated and will be replaced for a new
- // fixture reset function on QUnit 2.0/2.1.
- // It's still called here for backwards compatibility handling
- QUnit.reset();
-
- config.current = undefined;
- },
-
- queue: function() {
- var bad,
- test = this;
-
- if ( !this.valid() ) {
- return;
- }
-
- function run() {
-
- // each of these can by async
- synchronize([
- function() {
- test.before();
- },
-
- test.hooks( "beforeEach" ),
-
- function() {
- test.run();
- },
-
- test.hooks( "afterEach" ).reverse(),
-
- function() {
- test.after();
- },
- function() {
- test.finish();
- }
- ]);
- }
-
- // `bad` initialized at top of scope
- // defer when previous test run passed, if storage is available
- bad = QUnit.config.reorder && defined.sessionStorage &&
- +sessionStorage.getItem( "qunit-test-" + this.module.name + "-" + this.testName );
-
- if ( bad ) {
- run();
- } else {
- synchronize( run, true );
- }
- },
-
- push: function( result, actual, expected, message ) {
- var source,
- details = {
- module: this.module.name,
- name: this.testName,
- result: result,
- message: message,
- actual: actual,
- expected: expected,
- testId: this.testId,
- runtime: now() - this.started
- };
-
- if ( !result ) {
- source = sourceFromStacktrace();
-
- if ( source ) {
- details.source = source;
- }
- }
-
- runLoggingCallbacks( "log", details );
-
- this.assertions.push({
- result: !!result,
- message: message
- });
- },
-
- pushFailure: function( 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( promise, phase ) {
- var then, message,
- test = this;
- if ( promise != null ) {
- then = promise.then;
- if ( QUnit.objectType( then ) === "function" ) {
- QUnit.stop();
- then.call(
- promise,
- QUnit.start,
- function( error ) {
- message = "Promise rejected " +
- ( !phase ? "during" : phase.replace( /Each$/, "" ) ) +
- " " + test.testName + ": " + ( error.message || error );
- test.pushFailure( message, extractStacktrace( error, 0 ) );
-
- // else next test will carry the responsibility
- saveGlobal();
-
- // Unblock
- QUnit.start();
- }
- );
- }
- }
- },
-
- valid: function() {
- var include,
- filter = config.filter,
- module = QUnit.urlParams.module && QUnit.urlParams.module.toLowerCase(),
- fullName = ( this.module.name + ": " + this.testName ).toLowerCase();
-
- // Internally-generated tests are always valid
- if ( this.callback && this.callback.validTest ) {
- return true;
- }
-
- if ( config.testId.length > 0 && inArray( this.testId, config.testId ) < 0 ) {
- return false;
- }
-
- if ( module && ( !this.module.name || this.module.name.toLowerCase() !== module ) ) {
- return false;
- }
-
- if ( !filter ) {
- return true;
- }
-
- include = filter.charAt( 0 ) !== "!";
- if ( !include ) {
- filter = filter.toLowerCase().slice( 1 );
- }
-
- // If the filter matches, we need to honour include
- if ( fullName.indexOf( filter ) !== -1 ) {
- return include;
- }
-
- // Otherwise, do the opposite
- return !include;
- }
-
-};
-
-// Resets the test setup. Useful for tests that modify the DOM.
-/*
-DEPRECATED: Use multiple tests instead of resetting inside a test.
-Use testStart or testDone for custom cleanup.
-This method will throw an error in 2.0, and will be removed in 2.1
-*/
-QUnit.reset = function() {
-
- // Return on non-browser environments
- // This is necessary to not break on node tests
- if ( typeof window === "undefined" ) {
- return;
- }
-
- var fixture = defined.document && document.getElementById &&
- document.getElementById( "qunit-fixture" );
-
- if ( fixture ) {
- fixture.innerHTML = config.fixture;
- }
-};
-
-QUnit.pushFailure = function() {
- if ( !QUnit.config.current ) {
- throw new Error( "pushFailure() assertion outside test context, in " +
- sourceFromStacktrace( 2 ) );
- }
-
- // Gets current test obj
- var currentTest = QUnit.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 Assert( testContext ) {
- this.test = testContext;
-}
-
-// Assert helpers
-QUnit.assert = 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( asserts ) {
- if ( arguments.length === 1 ) {
- this.test.expected = asserts;
- } else {
- return this.test.expected;
- }
- },
-
- // Increment this Test's semaphore counter, then return a single-use function that
- // decrements that counter a maximum of once.
- async: function() {
- var test = this.test,
- popped = false;
-
- test.semaphore += 1;
- test.usedAsync = true;
- pauseProcessing();
-
- return function done() {
- if ( !popped ) {
- test.semaphore -= 1;
- popped = true;
- resumeProcessing();
- } else {
- test.pushFailure( "Called the callback returned from `assert.async` more than once",
- sourceFromStacktrace( 2 ) );
- }
- };
- },
-
- // Exports test.push() to the user API
- push: function( /* result, actual, expected, message */ ) {
- var assert = this,
- currentTest = ( assert instanceof Assert && assert.test ) || QUnit.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.push.apply( assert.test, arguments );
- },
-
- /**
- * Asserts rough true-ish result.
- * @name ok
- * @function
- * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
- */
- ok: function( result, message ) {
- message = message || ( result ? "okay" : "failed, expected argument to be truthy, was: " +
- QUnit.dump.parse( result ) );
- this.push( !!result, result, true, message );
- },
-
- /**
- * Assert that the first two arguments are equal, with an optional message.
- * Prints out both actual and expected values.
- * @name equal
- * @function
- * @example equal( format( "{0} bytes.", 2), "2 bytes.", "replaces {0} with next argument" );
- */
- equal: function( actual, expected, message ) {
- /*jshint eqeqeq:false */
- this.push( expected == actual, actual, expected, message );
- },
-
- /**
- * @name notEqual
- * @function
- */
- notEqual: function( actual, expected, message ) {
- /*jshint eqeqeq:false */
- this.push( expected != actual, actual, expected, message );
- },
-
- /**
- * @name propEqual
- * @function
- */
- propEqual: function( actual, expected, message ) {
- actual = objectValues( actual );
- expected = objectValues( expected );
- this.push( QUnit.equiv( actual, expected ), actual, expected, message );
- },
-
- /**
- * @name notPropEqual
- * @function
- */
- notPropEqual: function( actual, expected, message ) {
- actual = objectValues( actual );
- expected = objectValues( expected );
- this.push( !QUnit.equiv( actual, expected ), actual, expected, message );
- },
-
- /**
- * @name deepEqual
- * @function
- */
- deepEqual: function( actual, expected, message ) {
- this.push( QUnit.equiv( actual, expected ), actual, expected, message );
- },
-
- /**
- * @name notDeepEqual
- * @function
- */
- notDeepEqual: function( actual, expected, message ) {
- this.push( !QUnit.equiv( actual, expected ), actual, expected, message );
- },
-
- /**
- * @name strictEqual
- * @function
- */
- strictEqual: function( actual, expected, message ) {
- this.push( expected === actual, actual, expected, message );
- },
-
- /**
- * @name notStrictEqual
- * @function
- */
- notStrictEqual: function( actual, expected, message ) {
- this.push( expected !== actual, actual, expected, message );
- },
-
- "throws": function( block, expected, message ) {
- var actual, expectedType,
- expectedOutput = expected,
- ok = false;
-
- // 'expected' is optional unless doing string comparison
- if ( message == null && typeof expected === "string" ) {
- message = expected;
- expected = null;
- }
-
- this.test.ignoreGlobalErrors = true;
- try {
- block.call( this.test.testEnvironment );
- } catch (e) {
- actual = e;
- }
- this.test.ignoreGlobalErrors = false;
-
- if ( actual ) {
- expectedType = QUnit.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 string
- } else if ( expectedType === "string" ) {
- ok = expected === 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;
- }
-
- this.push( ok, actual, expectedOutput, message );
- } else {
- this.test.pushFailure( message, null, "No exception was thrown." );
- }
- }
-};
-
-// Provide an alternative to assert.throws(), for enviroments that consider throws a reserved word
-// Known to us are: Closure Compiler, Narwhal
-(function() {
- /*jshint sub:true */
- Assert.prototype.raises = Assert.prototype[ "throws" ];
-}());
-
-// Test for equality any JavaScript type.
-// Author: Philippe Rathé <prathe at gmail.com>
-QUnit.equiv = (function() {
-
- // Call the o related callback with the given arguments.
- function bindCallbacks( o, callbacks, args ) {
- var prop = QUnit.objectType( o );
- if ( prop ) {
- if ( QUnit.objectType( callbacks[ prop ] ) === "function" ) {
- return callbacks[ prop ].apply( callbacks, args );
- } else {
- return callbacks[ prop ]; // or undefined
- }
- }
- }
-
- // the real equiv function
- var innerEquiv,
-
- // stack to decide between skip/abort functions
- callers = [],
-
- // stack to avoiding loops from circular referencing
- parents = [],
- parentsB = [],
-
- getProto = Object.getPrototypeOf || function( obj ) {
- /* jshint camelcase: false, proto: true */
- return obj.__proto__;
- },
- callbacks = (function() {
-
- // for string, boolean, number and null
- function useStrictEquality( b, a ) {
-
- /*jshint eqeqeq:false */
- if ( b instanceof a.constructor || a instanceof b.constructor ) {
-
- // to catch short annotation VS 'new' annotation of a
- // declaration
- // e.g. var i = 1;
- // var j = new Number(1);
- return a == b;
- } else {
- return a === b;
- }
- }
-
- return {
- "string": useStrictEquality,
- "boolean": useStrictEquality,
- "number": useStrictEquality,
- "null": useStrictEquality,
- "undefined": useStrictEquality,
-
- "nan": function( b ) {
- return isNaN( b );
- },
-
- "date": function( b, a ) {
- return QUnit.objectType( b ) === "date" && a.valueOf() === b.valueOf();
- },
-
- "regexp": function( b, a ) {
- return QUnit.objectType( b ) === "regexp" &&
-
- // the regex itself
- a.source === b.source &&
-
- // and its modifiers
- a.global === b.global &&
-
- // (gmi) ...
- a.ignoreCase === b.ignoreCase &&
- a.multiline === b.multiline &&
- a.sticky === b.sticky;
- },
-
- // - skip when the property is a method of an instance (OOP)
- // - abort otherwise,
- // initial === would have catch identical references anyway
- "function": function() {
- var caller = callers[ callers.length - 1 ];
- return caller !== Object && typeof caller !== "undefined";
- },
-
- "array": function( b, a ) {
- var i, j, len, loop, aCircular, bCircular;
-
- // b could be an object literal here
- if ( QUnit.objectType( b ) !== "array" ) {
- return false;
- }
-
- 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;
- },
-
- "object": function( b, a ) {
-
- /*jshint forin:false */
- var i, j, loop, aCircular, bCircular,
- // Default to true
- eq = true,
- aProperties = [],
- bProperties = [];
-
- // comparing constructors is more strict than using
- // instanceof
- if ( a.constructor !== b.constructor ) {
-
- // Allow objects with no prototype to be equivalent to
- // objects with Object as their constructor.
- if ( !( ( getProto( a ) === null && getProto( b ) === Object.prototype ) ||
- ( getProto( b ) === null && getProto( a ) === Object.prototype ) ) ) {
- 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();
- callers.pop(); // unstack, we are done
-
- for ( i in b ) {
- bProperties.push( i ); // collect b's properties
- }
-
- // Ensures identical properties name
- return eq && innerEquiv( aProperties.sort(), bProperties.sort() );
- }
- };
- }());
-
- innerEquiv = function() { // can take multiple arguments
- var args = [].slice.apply( arguments );
- if ( args.length < 2 ) {
- return true; // end transition
- }
-
- return ( (function( a, b ) {
- if ( a === b ) {
- return true; // catch the most you can
- } else if ( a === null || b === null || typeof a === "undefined" ||
- typeof b === "undefined" ||
- QUnit.objectType( a ) !== QUnit.objectType( b ) ) {
-
- // don't lose time with error prone cases
- return false;
- } else {
- return bindCallbacks( a, callbacks, [ b, a ] );
- }
-
- // apply transition with (1..n) arguments
- }( args[ 0 ], args[ 1 ] ) ) &&
- innerEquiv.apply( this, args.splice( 1, args.length - 1 ) ) );
- };
-
- return innerEquiv;
-}());
-
-// Based on jsDump by Ariel Flesler
-// http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html
-QUnit.dump = (function() {
- function quote( str ) {
- return "\"" + str.toString().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, "]" );
- }
-
- var reName = /^function (\w+)/,
- dump = {
-
- // objType is used mostly internally, you can fix a (custom) type in advance
- parse: function( 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;
-
- 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( obj ) {
- var type;
- if ( obj === null ) {
- type = "null";
- } else if ( typeof obj === "undefined" ) {
- type = "undefined";
- } else if ( QUnit.is( "regexp", obj ) ) {
- type = "regexp";
- } else if ( QUnit.is( "date", obj ) ) {
- type = "date";
- } else if ( QUnit.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 (
-
- // 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 ) ) )
- ) {
- type = "array";
- } else if ( obj.constructor === Error.prototype.constructor ) {
- type = "error";
- } else {
- type = typeof obj;
- }
- return type;
- },
- separator: function() {
- return this.multiline ? this.HTML ? "<br />" : "\n" : this.HTML ? " " : " ";
- },
- // extra can be a number, shortcut for increasing-calling-decreasing
- indent: function( 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( a ) {
- this.depth += a || 1;
- },
- down: function( a ) {
- this.depth -= a || 1;
- },
- setParser: function( 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: 5,
-
- // This is the list of parsers, to modify them, use dump.setParser
- parsers: {
- window: "[Window]",
- document: "[Document]",
- error: function( error ) {
- return "Error(\"" + error.message + "\")";
- },
- unknown: "[Unknown]",
- "null": "null",
- "undefined": "undefined",
- "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( 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 && !( key in keys ) ) {
- 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 ) {
- 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( 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 an html attribute value
- attribute: quote,
- string: quote,
- date: quote,
- regexp: literal,
- number: literal,
- "boolean": literal
- },
- // 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;
-}());
-
-// back compat
-QUnit.jsDump = QUnit.dump;
-
-// For browser, export only select globals
-if ( typeof window !== "undefined" ) {
-
- // Deprecated
- // Extend assert methods to QUnit and Global scope through Backwards compatibility
- (function() {
- var i,
- assertions = Assert.prototype;
-
- function applyCurrent( current ) {
- return function() {
- var assert = new Assert( QUnit.config.current );
- current.apply( assert, arguments );
- };
- }
-
- for ( i in assertions ) {
- QUnit[ i ] = applyCurrent( assertions[ i ] );
- }
- })();
-
- (function() {
- var i, l,
- keys = [
- "test",
- "module",
- "expect",
- "asyncTest",
- "start",
- "stop",
- "ok",
- "equal",
- "notEqual",
- "propEqual",
- "notPropEqual",
- "deepEqual",
- "notDeepEqual",
- "strictEqual",
- "notStrictEqual",
- "throws"
- ];
-
- for ( i = 0, l = keys.length; i < l; i++ ) {
- window[ keys[ i ] ] = QUnit[ keys[ i ] ];
- }
- })();
-
- 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;
-}
-
-// Get a reference to the global object, like window in browsers
-}( (function() {
- return this;
-})() ));
-
-/*istanbul ignore next */
-// jscs:disable maximumLineLength
-/*
- * Javascript Diff Algorithm
- * By John Resig (http://ejohn.org/)
- * Modified by Chu Alan "sprite"
- *
- * Released under the MIT license.
- *
- * More Info:
- * http://ejohn.org/projects/javascript-diff-algorithm/
- *
- * Usage: QUnit.diff(expected, actual)
- *
- * QUnit.diff( "the quick brown fox jumped over", "the quick fox jumps over" ) == "the quick <del>brown </del> fox <del>jumped </del><ins>jumps </ins> over"
- */
-QUnit.diff = (function() {
- var hasOwn = Object.prototype.hasOwnProperty;
-
- /*jshint eqeqeq:false, eqnull:true */
- function diff( o, n ) {
- var i,
- ns = {},
- os = {};
-
- for ( i = 0; i < n.length; i++ ) {
- if ( !hasOwn.call( ns, n[ i ] ) ) {
- ns[ n[ i ] ] = {
- rows: [],
- o: null
- };
- }
- ns[ n[ i ] ].rows.push( i );
- }
-
- for ( i = 0; i < o.length; i++ ) {
- if ( !hasOwn.call( os, o[ i ] ) ) {
- os[ o[ i ] ] = {
- rows: [],
- n: null
- };
- }
- os[ o[ i ] ].rows.push( i );
- }
-
- for ( i in ns ) {
- if ( hasOwn.call( ns, i ) ) {
- if ( ns[ i ].rows.length === 1 && hasOwn.call( os, i ) && os[ i ].rows.length === 1 ) {
- n[ ns[ i ].rows[ 0 ] ] = {
- text: n[ ns[ i ].rows[ 0 ] ],
- row: os[ i ].rows[ 0 ]
- };
- o[ os[ i ].rows[ 0 ] ] = {
- text: o[ os[ i ].rows[ 0 ] ],
- row: ns[ i ].rows[ 0 ]
- };
- }
- }
- }
-
- for ( i = 0; i < n.length - 1; i++ ) {
- if ( n[ i ].text != null && n[ i + 1 ].text == null && n[ i ].row + 1 < o.length && o[ n[ i ].row + 1 ].text == null &&
- n[ i + 1 ] == o[ n[ i ].row + 1 ] ) {
-
- n[ i + 1 ] = {
- text: n[ i + 1 ],
- row: n[ i ].row + 1
- };
- o[ n[ i ].row + 1 ] = {
- text: o[ n[ i ].row + 1 ],
- row: i + 1
- };
- }
- }
-
- for ( i = n.length - 1; i > 0; i-- ) {
- if ( n[ i ].text != null && n[ i - 1 ].text == null && n[ i ].row > 0 && o[ n[ i ].row - 1 ].text == null &&
- n[ i - 1 ] == o[ n[ i ].row - 1 ] ) {
-
- n[ i - 1 ] = {
- text: n[ i - 1 ],
- row: n[ i ].row - 1
- };
- o[ n[ i ].row - 1 ] = {
- text: o[ n[ i ].row - 1 ],
- row: i - 1
- };
- }
- }
-
- return {
- o: o,
- n: n
- };
- }
-
- return function( o, n ) {
- o = o.replace( /\s+$/, "" );
- n = n.replace( /\s+$/, "" );
-
- var i, pre,
- str = "",
- out = diff( o === "" ? [] : o.split( /\s+/ ), n === "" ? [] : n.split( /\s+/ ) ),
- oSpace = o.match( /\s+/g ),
- nSpace = n.match( /\s+/g );
-
- if ( oSpace == null ) {
- oSpace = [ " " ];
- } else {
- oSpace.push( " " );
- }
-
- if ( nSpace == null ) {
- nSpace = [ " " ];
- } else {
- nSpace.push( " " );
- }
-
- if ( out.n.length === 0 ) {
- for ( i = 0; i < out.o.length; i++ ) {
- str += "<del>" + out.o[ i ] + oSpace[ i ] + "</del>";
- }
- } else {
- if ( out.n[ 0 ].text == null ) {
- for ( n = 0; n < out.o.length && out.o[ n ].text == null; n++ ) {
- str += "<del>" + out.o[ n ] + oSpace[ n ] + "</del>";
- }
- }
-
- for ( i = 0; i < out.n.length; i++ ) {
- if ( out.n[ i ].text == null ) {
- str += "<ins>" + out.n[ i ] + nSpace[ i ] + "</ins>";
- } else {
-
- // `pre` initialized at top of scope
- pre = "";
-
- for ( n = out.n[ i ].row + 1; n < out.o.length && out.o[ n ].text == null; n++ ) {
- pre += "<del>" + out.o[ n ] + oSpace[ n ] + "</del>";
- }
- str += " " + out.n[ i ].text + nSpace[ i ] + pre;
- }
- }
- }
-
- return str;
- };
-}());
-// jscs:enable
-
-(function() {
-
-// Deprecated QUnit.init - Ref #530
-// Re-initialize the configuration options
-QUnit.init = function() {
- var tests, banner, result, qunit,
- config = QUnit.config;
-
- config.stats = { all: 0, bad: 0 };
- config.moduleStats = { all: 0, bad: 0 };
- config.started = 0;
- config.updateRate = 1000;
- config.blocking = false;
- config.autostart = true;
- config.autorun = false;
- config.filter = "";
- config.queue = [];
-
- // Return on non-browser environments
- // This is necessary to not break on node tests
- if ( typeof window === "undefined" ) {
- return;
- }
-
- qunit = id( "qunit" );
- if ( qunit ) {
- qunit.innerHTML =
- "<h1 id='qunit-header'>" + escapeText( document.title ) + "</h1>" +
- "<h2 id='qunit-banner'></h2>" +
- "<div id='qunit-testrunner-toolbar'></div>" +
- "<h2 id='qunit-userAgent'></h2>" +
- "<ol id='qunit-tests'></ol>";
- }
-
- tests = id( "qunit-tests" );
- banner = id( "qunit-banner" );
- result = id( "qunit-testresult" );
-
- if ( tests ) {
- tests.innerHTML = "";
- }
-
- if ( banner ) {
- banner.className = "";
- }
-
- if ( result ) {
- result.parentNode.removeChild( result );
- }
-
- if ( tests ) {
- result = document.createElement( "p" );
- result.id = "qunit-testresult";
- result.className = "result";
- tests.parentNode.insertBefore( result, tests );
- result.innerHTML = "Running...<br /> ";
- }
-};
-
-// Don't load the HTML Reporter on non-Browser environments
-if ( typeof window === "undefined" ) {
- return;
-}
-
-var config = QUnit.config,
- hasOwn = Object.prototype.hasOwnProperty,
- defined = {
- document: window.document !== undefined,
- sessionStorage: (function() {
- var x = "qunit-test-string";
- try {
- sessionStorage.setItem( x, x );
- sessionStorage.removeItem( x );
- return true;
- } catch ( e ) {
- return false;
- }
- }())
- },
- modulesList = [];
-
-/**
-* 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 "&";
- }
- });
-}
-
-/**
- * @param {HTMLElement} elem
- * @param {string} type
- * @param {Function} fn
- */
-function addEvent( elem, type, fn ) {
- if ( elem.addEventListener ) {
-
- // Standards-based browsers
- elem.addEventListener( type, fn, false );
- } else if ( elem.attachEvent ) {
-
- // support: IE <9
- elem.attachEvent( "on" + type, fn );
- }
-}
-
-/**
- * @param {Array|NodeList} elems
- * @param {string} type
- * @param {Function} fn
- */
-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 ) {
- if ( hasClass( elem, name ) ) {
- removeClass( elem, name );
- } else {
- addClass( 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 defined.document && document.getElementById && document.getElementById( name );
-}
-
-function getUrlConfigHtml() {
- var i, j, val,
- escaped, escapedTooltip,
- selection = false,
- len = config.urlConfig.length,
- urlConfigHtml = "";
-
- for ( i = 0; i < len; i++ ) {
- val = config.urlConfig[ i ];
- if ( typeof val === "string" ) {
- val = {
- id: val,
- label: val
- };
- }
-
- escaped = escapeText( val.id );
- escapedTooltip = escapeText( val.tooltip );
-
- if ( config[ val.id ] === undefined ) {
- config[ val.id ] = QUnit.urlParams[ val.id ];
- }
-
- if ( !val.value || typeof val.value === "string" ) {
- urlConfigHtml += "<input id='qunit-urlconfig-" + escaped +
- "' name='" + escaped + "' type='checkbox'" +
- ( val.value ? " value='" + escapeText( val.value ) + "'" : "" ) +
- ( config[ val.id ] ? " checked='checked'" : "" ) +
- " title='" + escapedTooltip + "' /><label for='qunit-urlconfig-" + escaped +
- "' title='" + escapedTooltip + "'>" + 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,
- 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 );
-
- if ( "hidepassed" === field.name && "replaceState" in window.history ) {
- config[ field.name ] = value || false;
- if ( value ) {
- addClass( id( "qunit-tests" ), "hidepass" );
- } else {
- removeClass( id( "qunit-tests" ), "hidepass" );
- }
-
- // It is not necessary to refresh the whole page
- window.history.replaceState( null, "", updatedUrl );
- } else {
- window.location = updatedUrl;
- }
-}
-
-function setUrl( params ) {
- var key,
- querystring = "?";
-
- params = QUnit.extend( QUnit.extend( {}, QUnit.urlParams ), params );
-
- for ( key in params ) {
- if ( hasOwn.call( params, key ) ) {
- if ( params[ key ] === undefined ) {
- continue;
- }
- querystring += encodeURIComponent( key );
- if ( params[ key ] !== true ) {
- querystring += "=" + encodeURIComponent( params[ key ] );
- }
- querystring += "&";
- }
- }
- return location.protocol + "//" + location.host +
- location.pathname + querystring.slice( 0, -1 );
-}
-
-function applyUrlParams() {
- var selectBox = id( "qunit-modulefilter" ),
- selection = decodeURIComponent( selectBox.options[ selectBox.selectedIndex ].value ),
- filter = id( "qunit-filter-input" ).value;
-
- window.location = setUrl({
- module: ( selection === "" ) ? undefined : selection,
- filter: ( filter === "" ) ? undefined : filter,
-
- // Remove testId filter
- testId: undefined
- });
-}
-
-function toolbarUrlConfigContainer() {
- var urlConfigContainer = document.createElement( "span" );
-
- urlConfigContainer.innerHTML = getUrlConfigHtml();
- addClass( urlConfigContainer, "qunit-url-config" );
-
- // For oldIE support:
- // * Add handlers to the individual elements instead of the container
- // * Use "click" instead of "change" for checkboxes
- addEvents( urlConfigContainer.getElementsByTagName( "input" ), "click", toolbarChanged );
- addEvents( urlConfigContainer.getElementsByTagName( "select" ), "change", toolbarChanged );
-
- return urlConfigContainer;
-}
-
-function toolbarLooseFilter() {
- var filter = document.createElement( "form" ),
- label = document.createElement( "label" ),
- input = document.createElement( "input" ),
- button = document.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( button );
- addEvent( filter, "submit", function( ev ) {
- applyUrlParams();
-
- if ( ev && ev.preventDefault ) {
- ev.preventDefault();
- }
-
- return false;
- });
-
- return filter;
-}
-
-function toolbarModuleFilterHtml() {
- var i,
- moduleFilterHtml = "";
-
- if ( !modulesList.length ) {
- return false;
- }
-
- modulesList.sort(function( a, b ) {
- return a.localeCompare( b );
- });
-
- moduleFilterHtml += "<label for='qunit-modulefilter'>Module: </label>" +
- "<select id='qunit-modulefilter' name='modulefilter'><option value='' " +
- ( QUnit.urlParams.module === undefined ? "selected='selected'" : "" ) +
- ">< All Modules ></option>";
-
- for ( i = 0; i < modulesList.length; i++ ) {
- moduleFilterHtml += "<option value='" +
- escapeText( encodeURIComponent( modulesList[ i ] ) ) + "' " +
- ( QUnit.urlParams.module === modulesList[ i ] ? "selected='selected'" : "" ) +
- ">" + escapeText( modulesList[ i ] ) + "</option>";
- }
- moduleFilterHtml += "</select>";
-
- return moduleFilterHtml;
-}
-
-function toolbarModuleFilter() {
- var toolbar = id( "qunit-testrunner-toolbar" ),
- moduleFilter = document.createElement( "span" ),
- moduleFilterHtml = toolbarModuleFilterHtml();
-
- if ( !toolbar || !moduleFilterHtml ) {
- return false;
- }
-
- moduleFilter.setAttribute( "id", "qunit-modulefilter-container" );
- moduleFilter.innerHTML = moduleFilterHtml;
-
- addEvent( moduleFilter.lastChild, "change", applyUrlParams );
-
- toolbar.appendChild( moduleFilter );
-}
-
-function appendToolbar() {
- var toolbar = id( "qunit-testrunner-toolbar" );
-
- if ( toolbar ) {
- toolbar.appendChild( toolbarUrlConfigContainer() );
- toolbar.appendChild( toolbarLooseFilter() );
- }
-}
-
-function appendHeader() {
- var header = id( "qunit-header" );
-
- if ( header ) {
- header.innerHTML = "<a href='" +
- setUrl({ filter: undefined, module: undefined, testId: undefined }) +
- "'>" + 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.createElement( "p" );
- result.id = "qunit-testresult";
- result.className = "result";
- tests.parentNode.insertBefore( result, tests );
- result.innerHTML = "Running...<br /> ";
- }
-}
-
-function storeFixture() {
- var fixture = id( "qunit-fixture" );
- if ( fixture ) {
- config.fixture = fixture.innerHTML;
- }
-}
-
-function appendUserAgent() {
- var userAgent = id( "qunit-userAgent" );
- if ( userAgent ) {
- userAgent.innerHTML = "";
- userAgent.appendChild( document.createTextNode( navigator.userAgent ) );
- }
-}
-
-function appendTestsList( modules ) {
- var i, l, x, z, test, moduleObj;
-
- for ( i = 0, l = modules.length; i < l; i++ ) {
- moduleObj = modules[ i ];
-
- if ( moduleObj.name ) {
- modulesList.push( moduleObj.name );
- }
-
- 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.createElement( "strong" );
- title.innerHTML = getNameHtml( name, moduleName );
-
- rerunTrigger = document.createElement( "a" );
- rerunTrigger.innerHTML = "Rerun";
- rerunTrigger.href = setUrl({ testId: testId });
-
- testBlock = document.createElement( "li" );
- testBlock.appendChild( title );
- testBlock.appendChild( rerunTrigger );
- testBlock.id = "qunit-test-output-" + testId;
-
- assertList = document.createElement( "ol" );
- assertList.className = "qunit-assert-list";
-
- testBlock.appendChild( assertList );
-
- tests.appendChild( testBlock );
-}
-
-// HTML Reporter initialization and load
-QUnit.begin(function( details ) {
- var qunit = id( "qunit" );
-
- // Fixture is the only one necessary to run without the #qunit element
- storeFixture();
-
- if ( qunit ) {
- qunit.innerHTML =
- "<h1 id='qunit-header'>" + escapeText( document.title ) + "</h1>" +
- "<h2 id='qunit-banner'></h2>" +
- "<div id='qunit-testrunner-toolbar'></div>" +
- "<h2 id='qunit-userAgent'></h2>" +
- "<ol id='qunit-tests'></ol>";
- }
-
- appendHeader();
- appendBanner();
- appendTestResults();
- appendUserAgent();
- appendToolbar();
- appendTestsList( details.modules );
- toolbarModuleFilter();
-
- if ( qunit && config.hidepassed ) {
- addClass( qunit.lastChild, "hidepass" );
- }
-});
-
-QUnit.done(function( details ) {
- var i, key,
- 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 && defined.document && document.title ) {
-
- // show ✖ for good, ✔ for bad suite result in title
- // use escape sequences in case file gets loaded with non-utf-8-charset
- document.title = [
- ( details.failed ? "\u2716" : "\u2714" ),
- document.title.replace( /^[\u2714\u2716] /i, "" )
- ].join( " " );
- }
-
- // clear own sessionStorage items if all tests passed
- if ( config.reorder && defined.sessionStorage && details.failed === 0 ) {
- for ( i = 0; i < sessionStorage.length; i++ ) {
- key = sessionStorage.key( i++ );
- if ( key.indexOf( "qunit-test-" ) === 0 ) {
- sessionStorage.removeItem( key );
- }
- }
- }
-
- // 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;
-
- 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 ) {
- running.innerHTML = "Running: <br />" + getNameHtml( details.name, details.module );
- }
-
-});
-
-QUnit.log(function( details ) {
- var assertList, assertLi,
- message, expected, actual,
- 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>";
-
- // 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" ) ) {
- expected = escapeText( QUnit.dump.parse( details.expected ) );
- actual = escapeText( QUnit.dump.parse( details.actual ) );
- message += "<table><tr class='test-expected'><th>Expected: </th><td><pre>" +
- expected +
- "</pre></td></tr>";
-
- if ( actual !== expected ) {
- message += "<tr class='test-actual'><th>Result: </th><td><pre>" +
- actual + "</pre></td></tr>" +
- "<tr class='test-diff'><th>Diff: </th><td><pre>" +
- QUnit.diff( expected, actual ) + "</pre></td></tr>";
- }
-
- if ( details.source ) {
- message += "<tr class='test-source'><th>Source: </th><td><pre>" +
- escapeText( details.source ) + "</pre></td></tr>";
- }
-
- message += "</table>";
-
- // this occours 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.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,
- 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;
-
- // store result when possible
- if ( config.reorder && defined.sessionStorage ) {
- if ( bad ) {
- sessionStorage.setItem( "qunit-test-" + details.module + "-" + details.name, bad );
- } else {
- sessionStorage.removeItem( "qunit-test-" + details.module + "-" + details.name );
- }
- }
-
- if ( bad === 0 ) {
- addClass( assertList, "qunit-collapsed" );
- }
-
- // 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.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.createElement( "span" );
- time.className = "runtime";
- time.innerHTML = details.runtime + " ms";
- testItem.insertBefore( time, assertList );
- }
-});
-
-if ( !defined.document || document.readyState === "complete" ) {
- config.pageLoaded = true;
- config.autorun = true;
-}
-
-if ( defined.document ) {
- addEvent( window, "load", QUnit.load );
-}
-
-})();
diff --git a/external/requirejs/require.js b/external/requirejs/require.js
deleted file mode 100644
index 77a5bb1..0000000
--- a/external/requirejs/require.js
+++ /dev/null
@@ -1,2076 +0,0 @@
-/** vim: et:ts=4:sw=4:sts=4
- * @license RequireJS 2.1.15 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
- * Available via the MIT or new BSD license.
- * see: http://github.com/jrburke/requirejs for details
- */
-//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) {
- var req, s, head, baseElement, dataMain, src,
- interactiveScript, currentlyAddingScript, mainScript, subPath,
- version = '2.1.15',
- commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
- cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
- jsSuffixRegExp = /\.js$/,
- currDirRegExp = /^\.\//,
- op = Object.prototype,
- ostring = op.toString,
- hasOwn = op.hasOwnProperty,
- ap = Array.prototype,
- apsp = ap.splice,
- 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;
-
- 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 = '_ at 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) {
- //Array splice in the values since the context code has a
- //local var ref to defQueue, so cannot just reassign the one
- //on context.
- apsp.apply(defQueue,
- [defQueue.length, 0].concat(globalDefQueue));
- 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) {
- 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) {
- req.onResourceLoad(context, this.map, this.depMaps);
- }
- }
-
- //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.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) {
- this.defineDep(i, depExports);
- this.check();
- }));
-
- if (this.errback) {
- on(depMap, 'error', bind(this, this.errback));
- }
- }
-
- 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 = {
- config: config,
- contextName: contextName,
- registry: registry,
- defined: defined,
- urlFetched: urlFetched,
- defQueue: defQueue,
- 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 += '/';
- }
- }
-
- //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);
- }
- });
-
- //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);
-
- 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);
- }
- });
-
- 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);
- }
-
- //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\:|\?/.test(url) || skipExt ? '' : '.js'));
- url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
- }
-
- return config.urlArgs ? url +
- ((url.indexOf('?') === -1 ? '?' : '&') +
- config.urlArgs) : 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)) {
- return onError(makeError('scripterror', 'Script error for: ' + data.id, 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/jrburke/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/jrburke/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;
-
- //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 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.
- 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.
- if (!cfg.baseUrl) {
- //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, '')
- .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.
- (context ? context.defQueue : 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));
diff --git a/external/sinon/sinon-1.14.1.js b/external/sinon/sinon-1.14.1.js
deleted file mode 100644
index dfbeae4..0000000
--- a/external/sinon/sinon-1.14.1.js
+++ /dev/null
@@ -1,5931 +0,0 @@
-/**
- * Sinon.JS 1.14.1, 2015/03/16
- *
- * @author Christian Johansen (christian at cjohansen.no)
- * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS
- *
- * (The BSD License)
- *
- * Copyright (c) 2010-2014, Christian Johansen, christian at cjohansen.no
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without modification,
- * are permitted provided that the following conditions are met:
- *
- * * Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * * Neither the name of Christian Johansen nor the names of his contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-(function (root, factory) {
- if (typeof define === 'function' && define.amd) {
- define('sinon', [], function () {
- return (root.sinon = factory());
- });
- } else if (typeof exports === 'object') {
- module.exports = factory();
- } else {
- root.sinon = factory();
- }
-}(this, function () {
- var samsam, formatio;
- (function () {
- function define(mod, deps, fn) {
- if (mod == "samsam") {
- samsam = deps();
- } else if (typeof deps === "function" && mod.length === 0) {
- lolex = deps();
- } else if (typeof fn === "function") {
- formatio = fn(samsam);
- }
- }
- define.amd = {};
-((typeof define === "function" && define.amd && function (m) { define("samsam", m); }) ||
- (typeof module === "object" &&
- function (m) { module.exports = m(); }) || // Node
- function (m) { this.samsam = m(); } // Browser globals
-)(function () {
- var o = Object.prototype;
- var div = typeof document !== "undefined" && document.createElement("div");
-
- function isNaN(value) {
- // Unlike global isNaN, this avoids type coercion
- // typeof check avoids IE host object issues, hat tip to
- // lodash
- var val = value; // JsLint thinks value !== value is "weird"
- return typeof value === "number" && value !== val;
- }
-
- function getClass(value) {
- // Returns the internal [[Class]] by calling Object.prototype.toString
- // with the provided value as this. Return value is a string, naming the
- // internal class, e.g. "Array"
- return o.toString.call(value).split(/[ \]]/)[1];
- }
-
- /**
- * @name samsam.isArguments
- * @param Object object
- *
- * Returns ``true`` if ``object`` is an ``arguments`` object,
- * ``false`` otherwise.
- */
- function isArguments(object) {
- if (getClass(object) === 'Arguments') { return true; }
- if (typeof object !== "object" || typeof object.length !== "number" ||
- getClass(object) === "Array") {
- return false;
- }
- if (typeof object.callee == "function") { return true; }
- try {
- object[object.length] = 6;
- delete object[object.length];
- } catch (e) {
- return true;
- }
- return false;
- }
-
- /**
- * @name samsam.isElement
- * @param Object object
- *
- * Returns ``true`` if ``object`` is a DOM element node. Unlike
- * Underscore.js/lodash, this function will return ``false`` if ``object``
- * is an *element-like* object, i.e. a regular object with a ``nodeType``
- * property that holds the value ``1``.
- */
- function isElement(object) {
- if (!object || object.nodeType !== 1 || !div) { return false; }
- try {
- object.appendChild(div);
- object.removeChild(div);
- } catch (e) {
- return false;
- }
- return true;
- }
-
- /**
- * @name samsam.keys
- * @param Object object
- *
- * Return an array of own property names.
- */
- function keys(object) {
- var ks = [], prop;
- for (prop in object) {
- if (o.hasOwnProperty.call(object, prop)) { ks.push(prop); }
- }
- return ks;
- }
-
- /**
- * @name samsam.isDate
- * @param Object value
- *
- * Returns true if the object is a ``Date``, or *date-like*. Duck typing
- * of date objects work by checking that the object has a ``getTime``
- * function whose return value equals the return value from the object's
- * ``valueOf``.
- */
- function isDate(value) {
- return typeof value.getTime == "function" &&
- value.getTime() == value.valueOf();
- }
-
- /**
- * @name samsam.isNegZero
- * @param Object value
- *
- * Returns ``true`` if ``value`` is ``-0``.
- */
- function isNegZero(value) {
- return value === 0 && 1 / value === -Infinity;
- }
-
- /**
- * @name samsam.equal
- * @param Object obj1
- * @param Object obj2
- *
- * Returns ``true`` if two objects are strictly equal. Compared to
- * ``===`` there are two exceptions:
- *
- * - NaN is considered equal to NaN
- * - -0 and +0 are not considered equal
- */
- function identical(obj1, obj2) {
- if (obj1 === obj2 || (isNaN(obj1) && isNaN(obj2))) {
- return obj1 !== 0 || isNegZero(obj1) === isNegZero(obj2);
- }
- }
-
-
- /**
- * @name samsam.deepEqual
- * @param Object obj1
- * @param Object obj2
- *
- * Deep equal comparison. Two values are "deep equal" if:
- *
- * - They are equal, according to samsam.identical
- * - They are both date objects representing the same time
- * - They are both arrays containing elements that are all deepEqual
- * - They are objects with the same set of properties, and each property
- * in ``obj1`` is deepEqual to the corresponding property in ``obj2``
- *
- * Supports cyclic objects.
- */
- function deepEqualCyclic(obj1, obj2) {
-
- // used for cyclic comparison
- // contain already visited objects
- var objects1 = [],
- objects2 = [],
- // contain pathes (position in the object structure)
- // of the already visited objects
- // indexes same as in objects arrays
- paths1 = [],
- paths2 = [],
- // contains combinations of already compared objects
- // in the manner: { "$1['ref']$2['ref']": true }
- compared = {};
-
- /**
- * used to check, if the value of a property is an object
- * (cyclic logic is only needed for objects)
- * only needed for cyclic logic
- */
- function isObject(value) {
-
- if (typeof value === 'object' && value !== null &&
- !(value instanceof Boolean) &&
- !(value instanceof Date) &&
- !(value instanceof Number) &&
- !(value instanceof RegExp) &&
- !(value instanceof String)) {
-
- return true;
- }
-
- return false;
- }
-
- /**
- * returns the index of the given object in the
- * given objects array, -1 if not contained
- * only needed for cyclic logic
- */
- function getIndex(objects, obj) {
-
- var i;
- for (i = 0; i < objects.length; i++) {
- if (objects[i] === obj) {
- return i;
- }
- }
-
- return -1;
- }
-
- // does the recursion for the deep equal check
- return (function deepEqual(obj1, obj2, path1, path2) {
- var type1 = typeof obj1;
- var type2 = typeof obj2;
-
- // == null also matches undefined
- if (obj1 === obj2 ||
- isNaN(obj1) || isNaN(obj2) ||
- obj1 == null || obj2 == null ||
- type1 !== "object" || type2 !== "object") {
-
- return identical(obj1, obj2);
- }
-
- // Elements are only equal if identical(expected, actual)
- if (isElement(obj1) || isElement(obj2)) { return false; }
-
- var isDate1 = isDate(obj1), isDate2 = isDate(obj2);
- if (isDate1 || isDate2) {
- if (!isDate1 || !isDate2 || obj1.getTime() !== obj2.getTime()) {
- return false;
- }
- }
-
- if (obj1 instanceof RegExp && obj2 instanceof RegExp) {
- if (obj1.toString() !== obj2.toString()) { return false; }
- }
-
- var class1 = getClass(obj1);
- var class2 = getClass(obj2);
- var keys1 = keys(obj1);
- var keys2 = keys(obj2);
-
- if (isArguments(obj1) || isArguments(obj2)) {
- if (obj1.length !== obj2.length) { return false; }
- } else {
- if (type1 !== type2 || class1 !== class2 ||
- keys1.length !== keys2.length) {
- return false;
- }
- }
-
- var key, i, l,
- // following vars are used for the cyclic logic
- value1, value2,
- isObject1, isObject2,
- index1, index2,
- newPath1, newPath2;
-
- for (i = 0, l = keys1.length; i < l; i++) {
- key = keys1[i];
- if (!o.hasOwnProperty.call(obj2, key)) {
- return false;
- }
-
- // Start of the cyclic logic
-
- value1 = obj1[key];
- value2 = obj2[key];
-
- isObject1 = isObject(value1);
- isObject2 = isObject(value2);
-
- // determine, if the objects were already visited
- // (it's faster to check for isObject first, than to
- // get -1 from getIndex for non objects)
- index1 = isObject1 ? getIndex(objects1, value1) : -1;
- index2 = isObject2 ? getIndex(objects2, value2) : -1;
-
- // determine the new pathes of the objects
- // - for non cyclic objects the current path will be extended
- // by current property name
- // - for cyclic objects the stored path is taken
- newPath1 = index1 !== -1
- ? paths1[index1]
- : path1 + '[' + JSON.stringify(key) + ']';
- newPath2 = index2 !== -1
- ? paths2[index2]
- : path2 + '[' + JSON.stringify(key) + ']';
-
- // stop recursion if current objects are already compared
- if (compared[newPath1 + newPath2]) {
- return true;
- }
-
- // remember the current objects and their pathes
- if (index1 === -1 && isObject1) {
- objects1.push(value1);
- paths1.push(newPath1);
- }
- if (index2 === -1 && isObject2) {
- objects2.push(value2);
- paths2.push(newPath2);
- }
-
- // remember that the current objects are already compared
- if (isObject1 && isObject2) {
- compared[newPath1 + newPath2] = true;
- }
-
- // End of cyclic logic
-
- // neither value1 nor value2 is a cycle
- // continue with next level
- if (!deepEqual(value1, value2, newPath1, newPath2)) {
- return false;
- }
- }
-
- return true;
-
- }(obj1, obj2, '$1', '$2'));
- }
-
- var match;
-
- function arrayContains(array, subset) {
- if (subset.length === 0) { return true; }
- var i, l, j, k;
- for (i = 0, l = array.length; i < l; ++i) {
- if (match(array[i], subset[0])) {
- for (j = 0, k = subset.length; j < k; ++j) {
- if (!match(array[i + j], subset[j])) { return false; }
- }
- return true;
- }
- }
- return false;
- }
-
- /**
- * @name samsam.match
- * @param Object object
- * @param Object matcher
- *
- * Compare arbitrary value ``object`` with matcher.
- */
- match = function match(object, matcher) {
- if (matcher && typeof matcher.test === "function") {
- return matcher.test(object);
- }
-
- if (typeof matcher === "function") {
- return matcher(object) === true;
- }
-
- if (typeof matcher === "string") {
- matcher = matcher.toLowerCase();
- var notNull = typeof object === "string" || !!object;
- return notNull &&
- (String(object)).toLowerCase().indexOf(matcher) >= 0;
- }
-
- if (typeof matcher === "number") {
- return matcher === object;
- }
-
- if (typeof matcher === "boolean") {
- return matcher === object;
- }
-
- if (typeof(matcher) === "undefined") {
- return typeof(object) === "undefined";
- }
-
- if (matcher === null) {
- return object === null;
- }
-
- if (getClass(object) === "Array" && getClass(matcher) === "Array") {
- return arrayContains(object, matcher);
- }
-
- if (matcher && typeof matcher === "object") {
- if (matcher === object) {
- return true;
- }
- var prop;
- for (prop in matcher) {
- var value = object[prop];
- if (typeof value === "undefined" &&
- typeof object.getAttribute === "function") {
- value = object.getAttribute(prop);
- }
- if (matcher[prop] === null || typeof matcher[prop] === 'undefined') {
- if (value !== matcher[prop]) {
- return false;
- }
- } else if (typeof value === "undefined" || !match(value, matcher[prop])) {
- return false;
- }
- }
- return true;
- }
-
- throw new Error("Matcher was not a string, a number, a " +
- "function, a boolean or an object");
- };
-
- return {
- isArguments: isArguments,
- isElement: isElement,
- isDate: isDate,
- isNegZero: isNegZero,
- identical: identical,
- deepEqual: deepEqualCyclic,
- match: match,
- keys: keys
- };
-});
-((typeof define === "function" && define.amd && function (m) {
- define("formatio", ["samsam"], m);
-}) || (typeof module === "object" && function (m) {
- module.exports = m(require("samsam"));
-}) || function (m) { this.formatio = m(this.samsam); }
-)(function (samsam) {
-
- var formatio = {
- excludeConstructors: ["Object", /^.$/],
- quoteStrings: true,
- limitChildrenCount: 0
- };
-
- var hasOwn = Object.prototype.hasOwnProperty;
-
- var specialObjects = [];
- if (typeof global !== "undefined") {
- specialObjects.push({ object: global, value: "[object global]" });
- }
- if (typeof document !== "undefined") {
- specialObjects.push({
- object: document,
- value: "[object HTMLDocument]"
- });
- }
- if (typeof window !== "undefined") {
- specialObjects.push({ object: window, value: "[object Window]" });
- }
-
- function functionName(func) {
- if (!func) { return ""; }
- if (func.displayName) { return func.displayName; }
- if (func.name) { return func.name; }
- var matches = func.toString().match(/function\s+([^\(]+)/m);
- return (matches && matches[1]) || "";
- }
-
- function constructorName(f, object) {
- var name = functionName(object && object.constructor);
- var excludes = f.excludeConstructors ||
- formatio.excludeConstructors || [];
-
- var i, l;
- for (i = 0, l = excludes.length; i < l; ++i) {
- if (typeof excludes[i] === "string" && excludes[i] === name) {
- return "";
- } else if (excludes[i].test && excludes[i].test(name)) {
- return "";
- }
- }
-
- return name;
- }
-
- function isCircular(object, objects) {
- if (typeof object !== "object") { return false; }
- var i, l;
- for (i = 0, l = objects.length; i < l; ++i) {
- if (objects[i] === object) { return true; }
- }
- return false;
- }
-
- function ascii(f, object, processed, indent) {
- if (typeof object === "string") {
- var qs = f.quoteStrings;
- var quote = typeof qs !== "boolean" || qs;
- return processed || quote ? '"' + object + '"' : object;
- }
-
- if (typeof object === "function" && !(object instanceof RegExp)) {
- return ascii.func(object);
- }
-
- processed = processed || [];
-
- if (isCircular(object, processed)) { return "[Circular]"; }
-
- if (Object.prototype.toString.call(object) === "[object Array]") {
- return ascii.array.call(f, object, processed);
- }
-
- if (!object) { return String((1/object) === -Infinity ? "-0" : object); }
- if (samsam.isElement(object)) { return ascii.element(object); }
-
- if (typeof object.toString === "function" &&
- object.toString !== Object.prototype.toString) {
- return object.toString();
- }
-
- var i, l;
- for (i = 0, l = specialObjects.length; i < l; i++) {
- if (object === specialObjects[i].object) {
- return specialObjects[i].value;
- }
- }
-
- return ascii.object.call(f, object, processed, indent);
- }
-
- ascii.func = function (func) {
- return "function " + functionName(func) + "() {}";
- };
-
- ascii.array = function (array, processed) {
- processed = processed || [];
- processed.push(array);
- var pieces = [];
- var i, l;
- l = (this.limitChildrenCount > 0) ?
- Math.min(this.limitChildrenCount, array.length) : array.length;
-
- for (i = 0; i < l; ++i) {
- pieces.push(ascii(this, array[i], processed));
- }
-
- if(l < array.length)
- pieces.push("[... " + (array.length - l) + " more elements]");
-
- return "[" + pieces.join(", ") + "]";
- };
-
- ascii.object = function (object, processed, indent) {
- processed = processed || [];
- processed.push(object);
- indent = indent || 0;
- var pieces = [], properties = samsam.keys(object).sort();
- var length = 3;
- var prop, str, obj, i, k, l;
- l = (this.limitChildrenCount > 0) ?
- Math.min(this.limitChildrenCount, properties.length) : properties.length;
-
- for (i = 0; i < l; ++i) {
- prop = properties[i];
- obj = object[prop];
-
- if (isCircular(obj, processed)) {
- str = "[Circular]";
- } else {
- str = ascii(this, obj, processed, indent + 2);
- }
-
- str = (/\s/.test(prop) ? '"' + prop + '"' : prop) + ": " + str;
- length += str.length;
- pieces.push(str);
- }
-
- var cons = constructorName(this, object);
- var prefix = cons ? "[" + cons + "] " : "";
- var is = "";
- for (i = 0, k = indent; i < k; ++i) { is += " "; }
-
- if(l < properties.length)
- pieces.push("[... " + (properties.length - l) + " more elements]");
-
- if (length + indent > 80) {
- return prefix + "{\n " + is + pieces.join(",\n " + is) + "\n" +
- is + "}";
- }
- return prefix + "{ " + pieces.join(", ") + " }";
- };
-
- ascii.element = function (element) {
- var tagName = element.tagName.toLowerCase();
- var attrs = element.attributes, attr, pairs = [], attrName, i, l, val;
-
- for (i = 0, l = attrs.length; i < l; ++i) {
- attr = attrs.item(i);
- attrName = attr.nodeName.toLowerCase().replace("html:", "");
- val = attr.nodeValue;
- if (attrName !== "contenteditable" || val !== "inherit") {
- if (!!val) { pairs.push(attrName + "=\"" + val + "\""); }
- }
- }
-
- var formatted = "<" + tagName + (pairs.length > 0 ? " " : "");
- var content = element.innerHTML;
-
- if (content.length > 20) {
- content = content.substr(0, 20) + "[...]";
- }
-
- var res = formatted + pairs.join(" ") + ">" + content +
- "</" + tagName + ">";
-
- return res.replace(/ contentEditable="inherit"/, "");
- };
-
- function Formatio(options) {
- for (var opt in options) {
- this[opt] = options[opt];
- }
- }
-
- Formatio.prototype = {
- functionName: functionName,
-
- configure: function (options) {
- return new Formatio(options);
- },
-
- constructorName: function (object) {
- return constructorName(this, object);
- },
-
- ascii: function (object, processed, indent) {
- return ascii(this, object, processed, indent);
- }
- };
-
- return Formatio.prototype;
-});
-!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.lolex=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find [...]
-(function (global){
-/*jslint eqeqeq: false, plusplus: false, evil: true, onevar: false, browser: true, forin: false*/
-/*global global*/
-/**
- * @author Christian Johansen (christian at cjohansen.no) and contributors
- * @license BSD
- *
- * Copyright (c) 2010-2014 Christian Johansen
- */
-
-// node expects setTimeout/setInterval to return a fn object w/ .ref()/.unref()
-// browsers, a number.
-// see https://github.com/cjohansen/Sinon.JS/pull/436
-var timeoutResult = setTimeout(function() {}, 0);
-var addTimerReturnsObject = typeof timeoutResult === "object";
-clearTimeout(timeoutResult);
-
-var NativeDate = Date;
-var id = 1;
-
-/**
- * Parse strings like "01:10:00" (meaning 1 hour, 10 minutes, 0 seconds) into
- * number of milliseconds. This is used to support human-readable strings passed
- * to clock.tick()
- */
-function parseTime(str) {
- if (!str) {
- return 0;
- }
-
- var strings = str.split(":");
- var l = strings.length, i = l;
- var ms = 0, parsed;
-
- if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) {
- throw new Error("tick only understands numbers and 'h:m:s'");
- }
-
- while (i--) {
- parsed = parseInt(strings[i], 10);
-
- if (parsed >= 60) {
- throw new Error("Invalid time " + str);
- }
-
- ms += parsed * Math.pow(60, (l - i - 1));
- }
-
- return ms * 1000;
-}
-
-/**
- * Used to grok the `now` parameter to createClock.
- */
-function getEpoch(epoch) {
- if (!epoch) { return 0; }
- if (typeof epoch.getTime === "function") { return epoch.getTime(); }
- if (typeof epoch === "number") { return epoch; }
- throw new TypeError("now should be milliseconds since UNIX epoch");
-}
-
-function inRange(from, to, timer) {
- return timer && timer.callAt >= from && timer.callAt <= to;
-}
-
-function mirrorDateProperties(target, source) {
- if (source.now) {
- target.now = function now() {
- return target.clock.now;
- };
- } else {
- delete target.now;
- }
-
- if (source.toSource) {
- target.toSource = function toSource() {
- return source.toSource();
- };
- } else {
- delete target.toSource;
- }
-
- target.toString = function toString() {
- return source.toString();
- };
-
- target.prototype = source.prototype;
- target.parse = source.parse;
- target.UTC = source.UTC;
- target.prototype.toUTCString = source.prototype.toUTCString;
-
- for (var prop in source) {
- if (source.hasOwnProperty(prop)) {
- target[prop] = source[prop];
- }
- }
-
- return target;
-}
-
-function createDate() {
- function ClockDate(year, month, date, hour, minute, second, ms) {
- // Defensive and verbose to avoid potential harm in passing
- // explicit undefined when user does not pass argument
- switch (arguments.length) {
- case 0:
- return new NativeDate(ClockDate.clock.now);
- case 1:
- return new NativeDate(year);
- case 2:
- return new NativeDate(year, month);
- case 3:
- return new NativeDate(year, month, date);
- case 4:
- return new NativeDate(year, month, date, hour);
- case 5:
- return new NativeDate(year, month, date, hour, minute);
- case 6:
- return new NativeDate(year, month, date, hour, minute, second);
- default:
- return new NativeDate(year, month, date, hour, minute, second, ms);
- }
- }
-
- return mirrorDateProperties(ClockDate, NativeDate);
-}
-
-function addTimer(clock, timer) {
- if (typeof timer.func === "undefined") {
- throw new Error("Callback must be provided to timer calls");
- }
-
- if (!clock.timers) {
- clock.timers = {};
- }
-
- timer.id = id++;
- timer.createdAt = clock.now;
- timer.callAt = clock.now + (timer.delay || 0);
-
- clock.timers[timer.id] = timer;
-
- if (addTimerReturnsObject) {
- return {
- id: timer.id,
- ref: function() {},
- unref: function() {}
- };
- }
- else {
- return timer.id;
- }
-}
-
-function firstTimerInRange(clock, from, to) {
- var timers = clock.timers, timer = null;
-
- for (var id in timers) {
- if (!inRange(from, to, timers[id])) {
- continue;
- }
-
- if (!timer || ~compareTimers(timer, timers[id])) {
- timer = timers[id];
- }
- }
-
- return timer;
-}
-
-function compareTimers(a, b) {
- // Sort first by absolute timing
- if (a.callAt < b.callAt) {
- return -1;
- }
- if (a.callAt > b.callAt) {
- return 1;
- }
-
- // Sort next by immediate, immediate timers take precedence
- if (a.immediate && !b.immediate) {
- return -1;
- }
- if (!a.immediate && b.immediate) {
- return 1;
- }
-
- // Sort next by creation time, earlier-created timers take precedence
- if (a.createdAt < b.createdAt) {
- return -1;
- }
- if (a.createdAt > b.createdAt) {
- return 1;
- }
-
- // Sort next by id, lower-id timers take precedence
- if (a.id < b.id) {
- return -1;
- }
- if (a.id > b.id) {
- return 1;
- }
-
- // As timer ids are unique, no fallback `0` is necessary
-}
-
-function callTimer(clock, timer) {
- if (typeof timer.interval == "number") {
- clock.timers[timer.id].callAt += timer.interval;
- } else {
- delete clock.timers[timer.id];
- }
-
- try {
- if (typeof timer.func == "function") {
- timer.func.apply(null, timer.args);
- } else {
- eval(timer.func);
- }
- } catch (e) {
- var exception = e;
- }
-
- if (!clock.timers[timer.id]) {
- if (exception) {
- throw exception;
- }
- return;
- }
-
- if (exception) {
- throw exception;
- }
-}
-
-function uninstall(clock, target) {
- var method;
-
- for (var i = 0, l = clock.methods.length; i < l; i++) {
- method = clock.methods[i];
-
- if (target[method].hadOwnProperty) {
- target[method] = clock["_" + method];
- } else {
- try {
- delete target[method];
- } catch (e) {}
- }
- }
-
- // Prevent multiple executions which will completely remove these props
- clock.methods = [];
-}
-
-function hijackMethod(target, method, clock) {
- clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(target, method);
- clock["_" + method] = target[method];
-
- if (method == "Date") {
- var date = mirrorDateProperties(clock[method], target[method]);
- target[method] = date;
- } else {
- target[method] = function () {
- return clock[method].apply(clock, arguments);
- };
-
- for (var prop in clock[method]) {
- if (clock[method].hasOwnProperty(prop)) {
- target[method][prop] = clock[method][prop];
- }
- }
- }
-
- target[method].clock = clock;
-}
-
-var timers = {
- setTimeout: setTimeout,
- clearTimeout: clearTimeout,
- setImmediate: (typeof setImmediate !== "undefined" ? setImmediate : undefined),
- clearImmediate: (typeof clearImmediate !== "undefined" ? clearImmediate: undefined),
- setInterval: setInterval,
- clearInterval: clearInterval,
- Date: Date
-};
-
-var keys = Object.keys || function (obj) {
- var ks = [];
- for (var key in obj) {
- ks.push(key);
- }
- return ks;
-};
-
-exports.timers = timers;
-
-var createClock = exports.createClock = function (now) {
- var clock = {
- now: getEpoch(now),
- timeouts: {},
- Date: createDate()
- };
-
- clock.Date.clock = clock;
-
- clock.setTimeout = function setTimeout(func, timeout) {
- return addTimer(clock, {
- func: func,
- args: Array.prototype.slice.call(arguments, 2),
- delay: timeout
- });
- };
-
- clock.clearTimeout = function clearTimeout(timerId) {
- if (!timerId) {
- // null appears to be allowed in most browsers, and appears to be
- // relied upon by some libraries, like Bootstrap carousel
- return;
- }
- if (!clock.timers) {
- clock.timers = [];
- }
- // in Node, timerId is an object with .ref()/.unref(), and
- // its .id field is the actual timer id.
- if (typeof timerId === "object") {
- timerId = timerId.id
- }
- if (timerId in clock.timers) {
- delete clock.timers[timerId];
- }
- };
-
- clock.setInterval = function setInterval(func, timeout) {
- return addTimer(clock, {
- func: func,
- args: Array.prototype.slice.call(arguments, 2),
- delay: timeout,
- interval: timeout
- });
- };
-
- clock.clearInterval = function clearInterval(timerId) {
- clock.clearTimeout(timerId);
- };
-
- clock.setImmediate = function setImmediate(func) {
- return addTimer(clock, {
- func: func,
- args: Array.prototype.slice.call(arguments, 1),
- immediate: true
- });
- };
-
- clock.clearImmediate = function clearImmediate(timerId) {
- clock.clearTimeout(timerId);
- };
-
- clock.tick = function tick(ms) {
- ms = typeof ms == "number" ? ms : parseTime(ms);
- var tickFrom = clock.now, tickTo = clock.now + ms, previous = clock.now;
- var timer = firstTimerInRange(clock, tickFrom, tickTo);
-
- var firstException;
- while (timer && tickFrom <= tickTo) {
- if (clock.timers[timer.id]) {
- tickFrom = clock.now = timer.callAt;
- try {
- callTimer(clock, timer);
- } catch (e) {
- firstException = firstException || e;
- }
- }
-
- timer = firstTimerInRange(clock, previous, tickTo);
- previous = tickFrom;
- }
-
- clock.now = tickTo;
-
- if (firstException) {
- throw firstException;
- }
-
- return clock.now;
- };
-
- clock.reset = function reset() {
- clock.timers = {};
- };
-
- return clock;
-};
-
-exports.install = function install(target, now, toFake) {
- if (typeof target === "number") {
- toFake = now;
- now = target;
- target = null;
- }
-
- if (!target) {
- target = global;
- }
-
- var clock = createClock(now);
-
- clock.uninstall = function () {
- uninstall(clock, target);
- };
-
- clock.methods = toFake || [];
-
- if (clock.methods.length === 0) {
- clock.methods = keys(timers);
- }
-
- for (var i = 0, l = clock.methods.length; i < l; i++) {
- hijackMethod(target, clock.methods[i], clock);
- }
-
- return clock;
-};
-
-}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{}]},{},[1])(1)
-});
- })();
- var define;
-/**
- * Sinon core utilities. For internal use only.
- *
- * @author Christian Johansen (christian at cjohansen.no)
- * @license BSD
- *
- * Copyright (c) 2010-2013 Christian Johansen
- */
-
-var sinon = (function () {
-"use strict";
-
- var sinon;
- var isNode = typeof module !== "undefined" && module.exports && typeof require === "function";
- var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;
-
- function loadDependencies(require, exports, module) {
- sinon = module.exports = require("./sinon/util/core");
- require("./sinon/extend");
- require("./sinon/typeOf");
- require("./sinon/times_in_words");
- require("./sinon/spy");
- require("./sinon/call");
- require("./sinon/behavior");
- require("./sinon/stub");
- require("./sinon/mock");
- require("./sinon/collection");
- require("./sinon/assert");
- require("./sinon/sandbox");
- require("./sinon/test");
- require("./sinon/test_case");
- require("./sinon/match");
- require("./sinon/format");
- require("./sinon/log_error");
- }
-
- if (isAMD) {
- define(loadDependencies);
- } else if (isNode) {
- loadDependencies(require, module.exports, module);
- sinon = module.exports;
- } else {
- sinon = {};
- }
-
- return sinon;
-}());
-
-/**
- * @depend ../../sinon.js
- */
-/**
- * Sinon core utilities. For internal use only.
- *
- * @author Christian Johansen (christian at cjohansen.no)
- * @license BSD
- *
- * Copyright (c) 2010-2013 Christian Johansen
- */
-
-(function (sinon) {
- var div = typeof document != "undefined" && document.createElement("div");
- var hasOwn = Object.prototype.hasOwnProperty;
-
- function isDOMNode(obj) {
- var success = false;
-
- try {
- obj.appendChild(div);
- success = div.parentNode == obj;
- } catch (e) {
- return false;
- } finally {
- try {
- obj.removeChild(div);
- } catch (e) {
- // Remove failed, not much we can do about that
- }
- }
-
- return success;
- }
-
- function isElement(obj) {
- return div && obj && obj.nodeType === 1 && isDOMNode(obj);
- }
-
- function isFunction(obj) {
- return typeof obj === "function" || !!(obj && obj.constructor && obj.call && obj.apply);
- }
-
- function isReallyNaN(val) {
- return typeof val === "number" && isNaN(val);
- }
-
- function mirrorProperties(target, source) {
- for (var prop in source) {
- if (!hasOwn.call(target, prop)) {
- target[prop] = source[prop];
- }
- }
- }
-
- function isRestorable(obj) {
- return typeof obj === "function" && typeof obj.restore === "function" && obj.restore.sinon;
- }
-
- // Cheap way to detect if we have ES5 support.
- var hasES5Support = "keys" in Object;
-
- function makeApi(sinon) {
- sinon.wrapMethod = function wrapMethod(object, property, method) {
- if (!object) {
- throw new TypeError("Should wrap property of object");
- }
-
- if (typeof method != "function" && typeof method != "object") {
- throw new TypeError("Method wrapper should be a function or a property descriptor");
- }
-
- function checkWrappedMethod(wrappedMethod) {
- if (!isFunction(wrappedMethod)) {
- error = new TypeError("Attempted to wrap " + (typeof wrappedMethod) + " property " +
- property + " as function");
- } else if (wrappedMethod.restore && wrappedMethod.restore.sinon) {
- error = new TypeError("Attempted to wrap " + property + " which is already wrapped");
- } else if (wrappedMethod.calledBefore) {
- var verb = !!wrappedMethod.returns ? "stubbed" : "spied on";
- error = new TypeError("Attempted to wrap " + property + " which is already " + verb);
- }
-
- if (error) {
- if (wrappedMethod && wrappedMethod.stackTrace) {
- error.stack += "\n--------------\n" + wrappedMethod.stackTrace;
- }
- throw error;
- }
- }
-
- var error, wrappedMethod;
-
- // IE 8 does not support hasOwnProperty on the window object and Firefox has a problem
- // when using hasOwn.call on objects from other frames.
- var owned = object.hasOwnProperty ? object.hasOwnProperty(property) : hasOwn.call(object, property);
-
- if (hasES5Support) {
- var methodDesc = (typeof method == "function") ? {value: method} : method,
- wrappedMethodDesc = sinon.getPropertyDescriptor(object, property),
- i;
-
- if (!wrappedMethodDesc) {
- error = new TypeError("Attempted to wrap " + (typeof wrappedMethod) + " property " +
- property + " as function");
- } else if (wrappedMethodDesc.restore && wrappedMethodDesc.restore.sinon) {
- error = new TypeError("Attempted to wrap " + property + " which is already wrapped");
- }
- if (error) {
- if (wrappedMethodDesc && wrappedMethodDesc.stackTrace) {
- error.stack += "\n--------------\n" + wrappedMethodDesc.stackTrace;
- }
- throw error;
- }
-
- var types = sinon.objectKeys(methodDesc);
- for (i = 0; i < types.length; i++) {
- wrappedMethod = wrappedMethodDesc[types[i]];
- checkWrappedMethod(wrappedMethod);
- }
-
- mirrorProperties(methodDesc, wrappedMethodDesc);
- for (i = 0; i < types.length; i++) {
- mirrorProperties(methodDesc[types[i]], wrappedMethodDesc[types[i]]);
- }
- Object.defineProperty(object, property, methodDesc);
- } else {
- wrappedMethod = object[property];
- checkWrappedMethod(wrappedMethod);
- object[property] = method;
- method.displayName = property;
- }
-
- method.displayName = property;
-
- // Set up a stack trace which can be used later to find what line of
- // code the original method was created on.
- method.stackTrace = (new Error("Stack Trace for original")).stack;
-
- method.restore = function () {
- // For prototype properties try to reset by delete first.
- // If this fails (ex: localStorage on mobile safari) then force a reset
- // via direct assignment.
- if (!owned) {
- try {
- delete object[property];
- } catch (e) {}
- // For native code functions `delete` fails without throwing an error
- // on Chrome < 43, PhantomJS, etc.
- // Use strict equality comparison to check failures then force a reset
- // via direct assignment.
- if (object[property] === method) {
- object[property] = wrappedMethod;
- }
- } else if (hasES5Support) {
- Object.defineProperty(object, property, wrappedMethodDesc);
- }
-
- if (!hasES5Support && object[property] === method) {
- object[property] = wrappedMethod;
- }
- };
-
- method.restore.sinon = true;
-
- if (!hasES5Support) {
- mirrorProperties(method, wrappedMethod);
- }
-
- return method;
- };
-
- sinon.create = function create(proto) {
- var F = function () {};
- F.prototype = proto;
- return new F();
- };
-
- sinon.deepEqual = function deepEqual(a, b) {
- if (sinon.match && sinon.match.isMatcher(a)) {
- return a.test(b);
- }
-
- if (typeof a != "object" || typeof b != "object") {
- if (isReallyNaN(a) && isReallyNaN(b)) {
- return true;
- } else {
- return a === b;
- }
- }
-
- if (isElement(a) || isElement(b)) {
- return a === b;
- }
-
- if (a === b) {
- return true;
- }
-
- if ((a === null && b !== null) || (a !== null && b === null)) {
- return false;
- }
-
- if (a instanceof RegExp && b instanceof RegExp) {
- return (a.source === b.source) && (a.global === b.global) &&
- (a.ignoreCase === b.ignoreCase) && (a.multiline === b.multiline);
- }
-
- var aString = Object.prototype.toString.call(a);
- if (aString != Object.prototype.toString.call(b)) {
- return false;
- }
-
- if (aString == "[object Date]") {
- return a.valueOf() === b.valueOf();
- }
-
- var prop, aLength = 0, bLength = 0;
-
- if (aString == "[object Array]" && a.length !== b.length) {
- return false;
- }
-
- for (prop in a) {
- aLength += 1;
-
- if (!(prop in b)) {
- return false;
- }
-
- if (!deepEqual(a[prop], b[prop])) {
- return false;
- }
- }
-
- for (prop in b) {
- bLength += 1;
- }
-
- return aLength == bLength;
- };
-
- sinon.functionName = function functionName(func) {
- var name = func.displayName || func.name;
-
- // Use function decomposition as a last resort to get function
- // name. Does not rely on function decomposition to work - if it
- // doesn't debugging will be slightly less informative
- // (i.e. toString will say 'spy' rather than 'myFunc').
- if (!name) {
- var matches = func.toString().match(/function ([^\s\(]+)/);
- name = matches && matches[1];
- }
-
- return name;
- };
-
- sinon.functionToString = function toString() {
- if (this.getCall && this.callCount) {
- var thisValue, prop, i = this.callCount;
-
- while (i--) {
- thisValue = this.getCall(i).thisValue;
-
- for (prop in thisValue) {
- if (thisValue[prop] === this) {
- return prop;
- }
- }
- }
- }
-
- return this.displayName || "sinon fake";
- };
-
- sinon.objectKeys = function objectKeys(obj) {
- if (obj !== Object(obj)) {
- throw new TypeError("sinon.objectKeys called on a non-object");
- }
-
- var keys = [];
- var key;
- for (key in obj) {
- if (hasOwn.call(obj, key)) {
- keys.push(key);
- }
- }
-
- return keys;
- };
-
- sinon.getPropertyDescriptor = function getPropertyDescriptor(object, property) {
- var proto = object, descriptor;
- while (proto && !(descriptor = Object.getOwnPropertyDescriptor(proto, property))) {
- proto = Object.getPrototypeOf(proto);
- }
- return descriptor;
- }
-
- sinon.getConfig = function (custom) {
- var config = {};
- custom = custom || {};
- var defaults = sinon.defaultConfig;
-
- for (var prop in defaults) {
- if (defaults.hasOwnProperty(prop)) {
- config[prop] = custom.hasOwnProperty(prop) ? custom[prop] : defaults[prop];
- }
- }
-
- return config;
- };
-
- sinon.defaultConfig = {
- injectIntoThis: true,
- injectInto: null,
- properties: ["spy", "stub", "mock", "clock", "server", "requests"],
- useFakeTimers: true,
- useFakeServer: true
- };
-
- sinon.timesInWords = function timesInWords(count) {
- return count == 1 && "once" ||
- count == 2 && "twice" ||
- count == 3 && "thrice" ||
- (count || 0) + " times";
- };
-
- sinon.calledInOrder = function (spies) {
- for (var i = 1, l = spies.length; i < l; i++) {
- if (!spies[i - 1].calledBefore(spies[i]) || !spies[i].called) {
- return false;
- }
- }
-
- return true;
- };
-
- sinon.orderByFirstCall = function (spies) {
- return spies.sort(function (a, b) {
- // uuid, won't ever be equal
- var aCall = a.getCall(0);
- var bCall = b.getCall(0);
- var aId = aCall && aCall.callId || -1;
- var bId = bCall && bCall.callId || -1;
-
- return aId < bId ? -1 : 1;
- });
- };
-
- sinon.createStubInstance = function (constructor) {
- if (typeof constructor !== "function") {
- throw new TypeError("The constructor should be a function.");
- }
- return sinon.stub(sinon.create(constructor.prototype));
- };
-
- sinon.restore = function (object) {
- if (object !== null && typeof object === "object") {
- for (var prop in object) {
- if (isRestorable(object[prop])) {
- object[prop].restore();
- }
- }
- } else if (isRestorable(object)) {
- object.restore();
- }
- };
-
- return sinon;
- }
-
- var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
- var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;
-
- function loadDependencies(require, exports) {
- makeApi(exports);
- }
-
- if (isAMD) {
- define(loadDependencies);
- } else if (isNode) {
- loadDependencies(require, module.exports);
- } else if (!sinon) {
- return;
- } else {
- makeApi(sinon);
- }
-}(typeof sinon == "object" && sinon || null));
-
-/**
- * @depend util/core.js
- */
-
-(function (sinon) {
- function makeApi(sinon) {
-
- // Adapted from https://developer.mozilla.org/en/docs/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug
- var hasDontEnumBug = (function () {
- var obj = {
- constructor: function () {
- return "0";
- },
- toString: function () {
- return "1";
- },
- valueOf: function () {
- return "2";
- },
- toLocaleString: function () {
- return "3";
- },
- prototype: function () {
- return "4";
- },
- isPrototypeOf: function () {
- return "5";
- },
- propertyIsEnumerable: function () {
- return "6";
- },
- hasOwnProperty: function () {
- return "7";
- },
- length: function () {
- return "8";
- },
- unique: function () {
- return "9"
- }
- };
-
- var result = [];
- for (var prop in obj) {
- result.push(obj[prop]());
- }
- return result.join("") !== "0123456789";
- })();
-
- /* Public: Extend target in place with all (own) properties from sources in-order. Thus, last source will
- * override properties in previous sources.
- *
- * target - The Object to extend
- * sources - Objects to copy properties from.
- *
- * Returns the extended target
- */
- function extend(target /*, sources */) {
- var sources = Array.prototype.slice.call(arguments, 1),
- source, i, prop;
-
- for (i = 0; i < sources.length; i++) {
- source = sources[i];
-
- for (prop in source) {
- if (source.hasOwnProperty(prop)) {
- target[prop] = source[prop];
- }
- }
-
- // Make sure we copy (own) toString method even when in JScript with DontEnum bug
- // See https://developer.mozilla.org/en/docs/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug
- if (hasDontEnumBug && source.hasOwnProperty("toString") && source.toString !== target.toString) {
- target.toString = source.toString;
- }
- }
-
- return target;
- };
-
- sinon.extend = extend;
- return sinon.extend;
- }
-
- function loadDependencies(require, exports, module) {
- var sinon = require("./util/core");
- module.exports = makeApi(sinon);
- }
-
- var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
- var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;
-
- if (isAMD) {
- define(loadDependencies);
- } else if (isNode) {
- loadDependencies(require, module.exports, module);
- } else if (!sinon) {
- return;
- } else {
- makeApi(sinon);
- }
-}(typeof sinon == "object" && sinon || null));
-
-/**
- * @depend util/core.js
- */
-
-(function (sinon) {
- function makeApi(sinon) {
-
- function timesInWords(count) {
- switch (count) {
- case 1:
- return "once";
- case 2:
- return "twice";
- case 3:
- return "thrice";
- default:
- return (count || 0) + " times";
- }
- }
-
- sinon.timesInWords = timesInWords;
- return sinon.timesInWords;
- }
-
- function loadDependencies(require, exports, module) {
- var sinon = require("./util/core");
- module.exports = makeApi(sinon);
- }
-
- var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
- var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;
-
- if (isAMD) {
- define(loadDependencies);
- } else if (isNode) {
- loadDependencies(require, module.exports, module);
- } else if (!sinon) {
- return;
- } else {
- makeApi(sinon);
- }
-}(typeof sinon == "object" && sinon || null));
-
-/**
- * @depend util/core.js
- */
-/**
- * Format functions
- *
- * @author Christian Johansen (christian at cjohansen.no)
- * @license BSD
- *
- * Copyright (c) 2010-2014 Christian Johansen
- */
-
-(function (sinon, formatio) {
- function makeApi(sinon) {
- function typeOf(value) {
- if (value === null) {
- return "null";
- } else if (value === undefined) {
- return "undefined";
- }
- var string = Object.prototype.toString.call(value);
- return string.substring(8, string.length - 1).toLowerCase();
- };
-
- sinon.typeOf = typeOf;
- return sinon.typeOf;
- }
-
- function loadDependencies(require, exports, module) {
- var sinon = require("./util/core");
- module.exports = makeApi(sinon);
- }
-
- var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
- var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;
-
- if (isAMD) {
- define(loadDependencies);
- } else if (isNode) {
- loadDependencies(require, module.exports, module);
- } else if (!sinon) {
- return;
- } else {
- makeApi(sinon);
- }
-}(
- (typeof sinon == "object" && sinon || null),
- (typeof formatio == "object" && formatio)
-));
-
-/**
- * @depend util/core.js
- * @depend typeOf.js
- */
-/*jslint eqeqeq: false, onevar: false, plusplus: false*/
-/*global module, require, sinon*/
-/**
- * Match functions
- *
- * @author Maximilian Antoni (mail at maxantoni.de)
- * @license BSD
- *
- * Copyright (c) 2012 Maximilian Antoni
- */
-
-(function (sinon) {
- function makeApi(sinon) {
- function assertType(value, type, name) {
- var actual = sinon.typeOf(value);
- if (actual !== type) {
- throw new TypeError("Expected type of " + name + " to be " +
- type + ", but was " + actual);
- }
- }
-
- var matcher = {
- toString: function () {
- return this.message;
- }
- };
-
- function isMatcher(object) {
- return matcher.isPrototypeOf(object);
- }
-
- function matchObject(expectation, actual) {
- if (actual === null || actual === undefined) {
- return false;
- }
- for (var key in expectation) {
- if (expectation.hasOwnProperty(key)) {
- var exp = expectation[key];
- var act = actual[key];
- if (match.isMatcher(exp)) {
- if (!exp.test(act)) {
- return false;
- }
- } else if (sinon.typeOf(exp) === "object") {
- if (!matchObject(exp, act)) {
- return false;
- }
- } else if (!sinon.deepEqual(exp, act)) {
- return false;
- }
- }
- }
- return true;
- }
-
- matcher.or = function (m2) {
- if (!arguments.length) {
- throw new TypeError("Matcher expected");
- } else if (!isMatcher(m2)) {
- m2 = match(m2);
- }
- var m1 = this;
- var or = sinon.create(matcher);
- or.test = function (actual) {
- return m1.test(actual) || m2.test(actual);
- };
- or.message = m1.message + ".or(" + m2.message + ")";
- return or;
- };
-
- matcher.and = function (m2) {
- if (!arguments.length) {
- throw new TypeError("Matcher expected");
- } else if (!isMatcher(m2)) {
- m2 = match(m2);
- }
- var m1 = this;
- var and = sinon.create(matcher);
- and.test = function (actual) {
- return m1.test(actual) && m2.test(actual);
- };
- and.message = m1.message + ".and(" + m2.message + ")";
- return and;
- };
-
- var match = function (expectation, message) {
- var m = sinon.create(matcher);
- var type = sinon.typeOf(expectation);
- switch (type) {
- case "object":
- if (typeof expectation.test === "function") {
- m.test = function (actual) {
- return expectation.test(actual) === true;
- };
- m.message = "match(" + sinon.functionName(expectation.test) + ")";
- return m;
- }
- var str = [];
- for (var key in expectation) {
- if (expectation.hasOwnProperty(key)) {
- str.push(key + ": " + expectation[key]);
- }
- }
- m.test = function (actual) {
- return matchObject(expectation, actual);
- };
- m.message = "match(" + str.join(", ") + ")";
- break;
- case "number":
- m.test = function (actual) {
- return expectation == actual;
- };
- break;
- case "string":
- m.test = function (actual) {
- if (typeof actual !== "string") {
- return false;
- }
- return actual.indexOf(expectation) !== -1;
- };
- m.message = "match(\"" + expectation + "\")";
- break;
- case "regexp":
- m.test = function (actual) {
- if (typeof actual !== "string") {
- return false;
- }
- return expectation.test(actual);
- };
- break;
- case "function":
- m.test = expectation;
- if (message) {
- m.message = message;
- } else {
- m.message = "match(" + sinon.functionName(expectation) + ")";
- }
- break;
- default:
- m.test = function (actual) {
- return sinon.deepEqual(expectation, actual);
- };
- }
- if (!m.message) {
- m.message = "match(" + expectation + ")";
- }
- return m;
- };
-
- match.isMatcher = isMatcher;
-
- match.any = match(function () {
- return true;
- }, "any");
-
- match.defined = match(function (actual) {
- return actual !== null && actual !== undefined;
- }, "defined");
-
- match.truthy = match(function (actual) {
- return !!actual;
- }, "truthy");
-
- match.falsy = match(function (actual) {
- return !actual;
- }, "falsy");
-
- match.same = function (expectation) {
- return match(function (actual) {
- return expectation === actual;
- }, "same(" + expectation + ")");
- };
-
- match.typeOf = function (type) {
- assertType(type, "string", "type");
- return match(function (actual) {
- return sinon.typeOf(actual) === type;
- }, "typeOf(\"" + type + "\")");
- };
-
- match.instanceOf = function (type) {
- assertType(type, "function", "type");
- return match(function (actual) {
- return actual instanceof type;
- }, "instanceOf(" + sinon.functionName(type) + ")");
- };
-
- function createPropertyMatcher(propertyTest, messagePrefix) {
- return function (property, value) {
- assertType(property, "string", "property");
- var onlyProperty = arguments.length === 1;
- var message = messagePrefix + "(\"" + property + "\"";
- if (!onlyProperty) {
- message += ", " + value;
- }
- message += ")";
- return match(function (actual) {
- if (actual === undefined || actual === null ||
- !propertyTest(actual, property)) {
- return false;
- }
- return onlyProperty || sinon.deepEqual(value, actual[property]);
- }, message);
- };
- }
-
- match.has = createPropertyMatcher(function (actual, property) {
- if (typeof actual === "object") {
- return property in actual;
- }
- return actual[property] !== undefined;
- }, "has");
-
- match.hasOwn = createPropertyMatcher(function (actual, property) {
- return actual.hasOwnProperty(property);
- }, "hasOwn");
-
- match.bool = match.typeOf("boolean");
- match.number = match.typeOf("number");
- match.string = match.typeOf("string");
- match.object = match.typeOf("object");
- match.func = match.typeOf("function");
- match.array = match.typeOf("array");
- match.regexp = match.typeOf("regexp");
- match.date = match.typeOf("date");
-
- sinon.match = match;
- return match;
- }
-
- var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
- var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;
-
- function loadDependencies(require, exports, module) {
- var sinon = require("./util/core");
- require("./typeOf");
- module.exports = makeApi(sinon);
- }
-
- if (isAMD) {
- define(loadDependencies);
- } else if (isNode) {
- loadDependencies(require, module.exports, module);
- } else if (!sinon) {
- return;
- } else {
- makeApi(sinon);
- }
-}(typeof sinon == "object" && sinon || null));
-
-/**
- * @depend util/core.js
- */
-/**
- * Format functions
- *
- * @author Christian Johansen (christian at cjohansen.no)
- * @license BSD
- *
- * Copyright (c) 2010-2014 Christian Johansen
- */
-
-(function (sinon, formatio) {
- function makeApi(sinon) {
- function valueFormatter(value) {
- return "" + value;
- }
-
- function getFormatioFormatter() {
- var formatter = formatio.configure({
- quoteStrings: false,
- limitChildrenCount: 250
- });
-
- function format() {
- return formatter.ascii.apply(formatter, arguments);
- };
-
- return format;
- }
-
- function getNodeFormatter(value) {
- function format(value) {
- return typeof value == "object" && value.toString === Object.prototype.toString ? util.inspect(value) : value;
- };
-
- try {
- var util = require("util");
- } catch (e) {
- /* Node, but no util module - would be very old, but better safe than sorry */
- }
-
- return util ? format : valueFormatter;
- }
-
- var isNode = typeof module !== "undefined" && module.exports && typeof require == "function",
- formatter;
-
- if (isNode) {
- try {
- formatio = require("formatio");
- } catch (e) {}
- }
-
- if (formatio) {
- formatter = getFormatioFormatter()
- } else if (isNode) {
- formatter = getNodeFormatter();
- } else {
- formatter = valueFormatter;
- }
-
- sinon.format = formatter;
- return sinon.format;
- }
-
- function loadDependencies(require, exports, module) {
- var sinon = require("./util/core");
- module.exports = makeApi(sinon);
- }
-
- var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
- var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;
-
- if (isAMD) {
- define(loadDependencies);
- } else if (isNode) {
- loadDependencies(require, module.exports, module);
- } else if (!sinon) {
- return;
- } else {
- makeApi(sinon);
- }
-}(
- (typeof sinon == "object" && sinon || null),
- (typeof formatio == "object" && formatio)
-));
-
-/**
- * @depend util/core.js
- * @depend match.js
- * @depend format.js
- */
-/**
- * Spy calls
- *
- * @author Christian Johansen (christian at cjohansen.no)
- * @author Maximilian Antoni (mail at maxantoni.de)
- * @license BSD
- *
- * Copyright (c) 2010-2013 Christian Johansen
- * Copyright (c) 2013 Maximilian Antoni
- */
-
-(function (sinon) {
- function makeApi(sinon) {
- function throwYieldError(proxy, text, args) {
- var msg = sinon.functionName(proxy) + text;
- if (args.length) {
- msg += " Received [" + slice.call(args).join(", ") + "]";
- }
- throw new Error(msg);
- }
-
- var slice = Array.prototype.slice;
-
- var callProto = {
- calledOn: function calledOn(thisValue) {
- if (sinon.match && sinon.match.isMatcher(thisValue)) {
- return thisValue.test(this.thisValue);
- }
- return this.thisValue === thisValue;
- },
-
- calledWith: function calledWith() {
- var l = arguments.length;
- if (l > this.args.length) {
- return false;
- }
- for (var i = 0; i < l; i += 1) {
- if (!sinon.deepEqual(arguments[i], this.args[i])) {
- return false;
- }
- }
-
- return true;
- },
-
- calledWithMatch: function calledWithMatch() {
- var l = arguments.length;
- if (l > this.args.length) {
- return false;
- }
- for (var i = 0; i < l; i += 1) {
- var actual = this.args[i];
- var expectation = arguments[i];
- if (!sinon.match || !sinon.match(expectation).test(actual)) {
- return false;
- }
- }
- return true;
- },
-
- calledWithExactly: function calledWithExactly() {
- return arguments.length == this.args.length &&
- this.calledWith.apply(this, arguments);
- },
-
- notCalledWith: function notCalledWith() {
- return !this.calledWith.apply(this, arguments);
- },
-
- notCalledWithMatch: function notCalledWithMatch() {
- return !this.calledWithMatch.apply(this, arguments);
- },
-
- returned: function returned(value) {
- return sinon.deepEqual(value, this.returnValue);
- },
-
- threw: function threw(error) {
- if (typeof error === "undefined" || !this.exception) {
- return !!this.exception;
- }
-
- return this.exception === error || this.exception.name === error;
- },
-
- calledWithNew: function calledWithNew() {
- return this.proxy.prototype && this.thisValue instanceof this.proxy;
- },
-
- calledBefore: function (other) {
- return this.callId < other.callId;
- },
-
- calledAfter: function (other) {
- return this.callId > other.callId;
- },
-
- callArg: function (pos) {
- this.args[pos]();
- },
-
- callArgOn: function (pos, thisValue) {
- this.args[pos].apply(thisValue);
- },
-
- callArgWith: function (pos) {
- this.callArgOnWith.apply(this, [pos, null].concat(slice.call(arguments, 1)));
- },
-
- callArgOnWith: function (pos, thisValue) {
- var args = slice.call(arguments, 2);
- this.args[pos].apply(thisValue, args);
- },
-
- yield: function () {
- this.yieldOn.apply(this, [null].concat(slice.call(arguments, 0)));
- },
-
- yieldOn: function (thisValue) {
- var args = this.args;
- for (var i = 0, l = args.length; i < l; ++i) {
- if (typeof args[i] === "function") {
- args[i].apply(thisValue, slice.call(arguments, 1));
- return;
- }
- }
- throwYieldError(this.proxy, " cannot yield since no callback was passed.", args);
- },
-
- yieldTo: function (prop) {
- this.yieldToOn.apply(this, [prop, null].concat(slice.call(arguments, 1)));
- },
-
- yieldToOn: function (prop, thisValue) {
- var args = this.args;
- for (var i = 0, l = args.length; i < l; ++i) {
- if (args[i] && typeof args[i][prop] === "function") {
- args[i][prop].apply(thisValue, slice.call(arguments, 2));
- return;
- }
- }
- throwYieldError(this.proxy, " cannot yield to '" + prop +
- "' since no callback was passed.", args);
- },
-
- toString: function () {
- var callStr = this.proxy.toString() + "(";
- var args = [];
-
- for (var i = 0, l = this.args.length; i < l; ++i) {
- args.push(sinon.format(this.args[i]));
- }
-
- callStr = callStr + args.join(", ") + ")";
-
- if (typeof this.returnValue != "undefined") {
- callStr += " => " + sinon.format(this.returnValue);
- }
-
- if (this.exception) {
- callStr += " !" + this.exception.name;
-
- if (this.exception.message) {
- callStr += "(" + this.exception.message + ")";
- }
- }
-
- return callStr;
- }
- };
-
- callProto.invokeCallback = callProto.yield;
-
- function createSpyCall(spy, thisValue, args, returnValue, exception, id) {
- if (typeof id !== "number") {
- throw new TypeError("Call id is not a number");
- }
- var proxyCall = sinon.create(callProto);
- proxyCall.proxy = spy;
- proxyCall.thisValue = thisValue;
- proxyCall.args = args;
- proxyCall.returnValue = returnValue;
- proxyCall.exception = exception;
- proxyCall.callId = id;
-
- return proxyCall;
- }
- createSpyCall.toString = callProto.toString; // used by mocks
-
- sinon.spyCall = createSpyCall;
- return createSpyCall;
- }
-
- var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
- var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;
-
- function loadDependencies(require, exports, module) {
- var sinon = require("./util/core");
- require("./match");
- require("./format");
- module.exports = makeApi(sinon);
- }
-
- if (isAMD) {
- define(loadDependencies);
- } else if (isNode) {
- loadDependencies(require, module.exports, module);
- } else if (!sinon) {
- return;
- } else {
- makeApi(sinon);
- }
-}(typeof sinon == "object" && sinon || null));
-
-/**
- * @depend times_in_words.js
- * @depend util/core.js
- * @depend extend.js
- * @depend call.js
- * @depend format.js
- */
-/**
- * Spy functions
- *
- * @author Christian Johansen (christian at cjohansen.no)
- * @license BSD
- *
- * Copyright (c) 2010-2013 Christian Johansen
- */
-
-(function (sinon) {
-
- function makeApi(sinon) {
- var push = Array.prototype.push;
- var slice = Array.prototype.slice;
- var callId = 0;
-
- function spy(object, property, types) {
- if (!property && typeof object == "function") {
- return spy.create(object);
- }
-
- if (!object && !property) {
- return spy.create(function () { });
- }
-
- if (types) {
- var methodDesc = sinon.getPropertyDescriptor(object, property);
- for (var i = 0; i < types.length; i++) {
- methodDesc[types[i]] = spy.create(methodDesc[types[i]]);
- }
- return sinon.wrapMethod(object, property, methodDesc);
- } else {
- var method = object[property];
- return sinon.wrapMethod(object, property, spy.create(method));
- }
- }
-
- function matchingFake(fakes, args, strict) {
- if (!fakes) {
- return;
- }
-
- for (var i = 0, l = fakes.length; i < l; i++) {
- if (fakes[i].matches(args, strict)) {
- return fakes[i];
- }
- }
- }
-
- function incrementCallCount() {
- this.called = true;
- this.callCount += 1;
- this.notCalled = false;
- this.calledOnce = this.callCount == 1;
- this.calledTwice = this.callCount == 2;
- this.calledThrice = this.callCount == 3;
- }
-
- function createCallProperties() {
- this.firstCall = this.getCall(0);
- this.secondCall = this.getCall(1);
- this.thirdCall = this.getCall(2);
- this.lastCall = this.getCall(this.callCount - 1);
- }
-
- var vars = "a,b,c,d,e,f,g,h,i,j,k,l";
- function createProxy(func, proxyLength) {
- // Retain the function length:
- var p;
- if (proxyLength) {
- eval("p = (function proxy(" + vars.substring(0, proxyLength * 2 - 1) +
- ") { return p.invoke(func, this, slice.call(arguments)); });");
- } else {
- p = function proxy() {
- return p.invoke(func, this, slice.call(arguments));
- };
- }
- return p;
- }
-
- var uuid = 0;
-
- // Public API
- var spyApi = {
- reset: function () {
- if (this.invoking) {
- var err = new Error("Cannot reset Sinon function while invoking it. " +
- "Move the call to .reset outside of the callback.");
- err.name = "InvalidResetException";
- throw err;
- }
-
- this.called = false;
- this.notCalled = true;
- this.calledOnce = false;
- this.calledTwice = false;
- this.calledThrice = false;
- this.callCount = 0;
- this.firstCall = null;
- this.secondCall = null;
- this.thirdCall = null;
- this.lastCall = null;
- this.args = [];
- this.returnValues = [];
- this.thisValues = [];
- this.exceptions = [];
- this.callIds = [];
- if (this.fakes) {
- for (var i = 0; i < this.fakes.length; i++) {
- this.fakes[i].reset();
- }
- }
-
- return this;
- },
-
- create: function create(func, spyLength) {
- var name;
-
- if (typeof func != "function") {
- func = function () { };
- } else {
- name = sinon.functionName(func);
- }
-
- if (!spyLength) {
- spyLength = func.length;
- }
-
- var proxy = createProxy(func, spyLength);
-
- sinon.extend(proxy, spy);
- delete proxy.create;
- sinon.extend(proxy, func);
-
- proxy.reset();
- proxy.prototype = func.prototype;
- proxy.displayName = name || "spy";
- proxy.toString = sinon.functionToString;
- proxy.instantiateFake = sinon.spy.create;
- proxy.id = "spy#" + uuid++;
-
- return proxy;
- },
-
- invoke: function invoke(func, thisValue, args) {
- var matching = matchingFake(this.fakes, args);
- var exception, returnValue;
-
- incrementCallCount.call(this);
- push.call(this.thisValues, thisValue);
- push.call(this.args, args);
- push.call(this.callIds, callId++);
-
- // Make call properties available from within the spied function:
- createCallProperties.call(this);
-
- try {
- this.invoking = true;
-
- if (matching) {
- returnValue = matching.invoke(func, thisValue, args);
- } else {
- returnValue = (this.func || func).apply(thisValue, args);
- }
-
- var thisCall = this.getCall(this.callCount - 1);
- if (thisCall.calledWithNew() && typeof returnValue !== "object") {
- returnValue = thisValue;
- }
- } catch (e) {
- exception = e;
- } finally {
- delete this.invoking;
- }
-
- push.call(this.exceptions, exception);
- push.call(this.returnValues, returnValue);
-
- // Make return value and exception available in the calls:
- createCallProperties.call(this);
-
- if (exception !== undefined) {
- throw exception;
- }
-
- return returnValue;
- },
-
- named: function named(name) {
- this.displayName = name;
- return this;
- },
-
- getCall: function getCall(i) {
- if (i < 0 || i >= this.callCount) {
- return null;
- }
-
- return sinon.spyCall(this, this.thisValues[i], this.args[i],
- this.returnValues[i], this.exceptions[i],
- this.callIds[i]);
- },
-
- getCalls: function () {
- var calls = [];
- var i;
-
- for (i = 0; i < this.callCount; i++) {
- calls.push(this.getCall(i));
- }
-
- return calls;
- },
-
- calledBefore: function calledBefore(spyFn) {
- if (!this.called) {
- return false;
- }
-
- if (!spyFn.called) {
- return true;
- }
-
- return this.callIds[0] < spyFn.callIds[spyFn.callIds.length - 1];
- },
-
- calledAfter: function calledAfter(spyFn) {
- if (!this.called || !spyFn.called) {
- return false;
- }
-
- return this.callIds[this.callCount - 1] > spyFn.callIds[spyFn.callCount - 1];
- },
-
- withArgs: function () {
- var args = slice.call(arguments);
-
- if (this.fakes) {
- var match = matchingFake(this.fakes, args, true);
-
- if (match) {
- return match;
- }
- } else {
- this.fakes = [];
- }
-
- var original = this;
- var fake = this.instantiateFake();
- fake.matchingAguments = args;
- fake.parent = this;
- push.call(this.fakes, fake);
-
- fake.withArgs = function () {
- return original.withArgs.apply(original, arguments);
- };
-
- for (var i = 0; i < this.args.length; i++) {
- if (fake.matches(this.args[i])) {
- incrementCallCount.call(fake);
- push.call(fake.thisValues, this.thisValues[i]);
- push.call(fake.args, this.args[i]);
- push.call(fake.returnValues, this.returnValues[i]);
- push.call(fake.exceptions, this.exceptions[i]);
- push.call(fake.callIds, this.callIds[i]);
- }
- }
- createCallProperties.call(fake);
-
- return fake;
- },
-
- matches: function (args, strict) {
- var margs = this.matchingAguments;
-
- if (margs.length <= args.length &&
- sinon.deepEqual(margs, args.slice(0, margs.length))) {
- return !strict || margs.length == args.length;
- }
- },
-
- printf: function (format) {
- var spy = this;
- var args = slice.call(arguments, 1);
- var formatter;
-
- return (format || "").replace(/%(.)/g, function (match, specifyer) {
- formatter = spyApi.formatters[specifyer];
-
- if (typeof formatter == "function") {
- return formatter.call(null, spy, args);
- } else if (!isNaN(parseInt(specifyer, 10))) {
- return sinon.format(args[specifyer - 1]);
- }
-
- return "%" + specifyer;
- });
- }
- };
-
- function delegateToCalls(method, matchAny, actual, notCalled) {
- spyApi[method] = function () {
- if (!this.called) {
- if (notCalled) {
- return notCalled.apply(this, arguments);
- }
- return false;
- }
-
- var currentCall;
- var matches = 0;
-
- for (var i = 0, l = this.callCount; i < l; i += 1) {
- currentCall = this.getCall(i);
-
- if (currentCall[actual || method].apply(currentCall, arguments)) {
- matches += 1;
-
- if (matchAny) {
- return true;
- }
- }
- }
-
- return matches === this.callCount;
- };
- }
-
- delegateToCalls("calledOn", true);
- delegateToCalls("alwaysCalledOn", false, "calledOn");
- delegateToCalls("calledWith", true);
- delegateToCalls("calledWithMatch", true);
- delegateToCalls("alwaysCalledWith", false, "calledWith");
- delegateToCalls("alwaysCalledWithMatch", false, "calledWithMatch");
- delegateToCalls("calledWithExactly", true);
- delegateToCalls("alwaysCalledWithExactly", false, "calledWithExactly");
- delegateToCalls("neverCalledWith", false, "notCalledWith",
- function () { return true; });
- delegateToCalls("neverCalledWithMatch", false, "notCalledWithMatch",
- function () { return true; });
- delegateToCalls("threw", true);
- delegateToCalls("alwaysThrew", false, "threw");
- delegateToCalls("returned", true);
- delegateToCalls("alwaysReturned", false, "returned");
- delegateToCalls("calledWithNew", true);
- delegateToCalls("alwaysCalledWithNew", false, "calledWithNew");
- delegateToCalls("callArg", false, "callArgWith", function () {
- throw new Error(this.toString() + " cannot call arg since it was not yet invoked.");
- });
- spyApi.callArgWith = spyApi.callArg;
- delegateToCalls("callArgOn", false, "callArgOnWith", function () {
- throw new Error(this.toString() + " cannot call arg since it was not yet invoked.");
- });
- spyApi.callArgOnWith = spyApi.callArgOn;
- delegateToCalls("yield", false, "yield", function () {
- throw new Error(this.toString() + " cannot yield since it was not yet invoked.");
- });
- // "invokeCallback" is an alias for "yield" since "yield" is invalid in strict mode.
- spyApi.invokeCallback = spyApi.yield;
- delegateToCalls("yieldOn", false, "yieldOn", function () {
- throw new Error(this.toString() + " cannot yield since it was not yet invoked.");
- });
- delegateToCalls("yieldTo", false, "yieldTo", function (property) {
- throw new Error(this.toString() + " cannot yield to '" + property +
- "' since it was not yet invoked.");
- });
- delegateToCalls("yieldToOn", false, "yieldToOn", function (property) {
- throw new Error(this.toString() + " cannot yield to '" + property +
- "' since it was not yet invoked.");
- });
-
- spyApi.formatters = {
- c: function (spy) {
- return sinon.timesInWords(spy.callCount);
- },
-
- n: function (spy) {
- return spy.toString();
- },
-
- C: function (spy) {
- var calls = [];
-
- for (var i = 0, l = spy.callCount; i < l; ++i) {
- var stringifiedCall = " " + spy.getCall(i).toString();
- if (/\n/.test(calls[i - 1])) {
- stringifiedCall = "\n" + stringifiedCall;
- }
- push.call(calls, stringifiedCall);
- }
-
- return calls.length > 0 ? "\n" + calls.join("\n") : "";
- },
-
- t: function (spy) {
- var objects = [];
-
- for (var i = 0, l = spy.callCount; i < l; ++i) {
- push.call(objects, sinon.format(spy.thisValues[i]));
- }
-
- return objects.join(", ");
- },
-
- "*": function (spy, args) {
- var formatted = [];
-
- for (var i = 0, l = args.length; i < l; ++i) {
- push.call(formatted, sinon.format(args[i]));
- }
-
- return formatted.join(", ");
- }
- };
-
- sinon.extend(spy, spyApi);
-
- spy.spyCall = sinon.spyCall;
- sinon.spy = spy;
-
- return spy;
- }
-
- var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
- var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;
-
- function loadDependencies(require, exports, module) {
- var sinon = require("./util/core");
- require("./call");
- require("./extend");
- require("./times_in_words");
- require("./format");
- module.exports = makeApi(sinon);
- }
-
- if (isAMD) {
- define(loadDependencies);
- } else if (isNode) {
- loadDependencies(require, module.exports, module);
- } else if (!sinon) {
- return;
- } else {
- makeApi(sinon);
- }
-}(typeof sinon == "object" && sinon || null));
-
-/**
- * @depend util/core.js
- * @depend extend.js
- */
-/**
- * Stub behavior
- *
- * @author Christian Johansen (christian at cjohansen.no)
- * @author Tim Fischbach (mail at timfischbach.de)
- * @license BSD
- *
- * Copyright (c) 2010-2013 Christian Johansen
- */
-
-(function (sinon) {
- var slice = Array.prototype.slice;
- var join = Array.prototype.join;
- var useLeftMostCallback = -1;
- var useRightMostCallback = -2;
-
- var nextTick = (function () {
- if (typeof process === "object" && typeof process.nextTick === "function") {
- return process.nextTick;
- } else if (typeof setImmediate === "function") {
- return setImmediate;
- } else {
- return function (callback) {
- setTimeout(callback, 0);
- };
- }
- })();
-
- function throwsException(error, message) {
- if (typeof error == "string") {
- this.exception = new Error(message || "");
- this.exception.name = error;
- } else if (!error) {
- this.exception = new Error("Error");
- } else {
- this.exception = error;
- }
-
- return this;
- }
-
- function getCallback(behavior, args) {
- var callArgAt = behavior.callArgAt;
-
- if (callArgAt >= 0) {
- return args[callArgAt];
- }
-
- var argumentList;
-
- if (callArgAt === useLeftMostCallback) {
- argumentList = args;
- }
-
- if (callArgAt === useRightMostCallback) {
- argumentList = slice.call(args).reverse();
- }
-
- var callArgProp = behavior.callArgProp;
-
- for (var i = 0, l = argumentList.length; i < l; ++i) {
- if (!callArgProp && typeof argumentList[i] == "function") {
- return argumentList[i];
- }
-
- if (callArgProp && argumentList[i] &&
- typeof argumentList[i][callArgProp] == "function") {
- return argumentList[i][callArgProp];
- }
- }
-
- return null;
- }
-
- function makeApi(sinon) {
- function getCallbackError(behavior, func, args) {
- if (behavior.callArgAt < 0) {
- var msg;
-
- if (behavior.callArgProp) {
- msg = sinon.functionName(behavior.stub) +
- " expected to yield to '" + behavior.callArgProp +
- "', but no object with such a property was passed.";
- } else {
- msg = sinon.functionName(behavior.stub) +
- " expected to yield, but no callback was passed.";
- }
-
- if (args.length > 0) {
- msg += " Received [" + join.call(args, ", ") + "]";
- }
-
- return msg;
- }
-
- return "argument at index " + behavior.callArgAt + " is not a function: " + func;
- }
-
- function callCallback(behavior, args) {
- if (typeof behavior.callArgAt == "number") {
- var func = getCallback(behavior, args);
-
- if (typeof func != "function") {
- throw new TypeError(getCallbackError(behavior, func, args));
- }
-
- if (behavior.callbackAsync) {
- nextTick(function () {
- func.apply(behavior.callbackContext, behavior.callbackArguments);
- });
- } else {
- func.apply(behavior.callbackContext, behavior.callbackArguments);
- }
- }
- }
-
- var proto = {
- create: function create(stub) {
- var behavior = sinon.extend({}, sinon.behavior);
- delete behavior.create;
- behavior.stub = stub;
-
- return behavior;
- },
-
- isPresent: function isPresent() {
- return (typeof this.callArgAt == "number" ||
- this.exception ||
- typeof this.returnArgAt == "number" ||
- this.returnThis ||
- this.returnValueDefined);
- },
-
- invoke: function invoke(context, args) {
- callCallback(this, args);
-
- if (this.exception) {
- throw this.exception;
- } else if (typeof this.returnArgAt == "number") {
- return args[this.returnArgAt];
- } else if (this.returnThis) {
- return context;
- }
-
- return this.returnValue;
- },
-
- onCall: function onCall(index) {
- return this.stub.onCall(index);
- },
-
- onFirstCall: function onFirstCall() {
- return this.stub.onFirstCall();
- },
-
- onSecondCall: function onSecondCall() {
- return this.stub.onSecondCall();
- },
-
- onThirdCall: function onThirdCall() {
- return this.stub.onThirdCall();
- },
-
- withArgs: function withArgs(/* arguments */) {
- throw new Error("Defining a stub by invoking \"stub.onCall(...).withArgs(...)\" is not supported. " +
- "Use \"stub.withArgs(...).onCall(...)\" to define sequential behavior for calls with certain arguments.");
- },
-
- callsArg: function callsArg(pos) {
- if (typeof pos != "number") {
- throw new TypeError("argument index is not number");
- }
-
- this.callArgAt = pos;
- this.callbackArguments = [];
- this.callbackContext = undefined;
- this.callArgProp = undefined;
- this.callbackAsync = false;
-
- return this;
- },
-
- callsArgOn: function callsArgOn(pos, context) {
- if (typeof pos != "number") {
- throw new TypeError("argument index is not number");
- }
- if (typeof context != "object") {
- throw new TypeError("argument context is not an object");
- }
-
- this.callArgAt = pos;
- this.callbackArguments = [];
- this.callbackContext = context;
- this.callArgProp = undefined;
- this.callbackAsync = false;
-
- return this;
- },
-
- callsArgWith: function callsArgWith(pos) {
- if (typeof pos != "number") {
- throw new TypeError("argument index is not number");
- }
-
- this.callArgAt = pos;
- this.callbackArguments = slice.call(arguments, 1);
- this.callbackContext = undefined;
- this.callArgProp = undefined;
- this.callbackAsync = false;
-
- return this;
- },
-
- callsArgOnWith: function callsArgWith(pos, context) {
- if (typeof pos != "number") {
- throw new TypeError("argument index is not number");
- }
- if (typeof context != "object") {
- throw new TypeError("argument context is not an object");
- }
-
- this.callArgAt = pos;
- this.callbackArguments = slice.call(arguments, 2);
- this.callbackContext = context;
- this.callArgProp = undefined;
- this.callbackAsync = false;
-
- return this;
- },
-
- yields: function () {
- this.callArgAt = useLeftMostCallback;
- this.callbackArguments = slice.call(arguments, 0);
- this.callbackContext = undefined;
- this.callArgProp = undefined;
- this.callbackAsync = false;
-
- return this;
- },
-
- yieldsRight: function () {
- this.callArgAt = useRightMostCallback;
- this.callbackArguments = slice.call(arguments, 0);
- this.callbackContext = undefined;
- this.callArgProp = undefined;
- this.callbackAsync = false;
-
- return this;
- },
-
- yieldsOn: function (context) {
- if (typeof context != "object") {
- throw new TypeError("argument context is not an object");
- }
-
- this.callArgAt = useLeftMostCallback;
- this.callbackArguments = slice.call(arguments, 1);
- this.callbackContext = context;
- this.callArgProp = undefined;
- this.callbackAsync = false;
-
- return this;
- },
-
- yieldsTo: function (prop) {
- this.callArgAt = useLeftMostCallback;
- this.callbackArguments = slice.call(arguments, 1);
- this.callbackContext = undefined;
- this.callArgProp = prop;
- this.callbackAsync = false;
-
- return this;
- },
-
- yieldsToOn: function (prop, context) {
- if (typeof context != "object") {
- throw new TypeError("argument context is not an object");
- }
-
- this.callArgAt = useLeftMostCallback;
- this.callbackArguments = slice.call(arguments, 2);
- this.callbackContext = context;
- this.callArgProp = prop;
- this.callbackAsync = false;
-
- return this;
- },
-
- throws: throwsException,
- throwsException: throwsException,
-
- returns: function returns(value) {
- this.returnValue = value;
- this.returnValueDefined = true;
-
- return this;
- },
-
- returnsArg: function returnsArg(pos) {
- if (typeof pos != "number") {
- throw new TypeError("argument index is not number");
- }
-
- this.returnArgAt = pos;
-
- return this;
- },
-
- returnsThis: function returnsThis() {
- this.returnThis = true;
-
- return this;
- }
- };
-
- // create asynchronous versions of callsArg* and yields* methods
- for (var method in proto) {
- // need to avoid creating anotherasync versions of the newly added async methods
- if (proto.hasOwnProperty(method) &&
- method.match(/^(callsArg|yields)/) &&
- !method.match(/Async/)) {
- proto[method + "Async"] = (function (syncFnName) {
- return function () {
- var result = this[syncFnName].apply(this, arguments);
- this.callbackAsync = true;
- return result;
- };
- })(method);
- }
- }
-
- sinon.behavior = proto;
- return proto;
- }
-
- var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
- var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;
-
- function loadDependencies(require, exports, module) {
- var sinon = require("./util/core");
- require("./extend");
- module.exports = makeApi(sinon);
- }
-
- if (isAMD) {
- define(loadDependencies);
- } else if (isNode) {
- loadDependencies(require, module.exports, module);
- } else if (!sinon) {
- return;
- } else {
- makeApi(sinon);
- }
-}(typeof sinon == "object" && sinon || null));
-
-/**
- * @depend util/core.js
- * @depend extend.js
- * @depend spy.js
- * @depend behavior.js
- */
-/**
- * Stub functions
- *
- * @author Christian Johansen (christian at cjohansen.no)
- * @license BSD
- *
- * Copyright (c) 2010-2013 Christian Johansen
- */
-
-(function (sinon) {
- function makeApi(sinon) {
- function stub(object, property, func) {
- if (!!func && typeof func != "function" && typeof func != "object") {
- throw new TypeError("Custom stub should be a function or a property descriptor");
- }
-
- var wrapper;
-
- if (func) {
- if (typeof func == "function") {
- wrapper = sinon.spy && sinon.spy.create ? sinon.spy.create(func) : func;
- } else {
- wrapper = func;
- if (sinon.spy && sinon.spy.create) {
- var types = sinon.objectKeys(wrapper);
- for (var i = 0; i < types.length; i++) {
- wrapper[types[i]] = sinon.spy.create(wrapper[types[i]]);
- }
- }
- }
- } else {
- var stubLength = 0;
- if (typeof object == "object" && typeof object[property] == "function") {
- stubLength = object[property].length;
- }
- wrapper = stub.create(stubLength);
- }
-
- if (!object && typeof property === "undefined") {
- return sinon.stub.create();
- }
-
- if (typeof property === "undefined" && typeof object == "object") {
- for (var prop in object) {
- if (typeof object[prop] === "function") {
- stub(object, prop);
- }
- }
-
- return object;
- }
-
- return sinon.wrapMethod(object, property, wrapper);
- }
-
- function getDefaultBehavior(stub) {
- return stub.defaultBehavior || getParentBehaviour(stub) || sinon.behavior.create(stub);
- }
-
- function getParentBehaviour(stub) {
- return (stub.parent && getCurrentBehavior(stub.parent));
- }
-
- function getCurrentBehavior(stub) {
- var behavior = stub.behaviors[stub.callCount - 1];
- return behavior && behavior.isPresent() ? behavior : getDefaultBehavior(stub);
- }
-
- var uuid = 0;
-
- var proto = {
- create: function create(stubLength) {
- var functionStub = function () {
- return getCurrentBehavior(functionStub).invoke(this, arguments);
- };
-
- functionStub.id = "stub#" + uuid++;
- var orig = functionStub;
- functionStub = sinon.spy.create(functionStub, stubLength);
- functionStub.func = orig;
-
- sinon.extend(functionStub, stub);
- functionStub.instantiateFake = sinon.stub.create;
- functionStub.displayName = "stub";
- functionStub.toString = sinon.functionToString;
-
- functionStub.defaultBehavior = null;
- functionStub.behaviors = [];
-
- return functionStub;
- },
-
- resetBehavior: function () {
- var i;
-
- this.defaultBehavior = null;
- this.behaviors = [];
-
- delete this.returnValue;
- delete this.returnArgAt;
- this.returnThis = false;
-
- if (this.fakes) {
- for (i = 0; i < this.fakes.length; i++) {
- this.fakes[i].resetBehavior();
- }
- }
- },
-
- onCall: function onCall(index) {
- if (!this.behaviors[index]) {
- this.behaviors[index] = sinon.behavior.create(this);
- }
-
- return this.behaviors[index];
- },
-
- onFirstCall: function onFirstCall() {
- return this.onCall(0);
- },
-
- onSecondCall: function onSecondCall() {
- return this.onCall(1);
- },
-
- onThirdCall: function onThirdCall() {
- return this.onCall(2);
- }
- };
-
- for (var method in sinon.behavior) {
- if (sinon.behavior.hasOwnProperty(method) &&
- !proto.hasOwnProperty(method) &&
- method != "create" &&
- method != "withArgs" &&
- method != "invoke") {
- proto[method] = (function (behaviorMethod) {
- return function () {
- this.defaultBehavior = this.defaultBehavior || sinon.behavior.create(this);
- this.defaultBehavior[behaviorMethod].apply(this.defaultBehavior, arguments);
- return this;
- };
- }(method));
- }
- }
-
- sinon.extend(stub, proto);
- sinon.stub = stub;
-
- return stub;
- }
-
- var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
- var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;
-
- function loadDependencies(require, exports, module) {
- var sinon = require("./util/core");
- require("./behavior");
- require("./spy");
- require("./extend");
- module.exports = makeApi(sinon);
- }
-
- if (isAMD) {
- define(loadDependencies);
- } else if (isNode) {
- loadDependencies(require, module.exports, module);
- } else if (!sinon) {
- return;
- } else {
- makeApi(sinon);
- }
-}(typeof sinon == "object" && sinon || null));
-
-/**
- * @depend times_in_words.js
- * @depend util/core.js
- * @depend call.js
- * @depend extend.js
- * @depend match.js
- * @depend spy.js
- * @depend stub.js
- * @depend format.js
- */
-/**
- * Mock functions.
- *
- * @author Christian Johansen (christian at cjohansen.no)
- * @license BSD
- *
- * Copyright (c) 2010-2013 Christian Johansen
- */
-
-(function (sinon) {
- function makeApi(sinon) {
- var push = [].push;
- var match = sinon.match;
-
- function mock(object) {
- if (!object) {
- return sinon.expectation.create("Anonymous mock");
- }
-
- return mock.create(object);
- }
-
- function each(collection, callback) {
- if (!collection) {
- return;
- }
-
- for (var i = 0, l = collection.length; i < l; i += 1) {
- callback(collection[i]);
- }
- }
-
- sinon.extend(mock, {
- create: function create(object) {
- if (!object) {
- throw new TypeError("object is null");
- }
-
- var mockObject = sinon.extend({}, mock);
- mockObject.object = object;
- delete mockObject.create;
-
- return mockObject;
- },
-
- expects: function expects(method) {
- if (!method) {
- throw new TypeError("method is falsy");
- }
-
- if (!this.expectations) {
- this.expectations = {};
- this.proxies = [];
- }
-
- if (!this.expectations[method]) {
- this.expectations[method] = [];
- var mockObject = this;
-
- sinon.wrapMethod(this.object, method, function () {
- return mockObject.invokeMethod(method, this, arguments);
- });
-
- push.call(this.proxies, method);
- }
-
- var expectation = sinon.expectation.create(method);
- push.call(this.expectations[method], expectation);
-
- return expectation;
- },
-
- restore: function restore() {
- var object = this.object;
-
- each(this.proxies, function (proxy) {
- if (typeof object[proxy].restore == "function") {
- object[proxy].restore();
- }
- });
- },
-
- verify: function verify() {
- var expectations = this.expectations || {};
- var messages = [], met = [];
-
- each(this.proxies, function (proxy) {
- each(expectations[proxy], function (expectation) {
- if (!expectation.met()) {
- push.call(messages, expectation.toString());
- } else {
- push.call(met, expectation.toString());
- }
- });
- });
-
- this.restore();
-
- if (messages.length > 0) {
- sinon.expectation.fail(messages.concat(met).join("\n"));
- } else if (met.length > 0) {
- sinon.expectation.pass(messages.concat(met).join("\n"));
- }
-
- return true;
- },
-
- invokeMethod: function invokeMethod(method, thisValue, args) {
- var expectations = this.expectations && this.expectations[method];
- var length = expectations && expectations.length || 0, i;
-
- for (i = 0; i < length; i += 1) {
- if (!expectations[i].met() &&
- expectations[i].allowsCall(thisValue, args)) {
- return expectations[i].apply(thisValue, args);
- }
- }
-
- var messages = [], available, exhausted = 0;
-
- for (i = 0; i < length; i += 1) {
- if (expectations[i].allowsCall(thisValue, args)) {
- available = available || expectations[i];
- } else {
- exhausted += 1;
- }
- push.call(messages, " " + expectations[i].toString());
- }
-
- if (exhausted === 0) {
- return available.apply(thisValue, args);
- }
-
- messages.unshift("Unexpected call: " + sinon.spyCall.toString.call({
- proxy: method,
- args: args
- }));
-
- sinon.expectation.fail(messages.join("\n"));
- }
- });
-
- var times = sinon.timesInWords;
- var slice = Array.prototype.slice;
-
- function callCountInWords(callCount) {
- if (callCount == 0) {
- return "never called";
- } else {
- return "called " + times(callCount);
- }
- }
-
- function expectedCallCountInWords(expectation) {
- var min = expectation.minCalls;
- var max = expectation.maxCalls;
-
- if (typeof min == "number" && typeof max == "number") {
- var str = times(min);
-
- if (min != max) {
- str = "at least " + str + " and at most " + times(max);
- }
-
- return str;
- }
-
- if (typeof min == "number") {
- return "at least " + times(min);
- }
-
- return "at most " + times(max);
- }
-
- function receivedMinCalls(expectation) {
- var hasMinLimit = typeof expectation.minCalls == "number";
- return !hasMinLimit || expectation.callCount >= expectation.minCalls;
- }
-
- function receivedMaxCalls(expectation) {
- if (typeof expectation.maxCalls != "number") {
- return false;
- }
-
- return expectation.callCount == expectation.maxCalls;
- }
-
- function verifyMatcher(possibleMatcher, arg) {
- if (match && match.isMatcher(possibleMatcher)) {
- return possibleMatcher.test(arg);
- } else {
- return true;
- }
- }
-
- sinon.expectation = {
- minCalls: 1,
- maxCalls: 1,
-
- create: function create(methodName) {
- var expectation = sinon.extend(sinon.stub.create(), sinon.expectation);
- delete expectation.create;
- expectation.method = methodName;
-
- return expectation;
- },
-
- invoke: function invoke(func, thisValue, args) {
- this.verifyCallAllowed(thisValue, args);
-
- return sinon.spy.invoke.apply(this, arguments);
- },
-
- atLeast: function atLeast(num) {
- if (typeof num != "number") {
- throw new TypeError("'" + num + "' is not number");
- }
-
- if (!this.limitsSet) {
- this.maxCalls = null;
- this.limitsSet = true;
- }
-
- this.minCalls = num;
-
- return this;
- },
-
- atMost: function atMost(num) {
- if (typeof num != "number") {
- throw new TypeError("'" + num + "' is not number");
- }
-
- if (!this.limitsSet) {
- this.minCalls = null;
- this.limitsSet = true;
- }
-
- this.maxCalls = num;
-
- return this;
- },
-
- never: function never() {
- return this.exactly(0);
- },
-
- once: function once() {
- return this.exactly(1);
- },
-
- twice: function twice() {
- return this.exactly(2);
- },
-
- thrice: function thrice() {
- return this.exactly(3);
- },
-
- exactly: function exactly(num) {
- if (typeof num != "number") {
- throw new TypeError("'" + num + "' is not a number");
- }
-
- this.atLeast(num);
- return this.atMost(num);
- },
-
- met: function met() {
- return !this.failed && receivedMinCalls(this);
- },
-
- verifyCallAllowed: function verifyCallAllowed(thisValue, args) {
- if (receivedMaxCalls(this)) {
- this.failed = true;
- sinon.expectation.fail(this.method + " already called " + times(this.maxCalls));
- }
-
- if ("expectedThis" in this && this.expectedThis !== thisValue) {
- sinon.expectation.fail(this.method + " called with " + thisValue + " as thisValue, expected " +
- this.expectedThis);
- }
-
- if (!("expectedArguments" in this)) {
- return;
- }
-
- if (!args) {
- sinon.expectation.fail(this.method + " received no arguments, expected " +
- sinon.format(this.expectedArguments));
- }
-
- if (args.length < this.expectedArguments.length) {
- sinon.expectation.fail(this.method + " received too few arguments (" + sinon.format(args) +
- "), expected " + sinon.format(this.expectedArguments));
- }
-
- if (this.expectsExactArgCount &&
- args.length != this.expectedArguments.length) {
- sinon.expectation.fail(this.method + " received too many arguments (" + sinon.format(args) +
- "), expected " + sinon.format(this.expectedArguments));
- }
-
- for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) {
-
- if (!verifyMatcher(this.expectedArguments[i], args[i])) {
- sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) +
- ", didn't match " + this.expectedArguments.toString());
- }
-
- if (!sinon.deepEqual(this.expectedArguments[i], args[i])) {
- sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) +
- ", expected " + sinon.format(this.expectedArguments));
- }
- }
- },
-
- allowsCall: function allowsCall(thisValue, args) {
- if (this.met() && receivedMaxCalls(this)) {
- return false;
- }
-
- if ("expectedThis" in this && this.expectedThis !== thisValue) {
- return false;
- }
-
- if (!("expectedArguments" in this)) {
- return true;
- }
-
- args = args || [];
-
- if (args.length < this.expectedArguments.length) {
- return false;
- }
-
- if (this.expectsExactArgCount &&
- args.length != this.expectedArguments.length) {
- return false;
- }
-
- for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) {
- if (!verifyMatcher(this.expectedArguments[i], args[i])) {
- return false;
- }
-
- if (!sinon.deepEqual(this.expectedArguments[i], args[i])) {
- return false;
- }
- }
-
- return true;
- },
-
- withArgs: function withArgs() {
- this.expectedArguments = slice.call(arguments);
- return this;
- },
-
- withExactArgs: function withExactArgs() {
- this.withArgs.apply(this, arguments);
- this.expectsExactArgCount = true;
- return this;
- },
-
- on: function on(thisValue) {
- this.expectedThis = thisValue;
- return this;
- },
-
- toString: function () {
- var args = (this.expectedArguments || []).slice();
-
- if (!this.expectsExactArgCount) {
- push.call(args, "[...]");
- }
-
- var callStr = sinon.spyCall.toString.call({
- proxy: this.method || "anonymous mock expectation",
- args: args
- });
-
- var message = callStr.replace(", [...", "[, ...") + " " +
- expectedCallCountInWords(this);
-
- if (this.met()) {
- return "Expectation met: " + message;
- }
-
- return "Expected " + message + " (" +
- callCountInWords(this.callCount) + ")";
- },
-
- verify: function verify() {
- if (!this.met()) {
- sinon.expectation.fail(this.toString());
- } else {
- sinon.expectation.pass(this.toString());
- }
-
- return true;
- },
-
- pass: function pass(message) {
- sinon.assert.pass(message);
- },
-
- fail: function fail(message) {
- var exception = new Error(message);
- exception.name = "ExpectationError";
-
- throw exception;
- }
- };
-
- sinon.mock = mock;
- return mock;
- }
-
- var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
- var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;
-
- function loadDependencies(require, exports, module) {
- var sinon = require("./util/core");
- require("./times_in_words");
- require("./call");
- require("./extend");
- require("./match");
- require("./spy");
- require("./stub");
- require("./format");
-
- module.exports = makeApi(sinon);
- }
-
- if (isAMD) {
- define(loadDependencies);
- } else if (isNode) {
- loadDependencies(require, module.exports, module);
- } else if (!sinon) {
- return;
- } else {
- makeApi(sinon);
- }
-}(typeof sinon == "object" && sinon || null));
-
-/**
- * @depend util/core.js
- * @depend spy.js
- * @depend stub.js
- * @depend mock.js
- */
-/**
- * Collections of stubs, spies and mocks.
- *
- * @author Christian Johansen (christian at cjohansen.no)
- * @license BSD
- *
- * Copyright (c) 2010-2013 Christian Johansen
- */
-
-(function (sinon) {
- var push = [].push;
- var hasOwnProperty = Object.prototype.hasOwnProperty;
-
- function getFakes(fakeCollection) {
- if (!fakeCollection.fakes) {
- fakeCollection.fakes = [];
- }
-
- return fakeCollection.fakes;
- }
-
- function each(fakeCollection, method) {
- var fakes = getFakes(fakeCollection);
-
- for (var i = 0, l = fakes.length; i < l; i += 1) {
- if (typeof fakes[i][method] == "function") {
- fakes[i][method]();
- }
- }
- }
-
- function compact(fakeCollection) {
- var fakes = getFakes(fakeCollection);
- var i = 0;
- while (i < fakes.length) {
- fakes.splice(i, 1);
- }
- }
-
- function makeApi(sinon) {
- var collection = {
- verify: function resolve() {
- each(this, "verify");
- },
-
- restore: function restore() {
- each(this, "restore");
- compact(this);
- },
-
- reset: function restore() {
- each(this, "reset");
- },
-
- verifyAndRestore: function verifyAndRestore() {
- var exception;
-
- try {
- this.verify();
- } catch (e) {
- exception = e;
- }
-
- this.restore();
-
- if (exception) {
- throw exception;
- }
- },
-
- add: function add(fake) {
- push.call(getFakes(this), fake);
- return fake;
- },
-
- spy: function spy() {
- return this.add(sinon.spy.apply(sinon, arguments));
- },
-
- stub: function stub(object, property, value) {
- if (property) {
- var original = object[property];
-
- if (typeof original != "function") {
- if (!hasOwnProperty.call(object, property)) {
- throw new TypeError("Cannot stub non-existent own property " + property);
- }
-
- object[property] = value;
-
- return this.add({
- restore: function () {
- object[property] = original;
- }
- });
- }
- }
- if (!property && !!object && typeof object == "object") {
- var stubbedObj = sinon.stub.apply(sinon, arguments);
-
- for (var prop in stubbedObj) {
- if (typeof stubbedObj[prop] === "function") {
- this.add(stubbedObj[prop]);
- }
- }
-
- return stubbedObj;
- }
-
- return this.add(sinon.stub.apply(sinon, arguments));
- },
-
- mock: function mock() {
- return this.add(sinon.mock.apply(sinon, arguments));
- },
-
- inject: function inject(obj) {
- var col = this;
-
- obj.spy = function () {
- return col.spy.apply(col, arguments);
- };
-
- obj.stub = function () {
- return col.stub.apply(col, arguments);
- };
-
- obj.mock = function () {
- return col.mock.apply(col, arguments);
- };
-
- return obj;
- }
- };
-
- sinon.collection = collection;
- return collection;
- }
-
- var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
- var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;
-
- function loadDependencies(require, exports, module) {
- var sinon = require("./util/core");
- require("./mock");
- require("./spy");
- require("./stub");
- module.exports = makeApi(sinon);
- }
-
- if (isAMD) {
- define(loadDependencies);
- } else if (isNode) {
- loadDependencies(require, module.exports, module);
- } else if (!sinon) {
- return;
- } else {
- makeApi(sinon);
- }
-}(typeof sinon == "object" && sinon || null));
-
-/*global lolex */
-
-/**
- * Fake timer API
- * setTimeout
- * setInterval
- * clearTimeout
- * clearInterval
- * tick
- * reset
- * Date
- *
- * Inspired by jsUnitMockTimeOut from JsUnit
- *
- * @author Christian Johansen (christian at cjohansen.no)
- * @license BSD
- *
- * Copyright (c) 2010-2013 Christian Johansen
- */
-
-if (typeof sinon == "undefined") {
- var sinon = {};
-}
-
-(function (global) {
- function makeApi(sinon, lol) {
- var llx = typeof lolex !== "undefined" ? lolex : lol;
-
- sinon.useFakeTimers = function () {
- var now, methods = Array.prototype.slice.call(arguments);
-
- if (typeof methods[0] === "string") {
- now = 0;
- } else {
- now = methods.shift();
- }
-
- var clock = llx.install(now || 0, methods);
- clock.restore = clock.uninstall;
- return clock;
- };
-
- sinon.clock = {
- create: function (now) {
- return llx.createClock(now);
- }
- };
-
- sinon.timers = {
- setTimeout: setTimeout,
- clearTimeout: clearTimeout,
- setImmediate: (typeof setImmediate !== "undefined" ? setImmediate : undefined),
- clearImmediate: (typeof clearImmediate !== "undefined" ? clearImmediate : undefined),
- setInterval: setInterval,
- clearInterval: clearInterval,
- Date: Date
- };
- }
-
- var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
- var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;
-
- function loadDependencies(require, epxorts, module, lolex) {
- var sinon = require("./core");
- makeApi(sinon, lolex);
- module.exports = sinon;
- }
-
- if (isAMD) {
- define(loadDependencies);
- } else if (isNode) {
- loadDependencies(require, module.exports, module, require("lolex"));
- } else {
- makeApi(sinon);
- }
-}(typeof global != "undefined" && typeof global !== "function" ? global : this));
-
-/**
- * Minimal Event interface implementation
- *
- * Original implementation by Sven Fuchs: https://gist.github.com/995028
- * Modifications and tests by Christian Johansen.
- *
- * @author Sven Fuchs (svenfuchs at artweb-design.de)
- * @author Christian Johansen (christian at cjohansen.no)
- * @license BSD
- *
- * Copyright (c) 2011 Sven Fuchs, Christian Johansen
- */
-
-if (typeof sinon == "undefined") {
- this.sinon = {};
-}
-
-(function () {
- var push = [].push;
-
- function makeApi(sinon) {
- sinon.Event = function Event(type, bubbles, cancelable, target) {
- this.initEvent(type, bubbles, cancelable, target);
- };
-
- sinon.Event.prototype = {
- initEvent: function (type, bubbles, cancelable, target) {
- this.type = type;
- this.bubbles = bubbles;
- this.cancelable = cancelable;
- this.target = target;
- },
-
- stopPropagation: function () {},
-
- preventDefault: function () {
- this.defaultPrevented = true;
- }
- };
-
- sinon.ProgressEvent = function ProgressEvent(type, progressEventRaw, target) {
- this.initEvent(type, false, false, target);
- this.loaded = progressEventRaw.loaded || null;
- this.total = progressEventRaw.total || null;
- this.lengthComputable = !!progressEventRaw.total;
- };
-
- sinon.ProgressEvent.prototype = new sinon.Event();
-
- sinon.ProgressEvent.prototype.constructor = sinon.ProgressEvent;
-
- sinon.CustomEvent = function CustomEvent(type, customData, target) {
- this.initEvent(type, false, false, target);
- this.detail = customData.detail || null;
- };
-
- sinon.CustomEvent.prototype = new sinon.Event();
-
- sinon.CustomEvent.prototype.constructor = sinon.CustomEvent;
-
- sinon.EventTarget = {
- addEventListener: function addEventListener(event, listener) {
- this.eventListeners = this.eventListeners || {};
- this.eventListeners[event] = this.eventListeners[event] || [];
- push.call(this.eventListeners[event], listener);
- },
-
- removeEventListener: function removeEventListener(event, listener) {
- var listeners = this.eventListeners && this.eventListeners[event] || [];
-
- for (var i = 0, l = listeners.length; i < l; ++i) {
- if (listeners[i] == listener) {
- return listeners.splice(i, 1);
- }
- }
- },
-
- dispatchEvent: function dispatchEvent(event) {
- var type = event.type;
- var listeners = this.eventListeners && this.eventListeners[type] || [];
-
- for (var i = 0; i < listeners.length; i++) {
- if (typeof listeners[i] == "function") {
- listeners[i].call(this, event);
- } else {
- listeners[i].handleEvent(event);
- }
- }
-
- return !!event.defaultPrevented;
- }
- };
- }
-
- var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
- var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;
-
- function loadDependencies(require) {
- var sinon = require("./core");
- makeApi(sinon);
- }
-
- if (isAMD) {
- define(loadDependencies);
- } else if (isNode) {
- loadDependencies(require);
- } else {
- makeApi(sinon);
- }
-}());
-
-/**
- * @depend util/core.js
- */
-/**
- * Logs errors
- *
- * @author Christian Johansen (christian at cjohansen.no)
- * @license BSD
- *
- * Copyright (c) 2010-2014 Christian Johansen
- */
-
-(function (sinon) {
- // cache a reference to setTimeout, so that our reference won't be stubbed out
- // when using fake timers and errors will still get logged
- // https://github.com/cjohansen/Sinon.JS/issues/381
- var realSetTimeout = setTimeout;
-
- function makeApi(sinon) {
-
- function log() {}
-
- function logError(label, err) {
- var msg = label + " threw exception: ";
-
- sinon.log(msg + "[" + err.name + "] " + err.message);
-
- if (err.stack) {
- sinon.log(err.stack);
- }
-
- logError.setTimeout(function () {
- err.message = msg + err.message;
- throw err;
- }, 0);
- };
-
- // wrap realSetTimeout with something we can stub in tests
- logError.setTimeout = function (func, timeout) {
- realSetTimeout(func, timeout);
- }
-
- var exports = {};
- exports.log = sinon.log = log;
- exports.logError = sinon.logError = logError;
-
- return exports;
- }
-
- function loadDependencies(require, exports, module) {
- var sinon = require("./util/core");
- module.exports = makeApi(sinon);
- }
-
- var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
- var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;
-
- if (isAMD) {
- define(loadDependencies);
- } else if (isNode) {
- loadDependencies(require, module.exports, module);
- } else if (!sinon) {
- return;
- } else {
- makeApi(sinon);
- }
-}(typeof sinon == "object" && sinon || null));
-
-/**
- * @depend core.js
- * @depend ../extend.js
- * @depend event.js
- * @depend ../log_error.js
- */
-/**
- * Fake XDomainRequest object
- */
-
-if (typeof sinon == "undefined") {
- this.sinon = {};
-}
-
-// wrapper for global
-(function (global) {
- var xdr = { XDomainRequest: global.XDomainRequest };
- xdr.GlobalXDomainRequest = global.XDomainRequest;
- xdr.supportsXDR = typeof xdr.GlobalXDomainRequest != "undefined";
- xdr.workingXDR = xdr.supportsXDR ? xdr.GlobalXDomainRequest : false;
-
- function makeApi(sinon) {
- sinon.xdr = xdr;
-
- function FakeXDomainRequest() {
- this.readyState = FakeXDomainRequest.UNSENT;
- this.requestBody = null;
- this.requestHeaders = {};
- this.status = 0;
- this.timeout = null;
-
- if (typeof FakeXDomainRequest.onCreate == "function") {
- FakeXDomainRequest.onCreate(this);
- }
- }
-
- function verifyState(xdr) {
- if (xdr.readyState !== FakeXDomainRequest.OPENED) {
- throw new Error("INVALID_STATE_ERR");
- }
-
- if (xdr.sendFlag) {
- throw new Error("INVALID_STATE_ERR");
- }
- }
-
- function verifyRequestSent(xdr) {
- if (xdr.readyState == FakeXDomainRequest.UNSENT) {
- throw new Error("Request not sent");
- }
- if (xdr.readyState == FakeXDomainRequest.DONE) {
- throw new Error("Request done");
- }
- }
-
- function verifyResponseBodyType(body) {
- if (typeof body != "string") {
- var error = new Error("Attempted to respond to fake XDomainRequest with " +
- body + ", which is not a string.");
- error.name = "InvalidBodyException";
- throw error;
- }
- }
-
- sinon.extend(FakeXDomainRequest.prototype, sinon.EventTarget, {
- open: function open(method, url) {
- this.method = method;
- this.url = url;
-
- this.responseText = null;
- this.sendFlag = false;
-
- this.readyStateChange(FakeXDomainRequest.OPENED);
- },
-
- readyStateChange: function readyStateChange(state) {
- this.readyState = state;
- var eventName = "";
- switch (this.readyState) {
- case FakeXDomainRequest.UNSENT:
- break;
- case FakeXDomainRequest.OPENED:
- break;
- case FakeXDomainRequest.LOADING:
- if (this.sendFlag) {
- //raise the progress event
- eventName = "onprogress";
- }
- break;
- case FakeXDomainRequest.DONE:
- if (this.isTimeout) {
- eventName = "ontimeout"
- } else if (this.errorFlag || (this.status < 200 || this.status > 299)) {
- eventName = "onerror";
- } else {
- eventName = "onload"
- }
- break;
- }
-
- // raising event (if defined)
- if (eventName) {
- if (typeof this[eventName] == "function") {
- try {
- this[eventName]();
- } catch (e) {
- sinon.logError("Fake XHR " + eventName + " handler", e);
- }
- }
- }
- },
-
- send: function send(data) {
- verifyState(this);
-
- if (!/^(get|head)$/i.test(this.method)) {
- this.requestBody = data;
- }
- this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8";
-
- this.errorFlag = false;
- this.sendFlag = true;
- this.readyStateChange(FakeXDomainRequest.OPENED);
-
- if (typeof this.onSend == "function") {
- this.onSend(this);
- }
- },
-
- abort: function abort() {
- this.aborted = true;
- this.responseText = null;
- this.errorFlag = true;
-
- if (this.readyState > sinon.FakeXDomainRequest.UNSENT && this.sendFlag) {
- this.readyStateChange(sinon.FakeXDomainRequest.DONE);
- this.sendFlag = false;
- }
- },
-
- setResponseBody: function setResponseBody(body) {
- verifyRequestSent(this);
- verifyResponseBodyType(body);
-
- var chunkSize = this.chunkSize || 10;
- var index = 0;
- this.responseText = "";
-
- do {
- this.readyStateChange(FakeXDomainRequest.LOADING);
- this.responseText += body.substring(index, index + chunkSize);
- index += chunkSize;
- } while (index < body.length);
-
- this.readyStateChange(FakeXDomainRequest.DONE);
- },
-
- respond: function respond(status, contentType, body) {
- // content-type ignored, since XDomainRequest does not carry this
- // we keep the same syntax for respond(...) as for FakeXMLHttpRequest to ease
- // test integration across browsers
- this.status = typeof status == "number" ? status : 200;
- this.setResponseBody(body || "");
- },
-
- simulatetimeout: function simulatetimeout() {
- this.status = 0;
- this.isTimeout = true;
- // Access to this should actually throw an error
- this.responseText = undefined;
- this.readyStateChange(FakeXDomainRequest.DONE);
- }
- });
-
- sinon.extend(FakeXDomainRequest, {
- UNSENT: 0,
- OPENED: 1,
- LOADING: 3,
- DONE: 4
- });
-
- sinon.useFakeXDomainRequest = function useFakeXDomainRequest() {
- sinon.FakeXDomainRequest.restore = function restore(keepOnCreate) {
- if (xdr.supportsXDR) {
- global.XDomainRequest = xdr.GlobalXDomainRequest;
- }
-
- delete sinon.FakeXDomainRequest.restore;
-
- if (keepOnCreate !== true) {
- delete sinon.FakeXDomainRequest.onCreate;
- }
- };
- if (xdr.supportsXDR) {
- global.XDomainRequest = sinon.FakeXDomainRequest;
- }
- return sinon.FakeXDomainRequest;
- };
-
- sinon.FakeXDomainRequest = FakeXDomainRequest;
- }
-
- var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
- var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;
-
- function loadDependencies(require, exports, module) {
- var sinon = require("./core");
- require("../extend");
- require("./event");
- require("../log_error");
- makeApi(sinon);
- module.exports = sinon;
- }
-
- if (isAMD) {
- define(loadDependencies);
- } else if (isNode) {
- loadDependencies(require, module.exports, module);
- } else {
- makeApi(sinon);
- }
-})(this);
-
-/**
- * @depend core.js
- * @depend ../extend.js
- * @depend event.js
- * @depend ../log_error.js
- */
-/**
- * Fake XMLHttpRequest object
- *
- * @author Christian Johansen (christian at cjohansen.no)
- * @license BSD
- *
- * Copyright (c) 2010-2013 Christian Johansen
- */
-
-(function (global) {
-
- var supportsProgress = typeof ProgressEvent !== "undefined";
- var supportsCustomEvent = typeof CustomEvent !== "undefined";
- var sinonXhr = { XMLHttpRequest: global.XMLHttpRequest };
- sinonXhr.GlobalXMLHttpRequest = global.XMLHttpRequest;
- sinonXhr.GlobalActiveXObject = global.ActiveXObject;
- sinonXhr.supportsActiveX = typeof sinonXhr.GlobalActiveXObject != "undefined";
- sinonXhr.supportsXHR = typeof sinonXhr.GlobalXMLHttpRequest != "undefined";
- sinonXhr.workingXHR = sinonXhr.supportsXHR ? sinonXhr.GlobalXMLHttpRequest : sinonXhr.supportsActiveX
- ? function () { return new sinonXhr.GlobalActiveXObject("MSXML2.XMLHTTP.3.0") } : false;
- sinonXhr.supportsCORS = sinonXhr.supportsXHR && "withCredentials" in (new sinonXhr.GlobalXMLHttpRequest());
-
- /*jsl:ignore*/
- var unsafeHeaders = {
- "Accept-Charset": true,
- "Accept-Encoding": true,
- Connection: true,
- "Content-Length": true,
- Cookie: true,
- Cookie2: true,
- "Content-Transfer-Encoding": true,
- Date: true,
- Expect: true,
- Host: true,
- "Keep-Alive": true,
- Referer: true,
- TE: true,
- Trailer: true,
- "Transfer-Encoding": true,
- Upgrade: true,
- "User-Agent": true,
- Via: true
- };
- /*jsl:end*/
-
- function FakeXMLHttpRequest() {
- this.readyState = FakeXMLHttpRequest.UNSENT;
- this.requestHeaders = {};
- this.requestBody = null;
- this.status = 0;
- this.statusText = "";
- this.upload = new UploadProgress();
- if (sinonXhr.supportsCORS) {
- this.withCredentials = false;
- }
-
- var xhr = this;
- var events = ["loadstart", "load", "abort", "loadend"];
-
- function addEventListener(eventName) {
- xhr.addEventListener(eventName, function (event) {
- var listener = xhr["on" + eventName];
-
- if (listener && typeof listener == "function") {
- listener.call(this, event);
- }
- });
- }
-
- for (var i = events.length - 1; i >= 0; i--) {
- addEventListener(events[i]);
- }
-
- if (typeof FakeXMLHttpRequest.onCreate == "function") {
- FakeXMLHttpRequest.onCreate(this);
- }
- }
-
- // An upload object is created for each
- // FakeXMLHttpRequest and allows upload
- // events to be simulated using uploadProgress
- // and uploadError.
- function UploadProgress() {
- this.eventListeners = {
- progress: [],
- load: [],
- abort: [],
- error: []
- }
- }
-
- UploadProgress.prototype.addEventListener = function addEventListener(event, listener) {
- this.eventListeners[event].push(listener);
- };
-
- UploadProgress.prototype.removeEventListener = function removeEventListener(event, listener) {
- var listeners = this.eventListeners[event] || [];
-
- for (var i = 0, l = listeners.length; i < l; ++i) {
- if (listeners[i] == listener) {
- return listeners.splice(i, 1);
- }
- }
- };
-
- UploadProgress.prototype.dispatchEvent = function dispatchEvent(event) {
- var listeners = this.eventListeners[event.type] || [];
-
- for (var i = 0, listener; (listener = listeners[i]) != null; i++) {
- listener(event);
- }
- };
-
- function verifyState(xhr) {
- if (xhr.readyState !== FakeXMLHttpRequest.OPENED) {
- throw new Error("INVALID_STATE_ERR");
- }
-
- if (xhr.sendFlag) {
- throw new Error("INVALID_STATE_ERR");
- }
- }
-
- function getHeader(headers, header) {
- header = header.toLowerCase();
-
- for (var h in headers) {
- if (h.toLowerCase() == header) {
- return h;
- }
- }
-
- return null;
- }
-
- // filtering to enable a white-list version of Sinon FakeXhr,
- // where whitelisted requests are passed through to real XHR
- function each(collection, callback) {
- if (!collection) {
- return;
- }
-
- for (var i = 0, l = collection.length; i < l; i += 1) {
- callback(collection[i]);
- }
- }
- function some(collection, callback) {
- for (var index = 0; index < collection.length; index++) {
- if (callback(collection[index]) === true) {
- return true;
- }
- }
- return false;
- }
- // largest arity in XHR is 5 - XHR#open
- var apply = function (obj, method, args) {
- switch (args.length) {
- case 0: return obj[method]();
- case 1: return obj[method](args[0]);
- case 2: return obj[method](args[0], args[1]);
- case 3: return obj[method](args[0], args[1], args[2]);
- case 4: return obj[method](args[0], args[1], args[2], args[3]);
- case 5: return obj[method](args[0], args[1], args[2], args[3], args[4]);
- }
- };
-
- FakeXMLHttpRequest.filters = [];
- FakeXMLHttpRequest.addFilter = function addFilter(fn) {
- this.filters.push(fn)
- };
- var IE6Re = /MSIE 6/;
- FakeXMLHttpRequest.defake = function defake(fakeXhr, xhrArgs) {
- var xhr = new sinonXhr.workingXHR();
- each([
- "open",
- "setRequestHeader",
- "send",
- "abort",
- "getResponseHeader",
- "getAllResponseHeaders",
- "addEventListener",
- "overrideMimeType",
- "removeEventListener"
- ], function (method) {
- fakeXhr[method] = function () {
- return apply(xhr, method, arguments);
- };
- });
-
- var copyAttrs = function (args) {
- each(args, function (attr) {
- try {
- fakeXhr[attr] = xhr[attr]
- } catch (e) {
- if (!IE6Re.test(navigator.userAgent)) {
- throw e;
- }
- }
- });
- };
-
- var stateChange = function stateChange() {
- fakeXhr.readyState = xhr.readyState;
- if (xhr.readyState >= FakeXMLHttpRequest.HEADERS_RECEIVED) {
- copyAttrs(["status", "statusText"]);
- }
- if (xhr.readyState >= FakeXMLHttpRequest.LOADING) {
- copyAttrs(["responseText", "response"]);
- }
- if (xhr.readyState === FakeXMLHttpRequest.DONE) {
- copyAttrs(["responseXML"]);
- }
- if (fakeXhr.onreadystatechange) {
- fakeXhr.onreadystatechange.call(fakeXhr, { target: fakeXhr });
- }
- };
-
- if (xhr.addEventListener) {
- for (var event in fakeXhr.eventListeners) {
- if (fakeXhr.eventListeners.hasOwnProperty(event)) {
- each(fakeXhr.eventListeners[event], function (handler) {
- xhr.addEventListener(event, handler);
- });
- }
- }
- xhr.addEventListener("readystatechange", stateChange);
- } else {
- xhr.onreadystatechange = stateChange;
- }
- apply(xhr, "open", xhrArgs);
- };
- FakeXMLHttpRequest.useFilters = false;
-
- function verifyRequestOpened(xhr) {
- if (xhr.readyState != FakeXMLHttpRequest.OPENED) {
- throw new Error("INVALID_STATE_ERR - " + xhr.readyState);
- }
- }
-
- function verifyRequestSent(xhr) {
- if (xhr.readyState == FakeXMLHttpRequest.DONE) {
- throw new Error("Request done");
- }
- }
-
- function verifyHeadersReceived(xhr) {
- if (xhr.async && xhr.readyState != FakeXMLHttpRequest.HEADERS_RECEIVED) {
- throw new Error("No headers received");
- }
- }
-
- function verifyResponseBodyType(body) {
- if (typeof body != "string") {
- var error = new Error("Attempted to respond to fake XMLHttpRequest with " +
- body + ", which is not a string.");
- error.name = "InvalidBodyException";
- throw error;
- }
- }
-
- FakeXMLHttpRequest.parseXML = function parseXML(text) {
- var xmlDoc;
-
- if (typeof DOMParser != "undefined") {
- var parser = new DOMParser();
- xmlDoc = parser.parseFromString(text, "text/xml");
- } else {
- xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
- xmlDoc.async = "false";
- xmlDoc.loadXML(text);
- }
-
- return xmlDoc;
- };
-
- FakeXMLHttpRequest.statusCodes = {
- 100: "Continue",
- 101: "Switching Protocols",
- 200: "OK",
- 201: "Created",
- 202: "Accepted",
- 203: "Non-Authoritative Information",
- 204: "No Content",
- 205: "Reset Content",
- 206: "Partial Content",
- 207: "Multi-Status",
- 300: "Multiple Choice",
- 301: "Moved Permanently",
- 302: "Found",
- 303: "See Other",
- 304: "Not Modified",
- 305: "Use Proxy",
- 307: "Temporary Redirect",
- 400: "Bad Request",
- 401: "Unauthorized",
- 402: "Payment Required",
- 403: "Forbidden",
- 404: "Not Found",
- 405: "Method Not Allowed",
- 406: "Not Acceptable",
- 407: "Proxy Authentication Required",
- 408: "Request Timeout",
- 409: "Conflict",
- 410: "Gone",
- 411: "Length Required",
- 412: "Precondition Failed",
- 413: "Request Entity Too Large",
- 414: "Request-URI Too Long",
- 415: "Unsupported Media Type",
- 416: "Requested Range Not Satisfiable",
- 417: "Expectation Failed",
- 422: "Unprocessable Entity",
- 500: "Internal Server Error",
- 501: "Not Implemented",
- 502: "Bad Gateway",
- 503: "Service Unavailable",
- 504: "Gateway Timeout",
- 505: "HTTP Version Not Supported"
- };
-
- function makeApi(sinon) {
- sinon.xhr = sinonXhr;
-
- sinon.extend(FakeXMLHttpRequest.prototype, sinon.EventTarget, {
- async: true,
-
- open: function open(method, url, async, username, password) {
- this.method = method;
- this.url = url;
- this.async = typeof async == "boolean" ? async : true;
- this.username = username;
- this.password = password;
- this.responseText = null;
- this.responseXML = null;
- this.requestHeaders = {};
- this.sendFlag = false;
-
- if (FakeXMLHttpRequest.useFilters === true) {
- var xhrArgs = arguments;
- var defake = some(FakeXMLHttpRequest.filters, function (filter) {
- return filter.apply(this, xhrArgs)
- });
- if (defake) {
- return FakeXMLHttpRequest.defake(this, arguments);
- }
- }
- this.readyStateChange(FakeXMLHttpRequest.OPENED);
- },
-
- readyStateChange: function readyStateChange(state) {
- this.readyState = state;
-
- if (typeof this.onreadystatechange == "function") {
- try {
- this.onreadystatechange();
- } catch (e) {
- sinon.logError("Fake XHR onreadystatechange handler", e);
- }
- }
-
- this.dispatchEvent(new sinon.Event("readystatechange"));
-
- switch (this.readyState) {
- case FakeXMLHttpRequest.DONE:
- this.dispatchEvent(new sinon.Event("load", false, false, this));
- this.dispatchEvent(new sinon.Event("loadend", false, false, this));
- this.upload.dispatchEvent(new sinon.Event("load", false, false, this));
- if (supportsProgress) {
- this.upload.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100}));
- this.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100}));
- }
- break;
- }
- },
-
- setRequestHeader: function setRequestHeader(header, value) {
- verifyState(this);
-
- if (unsafeHeaders[header] || /^(Sec-|Proxy-)/.test(header)) {
- throw new Error("Refused to set unsafe header \"" + header + "\"");
- }
-
- if (this.requestHeaders[header]) {
- this.requestHeaders[header] += "," + value;
- } else {
- this.requestHeaders[header] = value;
- }
- },
-
- // Helps testing
- setResponseHeaders: function setResponseHeaders(headers) {
- verifyRequestOpened(this);
- this.responseHeaders = {};
-
- for (var header in headers) {
- if (headers.hasOwnProperty(header)) {
- this.responseHeaders[header] = headers[header];
- }
- }
-
- if (this.async) {
- this.readyStateChange(FakeXMLHttpRequest.HEADERS_RECEIVED);
- } else {
- this.readyState = FakeXMLHttpRequest.HEADERS_RECEIVED;
- }
- },
-
- // Currently treats ALL data as a DOMString (i.e. no Document)
- send: function send(data) {
- verifyState(this);
-
- if (!/^(get|head)$/i.test(this.method)) {
- var contentType = getHeader(this.requestHeaders, "Content-Type");
- if (this.requestHeaders[contentType]) {
- var value = this.requestHeaders[contentType].split(";");
- this.requestHeaders[contentType] = value[0] + ";charset=utf-8";
- } else if (!(data instanceof FormData)) {
- this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8";
- }
-
- this.requestBody = data;
- }
-
- this.errorFlag = false;
- this.sendFlag = this.async;
- this.readyStateChange(FakeXMLHttpRequest.OPENED);
-
- if (typeof this.onSend == "function") {
- this.onSend(this);
- }
-
- this.dispatchEvent(new sinon.Event("loadstart", false, false, this));
- },
-
- abort: function abort() {
- this.aborted = true;
- this.responseText = null;
- this.errorFlag = true;
- this.requestHeaders = {};
-
- if (this.readyState > FakeXMLHttpRequest.UNSENT && this.sendFlag) {
- this.readyStateChange(FakeXMLHttpRequest.DONE);
- this.sendFlag = false;
- }
-
- this.readyState = FakeXMLHttpRequest.UNSENT;
-
- this.dispatchEvent(new sinon.Event("abort", false, false, this));
-
- this.upload.dispatchEvent(new sinon.Event("abort", false, false, this));
-
- if (typeof this.onerror === "function") {
- this.onerror();
- }
- },
-
- getResponseHeader: function getResponseHeader(header) {
- if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) {
- return null;
- }
-
- if (/^Set-Cookie2?$/i.test(header)) {
- return null;
- }
-
- header = getHeader(this.responseHeaders, header);
-
- return this.responseHeaders[header] || null;
- },
-
- getAllResponseHeaders: function getAllResponseHeaders() {
- if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) {
- return "";
- }
-
- var headers = "";
-
- for (var header in this.responseHeaders) {
- if (this.responseHeaders.hasOwnProperty(header) &&
- !/^Set-Cookie2?$/i.test(header)) {
- headers += header + ": " + this.responseHeaders[header] + "\r\n";
- }
- }
-
- return headers;
- },
-
- setResponseBody: function setResponseBody(body) {
- verifyRequestSent(this);
- verifyHeadersReceived(this);
- verifyResponseBodyType(body);
-
- var chunkSize = this.chunkSize || 10;
- var index = 0;
- this.responseText = "";
-
- do {
- if (this.async) {
- this.readyStateChange(FakeXMLHttpRequest.LOADING);
- }
-
- this.responseText += body.substring(index, index + chunkSize);
- index += chunkSize;
- } while (index < body.length);
-
- var type = this.getResponseHeader("Content-Type");
-
- if (this.responseText &&
- (!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) {
- try {
- this.responseXML = FakeXMLHttpRequest.parseXML(this.responseText);
- } catch (e) {
- // Unable to parse XML - no biggie
- }
- }
-
- this.readyStateChange(FakeXMLHttpRequest.DONE);
- },
-
- respond: function respond(status, headers, body) {
- this.status = typeof status == "number" ? status : 200;
- this.statusText = FakeXMLHttpRequest.statusCodes[this.status];
- this.setResponseHeaders(headers || {});
- this.setResponseBody(body || "");
- },
-
- uploadProgress: function uploadProgress(progressEventRaw) {
- if (supportsProgress) {
- this.upload.dispatchEvent(new sinon.ProgressEvent("progress", progressEventRaw));
- }
- },
-
- downloadProgress: function downloadProgress(progressEventRaw) {
- if (supportsProgress) {
- this.dispatchEvent(new sinon.ProgressEvent("progress", progressEventRaw));
- }
- },
-
- uploadError: function uploadError(error) {
- if (supportsCustomEvent) {
- this.upload.dispatchEvent(new sinon.CustomEvent("error", {detail: error}));
- }
- }
- });
-
- sinon.extend(FakeXMLHttpRequest, {
- UNSENT: 0,
- OPENED: 1,
- HEADERS_RECEIVED: 2,
- LOADING: 3,
- DONE: 4
- });
-
- sinon.useFakeXMLHttpRequest = function () {
- FakeXMLHttpRequest.restore = function restore(keepOnCreate) {
- if (sinonXhr.supportsXHR) {
- global.XMLHttpRequest = sinonXhr.GlobalXMLHttpRequest;
- }
-
- if (sinonXhr.supportsActiveX) {
- global.ActiveXObject = sinonXhr.GlobalActiveXObject;
- }
-
- delete FakeXMLHttpRequest.restore;
-
- if (keepOnCreate !== true) {
- delete FakeXMLHttpRequest.onCreate;
- }
- };
- if (sinonXhr.supportsXHR) {
- global.XMLHttpRequest = FakeXMLHttpRequest;
- }
-
- if (sinonXhr.supportsActiveX) {
- global.ActiveXObject = function ActiveXObject(objId) {
- if (objId == "Microsoft.XMLHTTP" || /^Msxml2\.XMLHTTP/i.test(objId)) {
-
- return new FakeXMLHttpRequest();
- }
-
- return new sinonXhr.GlobalActiveXObject(objId);
- };
- }
-
- return FakeXMLHttpRequest;
- };
-
- sinon.FakeXMLHttpRequest = FakeXMLHttpRequest;
- }
-
- var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
- var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;
-
- function loadDependencies(require, exports, module) {
- var sinon = require("./core");
- require("../extend");
- require("./event");
- require("../log_error");
- makeApi(sinon);
- module.exports = sinon;
- }
-
- if (isAMD) {
- define(loadDependencies);
- } else if (isNode) {
- loadDependencies(require, module.exports, module);
- } else if (typeof sinon === "undefined") {
- return;
- } else {
- makeApi(sinon);
- }
-
-})(typeof global !== "undefined" ? global : this);
-
-/**
- * @depend fake_xdomain_request.js
- * @depend fake_xml_http_request.js
- * @depend ../format.js
- * @depend ../log_error.js
- */
-/**
- * The Sinon "server" mimics a web server that receives requests from
- * sinon.FakeXMLHttpRequest and provides an API to respond to those requests,
- * both synchronously and asynchronously. To respond synchronuously, canned
- * answers have to be provided upfront.
- *
- * @author Christian Johansen (christian at cjohansen.no)
- * @license BSD
- *
- * Copyright (c) 2010-2013 Christian Johansen
- */
-
-if (typeof sinon == "undefined") {
- var sinon = {};
-}
-
-(function () {
- var push = [].push;
- function F() {}
-
- function create(proto) {
- F.prototype = proto;
- return new F();
- }
-
- function responseArray(handler) {
- var response = handler;
-
- if (Object.prototype.toString.call(handler) != "[object Array]") {
- response = [200, {}, handler];
- }
-
- if (typeof response[2] != "string") {
- throw new TypeError("Fake server response body should be string, but was " +
- typeof response[2]);
- }
-
- return response;
- }
-
- var wloc = typeof window !== "undefined" ? window.location : {};
- var rCurrLoc = new RegExp("^" + wloc.protocol + "//" + wloc.host);
-
- function matchOne(response, reqMethod, reqUrl) {
- var rmeth = response.method;
- var matchMethod = !rmeth || rmeth.toLowerCase() == reqMethod.toLowerCase();
- var url = response.url;
- var matchUrl = !url || url == reqUrl || (typeof url.test == "function" && url.test(reqUrl));
-
- return matchMethod && matchUrl;
- }
-
- function match(response, request) {
- var requestUrl = request.url;
-
- if (!/^https?:\/\//.test(requestUrl) || rCurrLoc.test(requestUrl)) {
- requestUrl = requestUrl.replace(rCurrLoc, "");
- }
-
- if (matchOne(response, this.getHTTPMethod(request), requestUrl)) {
- if (typeof response.response == "function") {
- var ru = response.url;
- var args = [request].concat(ru && typeof ru.exec == "function" ? ru.exec(requestUrl).slice(1) : []);
- return response.response.apply(response, args);
- }
-
- return true;
- }
-
- return false;
- }
-
- function makeApi(sinon) {
- sinon.fakeServer = {
- create: function () {
- var server = create(this);
- if (!sinon.xhr.supportsCORS) {
- this.xhr = sinon.useFakeXDomainRequest();
- } else {
- this.xhr = sinon.useFakeXMLHttpRequest();
- }
- server.requests = [];
-
- this.xhr.onCreate = function (xhrObj) {
- server.addRequest(xhrObj);
- };
-
- return server;
- },
-
- addRequest: function addRequest(xhrObj) {
- var server = this;
- push.call(this.requests, xhrObj);
-
- xhrObj.onSend = function () {
- server.handleRequest(this);
-
- if (server.respondImmediately) {
- server.respond();
- } else if (server.autoRespond && !server.responding) {
- setTimeout(function () {
- server.responding = false;
- server.respond();
- }, server.autoRespondAfter || 10);
-
- server.responding = true;
- }
- };
- },
-
- getHTTPMethod: function getHTTPMethod(request) {
- if (this.fakeHTTPMethods && /post/i.test(request.method)) {
- var matches = (request.requestBody || "").match(/_method=([^\b;]+)/);
- return !!matches ? matches[1] : request.method;
- }
-
- return request.method;
- },
-
- handleRequest: function handleRequest(xhr) {
- if (xhr.async) {
- if (!this.queue) {
- this.queue = [];
- }
-
- push.call(this.queue, xhr);
- } else {
- this.processRequest(xhr);
- }
- },
-
- log: function log(response, request) {
- var str;
-
- str = "Request:\n" + sinon.format(request) + "\n\n";
- str += "Response:\n" + sinon.format(response) + "\n\n";
-
- sinon.log(str);
- },
-
- respondWith: function respondWith(method, url, body) {
- if (arguments.length == 1 && typeof method != "function") {
- this.response = responseArray(method);
- return;
- }
-
- if (!this.responses) { this.responses = []; }
-
- if (arguments.length == 1) {
- body = method;
- url = method = null;
- }
-
- if (arguments.length == 2) {
- body = url;
- url = method;
- method = null;
- }
-
- push.call(this.responses, {
- method: method,
- url: url,
- response: typeof body == "function" ? body : responseArray(body)
- });
- },
-
- respond: function respond() {
- if (arguments.length > 0) {
- this.respondWith.apply(this, arguments);
- }
-
- var queue = this.queue || [];
- var requests = queue.splice(0, queue.length);
- var request;
-
- while (request = requests.shift()) {
- this.processRequest(request);
- }
- },
-
- processRequest: function processRequest(request) {
- try {
- if (request.aborted) {
- return;
- }
-
- var response = this.response || [404, {}, ""];
-
- if (this.responses) {
- for (var l = this.responses.length, i = l - 1; i >= 0; i--) {
- if (match.call(this, this.responses[i], request)) {
- response = this.responses[i].response;
- break;
- }
- }
- }
-
- if (request.readyState != 4) {
- this.log(response, request);
-
- request.respond(response[0], response[1], response[2]);
- }
- } catch (e) {
- sinon.logError("Fake server request processing", e);
- }
- },
-
- restore: function restore() {
- return this.xhr.restore && this.xhr.restore.apply(this.xhr, arguments);
- }
- };
- }
-
- var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
- var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;
-
- function loadDependencies(require, exports, module) {
- var sinon = require("./core");
- require("./fake_xdomain_request");
- require("./fake_xml_http_request");
- require("../format");
- makeApi(sinon);
- module.exports = sinon;
- }
-
- if (isAMD) {
- define(loadDependencies);
- } else if (isNode) {
- loadDependencies(require, module.exports, module);
- } else {
- makeApi(sinon);
- }
-}());
-
-/**
- * @depend fake_server.js
- * @depend fake_timers.js
- */
-/**
- * Add-on for sinon.fakeServer that automatically handles a fake timer along with
- * the FakeXMLHttpRequest. The direct inspiration for this add-on is jQuery
- * 1.3.x, which does not use xhr object's onreadystatehandler at all - instead,
- * it polls the object for completion with setInterval. Dispite the direct
- * motivation, there is nothing jQuery-specific in this file, so it can be used
- * in any environment where the ajax implementation depends on setInterval or
- * setTimeout.
- *
- * @author Christian Johansen (christian at cjohansen.no)
- * @license BSD
- *
- * Copyright (c) 2010-2013 Christian Johansen
- */
-
-(function () {
- function makeApi(sinon) {
- function Server() {}
- Server.prototype = sinon.fakeServer;
-
- sinon.fakeServerWithClock = new Server();
-
- sinon.fakeServerWithClock.addRequest = function addRequest(xhr) {
- if (xhr.async) {
- if (typeof setTimeout.clock == "object") {
- this.clock = setTimeout.clock;
- } else {
- this.clock = sinon.useFakeTimers();
- this.resetClock = true;
- }
-
- if (!this.longestTimeout) {
- var clockSetTimeout = this.clock.setTimeout;
- var clockSetInterval = this.clock.setInterval;
- var server = this;
-
- this.clock.setTimeout = function (fn, timeout) {
- server.longestTimeout = Math.max(timeout, server.longestTimeout || 0);
-
- return clockSetTimeout.apply(this, arguments);
- };
-
- this.clock.setInterval = function (fn, timeout) {
- server.longestTimeout = Math.max(timeout, server.longestTimeout || 0);
-
- return clockSetInterval.apply(this, arguments);
- };
- }
- }
-
- return sinon.fakeServer.addRequest.call(this, xhr);
- };
-
- sinon.fakeServerWithClock.respond = function respond() {
- var returnVal = sinon.fakeServer.respond.apply(this, arguments);
-
- if (this.clock) {
- this.clock.tick(this.longestTimeout || 0);
- this.longestTimeout = 0;
-
- if (this.resetClock) {
- this.clock.restore();
- this.resetClock = false;
- }
- }
-
- return returnVal;
- };
-
- sinon.fakeServerWithClock.restore = function restore() {
- if (this.clock) {
- this.clock.restore();
- }
-
- return sinon.fakeServer.restore.apply(this, arguments);
- };
- }
-
- var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
- var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;
-
- function loadDependencies(require) {
- var sinon = require("./core");
- require("./fake_server");
- require("./fake_timers");
- makeApi(sinon);
- }
-
- if (isAMD) {
- define(loadDependencies);
- } else if (isNode) {
- loadDependencies(require);
- } else {
- makeApi(sinon);
- }
-}());
-
-/**
- * @depend util/core.js
- * @depend extend.js
- * @depend collection.js
- * @depend util/fake_timers.js
- * @depend util/fake_server_with_clock.js
- */
-/**
- * Manages fake collections as well as fake utilities such as Sinon's
- * timers and fake XHR implementation in one convenient object.
- *
- * @author Christian Johansen (christian at cjohansen.no)
- * @license BSD
- *
- * Copyright (c) 2010-2013 Christian Johansen
- */
-
-(function () {
- function makeApi(sinon) {
- var push = [].push;
-
- function exposeValue(sandbox, config, key, value) {
- if (!value) {
- return;
- }
-
- if (config.injectInto && !(key in config.injectInto)) {
- config.injectInto[key] = value;
- sandbox.injectedKeys.push(key);
- } else {
- push.call(sandbox.args, value);
- }
- }
-
- function prepareSandboxFromConfig(config) {
- var sandbox = sinon.create(sinon.sandbox);
-
- if (config.useFakeServer) {
- if (typeof config.useFakeServer == "object") {
- sandbox.serverPrototype = config.useFakeServer;
- }
-
- sandbox.useFakeServer();
- }
-
- if (config.useFakeTimers) {
- if (typeof config.useFakeTimers == "object") {
- sandbox.useFakeTimers.apply(sandbox, config.useFakeTimers);
- } else {
- sandbox.useFakeTimers();
- }
- }
-
- return sandbox;
- }
-
- sinon.sandbox = sinon.extend(sinon.create(sinon.collection), {
- useFakeTimers: function useFakeTimers() {
- this.clock = sinon.useFakeTimers.apply(sinon, arguments);
-
- return this.add(this.clock);
- },
-
- serverPrototype: sinon.fakeServer,
-
- useFakeServer: function useFakeServer() {
- var proto = this.serverPrototype || sinon.fakeServer;
-
- if (!proto || !proto.create) {
- return null;
- }
-
- this.server = proto.create();
- return this.add(this.server);
- },
-
- inject: function (obj) {
- sinon.collection.inject.call(this, obj);
-
- if (this.clock) {
- obj.clock = this.clock;
- }
-
- if (this.server) {
- obj.server = this.server;
- obj.requests = this.server.requests;
- }
-
- obj.match = sinon.match;
-
- return obj;
- },
-
- restore: function () {
- sinon.collection.restore.apply(this, arguments);
- this.restoreContext();
- },
-
- restoreContext: function () {
- if (this.injectedKeys) {
- for (var i = 0, j = this.injectedKeys.length; i < j; i++) {
- delete this.injectInto[this.injectedKeys[i]];
- }
- this.injectedKeys = [];
- }
- },
-
- create: function (config) {
- if (!config) {
- return sinon.create(sinon.sandbox);
- }
-
- var sandbox = prepareSandboxFromConfig(config);
- sandbox.args = sandbox.args || [];
- sandbox.injectedKeys = [];
- sandbox.injectInto = config.injectInto;
- var prop, value, exposed = sandbox.inject({});
-
- if (config.properties) {
- for (var i = 0, l = config.properties.length; i < l; i++) {
- prop = config.properties[i];
- value = exposed[prop] || prop == "sandbox" && sandbox;
- exposeValue(sandbox, config, prop, value);
- }
- } else {
- exposeValue(sandbox, config, "sandbox", value);
- }
-
- return sandbox;
- },
-
- match: sinon.match
- });
-
- sinon.sandbox.useFakeXMLHttpRequest = sinon.sandbox.useFakeServer;
-
- return sinon.sandbox;
- }
-
- var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
- var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;
-
- function loadDependencies(require, exports, module) {
- var sinon = require("./util/core");
- require("./extend");
- require("./util/fake_server_with_clock");
- require("./util/fake_timers");
- require("./collection");
- module.exports = makeApi(sinon);
- }
-
- if (isAMD) {
- define(loadDependencies);
- } else if (isNode) {
- loadDependencies(require, module.exports, module);
- } else if (!sinon) {
- return;
- } else {
- makeApi(sinon);
- }
-}());
-
-/**
- * @depend util/core.js
- * @depend sandbox.js
- */
-/**
- * Test function, sandboxes fakes
- *
- * @author Christian Johansen (christian at cjohansen.no)
- * @license BSD
- *
- * Copyright (c) 2010-2013 Christian Johansen
- */
-
-(function (sinon) {
- function makeApi(sinon) {
- var slice = Array.prototype.slice;
-
- function test(callback) {
- var type = typeof callback;
-
- if (type != "function") {
- throw new TypeError("sinon.test needs to wrap a test function, got " + type);
- }
-
- function sinonSandboxedTest() {
- var config = sinon.getConfig(sinon.config);
- config.injectInto = config.injectIntoThis && this || config.injectInto;
- var sandbox = sinon.sandbox.create(config);
- var args = slice.call(arguments);
- var oldDone = args.length && args[args.length - 1];
- var exception, result;
-
- if (typeof oldDone == "function") {
- args[args.length - 1] = function sinonDone(result) {
- if (result) {
- sandbox.restore();
- throw exception;
- } else {
- sandbox.verifyAndRestore();
- }
- oldDone(result);
- };
- }
-
- try {
- result = callback.apply(this, args.concat(sandbox.args));
- } catch (e) {
- exception = e;
- }
-
- if (typeof oldDone != "function") {
- if (typeof exception !== "undefined") {
- sandbox.restore();
- throw exception;
- } else {
- sandbox.verifyAndRestore();
- }
- }
-
- return result;
- }
-
- if (callback.length) {
- return function sinonAsyncSandboxedTest(callback) {
- return sinonSandboxedTest.apply(this, arguments);
- };
- }
-
- return sinonSandboxedTest;
- }
-
- test.config = {
- injectIntoThis: true,
- injectInto: null,
- properties: ["spy", "stub", "mock", "clock", "server", "requests"],
- useFakeTimers: true,
- useFakeServer: true
- };
-
- sinon.test = test;
- return test;
- }
-
- var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
- var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;
-
- function loadDependencies(require, exports, module) {
- var sinon = require("./util/core");
- require("./sandbox");
- module.exports = makeApi(sinon);
- }
-
- if (isAMD) {
- define(loadDependencies);
- } else if (isNode) {
- loadDependencies(require, module.exports, module);
- } else if (sinon) {
- makeApi(sinon);
- }
-}(typeof sinon == "object" && sinon || null));
-
-/**
- * @depend util/core.js
- * @depend test.js
- */
-/**
- * Test case, sandboxes all test functions
- *
- * @author Christian Johansen (christian at cjohansen.no)
- * @license BSD
- *
- * Copyright (c) 2010-2013 Christian Johansen
- */
-
-(function (sinon) {
- function createTest(property, setUp, tearDown) {
- return function () {
- if (setUp) {
- setUp.apply(this, arguments);
- }
-
- var exception, result;
-
- try {
- result = property.apply(this, arguments);
- } catch (e) {
- exception = e;
- }
-
- if (tearDown) {
- tearDown.apply(this, arguments);
- }
-
- if (exception) {
- throw exception;
- }
-
- return result;
- };
- }
-
- function makeApi(sinon) {
- function testCase(tests, prefix) {
- /*jsl:ignore*/
- if (!tests || typeof tests != "object") {
- throw new TypeError("sinon.testCase needs an object with test functions");
- }
- /*jsl:end*/
-
- prefix = prefix || "test";
- var rPrefix = new RegExp("^" + prefix);
- var methods = {}, testName, property, method;
- var setUp = tests.setUp;
- var tearDown = tests.tearDown;
-
- for (testName in tests) {
- if (tests.hasOwnProperty(testName)) {
- property = tests[testName];
-
- if (/^(setUp|tearDown)$/.test(testName)) {
- continue;
- }
-
- if (typeof property == "function" && rPrefix.test(testName)) {
- method = property;
-
- if (setUp || tearDown) {
- method = createTest(property, setUp, tearDown);
- }
-
- methods[testName] = sinon.test(method);
- } else {
- methods[testName] = tests[testName];
- }
- }
- }
-
- return methods;
- }
-
- sinon.testCase = testCase;
- return testCase;
- }
-
- var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
- var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;
-
- function loadDependencies(require, exports, module) {
- var sinon = require("./util/core");
- require("./test");
- module.exports = makeApi(sinon);
- }
-
- if (isAMD) {
- define(loadDependencies);
- } else if (isNode) {
- loadDependencies(require, module.exports, module);
- } else if (!sinon) {
- return;
- } else {
- makeApi(sinon);
- }
-}(typeof sinon == "object" && sinon || null));
-
-/**
- * @depend times_in_words.js
- * @depend util/core.js
- * @depend match.js
- * @depend format.js
- */
-/**
- * Assertions matching the test spy retrieval interface.
- *
- * @author Christian Johansen (christian at cjohansen.no)
- * @license BSD
- *
- * Copyright (c) 2010-2013 Christian Johansen
- */
-
-(function (sinon, global) {
- var slice = Array.prototype.slice;
-
- function makeApi(sinon) {
- var assert;
-
- function verifyIsStub() {
- var method;
-
- for (var i = 0, l = arguments.length; i < l; ++i) {
- method = arguments[i];
-
- if (!method) {
- assert.fail("fake is not a spy");
- }
-
- if (method.proxy) {
- verifyIsStub(method.proxy);
- } else {
- if (typeof method != "function") {
- assert.fail(method + " is not a function");
- }
-
- if (typeof method.getCall != "function") {
- assert.fail(method + " is not stubbed");
- }
- }
-
- }
- }
-
- function failAssertion(object, msg) {
- object = object || global;
- var failMethod = object.fail || assert.fail;
- failMethod.call(object, msg);
- }
-
- function mirrorPropAsAssertion(name, method, message) {
- if (arguments.length == 2) {
- message = method;
- method = name;
- }
-
- assert[name] = function (fake) {
- verifyIsStub(fake);
-
- var args = slice.call(arguments, 1);
- var failed = false;
-
- if (typeof method == "function") {
- failed = !method(fake);
- } else {
- failed = typeof fake[method] == "function" ?
- !fake[method].apply(fake, args) : !fake[method];
- }
-
- if (failed) {
- failAssertion(this, (fake.printf || fake.proxy.printf).apply(fake, [message].concat(args)));
- } else {
- assert.pass(name);
- }
- };
- }
-
- function exposedName(prefix, prop) {
- return !prefix || /^fail/.test(prop) ? prop :
- prefix + prop.slice(0, 1).toUpperCase() + prop.slice(1);
- }
-
- assert = {
- failException: "AssertError",
-
- fail: function fail(message) {
- var error = new Error(message);
- error.name = this.failException || assert.failException;
-
- throw error;
- },
-
- pass: function pass(assertion) {},
-
- callOrder: function assertCallOrder() {
- verifyIsStub.apply(null, arguments);
- var expected = "", actual = "";
-
- if (!sinon.calledInOrder(arguments)) {
- try {
- expected = [].join.call(arguments, ", ");
- var calls = slice.call(arguments);
- var i = calls.length;
- while (i) {
- if (!calls[--i].called) {
- calls.splice(i, 1);
- }
- }
- actual = sinon.orderByFirstCall(calls).join(", ");
- } catch (e) {
- // If this fails, we'll just fall back to the blank string
- }
-
- failAssertion(this, "expected " + expected + " to be " +
- "called in order but were called as " + actual);
- } else {
- assert.pass("callOrder");
- }
- },
-
- callCount: function assertCallCount(method, count) {
- verifyIsStub(method);
-
- if (method.callCount != count) {
- var msg = "expected %n to be called " + sinon.timesInWords(count) +
- " but was called %c%C";
- failAssertion(this, method.printf(msg));
- } else {
- assert.pass("callCount");
- }
- },
-
- expose: function expose(target, options) {
- if (!target) {
- throw new TypeError("target is null or undefined");
- }
-
- var o = options || {};
- var prefix = typeof o.prefix == "undefined" && "assert" || o.prefix;
- var includeFail = typeof o.includeFail == "undefined" || !!o.includeFail;
-
- for (var method in this) {
- if (method != "expose" && (includeFail || !/^(fail)/.test(method))) {
- target[exposedName(prefix, method)] = this[method];
- }
- }
-
- return target;
- },
-
- match: function match(actual, expectation) {
- var matcher = sinon.match(expectation);
- if (matcher.test(actual)) {
- assert.pass("match");
- } else {
- var formatted = [
- "expected value to match",
- " expected = " + sinon.format(expectation),
- " actual = " + sinon.format(actual)
- ]
- failAssertion(this, formatted.join("\n"));
- }
- }
- };
-
- mirrorPropAsAssertion("called", "expected %n to have been called at least once but was never called");
- mirrorPropAsAssertion("notCalled", function (spy) { return !spy.called; },
- "expected %n to not have been called but was called %c%C");
- mirrorPropAsAssertion("calledOnce", "expected %n to be called once but was called %c%C");
- mirrorPropAsAssertion("calledTwice", "expected %n to be called twice but was called %c%C");
- mirrorPropAsAssertion("calledThrice", "expected %n to be called thrice but was called %c%C");
- mirrorPropAsAssertion("calledOn", "expected %n to be called with %1 as this but was called with %t");
- mirrorPropAsAssertion("alwaysCalledOn", "expected %n to always be called with %1 as this but was called with %t");
- mirrorPropAsAssertion("calledWithNew", "expected %n to be called with new");
- mirrorPropAsAssertion("alwaysCalledWithNew", "expected %n to always be called with new");
- mirrorPropAsAssertion("calledWith", "expected %n to be called with arguments %*%C");
- mirrorPropAsAssertion("calledWithMatch", "expected %n to be called with match %*%C");
- mirrorPropAsAssertion("alwaysCalledWith", "expected %n to always be called with arguments %*%C");
- mirrorPropAsAssertion("alwaysCalledWithMatch", "expected %n to always be called with match %*%C");
- mirrorPropAsAssertion("calledWithExactly", "expected %n to be called with exact arguments %*%C");
- mirrorPropAsAssertion("alwaysCalledWithExactly", "expected %n to always be called with exact arguments %*%C");
- mirrorPropAsAssertion("neverCalledWith", "expected %n to never be called with arguments %*%C");
- mirrorPropAsAssertion("neverCalledWithMatch", "expected %n to never be called with match %*%C");
- mirrorPropAsAssertion("threw", "%n did not throw exception%C");
- mirrorPropAsAssertion("alwaysThrew", "%n did not always throw exception%C");
-
- sinon.assert = assert;
- return assert;
- }
-
- var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
- var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;
-
- function loadDependencies(require, exports, module) {
- var sinon = require("./util/core");
- require("./match");
- require("./format");
- module.exports = makeApi(sinon);
- }
-
- if (isAMD) {
- define(loadDependencies);
- } else if (isNode) {
- loadDependencies(require, module.exports, module);
- } else if (!sinon) {
- return;
- } else {
- makeApi(sinon);
- }
-
-}(typeof sinon == "object" && sinon || null, typeof window != "undefined" ? window : (typeof self != "undefined") ? self : global));
-
- return sinon;
-}));
diff --git a/external/sizzle/LICENSE.txt b/external/sizzle/LICENSE.txt
deleted file mode 100644
index dd7ce94..0000000
--- a/external/sizzle/LICENSE.txt
+++ /dev/null
@@ -1,36 +0,0 @@
-Copyright jQuery Foundation and other contributors, https://jquery.org/
-
-This software consists of voluntary contributions made by many
-individuals. For exact contribution history, see the revision history
-available at https://github.com/jquery/sizzle
-
-The following license applies to all parts of this software except as
-documented below:
-
-====
-
-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.
-
-====
-
-All files located in the node_modules and external directories are
-externally maintained libraries used by this software which have their
-own licenses; we recommend you read them, as their terms may differ from
-the terms above.
diff --git a/external/sizzle/dist/sizzle.js b/external/sizzle/dist/sizzle.js
deleted file mode 100644
index 9b1e5ba..0000000
--- a/external/sizzle/dist/sizzle.js
+++ /dev/null
@@ -1,2143 +0,0 @@
-/*!
- * Sizzle CSS Selector Engine v2.2.1
- * http://sizzlejs.com/
- *
- * Copyright jQuery Foundation and other contributors
- * Released under the MIT license
- * http://jquery.org/license
- *
- * Date: 2015-10-17
- */
-(function( window ) {
-
-var i,
- support,
- Expr,
- getText,
- isXML,
- tokenize,
- compile,
- select,
- outermostContext,
- sortInput,
- hasDuplicate,
-
- // Local document vars
- setDocument,
- document,
- docElem,
- documentIsHTML,
- rbuggyQSA,
- rbuggyMatches,
- matches,
- contains,
-
- // Instance-specific data
- expando = "sizzle" + 1 * new Date(),
- preferredDoc = window.document,
- dirruns = 0,
- done = 0,
- classCache = createCache(),
- tokenCache = createCache(),
- compilerCache = createCache(),
- sortOrder = function( a, b ) {
- if ( a === b ) {
- hasDuplicate = true;
- }
- return 0;
- },
-
- // General-purpose constants
- MAX_NEGATIVE = 1 << 31,
-
- // Instance methods
- hasOwn = ({}).hasOwnProperty,
- arr = [],
- pop = arr.pop,
- push_native = arr.push,
- push = arr.push,
- slice = arr.slice,
- // Use a stripped-down indexOf as it's faster than native
- // http://jsperf.com/thor-indexof-vs-for/5
- indexOf = function( list, elem ) {
- var i = 0,
- len = list.length;
- for ( ; i < len; i++ ) {
- if ( list[i] === elem ) {
- return i;
- }
- }
- return -1;
- },
-
- booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
-
- // Regular expressions
-
- // http://www.w3.org/TR/css3-selectors/#whitespace
- whitespace = "[\\x20\\t\\r\\n\\f]",
-
- // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
- identifier = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
-
- // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
- attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
- // Operator (capture 2)
- "*([*^$|!~]?=)" + whitespace +
- // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
- "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
- "*\\]",
-
- pseudos = ":(" + identifier + ")(?:\\((" +
- // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
- // 1. quoted (capture 3; capture 4 or capture 5)
- "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
- // 2. simple (capture 6)
- "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
- // 3. anything else (capture 2)
- ".*" +
- ")\\)|)",
-
- // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
- rwhitespace = new RegExp( whitespace + "+", "g" ),
- rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
-
- rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
- rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
-
- rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
-
- rpseudo = new RegExp( pseudos ),
- ridentifier = new RegExp( "^" + identifier + "$" ),
-
- matchExpr = {
- "ID": new RegExp( "^#(" + identifier + ")" ),
- "CLASS": new RegExp( "^\\.(" + identifier + ")" ),
- "TAG": new RegExp( "^(" + identifier + "|[*])" ),
- "ATTR": new RegExp( "^" + attributes ),
- "PSEUDO": new RegExp( "^" + pseudos ),
- "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
- "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
- "*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
- "bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
- // For use in libraries implementing .is()
- // We use this for POS matching in `select`
- "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
- whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
- },
-
- rinputs = /^(?:input|select|textarea|button)$/i,
- rheader = /^h\d$/i,
-
- rnative = /^[^{]+\{\s*\[native \w/,
-
- // Easily-parseable/retrievable ID or TAG or CLASS selectors
- rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
-
- rsibling = /[+~]/,
- rescape = /'|\\/g,
-
- // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
- runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
- funescape = function( _, escaped, escapedWhitespace ) {
- var high = "0x" + escaped - 0x10000;
- // NaN means non-codepoint
- // Support: Firefox<24
- // Workaround erroneous numeric interpretation of +"0x"
- return high !== high || escapedWhitespace ?
- escaped :
- high < 0 ?
- // BMP codepoint
- String.fromCharCode( high + 0x10000 ) :
- // Supplemental Plane codepoint (surrogate pair)
- String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
- },
-
- // Used for iframes
- // See setDocument()
- // Removing the function wrapper causes a "Permission Denied"
- // error in IE
- unloadHandler = function() {
- setDocument();
- };
-
-// Optimize for push.apply( _, NodeList )
-try {
- push.apply(
- (arr = slice.call( preferredDoc.childNodes )),
- preferredDoc.childNodes
- );
- // Support: Android<4.0
- // Detect silently failing push.apply
- arr[ preferredDoc.childNodes.length ].nodeType;
-} catch ( e ) {
- push = { apply: arr.length ?
-
- // Leverage slice if possible
- function( target, els ) {
- push_native.apply( target, slice.call(els) );
- } :
-
- // Support: IE<9
- // Otherwise append directly
- function( target, els ) {
- var j = target.length,
- i = 0;
- // Can't trust NodeList.length
- while ( (target[j++] = els[i++]) ) {}
- target.length = j - 1;
- }
- };
-}
-
-function Sizzle( selector, context, results, seed ) {
- var m, i, elem, nid, nidselect, match, groups, newSelector,
- newContext = context && context.ownerDocument,
-
- // nodeType defaults to 9, since context defaults to document
- nodeType = context ? context.nodeType : 9;
-
- results = results || [];
-
- // Return early from calls with invalid selector or context
- if ( typeof selector !== "string" || !selector ||
- nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
-
- return results;
- }
-
- // Try to shortcut find operations (as opposed to filters) in HTML documents
- if ( !seed ) {
-
- if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
- setDocument( context );
- }
- context = context || document;
-
- if ( documentIsHTML ) {
-
- // If the selector is sufficiently simple, try using a "get*By*" DOM method
- // (excepting DocumentFragment context, where the methods don't exist)
- if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {
-
- // ID selector
- if ( (m = match[1]) ) {
-
- // Document context
- if ( nodeType === 9 ) {
- if ( (elem = context.getElementById( m )) ) {
-
- // Support: IE, Opera, Webkit
- // TODO: identify versions
- // getElementById can match elements by name instead of ID
- if ( elem.id === m ) {
- results.push( elem );
- return results;
- }
- } else {
- return results;
- }
-
- // Element context
- } else {
-
- // Support: IE, Opera, Webkit
- // TODO: identify versions
- // getElementById can match elements by name instead of ID
- if ( newContext && (elem = newContext.getElementById( m )) &&
- contains( context, elem ) &&
- elem.id === m ) {
-
- results.push( elem );
- return results;
- }
- }
-
- // Type selector
- } else if ( match[2] ) {
- push.apply( results, context.getElementsByTagName( selector ) );
- return results;
-
- // Class selector
- } else if ( (m = match[3]) && support.getElementsByClassName &&
- context.getElementsByClassName ) {
-
- push.apply( results, context.getElementsByClassName( m ) );
- return results;
- }
- }
-
- // Take advantage of querySelectorAll
- if ( support.qsa &&
- !compilerCache[ selector + " " ] &&
- (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
-
- if ( nodeType !== 1 ) {
- newContext = context;
- newSelector = selector;
-
- // qSA looks outside Element context, which is not what we want
- // Thanks to Andrew Dupont for this workaround technique
- // Support: IE <=8
- // Exclude object elements
- } else if ( context.nodeName.toLowerCase() !== "object" ) {
-
- // Capture the context ID, setting it first if necessary
- if ( (nid = context.getAttribute( "id" )) ) {
- nid = nid.replace( rescape, "\\$&" );
- } else {
- context.setAttribute( "id", (nid = expando) );
- }
-
- // Prefix every selector in the list
- groups = tokenize( selector );
- i = groups.length;
- nidselect = ridentifier.test( nid ) ? "#" + nid : "[id='" + nid + "']";
- while ( i-- ) {
- groups[i] = nidselect + " " + toSelector( groups[i] );
- }
- newSelector = groups.join( "," );
-
- // Expand context for sibling selectors
- newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
- context;
- }
-
- if ( newSelector ) {
- try {
- push.apply( results,
- newContext.querySelectorAll( newSelector )
- );
- return results;
- } catch ( qsaError ) {
- } finally {
- if ( nid === expando ) {
- context.removeAttribute( "id" );
- }
- }
- }
- }
- }
- }
-
- // All others
- return select( selector.replace( rtrim, "$1" ), context, results, seed );
-}
-
-/**
- * Create key-value caches of limited size
- * @returns {function(string, object)} Returns the Object data after storing it on itself with
- * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
- * deleting the oldest entry
- */
-function createCache() {
- var keys = [];
-
- function cache( key, value ) {
- // Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
- if ( keys.push( key + " " ) > Expr.cacheLength ) {
- // Only keep the most recent entries
- delete cache[ keys.shift() ];
- }
- return (cache[ key + " " ] = value);
- }
- return cache;
-}
-
-/**
- * Mark a function for special use by Sizzle
- * @param {Function} fn The function to mark
- */
-function markFunction( fn ) {
- fn[ expando ] = true;
- return fn;
-}
-
-/**
- * Support testing using an element
- * @param {Function} fn Passed the created div and expects a boolean result
- */
-function assert( fn ) {
- var div = document.createElement("div");
-
- try {
- return !!fn( div );
- } catch (e) {
- return false;
- } finally {
- // Remove from its parent by default
- if ( div.parentNode ) {
- div.parentNode.removeChild( div );
- }
- // release memory in IE
- div = null;
- }
-}
-
-/**
- * Adds the same handler for all of the specified attrs
- * @param {String} attrs Pipe-separated list of attributes
- * @param {Function} handler The method that will be applied
- */
-function addHandle( attrs, handler ) {
- var arr = attrs.split("|"),
- i = arr.length;
-
- while ( i-- ) {
- Expr.attrHandle[ arr[i] ] = handler;
- }
-}
-
-/**
- * Checks document order of two siblings
- * @param {Element} a
- * @param {Element} b
- * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
- */
-function siblingCheck( a, b ) {
- var cur = b && a,
- diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
- ( ~b.sourceIndex || MAX_NEGATIVE ) -
- ( ~a.sourceIndex || MAX_NEGATIVE );
-
- // Use IE sourceIndex if available on both nodes
- if ( diff ) {
- return diff;
- }
-
- // Check if b follows a
- if ( cur ) {
- while ( (cur = cur.nextSibling) ) {
- if ( cur === b ) {
- return -1;
- }
- }
- }
-
- return a ? 1 : -1;
-}
-
-/**
- * Returns a function to use in pseudos for input types
- * @param {String} type
- */
-function createInputPseudo( type ) {
- return function( elem ) {
- var name = elem.nodeName.toLowerCase();
- return name === "input" && elem.type === type;
- };
-}
-
-/**
- * Returns a function to use in pseudos for buttons
- * @param {String} type
- */
-function createButtonPseudo( type ) {
- return function( elem ) {
- var name = elem.nodeName.toLowerCase();
- return (name === "input" || name === "button") && elem.type === type;
- };
-}
-
-/**
- * Returns a function to use in pseudos for positionals
- * @param {Function} fn
- */
-function createPositionalPseudo( fn ) {
- return markFunction(function( argument ) {
- argument = +argument;
- return markFunction(function( seed, matches ) {
- var j,
- matchIndexes = fn( [], seed.length, argument ),
- i = matchIndexes.length;
-
- // Match elements found at the specified indexes
- while ( i-- ) {
- if ( seed[ (j = matchIndexes[i]) ] ) {
- seed[j] = !(matches[j] = seed[j]);
- }
- }
- });
- });
-}
-
-/**
- * Checks a node for validity as a Sizzle context
- * @param {Element|Object=} context
- * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
- */
-function testContext( context ) {
- return context && typeof context.getElementsByTagName !== "undefined" && context;
-}
-
-// Expose support vars for convenience
-support = Sizzle.support = {};
-
-/**
- * Detects XML nodes
- * @param {Element|Object} elem An element or a document
- * @returns {Boolean} True iff elem is a non-HTML XML node
- */
-isXML = Sizzle.isXML = function( elem ) {
- // documentElement is verified for cases where it doesn't yet exist
- // (such as loading iframes in IE - #4833)
- var documentElement = elem && (elem.ownerDocument || elem).documentElement;
- return documentElement ? documentElement.nodeName !== "HTML" : false;
-};
-
-/**
- * Sets document-related variables once based on the current document
- * @param {Element|Object} [doc] An element or document object to use to set the document
- * @returns {Object} Returns the current document
- */
-setDocument = Sizzle.setDocument = function( node ) {
- var hasCompare, parent,
- doc = node ? node.ownerDocument || node : preferredDoc;
-
- // Return early if doc is invalid or already selected
- if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
- return document;
- }
-
- // Update global variables
- document = doc;
- docElem = document.documentElement;
- documentIsHTML = !isXML( document );
-
- // Support: IE 9-11, Edge
- // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
- if ( (parent = document.defaultView) && parent.top !== parent ) {
- // Support: IE 11
- if ( parent.addEventListener ) {
- parent.addEventListener( "unload", unloadHandler, false );
-
- // Support: IE 9 - 10 only
- } else if ( parent.attachEvent ) {
- parent.attachEvent( "onunload", unloadHandler );
- }
- }
-
- /* Attributes
- ---------------------------------------------------------------------- */
-
- // Support: IE<8
- // Verify that getAttribute really returns attributes and not properties
- // (excepting IE8 booleans)
- support.attributes = assert(function( div ) {
- div.className = "i";
- return !div.getAttribute("className");
- });
-
- /* getElement(s)By*
- ---------------------------------------------------------------------- */
-
- // Check if getElementsByTagName("*") returns only elements
- support.getElementsByTagName = assert(function( div ) {
- div.appendChild( document.createComment("") );
- return !div.getElementsByTagName("*").length;
- });
-
- // Support: IE<9
- support.getElementsByClassName = rnative.test( document.getElementsByClassName );
-
- // Support: IE<10
- // Check if getElementById returns elements by name
- // The broken getElementById methods don't pick up programatically-set names,
- // so use a roundabout getElementsByName test
- support.getById = assert(function( div ) {
- docElem.appendChild( div ).id = expando;
- return !document.getElementsByName || !document.getElementsByName( expando ).length;
- });
-
- // ID find and filter
- if ( support.getById ) {
- Expr.find["ID"] = function( id, context ) {
- if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
- var m = context.getElementById( id );
- return m ? [ m ] : [];
- }
- };
- Expr.filter["ID"] = function( id ) {
- var attrId = id.replace( runescape, funescape );
- return function( elem ) {
- return elem.getAttribute("id") === attrId;
- };
- };
- } else {
- // Support: IE6/7
- // getElementById is not reliable as a find shortcut
- delete Expr.find["ID"];
-
- Expr.filter["ID"] = function( id ) {
- var attrId = id.replace( runescape, funescape );
- return function( elem ) {
- var node = typeof elem.getAttributeNode !== "undefined" &&
- elem.getAttributeNode("id");
- return node && node.value === attrId;
- };
- };
- }
-
- // Tag
- Expr.find["TAG"] = support.getElementsByTagName ?
- function( tag, context ) {
- if ( typeof context.getElementsByTagName !== "undefined" ) {
- return context.getElementsByTagName( tag );
-
- // DocumentFragment nodes don't have gEBTN
- } else if ( support.qsa ) {
- return context.querySelectorAll( tag );
- }
- } :
-
- function( tag, context ) {
- var elem,
- tmp = [],
- i = 0,
- // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
- results = context.getElementsByTagName( tag );
-
- // Filter out possible comments
- if ( tag === "*" ) {
- while ( (elem = results[i++]) ) {
- if ( elem.nodeType === 1 ) {
- tmp.push( elem );
- }
- }
-
- return tmp;
- }
- return results;
- };
-
- // Class
- Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
- if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) {
- return context.getElementsByClassName( className );
- }
- };
-
- /* QSA/matchesSelector
- ---------------------------------------------------------------------- */
-
- // QSA and matchesSelector support
-
- // matchesSelector(:active) reports false when true (IE9/Opera 11.5)
- rbuggyMatches = [];
-
- // qSa(:focus) reports false when true (Chrome 21)
- // We allow this because of a bug in IE8/9 that throws an error
- // whenever `document.activeElement` is accessed on an iframe
- // So, we allow :focus to pass through QSA all the time to avoid the IE error
- // See http://bugs.jquery.com/ticket/13378
- rbuggyQSA = [];
-
- if ( (support.qsa = rnative.test( document.querySelectorAll )) ) {
- // Build QSA regex
- // Regex strategy adopted from Diego Perini
- assert(function( div ) {
- // Select is set to empty string on purpose
- // This is to test IE's treatment of not explicitly
- // setting a boolean content attribute,
- // since its presence should be enough
- // http://bugs.jquery.com/ticket/12359
- docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" +
- "<select id='" + expando + "-\r\\' msallowcapture=''>" +
- "<option selected=''></option></select>";
-
- // Support: IE8, Opera 11-12.16
- // Nothing should be selected when empty strings follow ^= or $= or *=
- // The test attribute must be unknown in Opera but "safe" for WinRT
- // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
- if ( div.querySelectorAll("[msallowcapture^='']").length ) {
- rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
- }
-
- // Support: IE8
- // Boolean attributes and "value" are not treated correctly
- if ( !div.querySelectorAll("[selected]").length ) {
- rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
- }
-
- // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
- if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
- rbuggyQSA.push("~=");
- }
-
- // Webkit/Opera - :checked should return selected option elements
- // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
- // IE8 throws error here and will not see later tests
- if ( !div.querySelectorAll(":checked").length ) {
- rbuggyQSA.push(":checked");
- }
-
- // Support: Safari 8+, iOS 8+
- // https://bugs.webkit.org/show_bug.cgi?id=136851
- // In-page `selector#id sibing-combinator selector` fails
- if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) {
- rbuggyQSA.push(".#.+[+~]");
- }
- });
-
- assert(function( div ) {
- // Support: Windows 8 Native Apps
- // The type and name attributes are restricted during .innerHTML assignment
- var input = document.createElement("input");
- input.setAttribute( "type", "hidden" );
- div.appendChild( input ).setAttribute( "name", "D" );
-
- // Support: IE8
- // Enforce case-sensitivity of name attribute
- if ( div.querySelectorAll("[name=d]").length ) {
- rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
- }
-
- // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
- // IE8 throws error here and will not see later tests
- if ( !div.querySelectorAll(":enabled").length ) {
- rbuggyQSA.push( ":enabled", ":disabled" );
- }
-
- // Opera 10-11 does not throw on post-comma invalid pseudos
- div.querySelectorAll("*,:x");
- rbuggyQSA.push(",.*:");
- });
- }
-
- if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
- docElem.webkitMatchesSelector ||
- docElem.mozMatchesSelector ||
- docElem.oMatchesSelector ||
- docElem.msMatchesSelector) )) ) {
-
- assert(function( div ) {
- // Check to see if it's possible to do matchesSelector
- // on a disconnected node (IE 9)
- support.disconnectedMatch = matches.call( div, "div" );
-
- // This should fail with an exception
- // Gecko does not error, returns false instead
- matches.call( div, "[s!='']:x" );
- rbuggyMatches.push( "!=", pseudos );
- });
- }
-
- rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
- rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
-
- /* Contains
- ---------------------------------------------------------------------- */
- hasCompare = rnative.test( docElem.compareDocumentPosition );
-
- // Element contains another
- // Purposefully self-exclusive
- // As in, an element does not contain itself
- contains = hasCompare || rnative.test( docElem.contains ) ?
- function( a, b ) {
- var adown = a.nodeType === 9 ? a.documentElement : a,
- bup = b && b.parentNode;
- return a === bup || !!( bup && bup.nodeType === 1 && (
- adown.contains ?
- adown.contains( bup ) :
- a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
- ));
- } :
- function( a, b ) {
- if ( b ) {
- while ( (b = b.parentNode) ) {
- if ( b === a ) {
- return true;
- }
- }
- }
- return false;
- };
-
- /* Sorting
- ---------------------------------------------------------------------- */
-
- // Document order sorting
- sortOrder = hasCompare ?
- function( a, b ) {
-
- // Flag for duplicate removal
- if ( a === b ) {
- hasDuplicate = true;
- return 0;
- }
-
- // Sort on method existence if only one input has compareDocumentPosition
- var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
- if ( compare ) {
- return compare;
- }
-
- // Calculate position if both inputs belong to the same document
- compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
- a.compareDocumentPosition( b ) :
-
- // Otherwise we know they are disconnected
- 1;
-
- // Disconnected nodes
- if ( compare & 1 ||
- (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
-
- // Choose the first element that is related to our preferred document
- if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
- return -1;
- }
- if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
- return 1;
- }
-
- // Maintain original order
- return sortInput ?
- ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
- 0;
- }
-
- return compare & 4 ? -1 : 1;
- } :
- function( a, b ) {
- // Exit early if the nodes are identical
- if ( a === b ) {
- hasDuplicate = true;
- return 0;
- }
-
- var cur,
- i = 0,
- aup = a.parentNode,
- bup = b.parentNode,
- ap = [ a ],
- bp = [ b ];
-
- // Parentless nodes are either documents or disconnected
- if ( !aup || !bup ) {
- return a === document ? -1 :
- b === document ? 1 :
- aup ? -1 :
- bup ? 1 :
- sortInput ?
- ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
- 0;
-
- // If the nodes are siblings, we can do a quick check
- } else if ( aup === bup ) {
- return siblingCheck( a, b );
- }
-
- // Otherwise we need full lists of their ancestors for comparison
- cur = a;
- while ( (cur = cur.parentNode) ) {
- ap.unshift( cur );
- }
- cur = b;
- while ( (cur = cur.parentNode) ) {
- bp.unshift( cur );
- }
-
- // Walk down the tree looking for a discrepancy
- while ( ap[i] === bp[i] ) {
- i++;
- }
-
- return i ?
- // Do a sibling check if the nodes have a common ancestor
- siblingCheck( ap[i], bp[i] ) :
-
- // Otherwise nodes in our document sort first
- ap[i] === preferredDoc ? -1 :
- bp[i] === preferredDoc ? 1 :
- 0;
- };
-
- return document;
-};
-
-Sizzle.matches = function( expr, elements ) {
- return Sizzle( expr, null, null, elements );
-};
-
-Sizzle.matchesSelector = function( elem, expr ) {
- // Set document vars if needed
- if ( ( elem.ownerDocument || elem ) !== document ) {
- setDocument( elem );
- }
-
- // Make sure that attribute selectors are quoted
- expr = expr.replace( rattributeQuotes, "='$1']" );
-
- if ( support.matchesSelector && documentIsHTML &&
- !compilerCache[ expr + " " ] &&
- ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
- ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
-
- try {
- var ret = matches.call( elem, expr );
-
- // IE 9's matchesSelector returns false on disconnected nodes
- if ( ret || support.disconnectedMatch ||
- // As well, disconnected nodes are said to be in a document
- // fragment in IE 9
- elem.document && elem.document.nodeType !== 11 ) {
- return ret;
- }
- } catch (e) {}
- }
-
- return Sizzle( expr, document, null, [ elem ] ).length > 0;
-};
-
-Sizzle.contains = function( context, elem ) {
- // Set document vars if needed
- if ( ( context.ownerDocument || context ) !== document ) {
- setDocument( context );
- }
- return contains( context, elem );
-};
-
-Sizzle.attr = function( elem, name ) {
- // Set document vars if needed
- if ( ( elem.ownerDocument || elem ) !== document ) {
- setDocument( elem );
- }
-
- var fn = Expr.attrHandle[ name.toLowerCase() ],
- // Don't get fooled by Object.prototype properties (jQuery #13807)
- val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
- fn( elem, name, !documentIsHTML ) :
- undefined;
-
- return val !== undefined ?
- val :
- support.attributes || !documentIsHTML ?
- elem.getAttribute( name ) :
- (val = elem.getAttributeNode(name)) && val.specified ?
- val.value :
- null;
-};
-
-Sizzle.error = function( msg ) {
- throw new Error( "Syntax error, unrecognized expression: " + msg );
-};
-
-/**
- * Document sorting and removing duplicates
- * @param {ArrayLike} results
- */
-Sizzle.uniqueSort = function( results ) {
- var elem,
- duplicates = [],
- j = 0,
- i = 0;
-
- // Unless we *know* we can detect duplicates, assume their presence
- hasDuplicate = !support.detectDuplicates;
- sortInput = !support.sortStable && results.slice( 0 );
- results.sort( sortOrder );
-
- if ( hasDuplicate ) {
- while ( (elem = results[i++]) ) {
- if ( elem === results[ i ] ) {
- j = duplicates.push( i );
- }
- }
- while ( j-- ) {
- results.splice( duplicates[ j ], 1 );
- }
- }
-
- // Clear input after sorting to release objects
- // See https://github.com/jquery/sizzle/pull/225
- sortInput = null;
-
- return results;
-};
-
-/**
- * Utility function for retrieving the text value of an array of DOM nodes
- * @param {Array|Element} elem
- */
-getText = Sizzle.getText = function( elem ) {
- var node,
- ret = "",
- i = 0,
- nodeType = elem.nodeType;
-
- if ( !nodeType ) {
- // If no nodeType, this is expected to be an array
- while ( (node = elem[i++]) ) {
- // Do not traverse comment nodes
- ret += getText( node );
- }
- } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
- // Use textContent for elements
- // innerText usage removed for consistency of new lines (jQuery #11153)
- if ( typeof elem.textContent === "string" ) {
- return elem.textContent;
- } else {
- // Traverse its children
- for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
- ret += getText( elem );
- }
- }
- } else if ( nodeType === 3 || nodeType === 4 ) {
- return elem.nodeValue;
- }
- // Do not include comment or processing instruction nodes
-
- return ret;
-};
-
-Expr = Sizzle.selectors = {
-
- // Can be adjusted by the user
- cacheLength: 50,
-
- createPseudo: markFunction,
-
- match: matchExpr,
-
- attrHandle: {},
-
- find: {},
-
- relative: {
- ">": { dir: "parentNode", first: true },
- " ": { dir: "parentNode" },
- "+": { dir: "previousSibling", first: true },
- "~": { dir: "previousSibling" }
- },
-
- preFilter: {
- "ATTR": function( match ) {
- match[1] = match[1].replace( runescape, funescape );
-
- // Move the given value to match[3] whether quoted or unquoted
- match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
-
- if ( match[2] === "~=" ) {
- match[3] = " " + match[3] + " ";
- }
-
- return match.slice( 0, 4 );
- },
-
- "CHILD": function( match ) {
- /* matches from matchExpr["CHILD"]
- 1 type (only|nth|...)
- 2 what (child|of-type)
- 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
- 4 xn-component of xn+y argument ([+-]?\d*n|)
- 5 sign of xn-component
- 6 x of xn-component
- 7 sign of y-component
- 8 y of y-component
- */
- match[1] = match[1].toLowerCase();
-
- if ( match[1].slice( 0, 3 ) === "nth" ) {
- // nth-* requires argument
- if ( !match[3] ) {
- Sizzle.error( match[0] );
- }
-
- // numeric x and y parameters for Expr.filter.CHILD
- // remember that false/true cast respectively to 0/1
- match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
- match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
-
- // other types prohibit arguments
- } else if ( match[3] ) {
- Sizzle.error( match[0] );
- }
-
- return match;
- },
-
- "PSEUDO": function( match ) {
- var excess,
- unquoted = !match[6] && match[2];
-
- if ( matchExpr["CHILD"].test( match[0] ) ) {
- return null;
- }
-
- // Accept quoted arguments as-is
- if ( match[3] ) {
- match[2] = match[4] || match[5] || "";
-
- // Strip excess characters from unquoted arguments
- } else if ( unquoted && rpseudo.test( unquoted ) &&
- // Get excess from tokenize (recursively)
- (excess = tokenize( unquoted, true )) &&
- // advance to the next closing parenthesis
- (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
-
- // excess is a negative index
- match[0] = match[0].slice( 0, excess );
- match[2] = unquoted.slice( 0, excess );
- }
-
- // Return only captures needed by the pseudo filter method (type and argument)
- return match.slice( 0, 3 );
- }
- },
-
- filter: {
-
- "TAG": function( nodeNameSelector ) {
- var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
- return nodeNameSelector === "*" ?
- function() { return true; } :
- function( elem ) {
- return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
- };
- },
-
- "CLASS": function( className ) {
- var pattern = classCache[ className + " " ];
-
- return pattern ||
- (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
- classCache( className, function( elem ) {
- return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" );
- });
- },
-
- "ATTR": function( name, operator, check ) {
- return function( elem ) {
- var result = Sizzle.attr( elem, name );
-
- if ( result == null ) {
- return operator === "!=";
- }
- if ( !operator ) {
- return true;
- }
-
- result += "";
-
- return operator === "=" ? result === check :
- operator === "!=" ? result !== check :
- operator === "^=" ? check && result.indexOf( check ) === 0 :
- operator === "*=" ? check && result.indexOf( check ) > -1 :
- operator === "$=" ? check && result.slice( -check.length ) === check :
- operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
- operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
- false;
- };
- },
-
- "CHILD": function( type, what, argument, first, last ) {
- var simple = type.slice( 0, 3 ) !== "nth",
- forward = type.slice( -4 ) !== "last",
- ofType = what === "of-type";
-
- return first === 1 && last === 0 ?
-
- // Shortcut for :nth-*(n)
- function( elem ) {
- return !!elem.parentNode;
- } :
-
- function( elem, context, xml ) {
- var cache, uniqueCache, outerCache, node, nodeIndex, start,
- dir = simple !== forward ? "nextSibling" : "previousSibling",
- parent = elem.parentNode,
- name = ofType && elem.nodeName.toLowerCase(),
- useCache = !xml && !ofType,
- diff = false;
-
- if ( parent ) {
-
- // :(first|last|only)-(child|of-type)
- if ( simple ) {
- while ( dir ) {
- node = elem;
- while ( (node = node[ dir ]) ) {
- if ( ofType ?
- node.nodeName.toLowerCase() === name :
- node.nodeType === 1 ) {
-
- return false;
- }
- }
- // Reverse direction for :only-* (if we haven't yet done so)
- start = dir = type === "only" && !start && "nextSibling";
- }
- return true;
- }
-
- start = [ forward ? parent.firstChild : parent.lastChild ];
-
- // non-xml :nth-child(...) stores cache data on `parent`
- if ( forward && useCache ) {
-
- // Seek `elem` from a previously-cached index
-
- // ...in a gzip-friendly way
- node = parent;
- outerCache = node[ expando ] || (node[ expando ] = {});
-
- // Support: IE <9 only
- // Defend against cloned attroperties (jQuery gh-1709)
- uniqueCache = outerCache[ node.uniqueID ] ||
- (outerCache[ node.uniqueID ] = {});
-
- cache = uniqueCache[ type ] || [];
- nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
- diff = nodeIndex && cache[ 2 ];
- node = nodeIndex && parent.childNodes[ nodeIndex ];
-
- while ( (node = ++nodeIndex && node && node[ dir ] ||
-
- // Fallback to seeking `elem` from the start
- (diff = nodeIndex = 0) || start.pop()) ) {
-
- // When found, cache indexes on `parent` and break
- if ( node.nodeType === 1 && ++diff && node === elem ) {
- uniqueCache[ type ] = [ dirruns, nodeIndex, diff ];
- break;
- }
- }
-
- } else {
- // Use previously-cached element index if available
- if ( useCache ) {
- // ...in a gzip-friendly way
- node = elem;
- outerCache = node[ expando ] || (node[ expando ] = {});
-
- // Support: IE <9 only
- // Defend against cloned attroperties (jQuery gh-1709)
- uniqueCache = outerCache[ node.uniqueID ] ||
- (outerCache[ node.uniqueID ] = {});
-
- cache = uniqueCache[ type ] || [];
- nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
- diff = nodeIndex;
- }
-
- // xml :nth-child(...)
- // or :nth-last-child(...) or :nth(-last)?-of-type(...)
- if ( diff === false ) {
- // Use the same loop as above to seek `elem` from the start
- while ( (node = ++nodeIndex && node && node[ dir ] ||
- (diff = nodeIndex = 0) || start.pop()) ) {
-
- if ( ( ofType ?
- node.nodeName.toLowerCase() === name :
- node.nodeType === 1 ) &&
- ++diff ) {
-
- // Cache the index of each encountered element
- if ( useCache ) {
- outerCache = node[ expando ] || (node[ expando ] = {});
-
- // Support: IE <9 only
- // Defend against cloned attroperties (jQuery gh-1709)
- uniqueCache = outerCache[ node.uniqueID ] ||
- (outerCache[ node.uniqueID ] = {});
-
- uniqueCache[ type ] = [ dirruns, diff ];
- }
-
- if ( node === elem ) {
- break;
- }
- }
- }
- }
- }
-
- // Incorporate the offset, then check against cycle size
- diff -= last;
- return diff === first || ( diff % first === 0 && diff / first >= 0 );
- }
- };
- },
-
- "PSEUDO": function( pseudo, argument ) {
- // pseudo-class names are case-insensitive
- // http://www.w3.org/TR/selectors/#pseudo-classes
- // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
- // Remember that setFilters inherits from pseudos
- var args,
- fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
- Sizzle.error( "unsupported pseudo: " + pseudo );
-
- // The user may use createPseudo to indicate that
- // arguments are needed to create the filter function
- // just as Sizzle does
- if ( fn[ expando ] ) {
- return fn( argument );
- }
-
- // But maintain support for old signatures
- if ( fn.length > 1 ) {
- args = [ pseudo, pseudo, "", argument ];
- return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
- markFunction(function( seed, matches ) {
- var idx,
- matched = fn( seed, argument ),
- i = matched.length;
- while ( i-- ) {
- idx = indexOf( seed, matched[i] );
- seed[ idx ] = !( matches[ idx ] = matched[i] );
- }
- }) :
- function( elem ) {
- return fn( elem, 0, args );
- };
- }
-
- return fn;
- }
- },
-
- pseudos: {
- // Potentially complex pseudos
- "not": markFunction(function( selector ) {
- // Trim the selector passed to compile
- // to avoid treating leading and trailing
- // spaces as combinators
- var input = [],
- results = [],
- matcher = compile( selector.replace( rtrim, "$1" ) );
-
- return matcher[ expando ] ?
- markFunction(function( seed, matches, context, xml ) {
- var elem,
- unmatched = matcher( seed, null, xml, [] ),
- i = seed.length;
-
- // Match elements unmatched by `matcher`
- while ( i-- ) {
- if ( (elem = unmatched[i]) ) {
- seed[i] = !(matches[i] = elem);
- }
- }
- }) :
- function( elem, context, xml ) {
- input[0] = elem;
- matcher( input, null, xml, results );
- // Don't keep the element (issue #299)
- input[0] = null;
- return !results.pop();
- };
- }),
-
- "has": markFunction(function( selector ) {
- return function( elem ) {
- return Sizzle( selector, elem ).length > 0;
- };
- }),
-
- "contains": markFunction(function( text ) {
- text = text.replace( runescape, funescape );
- return function( elem ) {
- return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
- };
- }),
-
- // "Whether an element is represented by a :lang() selector
- // is based solely on the element's language value
- // being equal to the identifier C,
- // or beginning with the identifier C immediately followed by "-".
- // The matching of C against the element's language value is performed case-insensitively.
- // The identifier C does not have to be a valid language name."
- // http://www.w3.org/TR/selectors/#lang-pseudo
- "lang": markFunction( function( lang ) {
- // lang value must be a valid identifier
- if ( !ridentifier.test(lang || "") ) {
- Sizzle.error( "unsupported lang: " + lang );
- }
- lang = lang.replace( runescape, funescape ).toLowerCase();
- return function( elem ) {
- var elemLang;
- do {
- if ( (elemLang = documentIsHTML ?
- elem.lang :
- elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
-
- elemLang = elemLang.toLowerCase();
- return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
- }
- } while ( (elem = elem.parentNode) && elem.nodeType === 1 );
- return false;
- };
- }),
-
- // Miscellaneous
- "target": function( elem ) {
- var hash = window.location && window.location.hash;
- return hash && hash.slice( 1 ) === elem.id;
- },
-
- "root": function( elem ) {
- return elem === docElem;
- },
-
- "focus": function( elem ) {
- return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
- },
-
- // Boolean properties
- "enabled": function( elem ) {
- return elem.disabled === false;
- },
-
- "disabled": function( elem ) {
- return elem.disabled === true;
- },
-
- "checked": function( elem ) {
- // In CSS3, :checked should return both checked and selected elements
- // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
- var nodeName = elem.nodeName.toLowerCase();
- return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
- },
-
- "selected": function( elem ) {
- // Accessing this property makes selected-by-default
- // options in Safari work properly
- if ( elem.parentNode ) {
- elem.parentNode.selectedIndex;
- }
-
- return elem.selected === true;
- },
-
- // Contents
- "empty": function( elem ) {
- // http://www.w3.org/TR/selectors/#empty-pseudo
- // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
- // but not by others (comment: 8; processing instruction: 7; etc.)
- // nodeType < 6 works because attributes (2) do not appear as children
- for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
- if ( elem.nodeType < 6 ) {
- return false;
- }
- }
- return true;
- },
-
- "parent": function( elem ) {
- return !Expr.pseudos["empty"]( elem );
- },
-
- // Element/input types
- "header": function( elem ) {
- return rheader.test( elem.nodeName );
- },
-
- "input": function( elem ) {
- return rinputs.test( elem.nodeName );
- },
-
- "button": function( elem ) {
- var name = elem.nodeName.toLowerCase();
- return name === "input" && elem.type === "button" || name === "button";
- },
-
- "text": function( elem ) {
- var attr;
- return elem.nodeName.toLowerCase() === "input" &&
- elem.type === "text" &&
-
- // Support: IE<8
- // New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
- ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
- },
-
- // Position-in-collection
- "first": createPositionalPseudo(function() {
- return [ 0 ];
- }),
-
- "last": createPositionalPseudo(function( matchIndexes, length ) {
- return [ length - 1 ];
- }),
-
- "eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
- return [ argument < 0 ? argument + length : argument ];
- }),
-
- "even": createPositionalPseudo(function( matchIndexes, length ) {
- var i = 0;
- for ( ; i < length; i += 2 ) {
- matchIndexes.push( i );
- }
- return matchIndexes;
- }),
-
- "odd": createPositionalPseudo(function( matchIndexes, length ) {
- var i = 1;
- for ( ; i < length; i += 2 ) {
- matchIndexes.push( i );
- }
- return matchIndexes;
- }),
-
- "lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
- var i = argument < 0 ? argument + length : argument;
- for ( ; --i >= 0; ) {
- matchIndexes.push( i );
- }
- return matchIndexes;
- }),
-
- "gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
- var i = argument < 0 ? argument + length : argument;
- for ( ; ++i < length; ) {
- matchIndexes.push( i );
- }
- return matchIndexes;
- })
- }
-};
-
-Expr.pseudos["nth"] = Expr.pseudos["eq"];
-
-// Add button/input type pseudos
-for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
- Expr.pseudos[ i ] = createInputPseudo( i );
-}
-for ( i in { submit: true, reset: true } ) {
- Expr.pseudos[ i ] = createButtonPseudo( i );
-}
-
-// Easy API for creating new setFilters
-function setFilters() {}
-setFilters.prototype = Expr.filters = Expr.pseudos;
-Expr.setFilters = new setFilters();
-
-tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
- var matched, match, tokens, type,
- soFar, groups, preFilters,
- cached = tokenCache[ selector + " " ];
-
- if ( cached ) {
- return parseOnly ? 0 : cached.slice( 0 );
- }
-
- soFar = selector;
- groups = [];
- preFilters = Expr.preFilter;
-
- while ( soFar ) {
-
- // Comma and first run
- if ( !matched || (match = rcomma.exec( soFar )) ) {
- if ( match ) {
- // Don't consume trailing commas as valid
- soFar = soFar.slice( match[0].length ) || soFar;
- }
- groups.push( (tokens = []) );
- }
-
- matched = false;
-
- // Combinators
- if ( (match = rcombinators.exec( soFar )) ) {
- matched = match.shift();
- tokens.push({
- value: matched,
- // Cast descendant combinators to space
- type: match[0].replace( rtrim, " " )
- });
- soFar = soFar.slice( matched.length );
- }
-
- // Filters
- for ( type in Expr.filter ) {
- if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
- (match = preFilters[ type ]( match ))) ) {
- matched = match.shift();
- tokens.push({
- value: matched,
- type: type,
- matches: match
- });
- soFar = soFar.slice( matched.length );
- }
- }
-
- if ( !matched ) {
- break;
- }
- }
-
- // Return the length of the invalid excess
- // if we're just parsing
- // Otherwise, throw an error or return tokens
- return parseOnly ?
- soFar.length :
- soFar ?
- Sizzle.error( selector ) :
- // Cache the tokens
- tokenCache( selector, groups ).slice( 0 );
-};
-
-function toSelector( tokens ) {
- var i = 0,
- len = tokens.length,
- selector = "";
- for ( ; i < len; i++ ) {
- selector += tokens[i].value;
- }
- return selector;
-}
-
-function addCombinator( matcher, combinator, base ) {
- var dir = combinator.dir,
- checkNonElements = base && dir === "parentNode",
- doneName = done++;
-
- return combinator.first ?
- // Check against closest ancestor/preceding element
- function( elem, context, xml ) {
- while ( (elem = elem[ dir ]) ) {
- if ( elem.nodeType === 1 || checkNonElements ) {
- return matcher( elem, context, xml );
- }
- }
- } :
-
- // Check against all ancestor/preceding elements
- function( elem, context, xml ) {
- var oldCache, uniqueCache, outerCache,
- newCache = [ dirruns, doneName ];
-
- // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
- if ( xml ) {
- while ( (elem = elem[ dir ]) ) {
- if ( elem.nodeType === 1 || checkNonElements ) {
- if ( matcher( elem, context, xml ) ) {
- return true;
- }
- }
- }
- } else {
- while ( (elem = elem[ dir ]) ) {
- if ( elem.nodeType === 1 || checkNonElements ) {
- outerCache = elem[ expando ] || (elem[ expando ] = {});
-
- // Support: IE <9 only
- // Defend against cloned attroperties (jQuery gh-1709)
- uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {});
-
- if ( (oldCache = uniqueCache[ dir ]) &&
- oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
-
- // Assign to newCache so results back-propagate to previous elements
- return (newCache[ 2 ] = oldCache[ 2 ]);
- } else {
- // Reuse newcache so results back-propagate to previous elements
- uniqueCache[ dir ] = newCache;
-
- // A match means we're done; a fail means we have to keep checking
- if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
- return true;
- }
- }
- }
- }
- }
- };
-}
-
-function elementMatcher( matchers ) {
- return matchers.length > 1 ?
- function( elem, context, xml ) {
- var i = matchers.length;
- while ( i-- ) {
- if ( !matchers[i]( elem, context, xml ) ) {
- return false;
- }
- }
- return true;
- } :
- matchers[0];
-}
-
-function multipleContexts( selector, contexts, results ) {
- var i = 0,
- len = contexts.length;
- for ( ; i < len; i++ ) {
- Sizzle( selector, contexts[i], results );
- }
- return results;
-}
-
-function condense( unmatched, map, filter, context, xml ) {
- var elem,
- newUnmatched = [],
- i = 0,
- len = unmatched.length,
- mapped = map != null;
-
- for ( ; i < len; i++ ) {
- if ( (elem = unmatched[i]) ) {
- if ( !filter || filter( elem, context, xml ) ) {
- newUnmatched.push( elem );
- if ( mapped ) {
- map.push( i );
- }
- }
- }
- }
-
- return newUnmatched;
-}
-
-function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
- if ( postFilter && !postFilter[ expando ] ) {
- postFilter = setMatcher( postFilter );
- }
- if ( postFinder && !postFinder[ expando ] ) {
- postFinder = setMatcher( postFinder, postSelector );
- }
- return markFunction(function( seed, results, context, xml ) {
- var temp, i, elem,
- preMap = [],
- postMap = [],
- preexisting = results.length,
-
- // Get initial elements from seed or context
- elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
-
- // Prefilter to get matcher input, preserving a map for seed-results synchronization
- matcherIn = preFilter && ( seed || !selector ) ?
- condense( elems, preMap, preFilter, context, xml ) :
- elems,
-
- matcherOut = matcher ?
- // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
- postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
-
- // ...intermediate processing is necessary
- [] :
-
- // ...otherwise use results directly
- results :
- matcherIn;
-
- // Find primary matches
- if ( matcher ) {
- matcher( matcherIn, matcherOut, context, xml );
- }
-
- // Apply postFilter
- if ( postFilter ) {
- temp = condense( matcherOut, postMap );
- postFilter( temp, [], context, xml );
-
- // Un-match failing elements by moving them back to matcherIn
- i = temp.length;
- while ( i-- ) {
- if ( (elem = temp[i]) ) {
- matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
- }
- }
- }
-
- if ( seed ) {
- if ( postFinder || preFilter ) {
- if ( postFinder ) {
- // Get the final matcherOut by condensing this intermediate into postFinder contexts
- temp = [];
- i = matcherOut.length;
- while ( i-- ) {
- if ( (elem = matcherOut[i]) ) {
- // Restore matcherIn since elem is not yet a final match
- temp.push( (matcherIn[i] = elem) );
- }
- }
- postFinder( null, (matcherOut = []), temp, xml );
- }
-
- // Move matched elements from seed to results to keep them synchronized
- i = matcherOut.length;
- while ( i-- ) {
- if ( (elem = matcherOut[i]) &&
- (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) {
-
- seed[temp] = !(results[temp] = elem);
- }
- }
- }
-
- // Add elements to results, through postFinder if defined
- } else {
- matcherOut = condense(
- matcherOut === results ?
- matcherOut.splice( preexisting, matcherOut.length ) :
- matcherOut
- );
- if ( postFinder ) {
- postFinder( null, results, matcherOut, xml );
- } else {
- push.apply( results, matcherOut );
- }
- }
- });
-}
-
-function matcherFromTokens( tokens ) {
- var checkContext, matcher, j,
- len = tokens.length,
- leadingRelative = Expr.relative[ tokens[0].type ],
- implicitRelative = leadingRelative || Expr.relative[" "],
- i = leadingRelative ? 1 : 0,
-
- // The foundational matcher ensures that elements are reachable from top-level context(s)
- matchContext = addCombinator( function( elem ) {
- return elem === checkContext;
- }, implicitRelative, true ),
- matchAnyContext = addCombinator( function( elem ) {
- return indexOf( checkContext, elem ) > -1;
- }, implicitRelative, true ),
- matchers = [ function( elem, context, xml ) {
- var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
- (checkContext = context).nodeType ?
- matchContext( elem, context, xml ) :
- matchAnyContext( elem, context, xml ) );
- // Avoid hanging onto element (issue #299)
- checkContext = null;
- return ret;
- } ];
-
- for ( ; i < len; i++ ) {
- if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
- matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
- } else {
- matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
-
- // Return special upon seeing a positional matcher
- if ( matcher[ expando ] ) {
- // Find the next relative operator (if any) for proper handling
- j = ++i;
- for ( ; j < len; j++ ) {
- if ( Expr.relative[ tokens[j].type ] ) {
- break;
- }
- }
- return setMatcher(
- i > 1 && elementMatcher( matchers ),
- i > 1 && toSelector(
- // If the preceding token was a descendant combinator, insert an implicit any-element `*`
- tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
- ).replace( rtrim, "$1" ),
- matcher,
- i < j && matcherFromTokens( tokens.slice( i, j ) ),
- j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
- j < len && toSelector( tokens )
- );
- }
- matchers.push( matcher );
- }
- }
-
- return elementMatcher( matchers );
-}
-
-function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
- var bySet = setMatchers.length > 0,
- byElement = elementMatchers.length > 0,
- superMatcher = function( seed, context, xml, results, outermost ) {
- var elem, j, matcher,
- matchedCount = 0,
- i = "0",
- unmatched = seed && [],
- setMatched = [],
- contextBackup = outermostContext,
- // We must always have either seed elements or outermost context
- elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
- // Use integer dirruns iff this is the outermost matcher
- dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
- len = elems.length;
-
- if ( outermost ) {
- outermostContext = context === document || context || outermost;
- }
-
- // Add elements passing elementMatchers directly to results
- // Support: IE<9, Safari
- // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
- for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
- if ( byElement && elem ) {
- j = 0;
- if ( !context && elem.ownerDocument !== document ) {
- setDocument( elem );
- xml = !documentIsHTML;
- }
- while ( (matcher = elementMatchers[j++]) ) {
- if ( matcher( elem, context || document, xml) ) {
- results.push( elem );
- break;
- }
- }
- if ( outermost ) {
- dirruns = dirrunsUnique;
- }
- }
-
- // Track unmatched elements for set filters
- if ( bySet ) {
- // They will have gone through all possible matchers
- if ( (elem = !matcher && elem) ) {
- matchedCount--;
- }
-
- // Lengthen the array for every element, matched or not
- if ( seed ) {
- unmatched.push( elem );
- }
- }
- }
-
- // `i` is now the count of elements visited above, and adding it to `matchedCount`
- // makes the latter nonnegative.
- matchedCount += i;
-
- // Apply set filters to unmatched elements
- // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
- // equals `i`), unless we didn't visit _any_ elements in the above loop because we have
- // no element matchers and no seed.
- // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
- // case, which will result in a "00" `matchedCount` that differs from `i` but is also
- // numerically zero.
- if ( bySet && i !== matchedCount ) {
- j = 0;
- while ( (matcher = setMatchers[j++]) ) {
- matcher( unmatched, setMatched, context, xml );
- }
-
- if ( seed ) {
- // Reintegrate element matches to eliminate the need for sorting
- if ( matchedCount > 0 ) {
- while ( i-- ) {
- if ( !(unmatched[i] || setMatched[i]) ) {
- setMatched[i] = pop.call( results );
- }
- }
- }
-
- // Discard index placeholder values to get only actual matches
- setMatched = condense( setMatched );
- }
-
- // Add matches to results
- push.apply( results, setMatched );
-
- // Seedless set matches succeeding multiple successful matchers stipulate sorting
- if ( outermost && !seed && setMatched.length > 0 &&
- ( matchedCount + setMatchers.length ) > 1 ) {
-
- Sizzle.uniqueSort( results );
- }
- }
-
- // Override manipulation of globals by nested matchers
- if ( outermost ) {
- dirruns = dirrunsUnique;
- outermostContext = contextBackup;
- }
-
- return unmatched;
- };
-
- return bySet ?
- markFunction( superMatcher ) :
- superMatcher;
-}
-
-compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
- var i,
- setMatchers = [],
- elementMatchers = [],
- cached = compilerCache[ selector + " " ];
-
- if ( !cached ) {
- // Generate a function of recursive functions that can be used to check each element
- if ( !match ) {
- match = tokenize( selector );
- }
- i = match.length;
- while ( i-- ) {
- cached = matcherFromTokens( match[i] );
- if ( cached[ expando ] ) {
- setMatchers.push( cached );
- } else {
- elementMatchers.push( cached );
- }
- }
-
- // Cache the compiled function
- cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
-
- // Save selector and tokenization
- cached.selector = selector;
- }
- return cached;
-};
-
-/**
- * A low-level selection function that works with Sizzle's compiled
- * selector functions
- * @param {String|Function} selector A selector or a pre-compiled
- * selector function built with Sizzle.compile
- * @param {Element} context
- * @param {Array} [results]
- * @param {Array} [seed] A set of elements to match against
- */
-select = Sizzle.select = function( selector, context, results, seed ) {
- var i, tokens, token, type, find,
- compiled = typeof selector === "function" && selector,
- match = !seed && tokenize( (selector = compiled.selector || selector) );
-
- results = results || [];
-
- // Try to minimize operations if there is only one selector in the list and no seed
- // (the latter of which guarantees us context)
- if ( match.length === 1 ) {
-
- // Reduce context if the leading compound selector is an ID
- tokens = match[0] = match[0].slice( 0 );
- if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
- support.getById && context.nodeType === 9 && documentIsHTML &&
- Expr.relative[ tokens[1].type ] ) {
-
- context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
- if ( !context ) {
- return results;
-
- // Precompiled matchers will still verify ancestry, so step up a level
- } else if ( compiled ) {
- context = context.parentNode;
- }
-
- selector = selector.slice( tokens.shift().value.length );
- }
-
- // Fetch a seed set for right-to-left matching
- i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
- while ( i-- ) {
- token = tokens[i];
-
- // Abort if we hit a combinator
- if ( Expr.relative[ (type = token.type) ] ) {
- break;
- }
- if ( (find = Expr.find[ type ]) ) {
- // Search, expanding context for leading sibling combinators
- if ( (seed = find(
- token.matches[0].replace( runescape, funescape ),
- rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
- )) ) {
-
- // If seed is empty or no tokens remain, we can return early
- tokens.splice( i, 1 );
- selector = seed.length && toSelector( tokens );
- if ( !selector ) {
- push.apply( results, seed );
- return results;
- }
-
- break;
- }
- }
- }
- }
-
- // Compile and execute a filtering function if one is not provided
- // Provide `match` to avoid retokenization if we modified the selector above
- ( compiled || compile( selector, match ) )(
- seed,
- context,
- !documentIsHTML,
- results,
- !context || rsibling.test( selector ) && testContext( context.parentNode ) || context
- );
- return results;
-};
-
-// One-time assignments
-
-// Sort stability
-support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
-
-// Support: Chrome 14-35+
-// Always assume duplicates if they aren't passed to the comparison function
-support.detectDuplicates = !!hasDuplicate;
-
-// Initialize against the default document
-setDocument();
-
-// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
-// Detached nodes confoundingly follow *each other*
-support.sortDetached = assert(function( div1 ) {
- // Should return 1, but returns 4 (following)
- return div1.compareDocumentPosition( document.createElement("div") ) & 1;
-});
-
-// Support: IE<8
-// Prevent attribute/property "interpolation"
-// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
-if ( !assert(function( div ) {
- div.innerHTML = "<a href='#'></a>";
- return div.firstChild.getAttribute("href") === "#" ;
-}) ) {
- addHandle( "type|href|height|width", function( elem, name, isXML ) {
- if ( !isXML ) {
- return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
- }
- });
-}
-
-// Support: IE<9
-// Use defaultValue in place of getAttribute("value")
-if ( !support.attributes || !assert(function( div ) {
- div.innerHTML = "<input/>";
- div.firstChild.setAttribute( "value", "" );
- return div.firstChild.getAttribute( "value" ) === "";
-}) ) {
- addHandle( "value", function( elem, name, isXML ) {
- if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
- return elem.defaultValue;
- }
- });
-}
-
-// Support: IE<9
-// Use getAttributeNode to fetch booleans when getAttribute lies
-if ( !assert(function( div ) {
- return div.getAttribute("disabled") == null;
-}) ) {
- addHandle( booleans, function( elem, name, isXML ) {
- var val;
- if ( !isXML ) {
- return elem[ name ] === true ? name.toLowerCase() :
- (val = elem.getAttributeNode( name )) && val.specified ?
- val.value :
- null;
- }
- });
-}
-
-// EXPOSE
-if ( typeof define === "function" && define.amd ) {
- define(function() { return Sizzle; });
-// Sizzle requires that there be a global window in Common-JS like environments
-} else if ( typeof module !== "undefined" && module.exports ) {
- module.exports = Sizzle;
-} else {
- window.Sizzle = Sizzle;
-}
-// EXPOSE
-
-})( window );
diff --git a/external/sizzle/dist/sizzle.min.js b/external/sizzle/dist/sizzle.min.js
deleted file mode 100644
index 8558975..0000000
--- a/external/sizzle/dist/sizzle.min.js
+++ /dev/null
@@ -1,3 +0,0 @@
-/*! Sizzle v2.2.1 | (c) jQuery Foundation, Inc. | jquery.org/license */
-!function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ga(),z=ga(),A=ga(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+ [...]
-//# sourceMappingURL=sizzle.min.map
\ No newline at end of file
diff --git a/external/sizzle/dist/sizzle.min.map b/external/sizzle/dist/sizzle.min.map
deleted file mode 100644
index 5438e0e..0000000
--- a/external/sizzle/dist/sizzle.min.map
+++ /dev/null
@@ -1 +0,0 @@
-{"version":3,"file":"sizzle.min.js","sources":["sizzle.js"],"names":["window","i","support","Expr","getText","isXML","tokenize","compile","select","outermostContext","sortInput","hasDuplicate","setDocument","document","docElem","documentIsHTML","rbuggyQSA","rbuggyMatches","matches","contains","expando","Date","preferredDoc","dirruns","done","classCache","createCache","tokenCache","compilerCache","sortOrder","a","b","MAX_NEGATIVE","hasOwn","hasOwnProperty","arr","pop","push_native","push" [...]
\ No newline at end of file
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/collab-maint/node-jquery.git
More information about the Pkg-javascript-commits
mailing list